Skip to content

feat: subscription clauses #235

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 16 commits into from
Jul 21, 2024
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ jobs:
run: git submodule update --init --recursive

- run: curl -L https://install.dojoengine.org | bash
- run: /home/runner/.config/.dojo/bin/dojoup -v v0.7.2
- run: /home/runner/.config/.dojo/bin/dojoup -v v1.0.0-alpha.2
- run: |
cd examples/dojo-starter
/home/runner/.config/.dojo/bin/sozo build
Expand Down
2 changes: 1 addition & 1 deletion examples/dojo-starter
Submodule dojo-starter updated 43 files
+1 −1 .github/workflows/test.yaml
+1 −1 README.md
+5 −5 Scarb.lock
+8 −4 Scarb.toml
+77 −4 manifests/dev/base/abis/contracts/dojo_starter-actions-7a1c7102.json
+98 −0 manifests/dev/base/abis/dojo-base.json
+207 −17 manifests/dev/base/abis/dojo-world.json
+47 −3 manifests/dev/base/abis/models/dojo_starter-DirectionsAvailable-77844f1f.json
+47 −3 manifests/dev/base/abis/models/dojo_starter-Moved-504403e5.json
+47 −3 manifests/dev/base/abis/models/dojo_starter-Moves-2a29373f.json
+47 −3 manifests/dev/base/abis/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
+6 −0 manifests/dev/base/dojo-base.toml
+6 −0 manifests/dev/base/dojo-world.toml
+0 −4 manifests/dev/base/dojo_base_base.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
+77 −4 manifests/dev/deployment/abis/contracts/dojo_starter-actions-7a1c7102.json
+98 −0 manifests/dev/deployment/abis/dojo-base.json
+207 −17 manifests/dev/deployment/abis/dojo-world.json
+47 −3 manifests/dev/deployment/abis/models/dojo_starter-DirectionsAvailable-77844f1f.json
+47 −3 manifests/dev/deployment/abis/models/dojo_starter-Moved-504403e5.json
+47 −3 manifests/dev/deployment/abis/models/dojo_starter-Moves-2a29373f.json
+47 −3 manifests/dev/deployment/abis/models/dojo_starter-Position-2ac8b4c1.json
+593 −148 manifests/dev/deployment/manifest.json
+122 −0 manifests/dev/deployment/manifest.toml
+0 −115 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
+6 −0 overlays/dev/actions.toml
+1 −3 src/systems/actions.cairo
+17 −19 src/tests/test_world.cairo
2 changes: 1 addition & 1 deletion examples/node/torii-bot/dojoConfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import manifest from "../../dojo-starter/manifests/dev/manifest.json" assert { type: "json" };
import manifest from "../../dojo-starter/manifests/dev/deployment/manifest.json" assert { type: "json" };

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

Expand Down
1 change: 0 additions & 1 deletion examples/node/torii-bot/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
"jsx": "preserve",
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"rootDir": "/Users/os/Documents/code/dojo.js/examples",
"allowJs": true,
"outDir": "dist",
"types": ["bun-types"]
Expand Down
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 ../../dojo-starter/manifests/dev/deployment/manifest.json src/dojo/generated/contractComponents.ts http://localhost:5050 0x3fc79ccfd72c1450d2ccb73c5c521a7ec68b6c6af0caf96a0f1c39ce58876c8"
},
"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
16 changes: 14 additions & 2 deletions examples/react/react-app/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useComponentValue } from "@dojoengine/react";
import "./App.css";
import { useComponentValue, useQuerySync } from "@dojoengine/react";
import { Entity } from "@dojoengine/recs";
import { useEffect, useState } from "react";
import "./App.css";
import { Direction } from "./utils";
import { getEntityIdFromKeys } from "@dojoengine/utils";
import { useDojo } from "./dojo/useDojo";
Expand All @@ -11,10 +11,22 @@ function App() {
setup: {
systemCalls: { spawn, move },
clientComponents: { Position, Moves, DirectionsAvailable },
toriiClient,
contractComponents,
},
account,
} = useDojo();

useQuerySync(toriiClient, contractComponents as any, [
{
Keys: {
keys: [BigInt(account?.account.address).toString()],
models: ["Position", "Moves", "DirectionsAvailable"],
pattern_matching: "FixedLen",
},
},
]);

const [clipboardStatus, setClipboardStatus] = useState({
message: "",
isError: false,
Expand Down
3 changes: 0 additions & 3 deletions examples/react/react-app/src/Loading.tsx

This file was deleted.

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
70 changes: 43 additions & 27 deletions examples/react/react-app/src/dojo/generated/generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,59 @@ import { Account, AccountInterface } from "starknet";
import { DojoProvider } from "@dojoengine/core";
import { Direction } from "../../utils";

export type IWorld = Awaited<ReturnType<typeof setupWorld>>;
const NAMESPACE = "dojo_starter";

export interface IWorld {
actions: {
spawn: (props: { account: AccountInterface }) => Promise<any>;
move: (props: MoveProps) => Promise<any>;
};
}

export interface MoveProps {
account: Account | AccountInterface;
direction: Direction;
}

export async function setupWorld(provider: DojoProvider) {
function actions() {
const spawn = async ({ account }: { account: AccountInterface }) => {
const handleError = (action: string, error: unknown) => {
console.error(`Error executing ${action}:`, error);
throw error;
};

export const setupWorld = async (provider: DojoProvider): Promise<IWorld> => {
const actions = () => ({
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;
handleError("spawn", error);
}
};
},

const move = async ({ account, direction }: MoveProps) => {
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;
handleError("move", error);
}
};
return { spawn, move };
}
return {
actions: actions(),
};
}
},
});

return { actions: actions() };
};
Loading
Loading