Skip to content

fix: issue #315: add comments in example-vite-react-sdk #316

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
Nov 8, 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
9 changes: 9 additions & 0 deletions examples/example-vite-react-sdk/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,17 @@ import { useDojo } from "./useDojo.tsx";
import useModel from "./useModel.tsx";
import { useSystemCalls } from "./useSystemCalls.ts";

/**
* Global store for managing Dojo game state.
*/
export const useDojoStore = createDojoStore<Schema>();

/**
* Main application component that provides game functionality and UI.
* Handles entity subscriptions, state management, and user interactions.
*
* @param props.sdk - The Dojo SDK instance configured with the game schema
*/
function App({ sdk }: { sdk: SDK<Schema> }) {
const {
account,
Expand Down
16 changes: 16 additions & 0 deletions examples/example-vite-react-sdk/src/DojoContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,30 @@ import { dojoConfig } from "../dojoConfig";
import { DojoProvider } from "@dojoengine/core";
import { client } from "./contracts.gen";

/**
* Interface defining the shape of the Dojo context.
*/
interface DojoContextType {
/** The master account used for administrative operations */
masterAccount: Account;
/** The Dojo client instance */
client: ReturnType<typeof client>;
/** The current burner account information */
account: BurnerAccount;
}

/**
* React context for sharing Dojo-related data throughout the application.
*/
export const DojoContext = createContext<DojoContextType | null>(null);

/**
* Provider component that makes Dojo context available to child components.
*
* @param props.children - Child components that will have access to the Dojo context
* @param props.burnerManager - Instance of BurnerManager for handling burner accounts
* @throws {Error} If DojoProvider is used more than once in the component tree
*/
export const DojoContextProvider = ({
children,
burnerManager,
Expand Down
34 changes: 34 additions & 0 deletions examples/example-vite-react-sdk/src/bindings.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,46 @@
/**
* Interface representing a player's movement capabilities and state.
*/
interface Moves {
/** Order of fields in the model */
fieldOrder: string[];
/** Player identifier */
player: string;
/** Number of moves remaining */
remaining: number;
/** Last direction moved */
last_direction: Direction;
/** Whether the player can currently move */
can_move: boolean;
}

/**
* Interface representing available movement directions for a player.
*/
interface DirectionsAvailable {
/** Order of fields in the model */
fieldOrder: string[];
/** Player identifier */
player: string;
/** List of available directions */
directions: Direction[];
}

/**
* Interface representing a player's position in the game world.
*/
interface Position {
/** Order of fields in the model */
fieldOrder: string[];
/** Player identifier */
player: string;
/** 2D vector representing position */
vec: Vec2;
}

/**
* Enum representing possible movement directions.
*/
enum Direction {
None = "0",
Left = "1",
Expand All @@ -26,11 +49,19 @@ enum Direction {
Down = "4",
}

/**
* Interface representing a 2D vector.
*/
interface Vec2 {
/** X coordinate */
x: number;
/** Y coordinate */
y: number;
}

/**
* Type representing the complete schema of game models.
*/
type Schema = {
dojo_starter: {
Moves: Moves;
Expand All @@ -39,6 +70,9 @@ type Schema = {
};
};

/**
* Enum representing model identifiers in the format "namespace-modelName".
*/
enum Models {
Moves = "dojo_starter-Moves",
DirectionsAvailable = "dojo_starter-DirectionsAvailable",
Expand Down
6 changes: 6 additions & 0 deletions examples/example-vite-react-sdk/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ import { dojoConfig } from "../dojoConfig.ts";
import { DojoContextProvider } from "./DojoContext.tsx";
import { setupBurnerManager } from "@dojoengine/create-burner";

/**
* Initializes and bootstraps the Dojo application.
* Sets up the SDK, burner manager, and renders the root component.
*
* @throws {Error} If initialization fails
*/
async function main() {
const sdk = await init<Schema>(
{
Expand Down
9 changes: 9 additions & 0 deletions examples/example-vite-react-sdk/src/useDojo.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { useContext } from "react";
import { DojoContext } from "./DojoContext";

/**
* Custom hook to access the Dojo context and account information.
* Must be used within a DojoProvider component.
*
* @returns An object containing:
* - setup: The Dojo setup configuration
* - account: The current account information
* @throws {Error} If used outside of a DojoProvider context
*/
export const useDojo = () => {
const context = useContext(DojoContext);

Expand Down
8 changes: 4 additions & 4 deletions examples/example-vite-react-sdk/src/useModel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import { Schema } from "./bindings";
* @param model - The model to retrieve, specified as a string in the format "namespace-modelName".
* @returns The model structure if found, otherwise undefined.
*/
function useModel<N extends keyof Schema, M extends keyof Schema[N] & string>(
entityId: string,
model: `${N}-${M}`
): Schema[N][M] | undefined {
function useModel<
N extends keyof Schema,
M extends keyof Schema[N] & string
>(entityId: string, model: `${N}-${M}`): Schema[N][M] | undefined {
const [namespace, modelName] = model.split("-") as [N, M];

// Select only the specific model data for the given entityId
Expand Down
16 changes: 16 additions & 0 deletions examples/example-vite-react-sdk/src/useSystemCalls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import { useDojoStore } from "./App";
import { useDojo } from "./useDojo";
import { v4 as uuidv4 } from "uuid";

/**
* Custom hook to handle system calls and state management in the Dojo application.
* Provides functionality for spawning entities and managing optimistic updates.
*
* @returns An object containing system call functions:
* - spawn: Function to spawn a new entity with initial moves
*/
export const useSystemCalls = () => {
const state = useDojoStore((state) => state);

Expand All @@ -11,10 +18,19 @@ export const useSystemCalls = () => {
account: { account },
} = useDojo();

/**
* Generates a unique entity ID based on the current account address.
* @returns {string} The generated entity ID
*/
const generateEntityId = () => {
return getEntityIdFromKeys([BigInt(account?.address)]);
};

Comment on lines +21 to 28
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 input validation for account address.

The function should validate that the account address exists before attempting to generate an entity ID.

 const generateEntityId = () => {
+    if (!account?.address) {
+        throw new Error('No account address available');
+    }
     return getEntityIdFromKeys([BigInt(account?.address)]);
 };
📝 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
/**
* Generates a unique entity ID based on the current account address.
* @returns {string} The generated entity ID
*/
const generateEntityId = () => {
return getEntityIdFromKeys([BigInt(account?.address)]);
};
/**
* Generates a unique entity ID based on the current account address.
* @returns {string} The generated entity ID
*/
const generateEntityId = () => {
if (!account?.address) {
throw new Error('No account address available');
}
return getEntityIdFromKeys([BigInt(account?.address)]);
};

/**
* Spawns a new entity with initial moves and handles optimistic updates.
* @returns {Promise<void>}
* @throws {Error} If the spawn action fails
*/
const spawn = async () => {
// Generate a unique entity ID
const entityId = generateEntityId();
Expand Down
Loading