Node.js SDK
Node.js SDK
Section titled “Node.js SDK”The Hyra Node.js SDK (@hyra-ai/hyra-client) is a comprehensive JavaScript/TypeScript library for interacting with the Hyra decentralized AI inference platform. It provides AI model integration, ZKP (Zero-Knowledge Proof) verification, and automated task management.
Installation
Section titled “Installation”npm install @hyra-ai/hyra-client# oryarn add @hyra-ai/hyra-client# orpnpm add @hyra-ai/hyra-client# orbun add @hyra-ai/hyra-clientQuick Start
Section titled “Quick Start”import { HyraClient } from '@hyra-ai/hyra-client';
// Initialize the client with your private keyconst privateKey = '0x...'; // Your Ethereum private keyconst client = new HyraClient(privateKey);
// Claim a taskconst task = await client.claimTask();console.log('Task claimed:', task);console.log('Task ID:', task.taskId);console.log('Model:', task.model.type);console.log('Input:', task.inputDecryptedData);
// Submit the task resultconst txHash = await client.submitTask(task.taskId, 'Your AI inference result');console.log('Task submitted:', txHash);API Reference
Section titled “API Reference”HyraClient
Section titled “HyraClient”Main client class for interacting with the Hyra Network.
Constructor
Section titled “Constructor”constructor(privateKey: string)Parameters:
privateKey: Your Ethereum private key (must start with0x)
Example:
const client = new HyraClient('0x1234567890abcdef...');Core Methods
Section titled “Core Methods”claimTask()
Section titled “claimTask()”Claims an available task from the network. If you already have an active task, it returns the current task details.
async claimTask(): Promise<TaskInfo>Returns: Promise resolving to a task object:
{ taskId: number; taskPool: string; reward: string; // Reward in ETH (formatted) deadline: string; // ISO 8601 timestamp assignedTo: string; // Wallet address requestId: number; model: { id: number; type: string; url: string; pricingType: number; isActive: boolean; createdAt: string; // ISO 8601 timestamp tokenPrice: string; // Price in ETH (formatted) }; inputRawData: string; inputDecryptedData: string; // Decrypted input data for AI processing}Example:
const task = await client.claimTask();console.log('Task ID:', task.taskId);console.log('Model:', task.model.type);console.log('Input:', task.inputDecryptedData);console.log('Reward:', task.reward);submitTask(taskId: number, result: string)
Section titled “submitTask(taskId: number, result: string)”Submits the result of a completed AI inference task. The result is encrypted and includes a zero-knowledge proof.
Parameters:
taskId: The ID of the task to submitresult: The AI inference result as a string
Returns: Promise resolving to the transaction hash (string)
Example:
const task = await client.claimTask();// ... process the task with your AI model ...const result = 'Your AI inference result here';const txHash = await client.submitTask(task.taskId, result);console.log('Transaction hash:', txHash);currentStatus()
Section titled “currentStatus()”Gets the current status of your active task.
async currentStatus(): Promise<UserStatus>Returns: Promise resolving to user status object:
{ activePool: string; activeTaskId: number; deadline: string; // ISO 8601 timestamp reward: number; // Reward in ETH hasActiveTask: boolean;}Example:
const status = await client.currentStatus();if (status.hasActiveTask) { console.log('Active task ID:', status.activeTaskId); console.log('Deadline:', status.deadline); console.log('Reward:', status.reward);}Task Management Methods
Section titled “Task Management Methods”taskDetails(poolAddress: string, taskId: number)
Section titled “taskDetails(poolAddress: string, taskId: number)”Gets detailed information about a specific task in a pool.
Parameters:
poolAddress: The address of the task pooltaskId: The ID of the task
Returns: Promise resolving to task details object:
{ taskId: number; reward: number; // Reward in ETH deadline: string; // ISO 8601 timestamp assignedTo: string; // Wallet address requestId: number; model: { id: string; // Model ID as string type: string; url: string; };}Example:
const details = await client.taskDetails('0x...', 123);console.log('Task reward:', details.reward);console.log('Model:', details.model.type);Network Statistics Methods
Section titled “Network Statistics Methods”getPoolsStatus()
Section titled “getPoolsStatus()”Gets global statistics about all pools in the network.
async getPoolsStatus(): Promise<PoolStats>Returns: Promise resolving to pool statistics:
{ totalPools: number; activePools: number; totalAvailableTasks: number; totalActiveTasks: number; totalPendingTasks: number; totalProcessedTasks: number; totalRewardsDistributed: number; // Total rewards in ETH}Example:
const stats = await client.getPoolsStatus();console.log('Total pools:', stats.totalPools);console.log('Available tasks:', stats.totalAvailableTasks);console.log('Total rewards distributed:', stats.totalRewardsDistributed);estimateClaimGas(poolAddress: string)
Section titled “estimateClaimGas(poolAddress: string)”Estimates the gas cost for claiming a task from a specific pool.
Parameters:
poolAddress: The address of the task pool
Returns: Promise resolving to the estimated gas cost (bigint)
Example:
const gasEstimate = await client.estimateClaimGas('0x...');console.log('Estimated gas:', gasEstimate.toString());Model Management Methods
Section titled “Model Management Methods”getActiveModels()
Section titled “getActiveModels()”Gets a list of all active model IDs in the registry.
async getActiveModels(): Promise<string[]>Returns: Promise resolving to an array of model IDs (strings)
Example:
const modelIds = await client.getActiveModels();console.log('Active models:', modelIds);getModelDetail(modelId: string)
Section titled “getModelDetail(modelId: string)”Gets detailed information about a specific AI model.
Parameters:
modelId: The ID of the model
Returns: Promise resolving to model details:
{ name: string; description: string; modelPricingType: number; isActive: boolean; createdAt: number; // Unix timestamp tokenPrice: number; // Price in ETH}Example:
const model = await client.getModelDetail('1');console.log('Model name:', model.name);console.log('Price:', model.tokenPrice);console.log('Active:', model.isActive);getInferenceRequest(requestId: number)
Section titled “getInferenceRequest(requestId: number)”Gets details about a specific inference request.
Parameters:
requestId: The ID of the inference request
Returns: Promise resolving to request details:
{ user: string; // Wallet address of the requester modelId: string; prompt: string; tokenCount: number; totalCost: number; // Cost in ETH timestamp: number; // Unix timestamp resultData: string; hasResult: boolean;}Example:
const request = await client.getInferenceRequest(123);console.log('Prompt:', request.prompt);console.log('Has result:', request.hasResult);console.log('Total cost:', request.totalCost);Utility Methods
Section titled “Utility Methods”getContractAddresses()
Section titled “getContractAddresses()”Gets the addresses of all deployed contracts used by the SDK.
getContractAddresses(): ContractAddressesReturns: Object containing contract addresses:
{ poolRouter: string; modelRegistry: string; publicKeyVault: string;}Example:
const addresses = client.getContractAddresses();console.log('Pool Router:', addresses.poolRouter);console.log('Model Registry:', addresses.modelRegistry);Complete Examples
Section titled “Complete Examples”Complete Task Workflow
Section titled “Complete Task Workflow”import { HyraClient } from '@hyra-ai/hyra-client';
const client = new HyraClient('0x...');
// Check current statusconst status = await client.currentStatus();if (status.hasActiveTask) { console.log(`You have an active task: ${status.activeTaskId}`); // You would need to submit the current task first}
// Claim a new taskconst task = await client.claimTask();console.log(`New task: ${task.taskId}`);console.log(`Model: ${task.model.type}`);console.log(`Input: ${task.inputDecryptedData}`);
// Process the task (your AI logic here)const result = await processAiTask(task.inputDecryptedData, task.model.type);
// Submit the resultconst txHash = await client.submitTask(task.taskId, result);console.log(`Task completed: ${txHash}`);Monitor Network Statistics
Section titled “Monitor Network Statistics”import { HyraClient } from '@hyra-ai/hyra-client';
const client = new HyraClient('0x...');
// Get global statisticsconst stats = await client.getPoolsStatus();console.log(`Total pools: ${stats.totalPools}`);console.log(`Active pools: ${stats.activePools}`);console.log(`Available tasks: ${stats.totalAvailableTasks}`);console.log(`Total rewards distributed: ${stats.totalRewardsDistributed} ETH`);
// Get active modelsconst modelIds = await client.getActiveModels();console.log(`Active models: ${modelIds.length}`);
// Get model detailsfor (const modelId of modelIds) { const model = await client.getModelDetail(modelId); console.log(`Model: ${model.name} - ${model.tokenPrice} ETH per token`);}Error Handling
Section titled “Error Handling”import { HyraClient } from '@hyra-ai/hyra-client';
const client = new HyraClient('0x...');
try { const task = await client.claimTask(); const result = await processAiTask(task.inputDecryptedData); const txHash = await client.submitTask(task.taskId, result); console.log(`Success: ${txHash}`);} catch (error) { console.error(`Error: ${error.message}`); // Common errors: // - "No active task found" - No task is currently assigned // - "Task ID mismatch" - The task ID doesn't match your active task // - "Failed to decrypt input data" - Decryption service error // - "Failed to generate proof" - ZKP generation failed // - "Failed to get model details" - Model not found or inactive // - "Failed to get task details" - Task not found in the specified pool}Features
Section titled “Features”- 🔐 Secure: End-to-end encryption for task data
- 🔒 Zero-Knowledge Proofs: ZKP verification for AI inference results
- ⚡ Fast: Optimized for performance
- 📦 TypeScript: Full TypeScript support with type definitions
- 🌐 Blockchain: Built on Ethereum-compatible networks
Requirements
Section titled “Requirements”- Node.js 18+ or Bun
- An Ethereum wallet with a private key
- Sufficient balance for gas fees
Network Configuration
Section titled “Network Configuration”The SDK is currently configured for the Hyra testnet:
- RPC URL: https://rpc-testnet.hyra.network
- Chain ID:
34131050525
TypeScript Support
Section titled “TypeScript Support”The SDK includes comprehensive TypeScript definitions:
import { HyraClient } from '@hyra-ai/hyra-client';
const client = new HyraClient('0x...');
// Type-safe task claimingconst task = await client.claimTask();console.log(`Task ID: ${task.taskId}`); // TypeScript knows taskId is number
// Type-safe status checkingconst status = await client.currentStatus();if (status.hasActiveTask) { console.log(`Active task: ${status.activeTaskId}`);}Security
Section titled “Security”Private Key Security
Section titled “Private Key Security”- Never commit private keys to version control
- Use environment variables for production deployments
- ZKP Verification: All task submissions are verified using Zero-Knowledge Proofs
- Smart Contract Integration: Direct interaction with audited smart contracts
Architecture
Section titled “Architecture”The Hyra SDK interacts with several smart contracts:
- Task Pool Router: Routes tasks to optimal pools
- Task Pool: Manages individual task pools
- Model Registry: Manages AI model information
- Public Key Vault: Stores encryption keys
Workflow
Section titled “Workflow”- Initialize the client with your private key
- Claim a task from the marketplace
- Process the task using the specified AI model
- Submit the result with ZKP proof
- Earn rewards for completed tasks
Support
Section titled “Support”- Documentation: https://docs.hyra.network
- Discord: https://discord.gg/hyra
- GitHub Issues: https://github.com/hyra-network/hyra-nodejs-sdk/issues
Built with ❤️ by the Hyra team