Skip to content

Commit

Permalink
add the dojo react starter
Browse files Browse the repository at this point in the history
  • Loading branch information
willemolding committed Sep 17, 2023
1 parent 4738f0d commit 7c485a2
Show file tree
Hide file tree
Showing 27 changed files with 1,053 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 ArcaneAssemblers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
7 changes: 7 additions & 0 deletions client/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
VITE_PUBLIC_ETH_CONTRACT_ADDRESS=0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7
VITE_PUBLIC_ACCOUNT_CLASS_HASH=0x04d07e40e93398ed3c76981e72dd1fd22557a78ce36c0515f679e27f0bb5bc5f
VITE_PUBLIC_MASTER_ADDRESS=0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973
VITE_PUBLIC_MASTER_PRIVATE_KEY=0x1800000000300000180000000000030000000000003006001800006600
VITE_PUBLIC_WORLD_ADDRESS=0x223b959926c92e10a5de78a76871fa40cefafbdce789137843df7c7b30e3e0
VITE_PUBLIC_NODE_URL=http://localhost:5050
VITE_PUBLIC_TORII=http://localhost:8080
14 changes: 14 additions & 0 deletions client/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = {
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': 'warn',
},
}
24 changes: 24 additions & 0 deletions client/.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?
Binary file added client/bun.lockb
Binary file not shown.
15 changes: 15 additions & 0 deletions client/codegen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
schema: 'http://localhost:8080',
documents: 'src/**/*.graphql',
generates: {
'src/generated/graphql.ts': {
plugins: ['typescript', 'typescript-operations', 'typescript-graphql-request'],
config: {
rawRequest: true
},
},
},
};
export default config;
13 changes: 13 additions & 0 deletions client/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
47 changes: 47 additions & 0 deletions client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"name": "react-example",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
"codegen": "graphql-codegen"
},
"dependencies": {
"@dojoengine/core": "^0.0.17",
"@dojoengine/create-burner": "^0.0.18",
"@dojoengine/react": "^0.0.3",
"@dojoengine/utils": "^0.0.2",
"@latticexyz/recs": "^1.43.0",
"@latticexyz/utils": "^1.43.0",
"ethers": "^5.7.2",
"graphql": "^16.7.1",
"graphql-request": "^6.1.0",
"mobx": "^6.9.0",
"proxy-deep": "^3.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rxjs": "^7.8.1",
"starknet": "^5.14.1"
},
"devDependencies": {
"@graphql-codegen/cli": "^5.0.0",
"@graphql-codegen/typescript": "^4.0.1",
"@graphql-codegen/typescript-graphql-request": "^5.0.0",
"@graphql-codegen/typescript-operations": "^4.0.1",
"@types/node": "^20.4.8",
"@types/react": "^18.0.37",
"@types/react-dom": "^18.0.11",
"@typescript-eslint/eslint-plugin": "^5.59.0",
"@typescript-eslint/parser": "^5.59.0",
"@vitejs/plugin-react": "^4.0.0",
"eslint": "^8.38.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.3.4",
"typescript": "^5.0.2",
"vite": "^4.3.9"
}
}
1 change: 1 addition & 0 deletions client/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.
71 changes: 71 additions & 0 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { useDojo } from './DojoContext';
import { useComponentValue } from "@dojoengine/react";
import { Direction, } from './dojo/createSystemCalls'
import { EntityIndex, setComponent } from '@latticexyz/recs';
import { useEffect } from 'react';
import { getFirstComponentByType } from './utils';
import { Moves, Position } from './generated/graphql';

function App() {
const {
setup: {
systemCalls: { spawn, move },
components: { Moves, Position },
network: { graphSdk, call }
},
account: { create, list, select, account, isDeploying }
} = useDojo();

// entity id - this example uses the account address as the entity id
const entityId = account.address;

// get current component values
const position = useComponentValue(Position, parseInt(entityId.toString()) as EntityIndex);
const moves = useComponentValue(Moves, parseInt(entityId.toString()) as EntityIndex);

useEffect(() => {

if (!entityId) return;

const fetchData = async () => {
const { data } = await graphSdk.getEntities();

if (data) {
const remaining = getFirstComponentByType(data.entities?.edges, 'Moves') as Moves;
const position = getFirstComponentByType(data.entities?.edges, 'Position') as Position;

setComponent(Moves, parseInt(entityId.toString()) as EntityIndex, { remaining: remaining.remaining })
setComponent(Position, parseInt(entityId.toString()) as EntityIndex, { x: position.x, y: position.y })
}
}
fetchData();
}, [account.address]);


return (
<>
<button onClick={create}>{isDeploying ? "deploying burner" : "create burner"}</button>
<div className="card">
select signer:{" "}
<select onChange={e => select(e.target.value)}>
{list().map((account, index) => {
return <option value={account.address} key={index}>{account.address}</option>
})}
</select>
</div>
<div className="card">
<button onClick={() => spawn(account)}>Spawn</button>
<div>Moves Left: {moves ? `${moves['remaining']}` : 'Need to Spawn'}</div>
<div>Position: {position ? `${position['x']}, ${position['y']}` : 'Need to Spawn'}</div>
</div>
<div className="card">
<button onClick={() => move(account, Direction.Up)}>Move Up</button> <br />
<button onClick={() => move(account, Direction.Left)}>Move Left</button>
<button onClick={() => move(account, Direction.Right)}>Move Right</button> <br />
<button onClick={() => move(account, Direction.Down)}>Move Down</button>
</div>
</>
);
}

export default App;
78 changes: 78 additions & 0 deletions client/src/DojoContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { createContext, ReactNode, useContext, useMemo } from "react";
import { SetupResult } from "./dojo/setup";
import { Account, RpcProvider } from "starknet";
import { useBurner } from "@dojoengine/create-burner";

type EternumContext = {
setup: SetupResult;
account: {
create: () => void;
list: () => any[];
get: (id: string) => any;
select: (id: string) => void;
account: Account;
masterAccount: Account;
isDeploying: boolean;
clear: () => void;
};
}

const DojoContext = createContext<EternumContext | null>(null);

type Props = {
children: ReactNode;
value: SetupResult;
};

export const DojoProvider = ({ children, value }: Props) => {

const { VITE_PUBLIC_MASTER_ADDRESS, VITE_PUBLIC_MASTER_PRIVATE_KEY, VITE_PUBLIC_ACCOUNT_CLASS_HASH, VITE_PUBLIC_NODE_URL } = import.meta.env;
const currentValue = useContext(DojoContext);
if (currentValue) throw new Error("DojoProvider can only be used once");

const provider = useMemo(
() =>
new RpcProvider({
nodeUrl: VITE_PUBLIC_NODE_URL!,
}),
[],
);

const masterAddress = VITE_PUBLIC_MASTER_ADDRESS!;
const privateKey = VITE_PUBLIC_MASTER_PRIVATE_KEY!;
const masterAccount = useMemo(
() => new Account(provider, masterAddress, privateKey),
[provider, masterAddress, privateKey],
);

const { create, list, get, account, select, isDeploying, clear } = useBurner({
masterAccount: masterAccount,
accountClassHash: VITE_PUBLIC_ACCOUNT_CLASS_HASH!,
});

const selectedAccount = useMemo(() => {
return account || masterAccount;
}, [account])

const contextValue: EternumContext = {
setup: value, // the provided setup
account: {
create, // create a new account
list, // list all accounts
get, // get an account by id
select, // select an account by id
account: selectedAccount, // the selected account
masterAccount, // the master account
isDeploying, // is the account being deployed
clear
}
}

return <DojoContext.Provider value={contextValue}>{children}</DojoContext.Provider>;
};

export const useDojo = () => {
const value = useContext(DojoContext);
if (!value) throw new Error("Must be used within a DojoProvider");
return value;
};
1 change: 1 addition & 0 deletions client/src/assets/react.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
65 changes: 65 additions & 0 deletions client/src/dojo/contractComponents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/* Autogenerated file. Do not edit manually. */

import { defineComponent, Type as RecsType, World } from "@latticexyz/recs";

export function defineContractComponents(world: World) {
return {
Moves: (() => {
const name = "Moves";
return defineComponent(
world,
{
remaining: RecsType.Number,
},
{
metadata: {
name: name,
},
}
);
})(),
Position: (() => {
const name = "Position";
return defineComponent(
world,
{
x: RecsType.Number,
y: RecsType.Number,
},
{
metadata: {
name: name,
},
}
);
})(),
AuthStatus: (() => {
const name = "AuthStatus";
return defineComponent(
world,
{
is_authorized: RecsType.Boolean,
},
{
metadata: {
name: name,
},
}
);
})(),
AuthRole: (() => {
const name = "AuthRole";
return defineComponent(
world,
{
id: RecsType.Number,
},
{
metadata: {
name: name,
},
}
);
})(),
};
}
13 changes: 13 additions & 0 deletions client/src/dojo/createClientComponents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { overridableComponent } from "@latticexyz/recs";
import { SetupNetworkResult } from "./setupNetwork";


export type ClientComponents = ReturnType<typeof createClientComponents>;

export function createClientComponents({ contractComponents }: SetupNetworkResult) {
return {
...contractComponents,
Position: overridableComponent(contractComponents.Position),
Moves: overridableComponent(contractComponents.Moves),
};
}
Loading

0 comments on commit 7c485a2

Please sign in to comment.