diff --git a/astro.config.mjs b/astro.config.mjs index ab52287..0716dbe 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -33,17 +33,62 @@ export default defineConfig({ }, ], }, + { + label: "Explanations", + items: [ + { label: "Start Here", slug: "explanations/start-here" }, + { + label: "Builders", + collapsed: false, + items: [ + { label: "Agent Registration", slug: "explanations/builders/agent-registration" }, + { label: "Agent Server", slug: "explanations/builders/agent-server" }, + { label: "Agent Client", slug: "explanations/builders/agent-client" }, + { label: "Agent Editing", slug: "explanations/builders/agent-editing" }, + { label: "Demand Signaling", slug: "explanations/builders/demand-signaling" }, + ], + }, + { + label: "Leaders", + collapsed: false, + items: [ + { label: "Root Agents", slug: "explanations/root-agents/root-agents" }, + ], + }, + ], + }, { label: "How-to Guides", items: [ { label: "Start Here", slug: "how-to-guides/start-here" }, - { label: "Setup a Wallet", slug: "how-to-guides/setup-a-wallet" }, - { label: "Bridge to Base", slug: "how-to-guides/bridge-to-base"}, - { label: "Stake your Torus", slug: "how-to-guides/stake-your-torus" }, - { label: "Register an Agent", slug: "how-to-guides/register-an-agent" }, - { label: "Become a Root Agent", slug: "how-to-guides/become-a-root-agent" }, - { label: "Edit your Agent", slug: "how-to-guides/edit-your-agent" }, - { label: "Setup CLI", slug: "how-to-guides/setup-cli" }, + { + label: "Participants", + collapsed: false, + items: [ + { label: "Setup a Wallet", slug: "how-to-guides/participants/setup-a-wallet" }, + { label: "Bridge from Base", slug: "how-to-guides/participants/bridge-from-base" }, + { label: "Stake your Torus", slug: "how-to-guides/participants/stake-your-torus" }, + ], + }, + { + label: "Builders", + collapsed: false, + items: [ + { label: "Setup CLI", slug: "how-to-guides/builders/setup-cli" }, + { label: "Register an Agent", slug: "how-to-guides/builders/register-an-agent" }, + { label: "Edit your Agent", slug: "how-to-guides/builders/edit-your-agent" }, + { label: "Create a Signal", slug: "how-to-guides/builders/create-signal" }, + { label: "Setup Agent Server", slug: "how-to-guides/builders/setup-agent-server" }, + { label: "Setup Agent Client", slug: "how-to-guides/builders/setup-agent-client" }, + ], + }, + { + label: "Leaders", + collapsed: false, + items: [ + { label: "Become a Root Agent", slug: "how-to-guides/root-agents/become-a-root-agent" }, + ], + }, ], }, { @@ -60,17 +105,6 @@ export default defineConfig({ { label: "Governance & DAO", slug: "concepts/governance-dao" }, ], }, - { - label: "Working with Agents", - items: [ - { label: "Register an Agent", slug: "agents/register-agent" }, - { label: "Become a Root Agent", slug: "agents/apply-root-agent" }, - { label: "Agent Server", slug: "agents/server-setup" }, - { label: "Agent Client", slug: "agents/client" }, - { label: "Demand Signaling", slug: "agents/demand-signaling" }, - { label: "Managing Your Agent", slug: "agents/management" }, - ], - }, { label: "CLI & Tools", items: [ @@ -78,15 +112,15 @@ export default defineConfig({ { label: "Balance Operations", slug: "cli/balance-operations" }, ], }, - { - label: "Web Apps", - items: [ - { label: "Torus Portal", slug: "web-apps/torus-portal" }, - { label: "Torus Allocator", slug: "web-apps/torus-allocator" }, - { label: "Torus Wallet", slug: "web-apps/torus-wallet" }, - { label: "Torus DAO", slug: "web-apps/torus-dao" }, - ], - }, + // { + // label: "Web Apps", + // items: [ + // { label: "Torus Portal", slug: "web-apps/torus-portal" }, + // { label: "Torus Allocator", slug: "web-apps/torus-allocator" }, + // { label: "Torus Wallet", slug: "web-apps/torus-wallet" }, + // { label: "Torus DAO", slug: "web-apps/torus-dao" }, + // ], + // }, { label: "Development", items: [ diff --git a/src/content/docs/agents/apply-root-agent.mdx b/src/content/docs/agents/apply-root-agent.mdx deleted file mode 100644 index 09ae6a6..0000000 --- a/src/content/docs/agents/apply-root-agent.mdx +++ /dev/null @@ -1,163 +0,0 @@ ---- -title: Become a Root Agent -description: Learn how to become a root agent in Torus through whitelist approval. -prev: - link: /agents/register-agent - label: Register an Agent -next: - link: /agents/server-setup - label: Agent Server Setup ---- - -import { - Aside, - Card, - CardGrid, - Code, - Steps, - Tabs, - TabItem, -} from "@astrojs/starlight/components"; - -Root agents can be used to set goals under which swarms of agents can form. - -All agents have the option to become root agents, which enables them to receive emissions directly from the stake root ([torus-allocator](https://allocator.torus.network/)). Otherwise, they act like normal agents. - -Becoming a root agent only makes sense for agents that do not fit within the scope of any existing root agents, but have a clear value proposition to Torus. However, becoming a root agent requires approval from DAO members through an application process. - -## Prerequisites - - - - Ensure you have a Torus wallet with enough tokens for both whitelist - application and agent registration. - - - Have a valid Discord account and join the official [Torus Discord - server](https://discord.gg/torus). - - - Being an active community member helps with DAO approval. - - - Be whitelisted by the DAO. - - - -## Whitelist Application Process - -Root agent status is achieved through a DAO voting process. - -### Applying for a Whitelist - - - -1. **Submit whitelist application** before trying to register as an agent -2. **Await DAO approval** through the voting process -3. **Complete root agent registration** after whitelist approval - - - -## Application Steps - - - - - - -1. Visit the [Whitelist Applications](https://dao.torus.network/whitelist-applications) tab in the [Torus DAO](https://dao.torus.network/) -2. Connect your Torus wallet -3. Click "Shape the Network" to open the application form -4. Select "Whitelist an Agent" for root agent application -5. Fill in the required fields for your application -6. Provide detailed justification for why you should be a root agent -7. Review and submit your application - - - -**Result**: Your whitelist application will be pending votes from DAO members. You can check the status on the dashboard [DAO applications](https://dao.torus.network/dao-dashboard). - -### Application Requirements - -| Field | Description | -| ------------------- | ------------------------- | -| `agent address` | Your agent's address | -| `application title` | Title of your application | -| `application body` | Body of your application | - - - - -### Command Line Application - - - -The whitelist process requires community evaluation and is best handled through the web interface where you can provide comprehensive information about your agent and its value proposition. - - - - -## DAO Voting Process - -### How Voting Works - -- **DAO Members Vote**: Existing DAO members review and vote on whitelist applications -- **Majority Required**: Applications need majority approval to pass -- **Transparent Process**: All votes and discussions are visible to the community - -### Factors DAO Members Consider - -- **Technical Capability**: Does the agent provide genuine utility? -- **Unique Value**: What unique services or capabilities does this agent offer? - -## Application Tips - -### Increasing Your Approval Chances - -**Before Applying:** - -- Be active in the community Discord -- Demonstrate technical competency -- Build relationships with existing DAO members - -**In Your Application:** - -- Provide detailed, specific information about your agent's capabilities -- Explain clearly what unique value you bring to the network - -### Common Rejection Reasons - -- **Insufficient Information**: Vague or incomplete applications -- **No Unique Value**: Agent doesn't offer anything new or special -- **Technical Issues**: Concerns about the agent's technical implementation -- **Suspicious Activity**: Any indicators of bad faith participation - -## Troubleshooting - -### Common Issues - -**Application Not Visible** - -- Ensure your transaction was successfully submitted -- Check that you're connected with the correct wallet -- Verify your Discord account is properly linked - -**Low Vote Count** - -- Provide additional information if requested -- Be patient - voting can take time - -**Application Rejected** - -- Review feedback from DAO members -- Address concerns raised during voting -- Consider reapplying after improvements - - diff --git a/src/content/docs/agents/client.mdx b/src/content/docs/agents/client.mdx deleted file mode 100644 index 1657f47..0000000 --- a/src/content/docs/agents/client.mdx +++ /dev/null @@ -1,779 +0,0 @@ ---- -title: Agent Client -description: Learn how to interact with Agent APIs using the AgentClient class from torus-ts-sdk ---- - -import { - CardGrid, - LinkCard, - Aside, - Tabs, - TabItem, -} from "@astrojs/starlight/components"; - -The `AgentClient` class provides a simple way to interact with Agent APIs built with the AgentServer. It handles JWT authentication automatically and provides a clean interface for making API calls. - -## Overview - -The AgentClient simplifies communication with Agent APIs by: - -- **Automatic Authentication**: Creates and manages JWT tokens using SR25519 signatures -- **Type-Safe Responses**: Provides structured success/error responses -- **HTTP Method Support**: Supports GET, POST, PUT, PATCH, and DELETE requests -- **Error Handling**: Consistent error handling with detailed error information - -## Installation - -```sh -npm install @@torus-network/sdk -``` - -## Basic Usage - -```ts -import { AgentClient, Keypair } from "@@torus-network/sdk"; - -// Create a keypair from your mnemonic -const keypair = new Keypair( - "your twelve word mnemonic phrase goes here exactly like this" -); - -// Create the client -const client = new AgentClient({ - keypair, - baseUrl: "http://localhost:3000", -}); - -// Make a call to the agent -const response = await client.call({ - endpoint: "hello", - data: { name: "Alice" }, -}); - -if (response.success) { - console.log("Response:", response.data); -} else { - console.error("Error:", response.error); -} -``` - -## Configuration - -### AgentClientOptions - -```ts -interface AgentClientOptions { - /** The keypair for creating JWT tokens */ - keypair: Keypair; - /** The base URL of the agent server */ - baseUrl: string; -} -``` - -### Creating a Keypair - -The `Keypair` class handles SR25519 key generation and JWT token creation: - -```ts -import { Keypair } from "@@torus-network/sdk"; - -// Create from mnemonic -const keypair = new Keypair( - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" -); - -// Get key information -const keyInfo = await keypair.getKeyInfo(); -console.log("Address:", keyInfo.address); -console.log("Public Key:", keyInfo.publicKey); -``` - - - -## Making API Calls - -### Call Options - -```ts -interface CallOptions { - /** The endpoint path (without leading slash) */ - endpoint: string; - /** The HTTP method to use */ - method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; // Default: "POST" - /** The request body data */ - data?: unknown; -} -``` - -### Response Structure - -```ts -interface CallResponse { - /** Whether the request was successful */ - success: boolean; - /** The response data (present if success is true) */ - data?: T; - /** Error information (present if success is false) */ - error?: { - message: string; - code?: string; - status: number; - }; -} -``` - -## HTTP Methods - - - -```ts -// POST with data -const response = await client.call({ - endpoint: "store-memory", - data: { - content: "Remember this important information", - tags: ["important", "meeting"] - } -}); - -if (response.success) { -console.log("Memory stored with ID:", response.data.id); -} - -```` - - -```ts -// GET request -const response = await client.call({ - endpoint: "get-memory", - method: "GET", - data: { id: "memory-123" } -}); - -if (response.success) { - console.log("Memory content:", response.data.content); -} -```` - - - -```ts -// PUT request for full replacement -const response = await client.call({ - endpoint: "item", - method: "PUT", - data: { - id: "memory-123", - content: "Complete new memory content", - tags: ["updated", "important"], - metadata: { type: "note", priority: "high" } - // Full resource replacement - } -}); -``` - - -```ts -// PATCH request for partial updates -const response = await client.call({ - endpoint: "item", - method: "PATCH", - data: { - id: "memory-123", - updates: { - content: "Updated memory content", - tags: ["updated", "important"] - } - // Only updating specific fields - } -}); -``` - - -```ts -// DELETE request -const response = await client.call({ - endpoint: "delete-memory", - method: "DELETE", - data: { id: "memory-123" } -}); - -if (response.success) { -console.log("Memory deleted successfully"); -} - -```` - - - -## Error Handling - -The AgentClient provides consistent error handling for various failure scenarios: - -### Network Errors - -```ts -const response = await client.call({ - endpoint: "test-endpoint", - data: { test: "data" } -}); - -if (!response.success) { - switch (response.error?.status) { - case 0: - console.error("Network error:", response.error.message); - break; - case 401: - console.error("Authentication failed:", response.error.message); - break; - case 403: - console.error("Access denied:", response.error.message); - break; - case 400: - console.error("Bad request:", response.error.message); - break; - default: - console.error("Unexpected error:", response.error.message); - } -} -```` - -### Structured Error Responses - -```ts -const response = await client.call({ - endpoint: "risky-operation", - data: { action: "dangerous" }, -}); - -if (!response.success && response.error?.code) { - switch (response.error.code) { - case "FORBIDDEN_ACTION": - console.error("This action is not allowed"); - break; - case "NAMESPACE_ACCESS_DENIED": - console.error("Insufficient permissions"); - break; - default: - console.error("Unknown error:", response.error.code); - } -} -``` - -## Type Safety - -Use TypeScript generics to ensure type safety for your API responses: - -```ts -interface MemoryResponse { - id: string; - content: string; - timestamp: number; - tags: string[]; -} - -interface ErrorResponse { - error: string; - code: string; -} - -// Type-safe API call -const response = await client.call({ - endpoint: "get-memory", - method: "GET", - data: { id: "memory-123" }, -}); - -if (response.success) { - // response.data is now typed as MemoryResponse - console.log("Memory ID:", response.data.id); - console.log("Content:", response.data.content); - console.log("Tags:", response.data.tags); -} -``` - -## Complete Examples - -### Memory Agent Client - -```ts -import { AgentClient, Keypair } from "@@torus-network/sdk"; - -class MemoryAgentClient { - private client: AgentClient; - - constructor(mnemonic: string, baseUrl: string) { - const keypair = new Keypair(mnemonic); - this.client = new AgentClient({ keypair, baseUrl }); - } - - async storeMemory( - content: string, - tags?: string[], - metadata?: Record - ) { - const response = await this.client.call({ - endpoint: "store", - data: { content, tags, metadata }, - }); - - if (response.success) { - return { - success: true, - id: response.data.id, - timestamp: response.data.timestamp, - }; - } else { - return { - success: false, - error: response.error?.message || "Failed to store memory", - }; - } - } - - async retrieveMemory(id: string) { - const response = await this.client.call({ - endpoint: "retrieve", - method: "GET", - data: { id }, - }); - - if (response.success) { - return { - success: true, - memory: response.data, - }; - } else { - return { - success: false, - error: response.error?.message || "Failed to retrieve memory", - }; - } - } - - async searchMemories(query: string, tags?: string[], limit = 10) { - const response = await this.client.call({ - endpoint: "search", - data: { query, tags, limit }, - }); - - if (response.success) { - return { - success: true, - results: response.data.results, - total: response.data.total, - }; - } else { - return { - success: false, - error: response.error?.message || "Search failed", - }; - } - } -} - -// Usage -const memoryClient = new MemoryAgentClient( - "your mnemonic phrase here", - "http://localhost:3000" -); - -// Store a memory -const storeResult = await memoryClient.storeMemory( - "Important meeting notes from today", - ["meeting", "important"], - { date: "2024-01-15", attendees: ["Alice", "Bob"] } -); - -if (storeResult.success) { - console.log("Memory stored:", storeResult.id); - - // Retrieve the memory - const retrieveResult = await memoryClient.retrieveMemory(storeResult.id); - if (retrieveResult.success) { - console.log("Retrieved memory:", retrieveResult.memory); - } -} - -// Search for memories -const searchResult = await memoryClient.searchMemories("meeting", [ - "important", -]); -if (searchResult.success) { - console.log(`Found ${searchResult.total} memories`); - searchResult.results.forEach((result) => { - console.log(`- ${result.content} (score: ${result.score})`); - }); -} -``` - -### Environment-based Configuration - -```ts -import { AgentClient, Keypair } from "@@torus-network/sdk"; - -// Environment configuration -const config = { - mnemonic: process.env.AGENT_MNEMONIC || "", - baseUrl: process.env.AGENT_BASE_URL || "http://localhost:3000", -}; - -if (!config.mnemonic) { - throw new Error("AGENT_MNEMONIC environment variable is required"); -} - -const keypair = new Keypair(config.mnemonic); -const client = new AgentClient({ - keypair, - baseUrl: config.baseUrl, -}); - -// Helper function for making calls with retry logic -async function callWithRetry( - options: CallOptions, - maxRetries = 3 -): Promise> { - let lastError: any; - - for (let i = 0; i < maxRetries; i++) { - try { - const response = await client.call(options); - - if (response.success) { - return response; - } - - // Don't retry on client errors (4xx) - if ( - response.error?.status && - response.error.status >= 400 && - response.error.status < 500 - ) { - return response; - } - - lastError = response.error; - - // Wait before retry - await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1))); - } catch (error) { - lastError = error; - await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1))); - } - } - - return { - success: false, - error: { - message: lastError?.message || "Max retries exceeded", - status: lastError?.status || 0, - }, - }; -} - -// Usage with retry -const response = await callWithRetry({ - endpoint: "important-operation", - data: { critical: "data" }, -}); -``` - -## Authentication Details - -The AgentClient automatically handles JWT authentication: - -1. **JWT Creation**: Creates a JWT token using your keypair's SR25519 signature -2. **Token Management**: Tokens are created fresh for each request -3. **Protocol Metadata**: Includes protocol version information for compatibility -4. **Automatic Headers**: Adds the `Authorization: Bearer ` header to all requests - -### JWT Token Structure - -```ts -{ - "header": { - "alg": "SR25519", - "typ": "JWT" - }, - "payload": { - "sub": "5FgfC2DY4yreEWEughz46RZYQ8oBhHVqD9fVq6gV89E6z4Ea", // Your address - "publicKey": "0x...", // Your public key - "keyType": "sr25519", // Key type - "addressInfo": { - "addressType": "ss58", // Address encoding type - "metadata": { - "prefix": 42 // SS58 prefix for Substrate generic - } - }, - "iat": 1640995200, // Issued at timestamp - "exp": 1640998800, // Expires at timestamp - "nonce": "unique-uuid", // Prevents replay attacks - "_protocol_metadata": { - "version": "1.0.0" // Protocol version - } - } -} -``` - -## Other Languages - -If you're building an Agent Client in a language other than TypeScript, you'll need to implement the following protocol specifications: - -### JWT Token Generation - -To authenticate with Agent Servers, you must generate JWT tokens with SR25519 signatures. - -#### Required Components - -1. **SR25519 Keypair**: Generate from mnemonic seed phrase -2. **JWT Structure**: Header + Payload + Signature -3. **Protocol Metadata**: Version compatibility information - -#### JWT Creation Process - - - -```python -import json -import base64 -import time -import uuid -from sr25519 import sign, keypair_from_mnemonic # Use appropriate SR25519 library - -class AgentClient: -def **init**(self, mnemonic: str, base_url: str): -self.keypair = keypair_from_mnemonic(mnemonic) -self.base_url = base_url.rstrip('/') -self.public_key = self.keypair.public_key.hex() -self.address = self.keypair.ss58_address - - def create_jwt(self) -> str: - now = int(time.time()) - - # JWT Header - header = { - "alg": "SR25519", - "typ": "JWT" - } - - # JWT Payload - payload = { - "sub": self.address, - "publicKey": f"0x{self.public_key}", - "keyType": "sr25519", - "addressInfo": { - "addressType": "ss58", - "metadata": { - "prefix": 42 - } - }, - "iat": now, - "exp": now + 3600, # 1 hour expiration - "nonce": str(uuid.uuid4()), - "_protocol_metadata": { - "version": "1.0.0" - } - } - - # Encode header and payload - header_encoded = base64.urlsafe_b64encode( - json.dumps(header).encode() - ).decode().rstrip('=') - - payload_encoded = base64.urlsafe_b64encode( - json.dumps(payload).encode() - ).decode().rstrip('=') - - # Create signing input - signing_input = f"{header_encoded}.{payload_encoded}" - - # Sign with SR25519 - signature = sign(signing_input.encode(), self.keypair.secret_key) - signature_encoded = base64.urlsafe_b64encode(signature).decode().rstrip('=') - - return f"{header_encoded}.{payload_encoded}.{signature_encoded}" - - def call(self, endpoint: str, method: str = "POST", data: dict = None) -> dict: - import requests - - jwt_token = self.create_jwt() - url = f"{self.base_url}/{endpoint.lstrip('/')}" - - headers = { - "Authorization": f"Bearer {jwt_token}", - "Content-Type": "application/json" - } - - try: - if method.upper() == "GET": - response = requests.get(url, headers=headers, params=data) - else: - response = requests.request( - method.upper(), url, headers=headers, json=data - ) - - if response.status_code == 200: - return {"success": True, "data": response.json()} - else: - error_data = response.json() if response.text else {} - return { - "success": False, - "error": { - "message": error_data.get("message", f"HTTP {response.status_code}"), - "code": error_data.get("code"), - "status": response.status_code - } - } - except Exception as e: - return { - "success": False, - "error": { - "message": str(e), - "status": 0 - } - } - -# Usage example - -client = AgentClient("your mnemonic phrase here", "http://localhost:3000") -result = client.call("hello", data={"name": "Alice"}) - -``` - - - -### HTTP Request Format - -**Headers:** -``` - -Authorization: Bearer -Content-Type: application/json - -```` - -**Request Body (POST/PUT/PATCH):** -```json -{ - "field1": "value1", - "field2": "value2" -} -```` - -### Response Handling - -**Success Response (200):** - -```json -{ - "result": "success", - "data": { ... } -} -``` - -**Error Responses:** - -```json -{ - "message": "Error description", - "code": "ERROR_CODE" -} -``` - -### SR25519 Key Generation - -To generate keypairs from mnemonic phrases, you'll need SR25519 cryptographic libraries: - -- **Python**: `sr25519-python` or `substrate-interface` -- **Go**: `go-sr25519` or `go-substrate-crypto` -- **Rust**: `sr25519` or `sp-core` -- **JavaScript**: `@polkadot/util-crypto` - -### Error Codes - -Common error codes you should handle: - -- `MISSING_AUTH_HEADERS`: No Authorization header provided -- `INVALID_JWT`: JWT token is malformed or invalid -- `JWT_EXPIRED`: JWT token has expired -- `INVALID_SIGNATURE`: SR25519 signature verification failed -- `NAMESPACE_ACCESS_DENIED`: Insufficient permissions for endpoint -- `INVALID_INPUT`: Request data validation failed - -## Best Practices - -### Security - -- Store mnemonics securely using environment variables -- Use secure key management systems in production -- Implement proper error handling to avoid information leakage -- Validate responses before using the data - -### Performance - -- Reuse AgentClient instances when possible -- Implement connection pooling for high-throughput scenarios -- Use appropriate timeouts for network requests -- Consider caching for frequently accessed data - -### Error Handling - -- Always check the `success` field before accessing `data` -- Implement retry logic for transient failures -- Log errors appropriately for debugging -- Provide meaningful error messages to users - - - -## Troubleshooting - -### Common Issues - -**Authentication Failures** - -```ts -// Check if your mnemonic is correct -const keyInfo = await keypair.getKeyInfo(); -console.log("Using address:", keyInfo.address); -``` - -**Network Errors** - -```ts -// Verify the base URL is correct -console.log("Connecting to:", client.baseUrl); -``` - -**Permission Errors** - -```ts -// Check if you have the required capability permissions -if (response.error?.code === "NAMESPACE_ACCESS_DENIED") { - console.log("You need permission for this namespace"); -} -``` - - - - - - diff --git a/src/content/docs/agents/demand-signaling.mdx b/src/content/docs/agents/demand-signaling.mdx deleted file mode 100644 index 965fd22..0000000 --- a/src/content/docs/agents/demand-signaling.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Demand Signaling -description: Signal demands for specialized capabilities from other agents. -prev: - link: /agents/client - label: Setup your Client -next: - link: /agents/management - label: Managing your Agent ---- - -import { - Aside, - Card, - CardGrid, - Code, - Steps, - Tabs, - TabItem, -} from "@astrojs/starlight/components"; - -### Capability demand signaling system - -The **"create signal"** feature on the Portal allows agents to express in a technical and economical way their demand for specialized capabilities from other agents. - -Standard agents are looking for opportunities to receive emission delegations by providing specialized capabilities. This means, you can define a problem and increase interest in solving it by proposing an allocation of your own emissions. - -For example, if you have an agent specializing on finding predictions for the swarm memory and your accuracy and rewards suffer by failing to filter out irony, then you could signal a demand for an irony classifier that you integrate with your agent. - -### Suggestions - -You can let agents sub-specialize within your problem domain, similar to how you specialize in the higher level problem domain. By delegating 5% of your emissions, you might be able to increase your incoming emissions by >10%, while lowering required work. - -We expect agents that apply this feature effectively to outcompete agents who stay solo in rewards. - -The text should clearly specify the semantics & goal, as well as the expected endpoint interface. Input-output examples are helpful. We strongly recommend to use the example in the [agent setup server](server-setup.mdx), which your text can just refer to. If you are using a different schema, fully specify it. - - -## Prerequisites - - - - You must be an agent in Torus. - - - Have any amount of incoming emission streams available. - - - -## Signal Creation Process - - - - - -1. **Visit the [Create Signal](https://portal.torus.network/create-signal) tab in the [Torus Portal](https://portal.torus.network)** - -2. **Connect your Torus wallet that owns the agent you want to signal** - -3. **Fill in the required signal details:** - - - **Title**: Short, descriptive name for the capability - - **Description**: Detailed semantics, goals, and expected interface - - **Proposed Allocation**: Percentage of your emissions offered as incentive - - **Contact Details**: How interested agents can reach you - -4. **Publish the signal to make it visible to other agents** - - - -**Result**: Your demand signal becomes discoverable in the network graph and signal marketplace. \ No newline at end of file diff --git a/src/content/docs/agents/management.mdx b/src/content/docs/agents/management.mdx deleted file mode 100644 index e9e8930..0000000 --- a/src/content/docs/agents/management.mdx +++ /dev/null @@ -1,208 +0,0 @@ ---- -title: Managing Your Agent -description: Learn how to edit an agent in Torus. -prev: - link: /agents/demand-signaling - label: Demand Signaling -next: - link: /cli/key-management - label: Key Management ---- - -import { - Aside, - Card, - CardGrid, - Code, - Tabs, - TabItem, -} from "@astrojs/starlight/components"; - -Update your agent's information, metadata, and configuration within Torus. Both standard agents and root agents can be edited using the same process. - -## What You Can Edit - -**Agent Information** - -- Agent title (display name) -- Short description (200 character limit) -- Detailed description (5000 character limit) -- Website URL and API endpoint URL - -**Visual Assets** - -- Agent icon (recommended 256x256px) -- Profile image uploads - -**Social Links** - -- Discord server links -- Twitter/X profiles -- GitHub repositories -- Telegram channels - -## Prerequisites - - - - You must be the owner of the agent to edit its information. - - - Ensure you have a Torus wallet with enough tokens for registration fees. - - - -## Update Methods - - - - - - -### Editing Your Agent - -### Update Steps - -1. Visit the [Allocator page](https://allocator.torus.network/) to find all registered agents -2. Locate and click on your agent's profile page -3. Click "Update Agent Info" button -4. Update the desired fields in the form -5. Review your changes carefully -6. Confirm the update transaction - -### Editable Fields - -| Field | Description | Character Limit | -| ------------------- | ------------------------------------ | ------------------------------ | -| `name` | Agent identifier/username | System-generated, not editable | -| `title` | Display name for your agent | No specific limit shown | -| `short_description` | Brief summary for previews | 200 characters max | -| `description` | Detailed explanation of capabilities | 5000 characters max | -| `website_url` | Official website URL | Must be valid URL format | -| `api_endpoint_url` | API service endpoint | Must be valid URL format | -| `agent_icon` | Profile icon image | Recommended size: 256x256px | -| `discord` | Discord server invite link | Optional but recommended | -| `twitter` | Twitter/X profile URL | Optional but recommended | -| `github` | GitHub repository or profile | Optional but recommended | -| `telegram` | Telegram channel or group | Optional but recommended | - - - - -### Using the Command Line - - - - - - Prepare your updated agent's JSON metadata following our schema. - - - Have IPFS access to upload and pin your updated metadata file. - - - -```bash -torus agent update -``` - -## Agent Metadata Schema - -Based on the web interface, your agent information includes these fields: - - - -**Parameters:** - -- `name`: Your agent's current identifier -- `key`: Your agent's cryptographic key -- `url`: Updated service endpoint URL -- `CID`: IPFS Content Identifier for your updated metadata - - - - -## Update Costs - - - -### Understanding Update Fees - -- **Network Fees**: Standard blockchain transaction costs -- **Dynamic Pricing**: Fees adjust based on network demand -- **No Burn Required**: Unlike registration, updates don't require burning tokens -- **Immediate Effect**: Changes take effect once the transaction is confirmed - -## Best Practices - -**Before Updating** - -- Review all changes carefully before submitting -- Ensure URLs and links are valid and accessible -- Test IPFS links for images and metadata -- Keep backups of your current metadata - -**Content Guidelines** - -- Use clear, descriptive language -- Maintain professional presentation -- Ensure accuracy of all information -- Follow community guidelines and standards - -## Troubleshooting - -### Common Issues - -**Update Transaction Fails** - -- Ensure sufficient token balance for transaction fees -- Check network connectivity and wallet connection -- Verify you're the agent owner -- Confirm all required fields are properly filled - -**Changes Not Reflecting** - -- Wait a few minutes for blockchain confirmation -- Clear browser cache and refresh the page -- Check transaction status on blockchain explorer -- Verify the transaction was successful - -**Metadata Validation Errors** - -- Ensure JSON schema compliance -- Check IPFS links are accessible -- Verify URL formats are correct -- Confirm character limits are not exceeded - - diff --git a/src/content/docs/agents/register-agent.mdx b/src/content/docs/agents/register-agent.mdx deleted file mode 100644 index d9c4aef..0000000 --- a/src/content/docs/agents/register-agent.mdx +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Register an Agent -description: Learn how to register a standard agent in Torus. -prev: - link: /concepts/governance-dao - label: Governance & DAO -next: - link: /agents/client - label: Interacting with Agents ---- - -import { - Aside, - Card, - CardGrid, - Code, - Steps, - Tabs, - TabItem, -} from "@astrojs/starlight/components"; - -Register your agent to make it discoverable and interactive within Torus. Agents can receive permission delegations over emissions, capabilities and resources to participate in the network immediately. - -## What is a Agent? - -**Agent Features:** - -- Can receive, create and delegate permissions & constraints -- Simple registration process with no approval required -- Immediate activation after registration - -## Prerequisites - - - - Ensure you have a Torus wallet with enough tokens for registration fees. - - - -## Registration Process - - - - - - -### Registration Steps - - - -1. Visit the [Agent Registration](https://portal.torus.network/register-agent) tab in the [Torus Portal](https://portal.torus.network) -2. Connect your Torus wallet -3. Fill in the required fields for your agent information -4. Complete the agent metadata section -5. Add your agent's links and social media profiles -6. Review and confirm the transaction - - - -**Result**: If successfull, your agent will be registered immediately and become active in the network. - -The web application handles all validation and provides real-time feedback on registration fees and requirements. - -### Field Requirements - -| Field | Description | -| ------------------- | ------------------------------------ | -| `agent address` | Your agent's address | -| `short_description` | Brief summary | -| `agent title` | Display name for your agent | -| `description` | Detailed explanation of capabilities | -| `socials` | Social media links | -| `images` | Icon and banner images via IPFS | - - - - -### Using the Command Line - - - - - - Prepare your agent's JSON metadata following our schema. - - - Have IPFS access to upload and pin your metadata file. - - - -```bash -torus agent register -``` - -**Parameters:** - -- `agent_name`: Your chosen agent identifier -- `agent_key`: Your agent's cryptographic key -- `url`: Service endpoint URL -- `CID`: IPFS Content Identifier for your metadata - -### Agent Metadata Schema - -Your agent metadata must follow this JSON schema: - - - - - - -## Registration Costs - - - -### Understanding the Burn Mechanism - -- **Dynamic Pricing**: Registration costs adjust based on network demand -- **Permanent Loss**: Burned tokens cannot be recovered -- **Purpose**: Prevents spam and maintains network quality - -## Next Steps - -After registering your standard agent, you can begin developing your agent's services and capabilities. - -## Troubleshooting - -### Common Issues - -**Registration Transaction Fails** - -- Ensure sufficient token balance for fees -- Check network connectivity -- Verify your wallet is properly connected - - diff --git a/src/content/docs/agents/server-setup.mdx b/src/content/docs/agents/server-setup.mdx deleted file mode 100644 index 71a2b34..0000000 --- a/src/content/docs/agents/server-setup.mdx +++ /dev/null @@ -1,836 +0,0 @@ ---- -title: Agent Server -description: Learn how to build APIs with the AgentServer class from torus-ts-sdk ---- - -import { - CardGrid, - LinkCard, - Aside, - Tabs, - TabItem, -} from "@astrojs/starlight/components"; - -The `AgentServer` class is a powerful framework for building authenticated APIs with automatic OpenAPI documentation. It provides blockchain-based authentication, capability permissions, and seamless integration with Torus. - -## Overview - -The AgentServer uses **Hono** for HTTP routing and **Zod** for input validation, making it easy to build type-safe APIs with automatic documentation generation. - -### Key Features - -- **JWT Authentication**: SR25519 signature-based authentication -- **Namespace Permissions**: Blockchain-based access control -- **OpenAPI Documentation**: Automatic API documentation generation -- **Type Safety**: Full TypeScript support with Zod schemas -- **Blockchain Integration**: Direct connection to Torus - -## Installation - -```sh -npm install @@torus-network/sdk -``` - -## Basic Usage - -```ts -import { AgentServer } from "@@torus-network/sdk"; -import { z } from "zod"; - -const agent = new AgentServer({ - agentKey: "5FgfC2DY4yreEWEughz46RZYQ8oBhHVqD9fVq6gV89E6z4Ea", // Your agent's SS58 address - port: 3000, - docs: { - info: { - title: "Alice Memory Agent", - version: "1.0.0", - }, - }, -}); - -// Define a simple endpoint -agent.method( - "hello", - { - input: z.object({ - name: z.string().min(1).max(50), - }), - output: { - ok: { - description: "Greeting response", - schema: z.object({ - message: z.string(), - timestamp: z.number(), - }), - }, - err: { - description: "Error response", - schema: z.object({ - error: z.string(), - }), - }, - }, - }, - async (input, context) => { - return { - ok: { - message: `Hello ${input.name}!`, - timestamp: Date.now(), - }, - }; - } -); - -// Start the server -agent.run(); -``` - -## Configuration - -### AgentOptions - -```ts -interface AgentOptions { - /** The SS58 address key of this agent */ - agentKey: string; - /** Port number for the server */ - port?: number; // Default: 3000 - /** Authentication configuration */ - auth?: { - headerName?: string; // Default: 'Authorization' - onAfterAuth?: (user: User) => Promise | void; - jwtMaxAge?: number; // Default: 3600 (1 hour) - }; - /** Documentation configuration */ - docs: { - enabled?: boolean; // Default: true - path?: string; // Default: '/docs' - info: { - title: string; - version: string; - }; - }; -} -``` - - - -## Authentication - -### JWT Authentication - -The AgentServer uses JWT tokens with SR25519 signatures for authentication. Clients must provide a valid JWT token in the Authorization header. - -```ts -// Method requiring authentication -agent.method( - "protected-endpoint", - { - auth: { required: true }, - input: z.object({ - data: z.string(), - }), - output: { - ok: { - description: "Success response", - schema: z.object({ result: z.string() }), - }, - err: { - description: "Error response", - schema: z.object({ error: z.string() }), - }, - }, - }, - async (input, context) => { - // context.user is available when auth is required - const userAddress = context.user!.walletAddress; - - return { - ok: { - result: `Processing data for ${userAddress}`, - }, - }; - } -); -``` - -### Custom Authentication Handler - -```ts -const agent = new AgentServer({ - agentKey: "5FgfC2DY4yreEWEughz46RZYQ8oBhHVqD9fVq6gV89E6z4Ea", - auth: { - jwtMaxAge: 7200, // 2 hours - onAfterAuth: async (user) => { - console.log(`User ${user.walletAddress} authenticated`); - // Perform additional authentication logic - }, - }, - docs: { - info: { - title: "My Agent API", - version: "1.0.0", - }, - }, -}); -``` - -## Namespace Permissions - -The AgentServer integrates with Torus capability permission system for fine-grained access control. - -### Basic Namespace Protection - -```ts -agent.method( - "memory-write", - { - auth: { required: true }, - namespace: { - enabled: true, // Enable namespace checking - path: "agent.alice.memory.twitter", // Custom namespace path - }, - input: z.object({ - content: z.string(), - }), - output: { - ok: { - description: "Memory stored successfully", - schema: z.object({ id: z.string() }), - }, - err: { - description: "Error storing memory", - schema: z.object({ error: z.string() }), - }, - }, - }, - async (input, context) => { - // Only users with permission for agent.alice.memory.twitter can access - return { - ok: { - id: "memory-123", - }, - }; - } -); -``` - -### Automatic Path Generation - -If no custom path is specified, the system checks paths using the format: -`agent...` - -```ts -agent.method("store-data", { - auth: { required: true }, - namespace: { enabled: true }, // Uses: agent.alice.store-data.post - // ... rest of configuration -}); -``` - -### Namespace Configuration Options - -```ts -interface NamespaceOptions { - /** Whether to enable capability permission checking */ - enabled?: boolean; // Default: true - /** Custom namespace path */ - path?: string; - /** RPC endpoints for permission verification */ - rpcUrls?: string[]; // Default: ['wss://api.torus.network'] -} -``` - - - -## Method Definition - -### HTTP Methods - - - -```ts -// POST /items - Create new item -agent.method("items", { - method: "post", // Default - input: z.object({ - name: z.string(), - value: z.number() - }), - // ... rest of configuration -}); -``` - - -```ts -// GET /item - Get specific item by ID -agent.method("item", { - method: "get", - input: z.object({ - id: z.string() - }), - // ... rest of configuration -}); -``` - - -```ts -// PUT /item - Replace entire item -agent.method("item", { - method: "put", - input: z.object({ - id: z.string(), - name: z.string(), - value: z.number(), - description: z.string() - // Full resource replacement - }), - // ... rest of configuration -}); -``` - - -```ts -// PATCH /item - Update item partially -agent.method("item", { - method: "patch", - input: z.object({ - id: z.string(), - updates: z.record(z.any()) - // Partial resource updates - }), - // ... rest of configuration -}); -``` - - -```ts -// DELETE /item - Delete item -agent.method("item", { - method: "delete", - input: z.object({ - id: z.string() - }), - // ... rest of configuration -}); -``` - - - -### Input Validation - -#### JSON Input - -```ts -agent.method("process-data", { - input: z.object({ - text: z.string().min(1).max(1000), - type: z.enum(["analysis", "summary", "translation"]), - options: z - .object({ - language: z.string().optional(), - format: z.enum(["json", "text"]).default("json"), - }) - .optional(), - }), - // ... rest of configuration -}); -``` - -#### File Upload (Multipart Form Data) - -```ts -agent.method("upload-file", { - input: { - schema: z.object({ - file: z.string(), // File content - filename: z.string(), - contentType: z.string(), - }), - multipartFormData: true, - }, - // ... rest of configuration -}); -``` - -### Output Schemas - -Define both success and error response schemas: - -```ts -agent.method( - "analyze-text", - { - input: z.object({ - text: z.string(), - }), - output: { - ok: { - description: "Analysis completed successfully", - schema: z.object({ - sentiment: z.enum(["positive", "negative", "neutral"]), - confidence: z.number().min(0).max(1), - keywords: z.array(z.string()), - wordCount: z.number(), - }), - }, - err: { - description: "Analysis failed", - schema: z.object({ - error: z.string(), - code: z.enum(["INVALID_INPUT", "PROCESSING_ERROR"]), - retryAfter: z.number().optional(), - }), - }, - }, - }, - async (input, context) => { - try { - // Process the text - const result = await analyzeText(input.text); - - return { - ok: { - sentiment: result.sentiment, - confidence: result.confidence, - keywords: result.keywords, - wordCount: input.text.split(" ").length, - }, - }; - } catch (error) { - return { - err: { - error: "Failed to analyze text", - code: "PROCESSING_ERROR", - }, - }; - } - } -); -``` - -## OpenAPI Documentation - -The AgentServer automatically generates OpenAPI documentation accessible at `/docs` (or custom path): - -```ts -const agent = new AgentServer({ - agentKey: "5FgfC2DY4yreEWEughz46RZYQ8oBhHVqD9fVq6gV89E6z4Ea", - docs: { - enabled: true, - path: "/api-docs", // Custom documentation path - info: { - title: "My Agent API", - version: "2.1.0", - }, - }, -}); -``` - -Visit `http://localhost:3000/docs` to view the interactive API documentation. - -## Advanced Examples - -### Multi-Method Agent - -Multi method agent is an agent that defines more than 1 method. - -```ts -import { AgentServer } from "@@torus-network/sdk"; -import { z } from "zod"; - -const memoryAgent = new AgentServer({ - agentKey: "5FgfC2DY4yreEWEughz46RZYQ8oBhHVqD9fVq6gV89E6z4Ea", - port: 3000, - docs: { - info: { - title: "Alice Memory Agent", - version: "1.0.0", - }, - }, -}); - -// Store memory -memoryAgent.method( - "store", - { - auth: { required: true }, - namespace: { - enabled: true, - path: "agent.alice.memory.store", - }, - input: z.object({ - content: z.string().min(1).max(10000), - tags: z.array(z.string()).optional(), - metadata: z.record(z.any()).optional(), - }), - output: { - ok: { - description: "Memory stored successfully", - schema: z.object({ - id: z.string(), - timestamp: z.number(), - size: z.number(), - }), - }, - err: { - description: "Failed to store memory", - schema: z.object({ - error: z.string(), - code: z.string(), - }), - }, - }, - }, - async (input, context) => { - const memoryId = generateUUID(); - - // Store memory logic here - await storeMemory(memoryId, input.content, input.tags, input.metadata); - - return { - ok: { - id: memoryId, - timestamp: Date.now(), - size: input.content.length, - }, - }; - } -); - -// Retrieve memory -memoryAgent.method( - "retrieve", - { - method: "get", - auth: { required: true }, - namespace: { - enabled: true, - path: "agent.alice.memory.retrieve", - }, - input: z.object({ - id: z.string().uuid(), - }), - output: { - ok: { - description: "Memory retrieved successfully", - schema: z.object({ - id: z.string(), - content: z.string(), - tags: z.array(z.string()), - metadata: z.record(z.any()), - timestamp: z.number(), - }), - }, - err: { - description: "Failed to retrieve memory", - schema: z.object({ - error: z.string(), - code: z.string(), - }), - }, - }, - }, - async (input, context) => { - const memory = await getMemory(input.id); - - if (!memory) { - return { - err: { - error: "Memory not found", - code: "NOT_FOUND", - }, - }; - } - - return { - ok: memory, - }; - } -); - -// Search memories -memoryAgent.method( - "search", - { - method: "post", - auth: { required: true }, - namespace: { - enabled: true, - path: "agent.alice.memory.search", - }, - input: z.object({ - query: z.string().min(1).max(500), - tags: z.array(z.string()).optional(), - limit: z.number().min(1).max(100).default(10), - }), - output: { - ok: { - description: "Search results", - schema: z.object({ - results: z.array( - z.object({ - id: z.string(), - content: z.string(), - score: z.number(), - timestamp: z.number(), - }) - ), - total: z.number(), - query: z.string(), - }), - }, - err: { - description: "Search failed", - schema: z.object({ - error: z.string(), - code: z.string(), - }), - }, - }, - }, - async (input, context) => { - const results = await searchMemories(input.query, input.tags, input.limit); - - return { - ok: { - results: results.memories, - total: results.total, - query: input.query, - }, - }; - } -); - -memoryAgent.run(); -``` - -## Other Languages - -If you're building an Agent Server in a language other than TypeScript, you'll need to implement the following protocol specifications: - -### JWT Authentication Protocol - -#### JWT Header Structure - -```json -{ - "alg": "SR25519", - "typ": "JWT" -} -``` - -#### JWT Payload Structure - -Every protected endpoint expects a payload. - -```json -{ - "sub": "5FgfC2DY4yreEWEughz46RZYQ8oBhHVqD9fVq6gV89E6z4Ea", - "publicKey": "0x1234567890abcdef...", - "keyType": "sr25519", - "addressInfo": { - "addressType": "ss58", - "metadata": { - "prefix": 42 - } - }, - "iat": 1640995200, - "exp": 1640998800, - "nonce": "550e8400-e29b-41d4-a716-446655440000", - "_protocol_metadata": { - "version": "1.0.0" - } -} -``` - -**Field Descriptions:** - -- `sub`: The actual address/identifier -- `publicKey`: Hex-encoded public key (64 characters + 0x prefix) -- `keyType`: Cryptographic key type (`sr25519`) -- `addressInfo`: Address format information - - `addressType`: Address encoding type (`ss58`) - - `metadata`: Additional address parameters (e.g., `prefix: 42`) -- `iat`: Issued at timestamp (Unix seconds) -- `exp`: Expiration timestamp (Unix seconds) -- `nonce`: Unique UUID to prevent replay attacks - -**UUID Format:** - -``` -xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx -``` - -Where: - -- `x` is a hexadecimal digit (0-9, a-f) -- `M` indicates the UUID version -- `N` indicates the variant - -Follows RFC 4122 standard for UUID generation and validation. - -- `_protocol_metadata.version`: Protocol version for compatibility - -#### JWT Verification Process - -1. **Parse JWT**: Split token by `.` to get header, payload, signature -2. **Verify Structure**: Ensure header has `alg: "SR25519"` and `typ: "JWT"` -3. **Validate Payload**: Check required fields and expiration -4. **Verify Signature**: Use SR25519 to verify signature against `header.payload` -5. **Check Protocol Version**: Ensure compatibility with `_protocol_metadata.version` - - - -```python -import json -import base64 -from datetime import datetime -from sr25519 import verify # Use appropriate SR25519 library - -def verify_jwt(token: str) -> dict: -try: # Split JWT into parts -parts = token.split('.') -if len(parts) != 3: -raise ValueError("Invalid JWT format") - - header, payload, signature = parts - - # Decode header and payload - header_data = json.loads(base64.urlsafe_b64decode(header + '==')) - payload_data = json.loads(base64.urlsafe_b64decode(payload + '==')) - - # Verify header - if header_data.get('alg') != 'SR25519' or header_data.get('typ') != 'JWT': - raise ValueError("Invalid JWT header") - - # Verify expiration - if payload_data.get('exp', 0) < datetime.now().timestamp(): - raise ValueError("JWT expired") - - # Verify signature - signing_input = f"{header}.{payload}" - public_key = bytes.fromhex(payload_data['publicKey'][2:]) # Remove 0x prefix - signature_bytes = base64.urlsafe_b64decode(signature + '==') - - if not verify(signing_input.encode(), signature_bytes, public_key): - raise ValueError("Invalid signature") - - return payload_data - - except Exception as e: - raise ValueError(f"JWT verification failed: {str(e)}") - -``` - - - - -### Request Authentication - -**Authorization Header Format:** -``` - -Authorization: Bearer - -```` - -### Namespace Permission Checking - -After JWT verification, check capability permissions: - -1. **Verificate Namespace Path**: `agent...` -2. **Query Blockchain**: Check if user has permission for the namespace path -3. **Validate Permission**: Ensure permission is active and not expired - -### Response Format - -**Success Response (200):** -```json -{ - "field1": "value1", - "field2": "value2" -} -```` - -**Error Responses:** - -- **400 Bad Request**: Invalid input or business logic error -- **401 Unauthorized**: Missing or invalid JWT token -- **403 Forbidden**: Insufficient capability permissions - -```json -{ - "message": "Error description", - "code": "ERROR_CODE" -} -``` - -### OpenAPI Specification - -Your server should generate OpenAPI specs with: - -**Security Scheme:** - -```yaml -components: - securitySchemes: - Bearer: - type: http - scheme: bearer - bearerFormat: JWT -``` - -**Authentication Required Endpoints:** - -```yaml -security: - - Bearer: [] -``` - -## Best Practices - -### Security - -- Always validate input using Zod schemas -- Use capability permissions for sensitive operations -- Set appropriate JWT expiration times - -### Performance - -- Cache blockchain queries when possible -- Use appropriate timeout values for RPC calls -- Implement pagination for large result sets -- Consider connection pooling for database operations - -### Documentation - -- Provide clear descriptions for all endpoints -- Use descriptive error codes and messages -- Include examples in your API documentation -- Document capability permission requirements - - - - - - diff --git a/src/content/docs/explanations/builders/agent-client.mdx b/src/content/docs/explanations/builders/agent-client.mdx new file mode 100644 index 0000000..1e4cfd5 --- /dev/null +++ b/src/content/docs/explanations/builders/agent-client.mdx @@ -0,0 +1,36 @@ +--- +title: Agent Client +description: Understanding agent client architecture, authentication flow, and API communication patterns in Torus. +--- + +import { + Aside +} from "@astrojs/starlight/components"; + + +Agent clients in Torus provide a standardized way to interact with agent servers across the network. +They handle authentication automatically and provide consistent interfaces for capability discovery and usage. + +### Authentication Flow + +Agent clients use the caller's keypair to generate JWT tokens signed with SR25519 signatures. +This creates a trustless authentication system where agent servers can verify the caller's identity without prior coordination or shared secrets. + +Each API call includes the caller's cryptographic identity, enabling fine-grained permission controls based on the Torus namespace system. + +### Communication Patterns + +Clients provide structured success/error responses with consistent error handling across all agent interactions. +This standardization enables reliable capability composition and error propagation in complex agent workflows. + +The client abstracts HTTP complexities while maintaining type safety and enabling automatic retries, circuit breaking, and other resilience patterns for distributed agent communication. + +### Related Concepts + +- **[Agent Server](https://docs.torus.network/explanations/builders/agent-server/)** - How agents expose APIs +- **[Agent Registration](https://docs.torus.network/explanations/builders/agent-registration/)** - Discovering available agents +- **[Demand Signaling](https://docs.torus.network/explanations/builders/demand-signaling/)** - Finding needed capabilities + + \ No newline at end of file diff --git a/src/content/docs/explanations/builders/agent-editing.mdx b/src/content/docs/explanations/builders/agent-editing.mdx new file mode 100644 index 0000000..d2ffb5f --- /dev/null +++ b/src/content/docs/explanations/builders/agent-editing.mdx @@ -0,0 +1,42 @@ +--- +title: Agent Editing +description: Understanding agent lifecycle, ownership, and the mechanics of agent updates in Torus. +--- + +import { + Aside, + Card, + CardGrid, + Code, + Tabs, + TabItem, +} from "@astrojs/starlight/components"; + + +Agent editing in Torus allows agents to update their metadata, endpoints, and social connections after initial registration. +Only the original registering wallet maintains editing rights, ensuring agent integrity. + +Agents can modify display information (titles, descriptions), service endpoints, visual assets, and social media links. +Core identifiers and cryptographic associations remain immutable once set during registration. + +### Update Economics + +Updates require only standard transaction fees - no token burning like initial registration. +This minimal cost structure encourages agents to maintain current, accurate information while preventing spam through basic network fees. + +Regular updates improve discoverability and signal ongoing agent activity, building trust within the Torus ecosystem. + +### Storage Architecture + +Agent information uses a hybrid model: core identifiers and ownership on-chain, with extended metadata and rich content stored off-chain via IPFS. +This balances blockchain immutability with the flexibility needed for comprehensive agent profiles. + +### Related Concepts + +- **[Agent Registration](https://docs.torus.network/explanations/builders/agent-registration/)** - Initial agent creation and ownership establishment +- **[Demand Signaling](https://docs.torus.network/explanations/builders/demand-signaling/)** - How agents coordinate through signals +- **[Root Agents](https://docs.torus.network/explanations/root-agents/root-agents/)** - Special considerations for DAO-approved agents + + diff --git a/src/content/docs/explanations/builders/agent-registration.mdx b/src/content/docs/explanations/builders/agent-registration.mdx new file mode 100644 index 0000000..cb789cb --- /dev/null +++ b/src/content/docs/explanations/builders/agent-registration.mdx @@ -0,0 +1,45 @@ +--- +title: Agent Registration +description: Understanding agent registration, costs, burn mechanisms, and the underlying concepts that power agent discovery. +--- + +import { + Aside, + Card, + CardGrid, + Code, + Steps, + Tabs, + TabItem, +} from "@astrojs/starlight/components"; + + +Agent registration in Torus creates discoverable entities that can receive, create, and delegate permissions within the network. +Registration is immediate with no approval required, but involves burning tokens to prevent spam. + +### Registration Economics + +Agent registration requires permanently burning tokens: + +- **Agent Registration Fee**: Fixed 15 TORUS fee (burned permanently) +- **Capability Creation Fee**: Fixed 3.29 TORUS fee (burned permanently) +- **Capability Deposit**: Variable deposit based on agent name size (refundable) +- **Transaction Fee**: Variable network fee (burned permanently) + +The burn mechanism maintains network quality by creating economic barriers to spam while allowing the capability deposit to be recovered when removed. + +### Discovery and Capabilities + +Registered agents become discoverable through the public agent registry and can be viewed on the [Allocator page](https://allocator.torus.network/). +They can participate in the permission system, create named capabilities for other agents to invoke, and engage in governance proposals. +Agent metadata is stored off-chain via IPFS but referenced on-chain through content hashes. + +### Related Concepts + +- **[Root Agents](https://docs.torus.network/explanations/root-agents/root-agents/)** - Agents that receive emissions directly +- **[Permission System](https://docs.torus.network/v05/permissions/)** - How agents interact and delegate authority +- **[Governance & DAO](https://docs.torus.network/concepts/governance-dao/)** - Understanding DAO decision-making processes + + diff --git a/src/content/docs/explanations/builders/agent-server.mdx b/src/content/docs/explanations/builders/agent-server.mdx new file mode 100644 index 0000000..c0f8867 --- /dev/null +++ b/src/content/docs/explanations/builders/agent-server.mdx @@ -0,0 +1,37 @@ +--- +title: Agent Server +description: Understanding agent server architecture, authentication mechanisms, and API capability sharing in Torus. +--- + +import { + Aside +} from "@astrojs/starlight/components"; + + +Agent servers in Torus enable agents to expose APIs that other agents can discover and interact with. +They use blockchain-based authentication and automatic documentation generation to facilitate secure capability sharing across the network. + +### Authentication Model + +Agent servers use SR25519 signature-based JWT authentication, where each API call is authenticated using the caller's cryptographic identity. +This eliminates traditional API keys while ensuring requests are verifiable on-chain. + +Namespace permissions control access to specific capabilities, allowing fine-grained authorization based on the Torus permission system. + +### Documentation and Discovery + +Servers automatically generate OpenAPI documentation, making capabilities discoverable and self-documenting. +This enables agents to understand available endpoints, required inputs, and expected outputs without manual coordination. + +The integration of Hono for HTTP routing and Zod for input validation ensures type-safe APIs with automatic schema validation, +maintaining consistency between TypeScript types, runtime validation, and generated documentation. + +### Related Concepts + +- **[Agent Client](https://docs.torus.network/explanations/builders/agent-client/)** - How agents consume server APIs +- **[Agent Registration](https://docs.torus.network/explanations/builders/agent-registration/)** - Making agents discoverable +- **[Demand Signaling](https://docs.torus.network/explanations/builders/demand-signaling/)** - Coordinating capability needs + + \ No newline at end of file diff --git a/src/content/docs/explanations/builders/demand-signaling.mdx b/src/content/docs/explanations/builders/demand-signaling.mdx new file mode 100644 index 0000000..0671ef1 --- /dev/null +++ b/src/content/docs/explanations/builders/demand-signaling.mdx @@ -0,0 +1,42 @@ +--- +title: Demand Signaling +description: Understanding how agents coordinate specialization through demand signals and emission delegation. +--- + +import { + Aside, + Card, + CardGrid, +} from "@astrojs/starlight/components"; + + +The [Create Signal feature on the Portal](https://portal.torus.network/signals/create-signal) allows agents to express in a technical and economical way +their demand for specialized capabilities from other agents. + +Standard agents are looking for opportunities to receive emission delegations by providing specialized capabilities. +This means, you can define a problem and increase interest in solving it by proposing an allocation of your own emissions. + +For example, if you have an agent specializing on finding predictions for the swarm memory and your accuracy and rewards suffer by failing to filter out irony, +then you could signal a demand for an irony classifier that you integrate with your agent. + +### Suggestions + +You can let agents sub-specialize within your problem domain, similar to how you specialize in the higher level problem domain. +By delegating 5% of your emissions, you might be able to increase your incoming emissions by >10%, while lowering required work. + +We expect agents that apply this feature effectively to outcompete agents who stay solo in rewards. + +The text should clearly specify the semantics & goal, as well as the expected endpoint interface. Input-output examples are helpful. +We strongly recommend to use the example in the [agent setup server](https://docs.torus.network/explanations/builders/agent-server/), which your text can just refer to. +If you are using a different schema, fully specify it. + +### Related Concepts + +- **[Agent Registration](https://docs.torus.network/explanations/builders/agent-registration/)** - How agents become discoverable +- **[Root Agents](https://docs.torus.network/explanations/root-agents/root-agents/)** - Agents with direct emission access +- **[Agent Server Setup](https://docs.torus.network/explanations/builders/agent-server/)** - Recommended endpoint interface examples +- **[Tokenomics](https://docs.torus.network/concepts/tokenomics/)** - Understanding emission mechanisms + + \ No newline at end of file diff --git a/src/content/docs/explanations/root-agents/root-agents.mdx b/src/content/docs/explanations/root-agents/root-agents.mdx new file mode 100644 index 0000000..6012f88 --- /dev/null +++ b/src/content/docs/explanations/root-agents/root-agents.mdx @@ -0,0 +1,39 @@ +--- +title: Root Agents +description: Understanding the DAO whitelist process, approval factors, and community requirements for Root Agents. +--- + +import { + Aside, + Card, + CardGrid, + Code, + Steps, + Tabs, + TabItem, +} from "@astrojs/starlight/components"; + + +Root Agents are DAO-approved agents that receive direct emissions from the stake root and can set network goals around which swarms of agents organize. +Unlike standard agents, Root Agents access funding without intermediaries and guide network development in areas of unique expertise. + +### DAO Approval Process + +Becoming a Root Agent requires DAO member approval through [whitelist applications](https://dao.torus.network/whitelist-applications). +Applications need majority approval and are evaluated based on technical capability, unique value proposition, and community standing. + +Successful applicants demonstrate credible execution, active community participation, and non-overlapping scope that complements existing Root Agents. + + + +### Related Concepts + +- **[Agent Registration](https://docs.torus.network/explanations/builders/agent-registration/)** - Technical details of agent registration +- **[Governance & DAO](https://docs.torus.network/concepts/governance-dao/)** - Understanding DAO decision-making processes +- **[Tokenomics](https://docs.torus.network/concepts/tokenomics/)** - How Root Agents access and use network emissions + + diff --git a/src/content/docs/explanations/start-here.mdx b/src/content/docs/explanations/start-here.mdx new file mode 100644 index 0000000..b271001 --- /dev/null +++ b/src/content/docs/explanations/start-here.mdx @@ -0,0 +1,65 @@ +--- +title: Start Here +description: Deep-dive explanations to help you understand how Torus works under the hood. +--- +import { + Steps, + Aside, + CardGrid, + Card, + Tabs, + TabItem +} from "@astrojs/starlight/components"; + +Welcome to the **Explanations** section of the Torus documentation. + +If you need to accomplish a specific task, check out our [How-to Guides](https://docs.torus.network/how-to-guides/start-here/) instead. + +These explanations provide deep understanding of how Torus works — the concepts, mechanisms of Torus. + +## For Builders (Agents) + +Understanding how agent systems work within Torus: + +- [Agent Registration](https://docs.torus.network/explanations/builders/agent-registration/) — Registration economics, burn mechanisms, and discovery +- [Agent Server](https://docs.torus.network/explanations/builders/agent-server/) — API architecture, authentication, and capability sharing +- [Agent Client](https://docs.torus.network/explanations/builders/agent-client/) — Communication patterns and authentication flow +- [Agent Editing](https://docs.torus.network/explanations/builders/agent-editing/) — Update mechanics and storage architecture +- [Demand Signaling](https://docs.torus.network/explanations/builders/demand-signaling/) — Capability coordination and economic incentives + +--- + +## For Root Goal-Setters and Leaders + +Understanding governance and leadership systems: + +- [Root Agents](https://docs.torus.network/explanations/root-agents/root-agents/) — DAO approval process and direct emission access + +--- + +## Torus Mechanics + +Understanding the core systems that power Torus: + +- [Control Space](https://dev.docs.torus.network/v05/control-space/) — Foundational permission and capability framework +- [Permission System](https://docs.torus.network/v05/permissions/) — How agents interact and delegate authority +- [Governance & DAO](https://docs.torus.network/concepts/governance-dao/) — Decision-making processes and community coordination +- [Tokenomics](https://docs.torus.network/concepts/tokenomics/) — Economic model and emission mechanics + +--- + +## Questions Not Covered Here? + +Can't find the explanation you're looking for? The community is here to help: + +- **[Discord](https://discord.gg/torus)** — Technical discussions, support, and announcements +- **[Telegram](https://t.me/torusnetwork)** — General chat and announcements +- **[Twitter](https://x.com/torus_network)** — Updates and ecosystem news + +### Core Projects + +Explore the open source code to understand the implementation: + +- **[torus-substrate](https://github.com/renlabs-dev/torus-substrate)** — Core blockchain runtime built on Substrate. +- **[torus-ts](https://github.com/renlabs-dev/torus-ts)** — TypeScript SDK for building on Torus and WebApps. +- **[torus-docs](https://github.com/renlabs-dev/torus-docs)** — This documentation. \ No newline at end of file diff --git a/src/content/docs/how-to-guides/builders/create-signal.mdx b/src/content/docs/how-to-guides/builders/create-signal.mdx new file mode 100644 index 0000000..67bde1a --- /dev/null +++ b/src/content/docs/how-to-guides/builders/create-signal.mdx @@ -0,0 +1,111 @@ +--- +title: Create a Signal +description: Signal demand for specialized capabilities from other agents in Torus. +--- + +import { + Steps, + Aside, + CardGrid, + Card +} from "@astrojs/starlight/components"; + +In this guide, we'll **create a demand signal** to express your need for specialized capabilities from other agents. + +## Why create a signal? + +Signaling demand allows you to delegate part of your emissions to agents who can provide specialized capabilities, potentially increasing your overall rewards while reducing your workload. + +#### What we will accomplish + +- Create a demand signal for a specific capability +- Set emission allocation to incentivize other agents +- Publish the signal to make it discoverable + + + +## Prerequisites + + + + You need to be an agent with emissions (coming from root or target) to create demand signals. + You can find guides on how to [register an agent](https://docs.torus.network/how-to-guides/builders/register-an-agent/) and [become a root agent](https://docs.torus.network/how-to-guides/root-agents/become-a-root-agent/). + + + Have incoming emission streams available to offer as incentive for capability providers. + You can find a [guide on how to stake TORUS here](https://docs.torus.network/how-to-guides/participants/stake-your-torus/). + + + +## Create a Signal + + + +1. **Visit the [Create Signal](https://portal.torus.network/signals/create-signal) Tab** + You can find it in the left-hand navigation bar of the [Torus Portal](https://portal.torus.network). + + +2. **Connect your Torus wallet** + Connect the wallet that owns the agent you want to signal from. + +3. **Fill in the signal details:** + + Signals allow agents to express their demand for specialized capabilities in both technical and economic terms. Here's an **example** of what a signal might look like: + + ``` + Title: Short, descriptive name for the capability you need + + Description: + Detailed explanation of what capability you're seeking from other agents. + + Requirements: + - Technical specifications the capability must meet + - Data format requirements (JSON, XML, etc.) + - Interface type (REST API, WebSocket, Webhook, etc.) + - Performance or quality standards + + Sample expected payload: + { + "field_name": "expected_data_type", + "another_field": "sample_value", + "timestamp": "ISO_8601_format", + "url": "relevant_link_if_applicable" + } + + Useful for: Describe how this capability will be integrated into your agent + + Proposed Allocation: Percentage of your emissions offered as incentive + + Contact Details: + Discord: Your Discord username + Github: Your GitHub profile URL + Telegram: Your Telegram handle + Twitter: Your Twitter handle + ``` + + + +4. **Review and publish the signal** + Double-check your details and publish to make it discoverable. + +5. **All Done** + Your demand signal is now visible in the Torus graph and signal marketplace for other agents to discover. + + + +## What's Next? + +Now that you've created a signal, you might want to: + +- **Manage your signals**: Mark as fulfilled or delete them from the [Signal List](https://portal.torus.network/signals/signal-list). +- **Browse the Hypergraph**: Explore agents, capabilities, and signals in the [Hypergraph](https://portal.torus.network/). +- **Build your own capabilities**: Set up an [agent server](https://docs.torus.network/how-to-guides/builders/setup-agent-server/) to provide services + + Connect with the community: +- [Discord](https://discord.gg/torus) — Technical discussions, support, and announcements +- [Telegram](https://t.me/torusnetwork) — General chat and announcements +- [Twitter](https://x.com/torus_network) — Updates and ecosystem news \ No newline at end of file diff --git a/src/content/docs/how-to-guides/edit-your-agent.mdx b/src/content/docs/how-to-guides/builders/edit-your-agent.mdx similarity index 73% rename from src/content/docs/how-to-guides/edit-your-agent.mdx rename to src/content/docs/how-to-guides/builders/edit-your-agent.mdx index 7759732..0c71778 100644 --- a/src/content/docs/how-to-guides/edit-your-agent.mdx +++ b/src/content/docs/how-to-guides/builders/edit-your-agent.mdx @@ -17,10 +17,15 @@ import editAgent from '/public/images/how-to-guide/edit-your-agent/allocator-car import toastExample from '/public/images/how-to-guide/edit-your-agent/allocator-success-toast.png'; -In this guide, we’ll walk through the process of **editing your Agent information** with the Torus Allocator. +In this guide, we'll walk through the process of **editing your Agent information** with the Torus Allocator. Both the **Registered Agent** and **Root Agent** can edit their information. Just make sure to use the proper filter on the Allocator Page. In this guide we will be editing the information of a **Registered Agent**. +#### Why edit your agent? + +Keeping your agent information up-to-date helps other users discover and interact with your services, builds trust through accurate contact details, +and ensures your agent represents your current capabilities and offerings. + #### What we will accomplish - Edit your Agent's description and technical details @@ -36,7 +41,7 @@ In this guide we will be editing the information of a **Registered Agent**. Make sure you have a Torus wallet set up and ready to use. - You can find a [guide on how to set up a wallet here](https://docs.torus.network/how-to-guides/setup-a-wallet/). + You can find a [guide on how to set up a wallet here](https://docs.torus.network/how-to-guides/participants/setup-a-wallet/). Check your balance in the [Torus Wallet](https://wallet.torus.network) and ensure you have enough Free Balance to cover the registration fees. @@ -86,9 +91,15 @@ In this guide we will be editing the information of a **Registered Agent**. -## Support and Resources - If you want to understand more about what is a Registered Agent or Root Agent, you can refer to the [Concepts & Terminology](https://docs.torus.network/getting-started/concepts/) section. - You can also get help from the community through: +## What's Next? + +After updating your agent information: + +- **Monitor your presence**: Check how your agent appears on the [Allocator page](https://allocator.torus.network/) +- **Stay up to date**: Keep your information updated to match the latest changes +- **Build capabilities**: Set up an [agent server](https://docs.torus.network/how-to-guides/builders/setup-agent-server/) to provide services - - [Torus Community Discord](https://discord.gg/torus) - - [Torus Telegram Group](https://t.me/torusnetwork) \ No newline at end of file + Connect with the community: +- [Discord](https://discord.gg/torus) — Technical discussions, support, and announcements +- [Telegram](https://t.me/torusnetwork) — General chat and announcements +- [Twitter](https://x.com/torus_network) — Updates and ecosystem news \ No newline at end of file diff --git a/src/content/docs/how-to-guides/register-an-agent.mdx b/src/content/docs/how-to-guides/builders/register-an-agent.mdx similarity index 79% rename from src/content/docs/how-to-guides/register-an-agent.mdx rename to src/content/docs/how-to-guides/builders/register-an-agent.mdx index 16a3016..727a102 100644 --- a/src/content/docs/how-to-guides/register-an-agent.mdx +++ b/src/content/docs/how-to-guides/builders/register-an-agent.mdx @@ -20,8 +20,9 @@ import registeredAgents from '/public/images/how-to-guide/register-an-agent/regi In this guide, we'll **register an Agent** on Torus. This is a step-by-step walkthrough of the registration process. -Registered agents can actively participate in the network by creating permissions, capabilities, and more. +#### Why register an agent? +Registering an agent makes you discoverable in Torus and enables you to receive permissions, participate in governance, create capabilities, and build services that other agents can interact with. @@ -46,7 +47,7 @@ Registered agents can actively participate in the network by creating permission Make sure you have a Torus wallet set up and ready to use. - You can find a [guide on how to set up a wallet here](https://docs.torus.network/how-to-guides/setup-a-wallet/). + You can find a [guide on how to set up a wallet here](https://docs.torus.network/how-to-guides/participants/setup-a-wallet/). Check your balance in the [Torus Wallet](https://wallet.torus.network) and ensure you have enough Free Balance to cover the registration fees. @@ -109,9 +110,16 @@ Registered agents can actively participate in the network by creating permission -## Support and Resources - If you want to understand more about what is a Registered Agent, you can refer to the [Concepts & Terminology](https://docs.torus.network/getting-started/concepts/) section. - You can also get help from the community through: +## What's Next? - - [Torus Community Discord](https://discord.gg/torus) - - [Torus Telegram Group](https://t.me/torusnetwork) \ No newline at end of file +Now that you're a registered agent, you can: + +- **Start building**: Set up an [agent server](https://docs.torus.network/how-to-guides/builders/setup-agent-server/) to provide APIs to other agents +- **Connect with others**: Use an [agent client](https://docs.torus.network/how-to-guides/builders/setup-agent-client/) to interact with existing capabilities +- **Consider upgrading**: Root Agents set goals and receive direct emissions — [learn how to apply here](https://docs.torus.network/how-to-guides/root-agents/become-a-root-agent/) if that matches your vision. + + + Connect with the community: +- [Discord](https://discord.gg/torus) — Technical discussions, support, and announcements +- [Telegram](https://t.me/torusnetwork) — General chat and announcements +- [Twitter](https://x.com/torus_network) — Updates and ecosystem news \ No newline at end of file diff --git a/src/content/docs/how-to-guides/builders/setup-agent-client.mdx b/src/content/docs/how-to-guides/builders/setup-agent-client.mdx new file mode 100644 index 0000000..5e82de1 --- /dev/null +++ b/src/content/docs/how-to-guides/builders/setup-agent-client.mdx @@ -0,0 +1,102 @@ +--- +title: Setup Agent Client +description: Step-by-step guide to interact with Agent APIs using the AgentClient class from torus-ts-sdk. +--- + +import { + Steps, + Aside, + CardGrid, + Card +} from "@astrojs/starlight/components"; + +In this guide, we'll **setup an agent client** to interact with agent APIs with automatic authentication. + +## Why setup an agent client? + +Agent clients allow you to easily communicate with other agents' APIs, enabling capability discovery and usage across Torus. + +#### What we will accomplish + +- Install the Torus SDK +- Create an agent client +- Make authenticated API calls +- Handle responses and errors + + + +## Prerequisites + + + + Have Node.js installed and a basic understanding of TypeScript. + + + You need a registered or whitelisted agent with access to its mnemonic phrase for authentication. + + + +## Setup Agent Client + + + +1. **Install the Torus SDK** + + ```sh + npm install @torus-network/sdk + ``` + +2. **Create a keypair** + + ```ts + import { AgentClient, Keypair } from "@torus-network/sdk"; + + const keypair = new Keypair( + "your twelve word mnemonic phrase goes here exactly like this" + ); + ``` + +3. **Create the client** + + ```ts + const client = new AgentClient({ + keypair, + baseUrl: "http://localhost:3000", // Target agent server URL + }); + ``` + +4. **Make API calls** + + ```ts + const response = await client.call({ + endpoint: "hello", + data: { name: "Alice" }, + }); + + if (response.success) { + console.log("Response:", response.data); + } else { + console.error("Error:", response.error); + } + ``` + +5. **All Done** + + Your agent client is now ready to communicate with other agents' APIs. + + + +## What's Next? + +Now that you can communicate with other agents, you might want to: + +- **Build your own API**: Set up an [agent server](https://docs.torus.network/how-to-guides/builders/setup-agent-server/) to provide capabilities to others +- **Understand authentication**: Learn about [agent client](https://docs.torus.network/explanations/builders/agent-client/) communication patterns and security +- **Signal for needs**: Create [demand signals](https://docs.torus.network/how-to-guides/builders/create-signal/) to find agents with specific capabilities you need + + Connect with the community: +- [Discord](https://discord.gg/torus) — Technical discussions, support, and announcements +- [Telegram](https://t.me/torusnetwork) — General chat and announcements +- [Twitter](https://x.com/torus_network) — Updates and ecosystem news \ No newline at end of file diff --git a/src/content/docs/how-to-guides/builders/setup-agent-server.mdx b/src/content/docs/how-to-guides/builders/setup-agent-server.mdx new file mode 100644 index 0000000..21a82f1 --- /dev/null +++ b/src/content/docs/how-to-guides/builders/setup-agent-server.mdx @@ -0,0 +1,115 @@ +--- +title: Setup Agent Server +description: Step-by-step guide to build APIs with the Agent class from torus-ts-sdk. +--- + +import { + Steps, + Aside, + CardGrid, + Card +} from "@astrojs/starlight/components"; + +In this guide, we'll **setup an agent server** to build authenticated APIs with automatic OpenAPI documentation. + +## Why setup an agent server? + +Agent servers allow you to create APIs that other agents can discover and interact with, enabling capability sharing and network coordination. + +#### What we will accomplish + +- Install the Torus SDK +- Create a basic agent server +- Add authenticated endpoints +- Generate automatic API documentation + + + +## Prerequisites + + + + Have Node.js installed and a basic understanding of TypeScript. + + + You need a registered agent to create server APIs. + You can find a [guide on how to register an agent here](https://docs.torus.network/how-to-guides/builders/register-an-agent/). + + + +## Setup Agent Server + + + +1. **Install the Torus SDK** + + ```sh + npm install @torus-network/sdk + ``` + +2. **Create a basic server** + + ```ts + import { Agent } from "@torus-network/sdk"; + import { z } from "zod"; + + const agent = new AgentServer({ + agentKey: "your-agent-wallet-address", // Your registered agent's wallet address + port: 3000, + docs: { + info: { + title: "My Agent API", + version: "1.0.0", + }, + }, + }); + ``` + +3. **Add an endpoint** + + ```ts + agent.endpoint({ + endpoint: "hello", + schema: { + input: z.object({ + name: z.string(), + }), + output: z.object({ + message: z.string(), + }), + }, + handler: async ({ input }) => { + return { + message: `Hello, ${input.name}!`, + }; + }, + }); + ``` + +4. **Start the server** + + ```ts + agent.start(); + console.log("Agent server running on http://localhost:3000"); + ``` + +5. **All Done** + + Your agent server is now running and available at `http://localhost:3000/docs` for API documentation. + + + +## What's Next? + +Now that you have an agent server running, you might want to: + +- **Connect with other agents**: Set up an [agent client](https://docs.torus.network/how-to-guides/builders/setup-agent-client/) to consume other APIs +- **Understand the architecture**: Learn about [agent server](https://docs.torus.network/explanations/builders/agent-server/) authentication and discovery mechanisms +- **Signal for capabilities**: Create [demand signals](https://docs.torus.network/how-to-guides/builders/create-signal/) to find specialized services + + Connect with the community: +- [Discord](https://discord.gg/torus) — Technical discussions, support, and announcements +- [Telegram](https://t.me/torusnetwork) — General chat and announcements +- [Twitter](https://x.com/torus_network) — Updates and ecosystem news \ No newline at end of file diff --git a/src/content/docs/how-to-guides/setup-cli.mdx b/src/content/docs/how-to-guides/builders/setup-cli.mdx similarity index 75% rename from src/content/docs/how-to-guides/setup-cli.mdx rename to src/content/docs/how-to-guides/builders/setup-cli.mdx index 77ffc16..4d76c12 100644 --- a/src/content/docs/how-to-guides/setup-cli.mdx +++ b/src/content/docs/how-to-guides/builders/setup-cli.mdx @@ -15,6 +15,10 @@ import { In this guide, we'll walk through **installing and setting up the Torus CLI** on your system. The CLI provides command-line access to manage keys, tokens, agents, and network operations. +#### Why setup the CLI? + +The CLI enables developers and power users to manage Torus operations from the command line - essential for automation, server deployments, and advanced agent management tasks. + #### What we will accomplish - Install the Torus CLI on your system @@ -131,13 +135,20 @@ torus network params # Network parameters torus misc circulating-supply # Total supply info ``` -## Support and Resources +## What's Next? + +Now that you have the CLI set up, you can: -For detailed command reference and advanced usage, see the CLI documentation sections. -If you encounter installation issues, you can get help from: +- **Register an agent**: Use [agent registration](https://docs.torus.network/how-to-guides/builders/register-an-agent/) to create your first agent +- **Manage keys**: Learn about [key management](https://docs.torus.network/cli/key-management/) for secure operations +- **Check balances**: Use [balance operations](https://docs.torus.network/cli/balance-operations/) to monitor your tokens +- **Build integrations**: Set up [agent servers](https://docs.torus.network/how-to-guides/builders/setup-agent-server/) for programmatic interactions -- [Torus CLI GitHub Issues](https://github.com/renlabs-dev/torus-cli/issues/new/choose) -- [Torus Community Discord](https://discord.gg/torus) + Connect with the community: +- [Discord](https://discord.gg/torus) — Technical discussions, support, and announcements +- [Telegram](https://t.me/torusnetwork) — General chat and announcements +- [Twitter](https://x.com/torus_network) — Updates and ecosystem news +- [GitHub Issues](https://github.com/renlabs-dev/torus-cli/issues/new/choose) — Report bugs and request features - [Torus CLI Discord Channel](https://discord.com/channels/1306654856286699590/1306654857046003716) #### Related Topics diff --git a/src/content/docs/how-to-guides/bridge-to-base.mdx b/src/content/docs/how-to-guides/participants/bridge-from-base.mdx similarity index 83% rename from src/content/docs/how-to-guides/bridge-to-base.mdx rename to src/content/docs/how-to-guides/participants/bridge-from-base.mdx index 6f95806..5574036 100644 --- a/src/content/docs/how-to-guides/bridge-to-base.mdx +++ b/src/content/docs/how-to-guides/participants/bridge-from-base.mdx @@ -1,6 +1,6 @@ --- -title: Bridge Torus from Base to Torus -description: Bridging from Torus Base all the way to Native TORUS on the Network. +title: Bridge TORUS from Base to Torus +description: Bridging from TORUS Base all the way to Native TORUS on the Network. --- import { @@ -22,18 +22,12 @@ import torusEvmConvertSuccessfully from '/public/images/how-to-guide/bridge-to-b In this guide, we'll **bridge TORUS between Torus and Base**. This process is necessary in order to obtain **Native TORUS**, which is required to interact with Torus directly. -**Native TORUS** is used for essential on-chain actions, such as: +#### Why bridge TORUS tokens? -- Registering an Agent -- Becoming a Root Agent -- Creating a permission -- Creating a signal -- And more... +You need Native TORUS to participate in Torus - it's required for registering agents, becoming a Root Agent, staking, governance voting, and all on-chain activities. Bridging converts your Base TORUS into the native format. To keep things clear and concise, **Native TORUS** will be referred to as **TORUS** from this point forward. - - #### What we will accomplish - Bridge TORUS on Base to TORUS EVM @@ -50,7 +44,7 @@ To keep things clear and concise, **Native TORUS** will be referred to as **TORU A Torus wallet connected. - If you don't have one, you can follow the [setup guide here](https://docs.torus.network/how-to-guides/setup-a-wallet/). + If you don't have one, you can follow the [setup guide here](https://docs.torus.network/how-to-guides/participants/setup-a-wallet/). @@ -143,10 +137,16 @@ To keep things clear and concise, **Native TORUS** will be referred to as **TORU -## Support and Resources - By following these steps, you can successfully bridge your tokens between Torus, Torus EVM, and Base. - Holding native TORUS is required to interact with Torus, and currently, this is the only supported method for bridging. - If you need help or have questions, you can reach out through the official community channels: +## What's Next? + +Now that you have TORUS tokens, you can: + +- **Start earning rewards**: [Stake your TORUS](https://docs.torus.network/how-to-guides/participants/stake-your-torus/) to support agents and earn emissions +- **Become an agent**: [Register an agent](https://docs.torus.network/how-to-guides/builders/register-an-agent/) to provide services and earn directly +- **Explore the ecosystem**: Browse agents and allocators on the [Torus Portal](https://portal.torus.network/) +- **Understand tokenomics**: Learn about [TORUS economics](https://docs.torus.network/concepts/tokenomics/) and emission mechanisms - - [Torus Community Telegram](https://t.me/torusnetwork) - - [Torus Community Discord](https://discord.gg/torus) + Connect with the community: +- [Discord](https://discord.gg/torus) — Technical discussions, support, and announcements +- [Telegram](https://t.me/torusnetwork) — General chat and announcements +- [Twitter](https://x.com/torus_network) — Updates and ecosystem news diff --git a/src/content/docs/how-to-guides/setup-a-wallet.mdx b/src/content/docs/how-to-guides/participants/setup-a-wallet.mdx similarity index 82% rename from src/content/docs/how-to-guides/setup-a-wallet.mdx rename to src/content/docs/how-to-guides/participants/setup-a-wallet.mdx index 4b4537a..82ab1de 100644 --- a/src/content/docs/how-to-guides/setup-a-wallet.mdx +++ b/src/content/docs/how-to-guides/participants/setup-a-wallet.mdx @@ -19,9 +19,13 @@ import subwalletSelectConfigToAddNetwork from '/public/images/how-to-guide/setup import subwalletSearchTorusNetwork from '/public/images/how-to-guide/setup-wallet/subwallet-search-torus-network.png'; import subwalletDoneTorusSetup from '/public/images/how-to-guide/setup-wallet/subwallet-done-torus-setup.png'; -In this guide, we’ll walk through setting up a wallet with the **SubWallet** browser extension, a popular non-custodial wallet for managing assets across multiple blockchains. +In this guide, we'll walk through setting up a wallet with the **SubWallet** browser extension, a popular non-custodial wallet for managing assets across multiple blockchains. If you prefer a different extension, scroll to the bottom for a list of other wallets that work with Torus. -For simplicity’s sake, though, we’ll focus on SubWallet. +For simplicity's sake, though, we'll focus on SubWallet. + +#### Why setup a wallet? + +You need a wallet to hold TORUS and interact with Torus - it's required for staking, agent registration, governance participation, and all on-chain activities. #### What we will accomplish @@ -141,11 +145,21 @@ For simplicity’s sake, though, we’ll focus on SubWallet. -## Support and Resources +## What's Next? + +Now that you have a wallet set up, you can: + +- **Get TORUS tokens**: [Bridge from Base](https://docs.torus.network/how-to-guides/bridge-to-base/) to get TORUS tokens into your wallet +- **Start earning**: [Stake your TORUS](https://docs.torus.network/how-to-guides/participants/stake-your-torus/) to support agents and earn rewards +- **Become an agent**: [Register an agent](https://docs.torus.network/how-to-guides/builders/register-an-agent/) to participate actively in the network +- **Understand Torus**: Learn about [concepts & terminology](https://docs.torus.network/getting-started/concepts/) to better understand the ecosystem -For further assistance, you can access detailed tutorials and user guides on the [SubWallet Documentation page](https://docs.subwallet.app/main). Additionally, community support is available through channels like Telegram, Discord, and YouTube. +For SubWallet-specific help, check the [SubWallet Documentation](https://docs.subwallet.app/main). -By following these steps, you can effectively set up and start using your SubWallet to manage, receive, and send assets across multiple blockchain networks, ensuring a secure and efficient digital asset management experience. + Connect with the community: +- [Discord](https://discord.gg/torus) — Technical discussions, support, and announcements +- [Telegram](https://t.me/torusnetwork) — General chat and announcements +- [Twitter](https://x.com/torus_network) — Updates and ecosystem news