Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion apps/events/src/components/playground.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getSmartAccountWalletClient } from '@/lib/smart-account';
import { _useDeleteEntityPublic, useQuery } from '@graphprotocol/hypergraph-react';
import { _useCreateEntityPublic, _useDeleteEntityPublic, useQuery } from '@graphprotocol/hypergraph-react';
import { useState } from 'react';
import { Event } from '../schema';
import { Button } from './ui/button';
Expand All @@ -14,17 +14,46 @@ export const Playground = () => {
},
});
const [isDeleting, setIsDeleting] = useState(false);
const [isCreating, setIsCreating] = useState(false);

const deleteEntity = _useDeleteEntityPublic(Event, {
space: '1c954768-7e14-4f0f-9396-0fe9dcd55fe8',
});

const createEntity = _useCreateEntityPublic(Event, {
space: '1c954768-7e14-4f0f-9396-0fe9dcd55fe8',
});

console.log({ isLoading, isError, data });

return (
<div>
{isLoading && <div>Loading...</div>}
{isError && <div>Error</div>}
<Button
disabled={isCreating}
onClick={async () => {
setIsCreating(true);
const walletClient = await getSmartAccountWalletClient();
if (!walletClient) {
alert('Wallet client not found');
setIsCreating(false);
return;
}
const { success, cid, txResult } = await createEntity(
{
name: 'Test Event 42 by Nik',
sponsors: ['347676a1-7cef-47dc-b6a7-c94fc6237dcd'],
},
// @ts-expect-error - TODO: fix the types error
Copy link

Copilot AI Jun 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider addressing the underlying type issues in the createEntity invocation so that the @ts-expect-error suppression can be removed. Improving type safety here will increase code robustness.

Copilot uses AI. Check for mistakes.

{ walletClient },
);
console.log('created', { success, cid, txResult });
setIsCreating(false);
}}
>
Create
</Button>
{data?.map((event) => (
<div key={event.id}>
<h2>{event.name}</h2>
Expand Down
1 change: 1 addition & 0 deletions packages/hypergraph-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export {
useUpdateEntity,
} from './HypergraphSpaceContext.js';
export { generateDeleteOps as _generateDeleteOps } from './internal/generate-delete-ops.js';
export { useCreateEntityPublic as _useCreateEntityPublic } from './internal/use-create-entity-public.js';
export { useDeleteEntityPublic as _useDeleteEntityPublic } from './internal/use-delete-entity-public.js';
export { useGenerateCreateOps as _useGenerateCreateOps } from './internal/use-generate-create-ops.js';
export { useQueryPublic as _useQueryPublic } from './internal/use-query-public.js';
Expand Down
100 changes: 100 additions & 0 deletions packages/hypergraph-react/src/internal/use-create-entity-public.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { type GeoSmartAccount, Graph, Id, type PropertiesParam, type RelationsParam } from '@graphprotocol/grc-20';
import type { Entity } from '@graphprotocol/hypergraph';
import { Type, store } from '@graphprotocol/hypergraph';
import { useQueryClient } from '@tanstack/react-query';
import { useSelector } from '@xstate/store/react';
import type * as Schema from 'effect/Schema';
import { publishOps } from '../publish-ops.js';

type CreateEntityPublicParams = {
space: string;
};

export function useCreateEntityPublic<const S extends Entity.AnyNoContext>(
type: S,
{ space }: CreateEntityPublicParams,
) {
const mapping = useSelector(store, (state) => state.context.mapping);
const queryClient = useQueryClient();

return async (
data: Readonly<Schema.Schema.Type<Entity.Insert<S>>>,
{ walletClient }: { walletClient: GeoSmartAccount },
// TODO: return the entity with this type: Promise<Entity.Entity<S>>
) => {
try {
// @ts-expect-error TODO should use the actual type instead of the name in the mapping
Copy link

Copilot AI Jun 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider refining the type definitions so that the actual type can be used instead of relying on @ts-expect-error. This will improve type safety and code clarity.

Suggested change
// @ts-expect-error TODO should use the actual type instead of the name in the mapping

Copilot uses AI. Check for mistakes.

const typeName = type.name;
const mappingEntry = mapping?.[typeName];
if (!mappingEntry) {
throw new Error(`Mapping entry for ${typeName} not found`);
}

const fields = type.fields;
const values: PropertiesParam = [];
for (const [key, value] of Object.entries(mappingEntry.properties || {})) {
let serializedValue: string = data[key];
if (fields[key] === Type.Checkbox) {
serializedValue = Graph.serializeCheckbox(data[key]);
} else if (fields[key] === Type.Date) {
serializedValue = Graph.serializeDate(data[key]);
} else if (fields[key] === Type.Point) {
serializedValue = Graph.serializePoint(data[key]);
} else if (fields[key] === Type.Number) {
serializedValue = Graph.serializeNumber(data[key]);
}

values.push({
property: Id.Id(value),
value: serializedValue,
});
}

const relations: RelationsParam = {};
for (const [key, relationId] of Object.entries(mappingEntry.relations || {})) {
const toIds: { toEntity: Id.Id }[] = [];

if (data[key]) {
// @ts-expect-error - TODO: fix the types error
for (const entity of data[key]) {
if (typeof entity === 'string') {
toIds.push({ toEntity: Id.Id(entity) });
} else {
toIds.push({ toEntity: Id.Id(entity.id) });
}
}
relations[Id.Id(relationId)] = toIds;
}
}

const { ops } = Graph.createEntity({
types: mappingEntry.typeIds,
id: data.id,
values,
relations,
});

const { cid, txResult } = await publishOps({
ops,
space,
name: `Create entity ${data.id}`,
walletClient,
network: 'TESTNET',
});
// TODO: temporary fix until we get the information from the API when a transaction is confirmed
await new Promise((resolve) => setTimeout(resolve, 2000));
queryClient.invalidateQueries({
queryKey: [
'hypergraph-public-entities',
// @ts-expect-error - TODO: find a better way to access the type.name
Copy link

Copilot AI Jun 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review the access to type.name and update the typing accordingly to avoid the need for an @ts-expect-error suppression. This change can enhance maintainability and type correctness.

Suggested change
// @ts-expect-error - TODO: find a better way to access the type.name

Copilot uses AI. Check for mistakes.

type.name,
space,
],
});
return { success: true, cid, txResult };
} catch (error) {
console.error(error);
return { success: false, error: 'Failed to create entity' };
}
};
}
Loading