Skip to content
Open
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
189 changes: 189 additions & 0 deletions client-new/pages/deployment/torii/client-integration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
---
title: "Torii Client Integration"
description: "Learn how to integrate Torii with your client applications using GraphQL and gRPC"
---

# Torii Client Integration

This guide shows you how to connect your client applications to Torii for efficient data querying and real-time updates.

## Configuration

### Environment Setup

First, configure your Torii URL based on your deployment environment:

```javascript
// config.js
const config = {
development: {
toriiUrl: "http://localhost:8080"
},
production: {
toriiUrl: "https://api.cartridge.gg/x/YOUR_INSTANCE_NAME/torii"
}
};

export const dojoConfig = config[process.env.NODE_ENV || 'development'];
```

### GraphQL Endpoint

```javascript
const TORII_GRAPHQL_URL = dojoConfig.toriiUrl + "/graphql";
```

## GraphQL Integration

### Basic Setup

```javascript
import { createClient } from '@urql/core';

const client = createClient({
url: TORII_GRAPHQL_URL,
});

// Example query
const GET_PLAYERS = `
query GetPlayers {
players {
id
position {
x
y
}
score
}
}
`;

// Execute query
const result = await client.query(GET_PLAYERS).toPromise();
console.log(result.data.players);
```

### Real-time Subscriptions

```javascript
// Subscribe to player position updates
const PLAYER_POSITION_SUBSCRIPTION = `
subscription PlayerPositionUpdates {
playerPositionUpdated {
id
position {
x
y
}
}
}
`;

const subscription = client.subscription(PLAYER_POSITION_SUBSCRIPTION)
.subscribe({
next: (result) => {
console.log('Player moved:', result.data.playerPositionUpdated);
},
error: (error) => {
console.error('Subscription error:', error);
}
});
```

## gRPC Integration

For high-performance applications, you can use gRPC:

```javascript
// Example with gRPC-Web
import { grpc } from '@improbable-eng/grpc-web';

const client = new grpc.Client(TORII_GRPC_URL);

// Define your service methods
const playerService = {
getPlayers: (request) => {
return client.unary(PlayerService.GetPlayers, request);
}
};
```

## React Integration

### Custom Hook Example

```javascript
import { useEffect, useState } from 'react';
import { createClient } from '@urql/core';

const useToriiQuery = (query, variables = {}) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
const client = createClient({
url: TORII_GRAPHQL_URL,
});

client.query(query, variables)
.toPromise()
.then(result => {
setData(result.data);
setLoading(false);
})
.catch(err => {
setError(err);
setLoading(false);
});
}, [query, variables]);

return { data, loading, error };
};

// Usage in component
const PlayerList = () => {
const { data, loading, error } = useToriiQuery(GET_PLAYERS);

if (loading) return <div>Loading players...</div>;
if (error) return <div>Error: {error.message}</div>;

return (
<div>
{data.players.map(player => (
<div key={player.id}>
Player {player.id}: ({player.position.x}, {player.position.y})
</div>
))}
</div>
);
};
```

## Error Handling

```javascript
const handleToriiError = (error) => {
if (error.networkError) {
console.error('Network error:', error.networkError);
// Handle connection issues
} else if (error.graphQLErrors) {
console.error('GraphQL errors:', error.graphQLErrors);
// Handle query errors
}
};
```

## Best Practices

1. **Connection Pooling**: Reuse client instances when possible
2. **Error Boundaries**: Implement proper error handling for network issues
3. **Caching**: Use appropriate caching strategies for frequently accessed data
4. **Subscriptions**: Clean up subscriptions when components unmount
5. **Environment Variables**: Use environment variables for different deployment URLs

## Next Steps

- Check the [Torii Overview](./overview.md) for more context
- See [Local Development](../local.md) for setup instructions
- Visit the [official Dojo docs](https://book.dojoengine.org/toolchain/torii) for advanced configuration
72 changes: 72 additions & 0 deletions client-new/pages/deployment/torii/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
title: "Torii Indexer Overview"
description: "Learn what Torii is, why you need it, and how it works in the Dojo ecosystem"
---

# Torii Indexer Overview

Torii is Dojo's built-in tool for making your game data fast and easy to access. Think of it as a "search engine" for your on-chain game world—it keeps everything up-to-date in a local database so your apps can query it instantly.

## What is Torii?

- **Official Indexing Engine**: Torii is the standard way to index data in Dojo worlds
- **Automatic Syncing**: It watches your blockchain (Starknet) and copies game state changes to a database
- **Efficient Queries**: Provides APIs for quick data access, avoiding slow direct blockchain calls
- **Built in Rust**: Designed for speed and reliability
- **Pre-Installed**: Comes bundled with the Dojo toolchain—no extra setup needed

## Why Use Torii?

Directly querying the blockchain is like searching a massive library book-by-book: slow and costly. Torii acts like a catalog system:

- **Speed**: Instant access to game data
- **Real-Time Updates**: Supports subscriptions for live changes (e.g., player moves)
- **Cost Savings**: Reduces on-chain queries
- **Multiple Options**: Query via GraphQL, gRPC, or even SQL

## How It Works (Simplified)

1. **Monitor**: Torii tracks your deployed World contract on Starknet
2. **Capture**: It records every state change (e.g., new player spawns or moves)
3. **Store**: Saves data in a local database for easy access
4. **Serve**: Exposes APIs for your client apps to read the data

No manual intervention—Torii runs in the background when you deploy or migrate your Dojo project.

## API Interfaces

- **GraphQL**: Flexible for custom queries and real-time subscriptions
- Local Development: `http://localhost:8080/graphql`
- Production (Cartridge): `https://api.cartridge.gg/x/YOUR_INSTANCE_NAME/torii/graphql`
- **gRPC**: Fast binary protocol for high-performance apps
- Local Development: `http://localhost:8080`
- Production (Cartridge): `https://api.cartridge.gg/x/YOUR_INSTANCE_NAME/torii`

### URL Configuration

For production deployments, you'll typically configure your Torii URL in your client:

```javascript
// Example configuration
const TORII_URL = dojoConfig.toriiUrl + "/graphql";
// Results in: https://api.cartridge.gg/x/YOUR_INSTANCE_NAME/torii/graphql
```

## When to Use Torii

- Fetching player stats (e.g., position, score)
- Building leaderboards or dashboards
- Real-time updates in games (e.g., multiplayer sync)
- Analyzing historical data without blockchain delays

## Installation Note

Torii is included by default with Dojo. Install Dojo via the official guide, and Torii is ready to go. Run `torii --world <WORLD_ADDRESS>` to start it manually if needed.

## Next Steps

- See the [Local Development](../local.md) guide for setup
- Check [Client Integration](./client-integration.md) for using Torii in apps
- For advanced config, visit the [official Dojo docs](https://book.dojoengine.org/toolchain/torii)

This overview keeps things simple—dive deeper as you build!
14 changes: 14 additions & 0 deletions client-new/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,20 @@ const sidebarConfig: SidebarItem[] = [
text: 'Slot',
link: '/deployment/slot',
},
{
text: 'Torii Indexer',
collapsed: true,
items: [
{
text: 'Overview',
link: '/deployment/torii/overview',
},
{
text: 'Client Integration',
link: '/deployment/torii/client-integration',
},
],
},
],
},
{
Expand Down