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: add ToriiQueryBuilder and ClauseBuilder #378

Merged
merged 2 commits into from
Jan 20, 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/witty-moons-care.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"@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": patch
"@dojoengine/utils-wasm": patch
---

Added experimental ToriiQueryBuilder and ClauseBuilder to be closer to how we should query ECS through torii
24 changes: 24 additions & 0 deletions examples/example-vite-experimental-sdk/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
7 changes: 7 additions & 0 deletions examples/example-vite-experimental-sdk/dojoConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { createDojoConfig } from "@dojoengine/core";

import manifest from "../../worlds/dojo-starter/manifest_dev.json";

export const dojoConfig = createDojoConfig({
manifest,
});
16 changes: 16 additions & 0 deletions examples/example-vite-experimental-sdk/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/atom-one-dark.min.css"
/>
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + TS</title>
</head>
<body>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
23 changes: 23 additions & 0 deletions examples/example-vite-experimental-sdk/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "example-vite-experimental-sdk",
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"@dojoengine/core": "workspace:*",
"@dojoengine/sdk": "workspace:*",
"highlight.js": "^11.11.1",
"starknet": "catalog:"
},
"devDependencies": {
"@types/highlight.js": "^10.1.0",
"typescript": "~5.6.3",
"vite": "^6.0.7",
"vite-plugin-top-level-await": "^1.4.4",
"vite-plugin-wasm": "^3.4.1"
}
}
1 change: 1 addition & 0 deletions examples/example-vite-experimental-sdk/public/vite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
63 changes: 63 additions & 0 deletions examples/example-vite-experimental-sdk/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import "./style.css";
import { init } from "@dojoengine/sdk/experimental";
import { ModelsMapping } from "./typescript/models.gen";
import { dojoConfig } from "../dojoConfig.ts";
import { ThemeManager } from "./theme-manager";
import { UpdateManager } from "./update-manager";
import { ClauseBuilder, ToriiQueryBuilder } from "@dojoengine/sdk";

async function main() {
const um = new UpdateManager();
new ThemeManager();

const sdk = await init({
client: {
rpcUrl: dojoConfig.rpcUrl,
toriiUrl: dojoConfig.toriiUrl,
relayUrl: dojoConfig.relayUrl,
worldAddress: dojoConfig.manifest.world.address,
},
domain: {
name: "WORLD_NAME",
version: "1.0",
chainId: "KATANA",
revision: "1",
},
});
const entities = await sdk.getEntities(
new ToriiQueryBuilder()
.withClause(new ClauseBuilder().keys([], [undefined]).build())
.addOrderBy(ModelsMapping.Moves, "remaining", "Asc")
.build()
);
console.log("entities", entities);

const events = await sdk.getEvents(
new ToriiQueryBuilder()
.withClause(new ClauseBuilder().keys([], [undefined]).build())
.build(),
true
);
console.log("events", events);

const [initialEntities, freeSubscription] = await sdk.subscribeEntities(
new ToriiQueryBuilder()
.withClause(new ClauseBuilder().keys([], [undefined]).build())
.addOrderBy(ModelsMapping.Moves, "remaining", "Asc")
.includeHashedKeys()
.build(),
({ data, error }: { data: any; error: Error }) => {
if (data) {
console.log(data);
}
if (error) {
console.log(error);
}
}
);
Comment on lines +49 to +57
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance subscription error handling.

The error callback only logs the error. Consider implementing proper error recovery or retry logic for subscription failures.

 ({ data, error }: { data: any; error: Error }) => {
     if (data) {
         console.log(data);
     }
     if (error) {
-        console.log(error);
+        console.error('Subscription error:', error);
+        // Implement retry logic or error recovery
+        setTimeout(() => {
+            console.log('Attempting to reconnect...');
+            // Implement reconnection logic
+        }, 5000);
     }
 }

Committable suggestion skipped: line range outside the PR's diff.

console.log(initialEntities, freeSubscription);

um.displayUpdate("fetch", initialEntities);
}

main().catch(console.error);
87 changes: 87 additions & 0 deletions examples/example-vite-experimental-sdk/src/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;

color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;

font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}

h1 {
font-size: 3.2em;
line-height: 1.1;
}

#updates {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
}

.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vanilla:hover {
filter: drop-shadow(0 0 2em #3178c6aa);
}

.card {
padding: 2em;
}

.read-the-docs {
color: #888;
}

button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}

@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
40 changes: 40 additions & 0 deletions examples/example-vite-experimental-sdk/src/theme-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* A simple theme manager for the playground,
* using highlight.js.
*/
export class ThemeManager {
currentTheme: number;
themes: string[];
constructor() {
this.themes = [
"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/atom-one-dark.min.css",
"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/atom-one-light.min.css",
];
this.currentTheme = 0;
this.setupToggleButton();
}

/**
* Setups a button to toggle the theme.
* The button is positioned at the top right of the screen.
*/
setupToggleButton() {
const button = document.createElement("button");
button.id = "themeToggle";
button.textContent = "Toggle Theme";
button.style.position = "fixed";
button.style.top = "10px";
button.style.right = "10px";
button.style.padding = "5px";

button.onclick = () => this.toggleTheme();
document.body.appendChild(button);
}
Comment on lines +21 to +32
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance button accessibility and implement cleanup.

The theme toggle button lacks accessibility features and proper cleanup.

 setupToggleButton() {
     const button = document.createElement("button");
     button.id = "themeToggle";
     button.textContent = "Toggle Theme";
+    button.setAttribute("aria-label", "Toggle color theme");
+    button.setAttribute("role", "switch");
+    button.setAttribute("aria-checked", "false");
     button.style.position = "fixed";
     button.style.top = "10px";
     button.style.right = "10px";
     button.style.padding = "5px";

-    button.onclick = () => this.toggleTheme();
+    const handleClick = () => {
+        this.toggleTheme();
+        button.setAttribute("aria-checked", String(this.currentTheme === 1));
+    };
+    button.addEventListener("click", handleClick);
     document.body.appendChild(button);
+
+    // Return cleanup function
+    return () => {
+        button.removeEventListener("click", handleClick);
+        button.remove();
+    };
 }
📝 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
setupToggleButton() {
const button = document.createElement("button");
button.id = "themeToggle";
button.textContent = "Toggle Theme";
button.style.position = "fixed";
button.style.top = "10px";
button.style.right = "10px";
button.style.padding = "5px";
button.onclick = () => this.toggleTheme();
document.body.appendChild(button);
}
setupToggleButton() {
const button = document.createElement("button");
button.id = "themeToggle";
button.textContent = "Toggle Theme";
button.setAttribute("aria-label", "Toggle color theme");
button.setAttribute("role", "switch");
button.setAttribute("aria-checked", "false");
button.style.position = "fixed";
button.style.top = "10px";
button.style.right = "10px";
button.style.padding = "5px";
const handleClick = () => {
this.toggleTheme();
button.setAttribute("aria-checked", String(this.currentTheme === 1));
};
button.addEventListener("click", handleClick);
document.body.appendChild(button);
// Return cleanup function
return () => {
button.removeEventListener("click", handleClick);
button.remove();
};
}


toggleTheme() {
this.currentTheme = (this.currentTheme + 1) % this.themes.length;
(
document.querySelector('link[rel="stylesheet"]')! as HTMLLinkElement
).href = this.themes[this.currentTheme];
}
Comment on lines +34 to +39
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for theme switching.

The theme toggle function uses non-null assertion and lacks error handling.

 toggleTheme() {
     this.currentTheme = (this.currentTheme + 1) % this.themes.length;
-    (
-        document.querySelector('link[rel="stylesheet"]')! as HTMLLinkElement
-    ).href = this.themes[this.currentTheme];
+    const stylesheet = document.querySelector('link[rel="stylesheet"]');
+    if (!stylesheet) {
+        console.error("Theme stylesheet not found");
+        return;
+    }
+    (stylesheet as HTMLLinkElement).href = this.themes[this.currentTheme];
 }
📝 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
toggleTheme() {
this.currentTheme = (this.currentTheme + 1) % this.themes.length;
(
document.querySelector('link[rel="stylesheet"]')! as HTMLLinkElement
).href = this.themes[this.currentTheme];
}
toggleTheme() {
this.currentTheme = (this.currentTheme + 1) % this.themes.length;
const stylesheet = document.querySelector('link[rel="stylesheet"]');
if (!stylesheet) {
console.error("Theme stylesheet not found");
return;
}
(stylesheet as HTMLLinkElement).href = this.themes[this.currentTheme];
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { DojoProvider, DojoCall } from "@dojoengine/core";
import { Account, AccountInterface, CairoCustomEnum } from "starknet";

export function setupWorld(provider: DojoProvider) {
const build_actions_move_calldata = (
direction: CairoCustomEnum
): DojoCall => {
return {
contractName: "actions",
entrypoint: "move",
calldata: [direction],
};
};

const actions_move = async (
snAccount: Account | AccountInterface,
direction: CairoCustomEnum
) => {
try {
return await provider.execute(
snAccount,
build_actions_move_calldata(direction),
"dojo_starter"
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract hardcoded contract name to a configuration parameter.

The contract name "dojo_starter" is hardcoded, which reduces reusability and makes the code less maintainable.

-export function setupWorld(provider: DojoProvider) {
+export function setupWorld(provider: DojoProvider, contractName: string = "dojo_starter") {
     // ... other code ...
-                "dojo_starter"
+                contractName
     // ... other code ...
-                "dojo_starter"
+                contractName

Also applies to: 44-44

);
} catch (error) {
console.error(error);
throw error;
}
};

const build_actions_spawn_calldata = (): DojoCall => {
return {
contractName: "actions",
entrypoint: "spawn",
calldata: [],
};
};

const actions_spawn = async (snAccount: Account | AccountInterface) => {
try {
return await provider.execute(
snAccount,
build_actions_spawn_calldata(),
"dojo_starter"
);
} catch (error) {
console.error(error);
throw error;
}
};

return {
actions: {
move: actions_move,
buildMoveCalldata: build_actions_move_calldata,
spawn: actions_spawn,
buildSpawnCalldata: build_actions_spawn_calldata,
},
};
}
Loading
Loading