Skip to content
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

feat: subscription clauses #235

Merged
merged 16 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
2 changes: 1 addition & 1 deletion examples/dojo-starter
Submodule dojo-starter updated 39 files
+1 −1 .github/workflows/test.yaml
+1 −1 README.md
+5 −5 Scarb.lock
+4 −2 Scarb.toml
+66 −4 manifests/dev/abis/base/contracts/dojo_starter-actions-7a1c7102.json
+98 −0 manifests/dev/abis/base/dojo-base.json
+113 −4 manifests/dev/abis/base/dojo-world.json
+33 −0 manifests/dev/abis/base/models/dojo_starter-DirectionsAvailable-77844f1f.json
+33 −0 manifests/dev/abis/base/models/dojo_starter-Moved-504403e5.json
+33 −0 manifests/dev/abis/base/models/dojo_starter-Moves-2a29373f.json
+33 −0 manifests/dev/abis/base/models/dojo_starter-Position-2ac8b4c1.json
+66 −4 manifests/dev/abis/deployments/contracts/dojo_starter-actions-7a1c7102.json
+113 −4 manifests/dev/abis/deployments/dojo-world.json
+33 −0 manifests/dev/abis/deployments/models/dojo_starter-DirectionsAvailable-77844f1f.json
+33 −0 manifests/dev/abis/deployments/models/dojo_starter-Moved-504403e5.json
+33 −0 manifests/dev/abis/deployments/models/dojo_starter-Moves-2a29373f.json
+33 −0 manifests/dev/abis/deployments/models/dojo_starter-Position-2ac8b4c1.json
+11 −0 manifests/dev/base/contracts/dojo_starter-actions-7a1c7102.toml
+0 −10 manifests/dev/base/contracts/dojo_starter_systems_actions_actions.toml
+3 −1 manifests/dev/base/dojo-base.toml
+6 −0 manifests/dev/base/dojo-world.toml
+0 −5 manifests/dev/base/dojo_world_world.toml
+16 −0 manifests/dev/base/models/dojo_starter-DirectionsAvailable-77844f1f.toml
+16 −0 manifests/dev/base/models/dojo_starter-Moved-504403e5.toml
+26 −0 manifests/dev/base/models/dojo_starter-Moves-2a29373f.toml
+16 −0 manifests/dev/base/models/dojo_starter-Position-2ac8b4c1.toml
+0 −15 manifests/dev/base/models/dojo_starter_models_moves_directions_available.toml
+0 −25 manifests/dev/base/models/dojo_starter_models_moves_moves.toml
+0 −15 manifests/dev/base/models/dojo_starter_models_position_position.toml
+0 −15 manifests/dev/base/models/dojo_starter_systems_actions_actions_moved.toml
+427 −122 manifests/dev/manifest.json
+49 −46 manifests/dev/manifest.toml
+0 −4 manifests/dev/overlays/contracts/dojo_starter_systems_actions_actions.toml
+0 −1 manifests/dev/overlays/dojo_base_base.toml
+0 −1 manifests/dev/overlays/dojo_world_world.toml
+0 −1 manifests/dev/overlays/models/dojo_starter_models_moves_moves.toml
+0 −1 manifests/dev/overlays/models/dojo_starter_models_position_position.toml
+1 −3 src/systems/actions.cairo
+17 −19 src/tests/test_world.cairo
3 changes: 2 additions & 1 deletion examples/react/react-app/dojoConfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import manifest from "../../dojo-starter/manifests/dev/manifest.json";
import manifest from "../../dojo-starter/manifests/dev/deployment/manifest.json";

import { createDojoConfig } from "@dojoengine/core";

export const dojoConfig = createDojoConfig({
Expand Down
4 changes: 2 additions & 2 deletions examples/react/react-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"build": "tsc && vite build",
"lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
"create-components": "npx @dojoengine/core ../../dojo-starter/manifests/dev/manifest.json src/dojo/generated/contractComponents.ts http://localhost:5050 0xb4079627ebab1cd3cf9fd075dda1ad2454a7a448bf659591f259efa2519b18"
"create-components": "npx /Users/os/Documents/code/dojo/dojo.js/packages/core/bin/generateComponents.cjs /Users/os/Documents/code/dojo/dojo.js/examples/dojo-starter/manifests/dev/deployment/manifest.json src/dojo/generated/contractComponents.ts http://0.0.0.0:5050 0x16a15cc2a571bf95eef741c701a5657e4dbf1a5b9ce3785b4060b60f58913f4"
},
"dependencies": {
"@dojoengine/core": "workspace:*",
Expand All @@ -26,7 +26,7 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rxjs": "^7.8.1",
"starknet": "6.1.5",
"starknet": "6.11.0",
"vite-plugin-top-level-await": "^1.3.1",
"vite-plugin-wasm": "^3.2.2"
},
Expand Down
19 changes: 17 additions & 2 deletions examples/react/react-app/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { useComponentValue } from "@dojoengine/react";
import { Entity } from "@dojoengine/recs";
import {
useComponentValue,
useEntityQuery,
useQuerySync,
} from "@dojoengine/react";
import { Entity, HasValue } from "@dojoengine/recs";
import { useEffect, useState } from "react";
import "./App.css";
import { Direction } from "./utils";
Expand All @@ -11,10 +15,21 @@ function App() {
setup: {
systemCalls: { spawn, move },
clientComponents: { Position, Moves, DirectionsAvailable },
toriiClient,
contractComponents,
},
account,
} = useDojo();

useQuerySync(
toriiClient,
contractComponents as any,
["Moves", "Position", "DirectionsAvailable"],
[account?.account.address.toString()]
);

// get entites = filter by

const [clipboardStatus, setClipboardStatus] = useState({
message: "",
isError: false,
Expand Down
143 changes: 96 additions & 47 deletions examples/react/react-app/src/dojo/createSystemCalls.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,78 @@
import { AccountInterface } from "starknet";
import { Entity, getComponentValue } from "@dojoengine/recs";
import {
Entity,
Has,
HasValue,
World,
defineSystem,
getComponentValue,
} from "@dojoengine/recs";
import { uuid } from "@latticexyz/utils";
import { ClientComponents } from "./createClientComponents";
import { Direction, updatePositionWithDirection } from "../utils";
import { getEntityIdFromKeys } from "@dojoengine/utils";
import { ContractComponents } from "./generated/contractComponents";
import type { IWorld } from "./generated/generated";

export type SystemCalls = ReturnType<typeof createSystemCalls>;

export function createSystemCalls(
{ client }: { client: IWorld },
_contractComponents: ContractComponents,
{ Position, Moves }: ClientComponents
{ Position, Moves }: ClientComponents,
world: World
) {
const spawn = async (account: AccountInterface) => {
const entityId = getEntityIdFromKeys([
BigInt(account.address),
]) as Entity;

const movesId = uuid();
Moves.addOverride(movesId, {
entity: entityId,
value: {
player: BigInt(entityId),
remaining:
(getComponentValue(Moves, entityId)?.remaining || 0) + 100,
},
});

const positionId = uuid();
Position.addOverride(positionId, {
entity: entityId,
value: {
player: BigInt(entityId),
vec: {
x: 10 + (getComponentValue(Position, entityId)?.vec.x || 0),
y: 10 + (getComponentValue(Position, entityId)?.vec.y || 0),
},
},
});

try {
const { transaction_hash } = await client.actions.spawn({
await client.actions.spawn({
account,
});

console.log(
await account.waitForTransaction(transaction_hash, {
retryInterval: 100,
})
);

await new Promise((resolve) => setTimeout(resolve, 1000));
// Wait for the indexer to update the entity
// By doing this we keep the optimistic UI in sync with the actual state
await new Promise<void>((resolve) => {
defineSystem(
world,
[
Has(Moves),
HasValue(Moves, { player: BigInt(account.address) }),
],
() => {
resolve();
}
);
});
} catch (e) {
console.log(e);
Position.removeOverride(positionId);
Moves.removeOverride(movesId);
} finally {
Comment on lines 70 to +73
Copy link

Choose a reason for hiding this comment

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

Remove redundant catch clause.

The catch clause that only logs the error and then removes the overrides is redundant and should be simplified.

-        } catch (e) {
-            console.log(e);
-            Position.removeOverride(positionId);
-            Moves.removeOverride(movesId);
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
console.log(e);
Position.removeOverride(positionId);
Moves.removeOverride(movesId);
} finally {
} finally {

Position.removeOverride(positionId);
Moves.removeOverride(movesId);
Comment on lines +74 to +75
Copy link

Choose a reason for hiding this comment

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

Remove redundant finally clause.

The finally clause that removes overrides is redundant if the catch clause already handles the removal.

-        } finally {
-            Position.removeOverride(positionId);
-            Moves.removeOverride(movesId);

Committable suggestion was skipped due to low confidence.

}
};

Expand All @@ -37,52 +81,57 @@ export function createSystemCalls(
BigInt(account.address),
]) as Entity;

// const positionId = uuid();
// Position.addOverride(positionId, {
// entity: entityId,
// value: {
// player: BigInt(entityId),
// vec: updatePositionWithDirection(
// direction,
// getComponentValue(Position, entityId) as any
// ).vec,
// },
// });
// Update the state before the transaction
const positionId = uuid();
Position.addOverride(positionId, {
entity: entityId,
value: {
player: BigInt(entityId),
vec: updatePositionWithDirection(
direction,
getComponentValue(Position, entityId) as any
).vec,
},
});

// const movesId = uuid();
// Moves.addOverride(movesId, {
// entity: entityId,
// value: {
// player: BigInt(entityId),
// remaining:
// (getComponentValue(Moves, entityId)?.remaining || 0) - 1,
// },
// });
// Update the state before the transaction
const movesId = uuid();
Moves.addOverride(movesId, {
entity: entityId,
value: {
player: BigInt(entityId),
remaining:
(getComponentValue(Moves, entityId)?.remaining || 0) - 1,
},
});

try {
const { transaction_hash } = await client.actions.move({
await client.actions.move({
account,
direction,
});

await account.waitForTransaction(transaction_hash, {
retryInterval: 100,
// Wait for the indexer to update the entity
// By doing this we keep the optimistic UI in sync with the actual state
await new Promise<void>((resolve) => {
defineSystem(
world,
[
Has(Moves),
HasValue(Moves, { player: BigInt(account.address) }),
],
() => {
resolve();
}
);
});

// console.log(
// await account.waitForTransaction(transaction_hash, {
// retryInterval: 100,
// })
// );

await new Promise((resolve) => setTimeout(resolve, 1000));
} catch (e) {
console.log(e);
// Position.removeOverride(positionId);
// Moves.removeOverride(movesId);
Position.removeOverride(positionId);
Moves.removeOverride(movesId);
Comment on lines 129 to +131
Copy link

Choose a reason for hiding this comment

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

Remove redundant catch clause.

The catch clause that only logs the error and then removes the overrides is redundant and should be simplified.

-        } catch (e) {
-            console.log(e);
-            Position.removeOverride(positionId);
-            Moves.removeOverride(movesId);
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
console.log(e);
// Position.removeOverride(positionId);
// Moves.removeOverride(movesId);
Position.removeOverride(positionId);
Moves.removeOverride(movesId);

} finally {
// Position.removeOverride(positionId);
// Moves.removeOverride(movesId);
Position.removeOverride(positionId);
Moves.removeOverride(movesId);
Comment on lines +133 to +134
Copy link

Choose a reason for hiding this comment

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

Remove redundant finally clause.

The finally clause that removes overrides is redundant if the catch clause already handles the removal.

-        } finally {
-            Position.removeOverride(positionId);
-            Moves.removeOverride(movesId);

Committable suggestion was skipped due to low confidence.

}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function defineContractComponents(world: World) {
{ player: RecsType.BigInt, directions: RecsType.StringArray },
{
metadata: {
name: "DirectionsAvailable",
name: "dojo_starter-DirectionsAvailable",
types: ["contractaddress"],
customTypes: ["Direction"],
},
Expand All @@ -36,7 +36,7 @@ export function defineContractComponents(world: World) {
},
{
metadata: {
name: "Moves",
name: "dojo_starter-Moves",
types: ["contractaddress", "u8", "enum", "bool"],
customTypes: ["Direction"],
},
Expand All @@ -52,7 +52,7 @@ export function defineContractComponents(world: World) {
},
{
metadata: {
name: "Position",
name: "dojo_starter-Position",
types: ["contractaddress", "u32", "u32"],
customTypes: ["Vec2"],
},
Expand Down
29 changes: 19 additions & 10 deletions examples/react/react-app/src/dojo/generated/generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,19 @@ export interface MoveProps {
}

export async function setupWorld(provider: DojoProvider) {
const nameSpace = "dojo_starter";
function actions() {
const spawn = async ({ account }: { account: AccountInterface }) => {
try {
return await provider.execute(account, {
contractName: "actions",
entrypoint: "spawn",
calldata: [],
});
return await provider.execute(
account,
{
contractName: "actions",
entrypoint: "spawn",
calldata: [],
},
nameSpace
);
} catch (error) {
console.error("Error executing spawn:", error);
throw error;
Expand All @@ -26,11 +31,15 @@ export async function setupWorld(provider: DojoProvider) {

const move = async ({ account, direction }: MoveProps) => {
try {
return await provider.execute(account, {
contractName: "actions",
entrypoint: "move",
calldata: [direction],
});
return await provider.execute(
account,
{
contractName: "actions",
entrypoint: "move",
calldata: [direction],
},
nameSpace
);
} catch (error) {
console.error("Error executing move:", error);
throw error;
Expand Down
15 changes: 3 additions & 12 deletions examples/react/react-app/src/dojo/generated/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export type SetupResult = Awaited<ReturnType<typeof setup>>;

export async function setup({ ...config }: DojoConfig) {
// torii client
const toriiClient = await torii.createClient([], {
const toriiClient = await torii.createClient({
rpcUrl: config.rpcUrl,
toriiUrl: config.toriiUrl,
relayUrl: "",
Expand All @@ -27,11 +27,6 @@ export async function setup({ ...config }: DojoConfig) {
const clientComponents = createClientComponents({ contractComponents });

// fetch all existing entities from torii
const sync = await getSyncEntities(
toriiClient,
contractComponents as any,
[]
);

// create dojo provider
const dojoProvider = new DojoProvider(config.manifest, config.rpcUrl);
Expand Down Expand Up @@ -66,11 +61,7 @@ export async function setup({ ...config }: DojoConfig) {
client,
clientComponents,
contractComponents,
systemCalls: createSystemCalls(
{ client },
contractComponents,
clientComponents
),
systemCalls: createSystemCalls({ client }, clientComponents, world),
publish: (typedData: string, signature: WeierstrassSignatureType) => {
toriiClient.publishMessage(typedData, {
r: signature.r.toString(),
Expand All @@ -81,6 +72,6 @@ export async function setup({ ...config }: DojoConfig) {
dojoProvider,
burnerManager,
toriiClient,
sync,
// sync,
};
}
2 changes: 1 addition & 1 deletion examples/react/react-phaser-example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"react-dom": "^18.2.0",
"rxjs": "^7.8.1",
"simplex-noise": "^4.0.1",
"starknet": "6.1.5",
"starknet": "6.11.0",
"styled-components": "^6.0.7",
"tailwind-merge": "^2.0.0",
"tailwindcss-animate": "^1.0.7",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export type SetupResult = Awaited<ReturnType<typeof setup>>;

export async function setup({ ...config }: DojoConfig) {
// torii client
const toriiClient = await torii.createClient([], {
const toriiClient = await torii.createClient({
rpcUrl: config.rpcUrl,
toriiUrl: config.toriiUrl,
relayUrl: config.relayUrl,
Expand All @@ -33,7 +33,7 @@ export async function setup({ ...config }: DojoConfig) {
const sync = await getSyncEntities(
toriiClient,
contractComponents as any,
[]
undefined // syncs all entities
);

const client = await setupWorld(
Expand Down
2 changes: 1 addition & 1 deletion examples/react/react-pwa-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rxjs": "^7.8.1",
"starknet": "6.1.5",
"starknet": "6.11.0",
"vite-plugin-top-level-await": "^1.3.1",
"vite-plugin-wasm": "^3.2.2"
},
Expand Down
Loading
Loading