Skip to content

feat: add useModels hook #420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 14, 2025
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
15 changes: 15 additions & 0 deletions .changeset/brave-kiwis-explode.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"@dojoengine/utils": patch
"@dojoengine/sdk": patch
"@dojoengine/core": patch
"@dojoengine/create-burner": patch
"@dojoengine/create-dojo": patch
"@dojoengine/predeployed-connector": patch
"@dojoengine/react": patch
"@dojoengine/state": patch
"@dojoengine/torii-client": patch
"@dojoengine/torii-wasm": patch
"@dojoengine/utils-wasm": patch
---

fix: cairo option and enum ignore in zustand merge
6 changes: 5 additions & 1 deletion examples/example-vite-react-sdk/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ function App() {
// Querying Moves and Position models that has at least [account.address] as key
KeysClause(
[ModelsMapping.Moves, ModelsMapping.Position],
[addAddressPadding(account?.address ?? "0")],
[
account?.address
? addAddressPadding(account.address)
: undefined,
],
"FixedLen"
).build()
)
Expand Down
2 changes: 0 additions & 2 deletions examples/example-vite-react-sdk/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ import StarknetProvider from "./starknet-provider.tsx";
async function main() {
const sdk = await init<SchemaType>({
client: {
toriiUrl: dojoConfig.toriiUrl,
relayUrl: dojoConfig.relayUrl,
worldAddress: dojoConfig.manifest.world.address,
},
domain: {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"format:check": "turbo format:check",
"release": "pnpm build && pnpm -F './packages/**' publish -r --force --no-git-checks",
"release:dry-run": "pnpm -F './packages/**' publish -r --force --dry-run",
"dev": "turbo dev --concurrency 15"
"dev": "turbo watch dev --concurrency 15",
"docs": "turbo run docs --ui stream"
},
"devDependencies": {
"@commitlint/cli": "^18.6.1",
Expand Down
8 changes: 7 additions & 1 deletion packages/sdk/src/experimental/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,20 @@ import { SchemaType, SDKConfig, StandardizedQueryResult } from "../types";
import { parseEntities } from "../parseEntities";
import { parseHistoricalEvents } from "../parseHistoricalEvents";
import { intoEntityKeysClause } from "../convertClauseToEntityKeysClause";
import { defaultClientConfig } from "..";

export type ToriiSubscriptionCallback<T extends SchemaType> = (response: {
data?: StandardizedQueryResult<T> | StandardizedQueryResult<T>[];
error?: Error;
}) => void;

export async function init<T extends SchemaType>(options: SDKConfig) {
const client = await torii.createClient(options.client);
const clientConfig = {
...defaultClientConfig,
...options.client,
} as torii.ClientConfig;

const client = await torii.createClient(clientConfig);

return {
getEntities: async (query: torii.Query) => {
Expand Down
18 changes: 14 additions & 4 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as torii from "@dojoengine/torii-client";
import { Account, Signature, StarknetDomain, TypedData } from "starknet";
import type { Account, Signature, StarknetDomain, TypedData } from "starknet";

import {
import type {
GetParams,
SchemaType,
SDK,
Expand All @@ -14,7 +14,7 @@ import {
import { intoEntityKeysClause } from "./convertClauseToEntityKeysClause";
import { parseEntities } from "./parseEntities";
import { parseHistoricalEvents } from "./parseHistoricalEvents";
import { ToriiQueryBuilder } from "./toriiQueryBuilder";
import type { ToriiQueryBuilder } from "./toriiQueryBuilder";
import { generateTypedData } from "./generateTypedData";

export * from "./types";
Expand All @@ -34,6 +34,11 @@ export async function createClient(
return await torii.createClient(config);
}

export const defaultClientConfig: Partial<torii.ClientConfig> = {
toriiUrl: "http://localhost:8080",
relayUrl: "/ip4/127.0.0.1/tcp/9090",
};

/**
* Initializes the SDK with the provided configuration and schema.
*
Expand All @@ -43,7 +48,11 @@ export async function createClient(
export async function init<T extends SchemaType>(
options: SDKConfig
): Promise<SDK<T>> {
const client = await createClient(options.client);
const clientConfig = {
...defaultClientConfig,
...options.client,
} as torii.ClientConfig;
const client = await createClient(clientConfig);

return {
client,
Expand Down Expand Up @@ -137,6 +146,7 @@ export async function init<T extends SchemaType>(
const parsedData = historical
? parseHistoricalEvents<T>(data)
: parseEntities<T>(data);

callback({
data: parsedData as ToriiResponse<
T,
Expand Down
3 changes: 2 additions & 1 deletion packages/sdk/src/parseEntities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ function parseValue(value: torii.Ty): any {
CairoOptionVariant.Some,
parseValue((value.value as torii.EnumValue).value)
);
} else if ("None" === (value.value as torii.EnumValue).option) {
}
if ("None" === (value.value as torii.EnumValue).option) {
return new CairoOption(CairoOptionVariant.None);
}

Expand Down
26 changes: 26 additions & 0 deletions packages/sdk/src/react/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,31 @@ export function useModel<
return modelData;
}

/**
* Custom hook to retrieve all entities that have a specific model.
*
* @param model - The model to retrieve, specified as a string in the format "namespace-modelName".
* @returns The model structure if found, otherwise undefined.
*/
export function useModels<
N extends keyof SchemaType,
M extends keyof SchemaType[N] & string,
Client extends (...args: any) => any,
Schema extends SchemaType
>(model: `${N}-${M}`): { [entityId: string]: SchemaType[N][M] | undefined } {
const [namespace, modelName] = model.split("-") as [N, M];
const { useDojoStore } =
useContext<DojoContextType<Client, Schema>>(DojoContext);

const modelData = useDojoStore((state) =>
state.getEntitiesByModel(namespace, modelName).map((entity) => ({
[entity.entityId]: entity.models?.[namespace]?.[modelName],
}))
) as unknown as { [entityId: string]: SchemaType[N][M] | undefined };
Comment on lines +82 to +86
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential issue with return value mapping

The current implementation is mapping entities to an array of objects (each with a single key-value pair) but then casting it to a single object. This might not work as intended.

-    const modelData = useDojoStore((state) =>
-        state.getEntitiesByModel(namespace, modelName).map((entity) => ({
-            [entity.entityId]: entity.models?.[namespace]?.[modelName],
-        }))
-    ) as unknown as { [entityId: string]: SchemaType[N][M] | undefined };
+    const modelData = useDojoStore((state) =>
+        state.getEntitiesByModel(namespace, modelName).reduce((acc, entity) => ({
+            ...acc,
+            [entity.entityId]: entity.models?.[namespace]?.[modelName],
+        }), {})
+    ) as { [entityId: string]: SchemaType[N][M] | undefined };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const modelData = useDojoStore((state) =>
state.getEntitiesByModel(namespace, modelName).map((entity) => ({
[entity.entityId]: entity.models?.[namespace]?.[modelName],
}))
) as unknown as { [entityId: string]: SchemaType[N][M] | undefined };
const modelData = useDojoStore((state) =>
state.getEntitiesByModel(namespace, modelName).reduce((acc, entity) => ({
...acc,
[entity.entityId]: entity.models?.[namespace]?.[modelName],
}), {})
) as { [entityId: string]: SchemaType[N][M] | undefined };


return modelData;
}

/**
* Hook that exposes sdk features.
*
Expand Down Expand Up @@ -223,6 +248,7 @@ export function useEntityQuery<Schema extends SchemaType>(
processInitialData: (data) => state.mergeEntities(data),
processUpdateData: (data) => {
const entity = data.pop();

if (entity && entity.entityId !== "0x0") {
state.updateEntity(entity);
}
Expand Down
Loading
Loading