Task Pool
Task Pool
Section titled “Task Pool”The TaskPoolImplementation is the core task pool contract that manages AI tasks with full metadata support. It handles task creation, assignment, processing, and reward distribution in the Hyra Network.
Overview
Section titled “Overview”The TaskPoolImplementation contract serves as the central hub for AI task management, providing:
- Task Management: Create, assign, and track AI tasks
- Queue Management: Efficient task distribution and queuing
- ZKP Verification: Handle Zero-Knowledge Proof verification
- Reward Distribution: Manage HYRA token rewards for completed tasks
- Integration: Seamless integration with ModelRegistry and TaskRouter
Key Features
Section titled “Key Features”Extended Task Structure
Section titled “Extended Task Structure”- AI-Specific Fields: requestId, modelId, inputData, resultData
- Task Metadata: Complete task information for AI workers
- ZKP Integration: Built-in support for Zero-Knowledge Proofs
- Reward Management: Transparent reward calculation and distribution
Queue Management
Section titled “Queue Management”- Efficient Distribution: Optimized task assignment algorithms
- Load Balancing: Distribute tasks across multiple workers
- Deadline Management: Handle task expiration and release
- Priority Queuing: Support for task prioritization
ZKP Verification
Section titled “ZKP Verification”- Proof Validation: Verify Zero-Knowledge Proofs
- Anti-Cheating: Prevent workers from submitting fake results
- Privacy Protection: Maintain input/output privacy
- Automated Verification: Streamlined verification process
Contract Structure
Section titled “Contract Structure”State Variables
Section titled “State Variables”// Task managementmapping(uint256 => Task) public tasks;mapping(address => uint256) public userActiveTask;uint256 public taskCounter;
// Pool informationaddress public owner;bool public isActive;string public category;string public metadata;
// System integrationaddress public modelRegistry;address public zkpVerifier;Data Structures
Section titled “Data Structures”Task Struct
Section titled “Task Struct”struct Task { uint256 taskId; // Unique task identifier address assignedTo; // Worker assigned to task uint256 reward; // Reward amount in HYRA uint256 deadline; // Task deadline timestamp bool isCompleted; // Completion status bool isVerified; // Verification status
// AI-specific fields uint256 requestId; // ModelRegistry request ID string modelId; // AI model identifier string inputData; // Task input data string resultData; // AI result data
// ZKP fields string resultHash; // Result hash for verification bytes zkpProof; // Zero-Knowledge Proof uint256 zkpPublicInput; // ZKP public input uint256 zkpPublicResult; // ZKP public result}Core Functions
Section titled “Core Functions”Task Management
Section titled “Task Management”Add AI Tasks
Section titled “Add AI Tasks”function addAITasks( uint256[] calldata rewards, uint256[] calldata requestIds, string[] calldata modelIds, string[] calldata inputData, uint256[] calldata deadlines) external payable onlyOwnerOrModelRegistryParameters:
rewards: Array of reward amounts in HYRArequestIds: Array of ModelRegistry request IDsmodelIds: Array of AI model identifiersinputData: Array of task input datadeadlines: Array of task deadline timestamps
Access Control: Only owner or ModelRegistry can add tasks
Example:
// Add multiple AI tasksconst rewards = [ethers.parseEther("0.1"), ethers.parseEther("0.2")];const requestIds = [1, 2];const modelIds = ["llm-chat-v1", "image-classifier-v1"];const inputData = ["What is AI?", "Classify this image"];const deadlines = [Date.now() + 3600, Date.now() + 7200]; // 1 hour, 2 hours
await taskPool.addAITasks( rewards, requestIds, modelIds, inputData, deadlines, { value: ethers.parseEther("0.3") } // Total rewards);Claim Task for User
Section titled “Claim Task for User”function claimTaskForUser(address user) external returns (uint256 taskId)Parameters:
user: Address of the user claiming the task
Returns:
taskId: ID of the claimed task
Example:
// AI worker claims a taskconst taskId = await taskPool.claimTaskForUser(aiWorker.address);console.log(`Claimed task ID: ${taskId}`);
// Get task detailsconst task = await taskPool.tasks(taskId);console.log(`Model ID: ${task.modelId}`);console.log(`Input: ${task.inputData}`);console.log(`Reward: ${ethers.formatEther(task.reward)} HYRA`);Task Submission
Section titled “Task Submission”Submit Task for User
Section titled “Submit Task for User”function submitTaskForUser( address user, uint256 taskId, string calldata resultHash, bytes calldata zkpProof, uint256 zkpPublicInput, uint256 zkpPublicResult, string calldata resultData) externalParameters:
user: Address of the user submitting the tasktaskId: ID of the task being submittedresultHash: Hash of the result for verificationzkpProof: Zero-Knowledge ProofzkpPublicInput: ZKP public inputzkpPublicResult: ZKP public resultresultData: AI result data
Example:
// AI worker submits task resultawait taskPool.submitTaskForUser( aiWorker.address, taskId, "0x1234567890abcdef", // Result hash "0x1234567890abcdef", // ZKP proof 123, // ZKP public input 456, // ZKP public result "The capital of France is Paris." // AI result);ZKP Verification
Section titled “ZKP Verification”Verify and Pay
Section titled “Verify and Pay”function verifyAndPay( uint256 taskId, bool isValid) external onlyVerifierParameters:
taskId: ID of the task to verifyisValid: Whether the ZKP proof is valid
Access Control: Only verifiers can verify and pay
Example:
// Verifier validates ZKP proof and pays rewardsawait taskPool.connect(verifier).verifyAndPay(taskId, true);
// Check if task is verifiedconst task = await taskPool.tasks(taskId);console.log(`Task verified: ${task.isVerified}`);Task Lifecycle
Section titled “Task Lifecycle”1. Task Creation
Section titled “1. Task Creation”// ModelRegistry creates tasks automaticallyawait modelRegistry.requestInference("llm-chat-v1", "Hello world");2. Task Assignment
Section titled “2. Task Assignment”// AI worker claims taskconst taskId = await taskPool.claimTaskForUser(aiWorker.address);3. Task Processing
Section titled “3. Task Processing”// AI worker processes task (off-chain)const result = await processAITask(task.inputData, task.modelId);4. Result Submission
Section titled “4. Result Submission”// AI worker submits result with ZKP proofawait taskPool.submitTaskForUser( aiWorker.address, taskId, resultHash, zkpProof, zkpPublicInput, zkpPublicResult, result);5. Verification and Payment
Section titled “5. Verification and Payment”// Verifier validates and pays rewardsawait taskPool.connect(verifier).verifyAndPay(taskId, true);Events
Section titled “Events”Task Events
Section titled “Task Events”event TasksAdded( uint256[] taskIds, uint256[] requestIds, string[] modelIds);
event TaskClaimed( address indexed user, uint256 indexed taskId);
event TaskSubmitted( address indexed user, uint256 indexed taskId, string resultHash);
event TaskVerified( uint256 indexed taskId, bool isValid, uint256 reward);Pool Events
Section titled “Pool Events”event PoolActivated(address indexed pool);event PoolDeactivated(address indexed pool);event PoolFunded(address indexed pool, uint256 amount);Access Control
Section titled “Access Control”Owner Functions
Section titled “Owner Functions”addAITasks(): Add new AI tasksactivatePool(): Activate the pooldeactivatePool(): Deactivate the poolsetModelRegistry(): Set ModelRegistry addresssetZKPVerifier(): Set ZKP verifier addresswithdrawFunds(): Withdraw pool funds
Verifier Functions
Section titled “Verifier Functions”verifyAndPay(): Verify ZKP proofs and pay rewards
Public Functions
Section titled “Public Functions”claimTaskForUser(): Claim taskssubmitTaskForUser(): Submit task resultsgetTask(): Get task detailsgetUserActiveTask(): Get user’s active task
Integration with Other Contracts
Section titled “Integration with Other Contracts”ModelRegistry Integration
Section titled “ModelRegistry Integration”// ModelRegistry creates tasksawait modelRegistry.requestInference(modelId, prompt);
// TaskPool receives tasks automatically// Results are updated in ModelRegistryTaskRouter Integration
Section titled “TaskRouter Integration”// TaskRouter helps workers find tasksconst taskId = await taskRouter.claimBestTask();
// TaskRouter submits resultsawait taskRouter.submitTask(poolAddress, taskId, resultHash, zkpProof, ...);Error Handling
Section titled “Error Handling”Custom Errors
Section titled “Custom Errors”error TaskNotFound(); // Task doesn't existerror TaskAlreadyClaimed(); // Task already claimederror TaskNotClaimed(); // Task not claimed by usererror TaskExpired(); // Task deadline passederror InvalidZKPProof(); // ZKP proof is invaliderror InsufficientFunds(); // Not enough funds for rewardserror Unauthorized(); // Access deniedInput Validation
Section titled “Input Validation”- Task existence checks
- Deadline validation
- ZKP proof validation
- Access control checks
Gas Optimization
Section titled “Gas Optimization”Efficient Storage
Section titled “Efficient Storage”- Packed structs for gas efficiency
- Minimal storage operations
- Optimized data types
Batch Operations
Section titled “Batch Operations”function addAITasks( uint256[] calldata rewards, uint256[] calldata requestIds, string[] calldata modelIds, string[] calldata inputData, uint256[] calldata deadlines) external payableCustom Errors
Section titled “Custom Errors”- Use custom errors instead of string messages
- Reduced gas costs for error handling
Usage Examples
Section titled “Usage Examples”Complete Workflow
Section titled “Complete Workflow”// 1. Create task poolconst taskPool = await TaskPoolImplementation.deploy();
// 2. Add AI tasksawait taskPool.addAITasks( [ethers.parseEther("0.1")], [1], ["llm-chat-v1"], ["What is AI?"], [Date.now() + 3600], { value: ethers.parseEther("0.1") });
// 3. AI worker claims taskconst taskId = await taskPool.claimTaskForUser(aiWorker.address);
// 4. AI worker processes taskconst result = await processAITask(task.inputData, task.modelId);
// 5. AI worker submits resultawait taskPool.submitTaskForUser( aiWorker.address, taskId, resultHash, zkpProof, zkpPublicInput, zkpPublicResult, result);
// 6. Verifier validates and paysawait taskPool.connect(verifier).verifyAndPay(taskId, true);Security Considerations
Section titled “Security Considerations”Access Control
Section titled “Access Control”- Owner-only task creation
- Verifier-only ZKP validation
- Proper authorization checks
Reentrancy Protection
Section titled “Reentrancy Protection”- All external functions use ReentrancyGuard
- Safe external calls
ZKP Verification
Section titled “ZKP Verification”- Cryptographic proof validation
- Anti-cheating mechanisms
- Privacy protection
Next Steps
Section titled “Next Steps”Ready to learn about other smart contracts? Check out:
- Model Registry - Learn about AI model management
- Task Router - Explore task routing
- Task Pool Factory - Learn about pool creation