Technical Architecture
We are currently under development in terms of migration to Solana. Stay tuned!
EhanLabs is built on a fully on-chain architecture leveraging the Internet Computer Protocol (ICP), ensuring all data, transactions, and verification occur directly on the blockchain without reliance on centralized databases.
Internet Computer Protocol (ICP) Foundation
Why ICP?
EhanLabs chose Internet Computer Protocol as its foundation for several critical advantages:
Canister Smart Contracts: ICP's canister model enables complex, stateful smart contracts with web-speed performance
Low Cost: Transaction fees are minimal compared to Ethereum and other blockchains
Infinite Scalability: Canister architecture scales horizontally without gas limit constraints
Web-Speed: Sub-second finality enables real-time user experiences
Native Integration: Built-in support for HTTP requests, enabling direct web integration
Fully On-Chain Architecture
Unlike hybrid platforms that use off-chain databases, EhanLabs stores:
All marketplace data (items, users, licenses, transactions)
Content hashes and verification records
License history and royalty distributions
Governance proposals and voting records
This eliminates single points of failure and ensures complete transparency and immutability.
Smart Contract Layer
EhanLabs uses Motoko, ICP's native smart contract language, to build modular, composable canister architecture.
Main Marketplace Canister
The core marketplace functionality is implemented in main.mo, which orchestrates all marketplace operations:
Key Functions:
Item listing and management
User registration and profile management
Purchase processing and license issuance
ICP payment integration via ICRC-1 ledger
Transaction recording and tracking
Code Structure:
actor class PromptMarketplace(ledger_id : Principal) = this {
// Initialize all modules
private let categories = Categories.Categories();
private let users = Users.Users();
private let verification = Verification.Verification();
private let items = Items.Items(verification);
private let licenses = Licenses.Licenses();
private let transactions = Transactions.Transactions();
private let ledger = Ledger.Ledger(ledger_id);
// ... additional modules
}Modular Architecture
The system is built with separation of concerns:
Categories Module (
Categories.mo):Manages item types (prompts, datasets, AI outputs)
Category hierarchy and organization
Dynamic category creation and management
Users Module (
Users.mo):User registration and profile management
User reputation and statistics
Profile customization (bio, rates, etc.)
Items Module (
Items.mo):Item creation, update, and deletion
Content hash verification
Item search and filtering
Featured and trending item algorithms
Licenses Module (
Licenses.mo):License issuance and management
Royalty calculation and distribution
License expiration and renewal
Platform fee management (5% default)
Verification Module (
Verification.mo):On-chain content hash storage
Duplicate detection via content hash matching
Verification status tracking
On-chain record management
Transactions Module (
Transactions.mo):Transaction recording and status tracking
Payment processing history
Transaction verification and auditing
Ledger Module (
Ledger.mo):ICP balance queries
ICP transfer execution
Transfer fee calculation
Native ICRC-1 integration
ICP Payment Integration
Native ICRC-1 Support:
Token Standard: Uses ICP's ICRC-1 fungible token standard
Direct Integration: Canister directly interacts with ICP ledger canister
Automatic Fee Handling: Transfer fees calculated and included automatically
Balance Verification: Real-time balance checking from ledger
Canister verifies sufficient balance.
Platform fee (5%) calculated and reserved.
Creator payment (95% minus royalties) transferred to seller.
License issued and recorded on-chain.
Transaction recorded with timestamp and status.
Code Example:
public shared ({ caller }) func finalize_purchase(itemId : Nat) : async Types.Result<Nat, Types.Error> {
// Calculate platform fee (5%)
let platformFee = licenses.calculatePlatformFee(item.price);
let sellerAmount = priceInE8s - platformFeeInE8s;
// Transfer to seller
let transferResult = await ledger.transferICP(
Principal.fromActor(this),
item.owner,
sellerAmount,
1, // memo
transferFee
);
// Issue license and record transaction
// ...
}Content Hash Verification System
How It Works:
Code Example:
public func storeOnChain(
itemId : Nat,
contentHash : Text,
ownerWallet : Principal,
licenseTerms : Text,
royaltyPercent : Nat
) : OnChainRecord {
let record : OnChainRecord = {
id = nextRecordId;
itemId = itemId;
contentHash = contentHash;
ownerWallet = ownerWallet;
timestamp = Time.now();
licenseTerms = licenseTerms;
royaltyPercent = royaltyPercent;
isVerified = true;
};
// Store on-chain...
}Agentic AI Layer
EhanLabs integrates Mastra framework to deploy autonomous AI agents that interact directly with blockchain smart contracts.
Architecture Overview
AI Agent Components:
Tools: Specific capabilities (duplicate detection, marketplace queries)
Agents: Autonomous agents using tools to perform tasks
Scorers: Evaluation systems to monitor agent performance
Duplicate Detection Agent
Purpose: Detect content similarity and prevent duplicate listings
Technical Implementation:
Framework: Mastra Agent framework
Model: OpenAI GPT-4o for analysis
Tool:
duplicateDetectionToolfor similarity calculations
How It Works:
Code Structure:
export const duplicateDetectionAgent = new Agent({
name: 'Content Duplicate Detection Agent',
instructions: `You are an AI agent specialized in detecting content similarity...`,
model: 'openai/gpt-4o',
tools: { duplicateDetectionTool },
scorers: {
accuracy: {
scorer: duplicateAgentAccuracyScorer,
sampling: { type: 'ratio', rate: 1 }
}
}
});Similarity Algorithm:
Embedding-Based: Uses OpenAI text-embedding-3-small for semantic analysis
Character-Level Fallback: Jaccard similarity for exact matches
Caching: Embeddings cached to reduce API calls and improve performance
Multi-Metric: Combines semantic and character-level analysis for accuracy
Marketplace Agent
Purpose: Provide intelligent marketplace assistance and recommendations
Capabilities:
Search items by keywords
Get detailed item information
Show categories and item types
Find featured and trending items
Retrieve user profiles and comments
Answer marketplace-related questions
Restrictions:
Read-Only: Cannot create, update, or delete items
Data Source: All data pulled from on-chain sources via API
Real-Time: Always reflects current blockchain state
Tool Integration:
marketplaceTool: Provides comprehensive marketplace query capabilitiesConnects to Next.js API routes that query ICP canisters
Returns real-time, on-chain data
AI-Blockchain Integration
Key Innovation: AI agents interact directly with blockchain data
How It Works:
Data Reading:
Agent → Next.js API Route → ICP Canister Query → Blockchain DataVerification:
Content hashes stored on-chain
Semantic analysis performed by agents
Results compared and validated
Decision Execution:
Accept: Item listing proceeds
Review: Flagged for human review
Reject: Listing blocked, duplicate detected
Transparency: All agent decisions logged and auditable
Benefits:
Autonomous: No human intervention required for verification
Scalable: Handles millions of items automatically
Trustworthy: Verifies against immutable blockchain records
Efficient: Reduces manual review workload
Frontend & User Experience
Technology Stack:
Framework: Next.js 14+ with React
Authentication: Internet Identity (ICP's native authentication)
Styling: Tailwind CSS with custom components
State Management: React Context API
API Integration: Server-side API routes querying ICP canisters
Key Features:
Internet Identity Integration:
One-click authentication without seed phrases
Secure, decentralized identity management
No wallet setup required
Real-Time Data:
All data fetched from ICP canisters
Automatic refresh on state changes
No caching of stale data
User Interface:
Marketplace browsing and search
Item creation and management
License viewing and tracking
Profile management
Transaction history
Responsive Design:
Mobile-first approach
Desktop and mobile optimized
Accessible UI components
Security Architecture
On-Chain Security:
Immutable Records: All data stored on blockchain cannot be altered
Cryptographic Verification: Content hashes provide tamper-proof verification
Principal-Based Access: ICP Principals ensure secure, cryptographic authentication
AI Agent Security:
Read-Only Operations: Agents cannot modify blockchain state
Verification: Agent decisions verified against on-chain records
Audit Trail: All agent actions logged for transparency
Payment Security:
Smart Contract Execution: Payments handled by smart contracts, not manual processes
Automatic Verification: Balance and transfer verification built into contracts
Transparent Accounting: All transactions recorded on-chain
Scalability & Performance
ICP Advantages:
Horizontal Scaling: Canister architecture scales infinitely
Web-Speed: Sub-second finality enables real-time experiences
Low Latency: No gas fees or network congestion delays
Efficient Storage: On-chain data storage with efficient query patterns
Optimization Strategies:
Embedding Caching: AI embeddings cached to reduce API calls
Pagination: Large datasets paginated for efficient loading
Indexed Queries: Optimized query patterns for fast retrieval
Batch Operations: Multiple operations batched when possible
Next: See Section 5 - Product Features
Last updated