Task Pool Factory
Task Pool Factory
Section titled “Task Pool Factory”The TaskPoolFactory is the factory contract for creating and managing multiple TaskPool instances using the minimal proxy pattern. It provides efficient pool creation, management, and integration with the ModelRegistry for automatic task creation.
Overview
Section titled “Overview”The TaskPoolFactory contract serves as the central factory for task pools, providing:
- Pool Creation: Create new task pools using minimal proxy pattern
- Pool Management: Manage pool lifecycle (active/inactive)
- Gas Efficiency: Minimal proxy pattern for gas-efficient pool creation
- Integration: Seamless integration with ModelRegistry
- Pool Discovery: Efficient pool discovery and management
Key Features
Section titled “Key Features”Minimal Proxy Pattern
Section titled “Minimal Proxy Pattern”- Gas Efficiency: Create pools with minimal gas costs
- Single Implementation: One implementation contract for all pools
- Clone Creation: Efficient pool cloning
- Storage Optimization: Optimized storage layout
Pool Management
Section titled “Pool Management”- Lifecycle Management: Activate/deactivate pools
- Pool Discovery: Track and discover active pools
- Category Organization: Organize pools by category
- Metadata Support: Store pool metadata and information
System Integration
Section titled “System Integration”- ModelRegistry Integration: Automatic task creation
- TaskRouter Integration: Pool discovery and routing
- Owner Management: Owner and user pool creation
- Access Control: Proper authorization and permissions
Contract Structure
Section titled “Contract Structure”State Variables
Section titled “State Variables”// Implementation and registryaddress public immutable implementation;address public modelRegistry;
// Pool managementaddress[] public allPools;mapping(address => PoolInfo) public poolInfo;mapping(string => address[]) public poolsByCategory;mapping(address => string) public poolCategory;
// Pool discovery optimizationaddress[] public activePools;mapping(address => uint256) public activePoolIndex;mapping(address => bool) public isRegisteredPool;Data Structures
Section titled “Data Structures”PoolInfo Struct
Section titled “PoolInfo Struct”struct PoolInfo { address owner; // Pool owner uint256 createdAt; // Creation timestamp bool isActive; // Pool status string metadata; // Pool metadata}Core Functions
Section titled “Core Functions”Pool Creation
Section titled “Pool Creation”Create Pool
Section titled “Create Pool”function createPool( string calldata category, string calldata metadata) external returns (address)Parameters:
category: Pool category (e.g., “AI Tasks”, “Image Processing”)metadata: Pool metadata and description
Returns:
address: Address of the created pool
Example:
// Create a new task poolconst tx = await taskPoolFactory.createPool( "AI Tasks", "Pool for AI inference tasks");const receipt = await tx.wait();
// Get the pool address from the eventconst poolAddress = receipt.logs[0].args.pool;console.log(`Created pool: ${poolAddress}`);Create Pool for Specific User
Section titled “Create Pool for Specific User”function createPoolFor( address user, string calldata category, string calldata metadata) external onlyOwner returns (address)Parameters:
user: Address of the user to create pool forcategory: Pool categorymetadata: Pool metadata
Access Control: Only owner can create pools for specific users
Example:
// Owner creates pool for specific userconst poolAddress = await taskPoolFactory.createPoolFor( userAddress, "AI Tasks", "Pool for specific user");Pool Management
Section titled “Pool Management”Get Active Pools
Section titled “Get Active Pools”function getActivePools() external view returns (address[] memory)Returns:
address[]: Array of active pool addresses
Example:
// Get all active poolsconst activePools = await taskPoolFactory.getActivePools();console.log(`Found ${activePools.length} active pools`);
activePools.forEach((pool, index) => { console.log(`Pool ${index + 1}: ${pool}`);});Get Pools by Category
Section titled “Get Pools by Category”function getPoolsByCategory(string calldata category) external view returns (address[] memory)Parameters:
category: Pool category
Returns:
address[]: Array of pool addresses in the category
Example:
// Get pools by categoryconst aiPools = await taskPoolFactory.getPoolsByCategory("AI Tasks");console.log(`Found ${aiPools.length} AI task pools`);Get Pool Information
Section titled “Get Pool Information”function getPoolInfo(address pool) external view returns (PoolInfo memory)Parameters:
pool: Pool address
Returns:
PoolInfo: Pool information struct
Example:
// Get pool informationconst poolInfo = await taskPoolFactory.getPoolInfo(poolAddress);console.log(`Owner: ${poolInfo.owner}`);console.log(`Created: ${new Date(poolInfo.createdAt * 1000)}`);console.log(`Active: ${poolInfo.isActive}`);console.log(`Metadata: ${poolInfo.metadata}`);Pool Lifecycle Management
Section titled “Pool Lifecycle Management”Activate Pool
Section titled “Activate Pool”function activatePool(address pool) external onlyOwnerParameters:
pool: Pool address to activate
Access Control: Only owner can activate pools
Example:
// Activate a poolawait taskPoolFactory.activatePool(poolAddress);console.log("Pool activated");Deactivate Pool
Section titled “Deactivate Pool”function deactivatePool(address pool) external onlyOwnerParameters:
pool: Pool address to deactivate
Access Control: Only owner can deactivate pools
Example:
// Deactivate a poolawait taskPoolFactory.deactivatePool(poolAddress);console.log("Pool deactivated");System Integration
Section titled “System Integration”Set Model Registry
Section titled “Set Model Registry”function setModelRegistry(address _modelRegistry) external onlyOwnerParameters:
_modelRegistry: ModelRegistry contract address
Access Control: Only owner can set ModelRegistry
Example:
// Set ModelRegistry for automatic task creationawait taskPoolFactory.setModelRegistry(modelRegistryAddress);console.log("ModelRegistry set");Pool Creation Process
Section titled “Pool Creation Process”1. Deploy Implementation
Section titled “1. Deploy Implementation”// Deploy the implementation contractconst TaskPoolImplementation = await ethers.getContractFactory( "TaskPoolImplementation");const taskPoolImplementation = await TaskPoolImplementation.deploy();2. Deploy Factory
Section titled “2. Deploy Factory”// Deploy the factory with implementation addressconst TaskPoolFactory = await ethers.getContractFactory("TaskPoolFactory");const taskPoolFactory = await TaskPoolFactory.deploy( await taskPoolImplementation.getAddress());3. Create Pools
Section titled “3. Create Pools”// Create multiple poolsconst pool1 = await taskPoolFactory.createPool("AI Tasks", "Pool 1");const pool2 = await taskPoolFactory.createPool("AI Tasks", "Pool 2");const pool3 = await taskPoolFactory.createPool("Image Processing", "Pool 3");4. Fund Pools
Section titled “4. Fund Pools”// Fund the pools with HYRA tokensawait owner.sendTransaction({ to: pool1Address, value: ethers.parseEther("1.0"),});await owner.sendTransaction({ to: pool2Address, value: ethers.parseEther("1.0"),});await owner.sendTransaction({ to: pool3Address, value: ethers.parseEther("1.0"),});Events
Section titled “Events”Pool Events
Section titled “Pool Events”event PoolCreated( address indexed pool, address indexed owner, uint256 poolId, string category);
event PoolActivated(address indexed pool);event PoolDeactivated(address indexed pool);System Events
Section titled “System Events”event ModelRegistryUpdated(address indexed oldRegistry, address indexed newRegistry);event PoolCategoryUpdated(address indexed pool, string oldCategory, string newCategory);Integration with Other Contracts
Section titled “Integration with Other Contracts”ModelRegistry Integration
Section titled “ModelRegistry Integration”// ModelRegistry creates tasks in poolsawait modelRegistry.requestInference("llm-chat-v1", "Hello world");
// Factory manages pool creation and discoveryconst activePools = await taskPoolFactory.getActivePools();TaskRouter Integration
Section titled “TaskRouter Integration”// TaskRouter uses factory to discover poolsconst activePools = await taskPoolFactory.getActivePools();
// TaskRouter routes tasks to poolsawait taskRouter.claimBestTask();TaskPoolViewer Integration
Section titled “TaskPoolViewer Integration”// TaskPoolViewer reads pool dataconst poolInfo = await taskPoolFactory.getPoolInfo(poolAddress);const poolStats = await taskPoolViewer.getPoolStatistics(poolAddress);Gas Optimization
Section titled “Gas Optimization”Minimal Proxy Pattern
Section titled “Minimal Proxy Pattern”- Single Implementation: One implementation contract for all pools
- Clone Creation: Efficient pool cloning
- Storage Optimization: Minimal storage overhead
- Gas Efficiency: Reduced deployment costs
Efficient Pool Management
Section titled “Efficient Pool Management”- Active Pool Tracking: Optimized active pool management
- Category Organization: Efficient category-based organization
- Batch Operations: Support for batch pool operations
Custom 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 Pool Setup
Section titled “Complete Pool Setup”// 1. Deploy implementationconst TaskPoolImplementation = await ethers.getContractFactory( "TaskPoolImplementation");const taskPoolImplementation = await TaskPoolImplementation.deploy();
// 2. Deploy factoryconst TaskPoolFactory = await ethers.getContractFactory("TaskPoolFactory");const taskPoolFactory = await TaskPoolFactory.deploy( await taskPoolImplementation.getAddress());
// 3. Set ModelRegistryawait taskPoolFactory.setModelRegistry(modelRegistryAddress);
// 4. Create poolsconst pool1 = await taskPoolFactory.createPool( "AI Tasks", "Pool for AI inference");const pool2 = await taskPoolFactory.createPool( "Image Processing", "Pool for image tasks");
// 5. Fund poolsawait owner.sendTransaction({ to: pool1, value: ethers.parseEther("1.0") });await owner.sendTransaction({ to: pool2, value: ethers.parseEther("1.0") });
// 6. Get active poolsconst activePools = await taskPoolFactory.getActivePools();console.log(`Active pools: ${activePools.length}`);Pool Management
Section titled “Pool Management”// Get all poolsconst allPools = await taskPoolFactory.getAllPools();console.log(`Total pools: ${allPools.length}`);
// Get pools by categoryconst aiPools = await taskPoolFactory.getPoolsByCategory("AI Tasks");console.log(`AI pools: ${aiPools.length}`);
// Get pool informationconst poolInfo = await taskPoolFactory.getPoolInfo(poolAddress);console.log(`Pool owner: ${poolInfo.owner}`);console.log(`Pool active: ${poolInfo.isActive}`);
// Activate/deactivate poolsawait taskPoolFactory.activatePool(poolAddress);await taskPoolFactory.deactivatePool(poolAddress);Error Handling
Section titled “Error Handling”Custom Errors
Section titled “Custom Errors”error PoolNotFound(); // Pool doesn't existerror PoolAlreadyActive(); // Pool already activeerror PoolAlreadyInactive(); // Pool already inactiveerror InvalidCategory(); // Invalid categoryerror Unauthorized(); // Access deniedInput Validation
Section titled “Input Validation”- Pool existence checks
- Category validation
- Access control checks
- Parameter validation
Security Considerations
Section titled “Security Considerations”Access Control
Section titled “Access Control”- Owner-only pool management
- Proper authorization checks
- Secure pool creation and management
Input Validation
Section titled “Input Validation”- Comprehensive parameter validation
- Pool existence checks
- Category validation
Reentrancy Protection
Section titled “Reentrancy Protection”- All external functions use ReentrancyGuard
- Safe external calls
Performance Optimization
Section titled “Performance Optimization”Pool Discovery
Section titled “Pool Discovery”- Efficient active pool tracking
- Optimized pool scanning
- Cached pool data
Category Management
Section titled “Category Management”- Efficient category-based organization
- Optimized pool filtering
- Fast pool lookup
Next Steps
Section titled “Next Steps”Ready to learn about other smart contracts? Check out:
- Model Registry - Learn about AI model management
- Task Pool - Learn about task management
- Task Router - Explore task routing