polkamesh-sdk
v1.1.0
Published
Production-grade SDK for PolkaMesh - Decentralized AI Compute & Data Marketplace on Polkadot with MEV Protection and Confidential Computing
Readme
PolkaMesh SDK
Streamline decentralized AI compute and data marketplace operations on Polkadot with a type-safe, production-grade SDK. Manage job lifecycles, handle secure escrow payments, register compute providers, and create privacy-controlled data NFTs through unified contract interfaces.
Latest Updates (v1.1.0)
- 🛡️ MEV Protection Module - Intent-based batch execution with cross-DEX arbitrage prevention
- 🔐 Phala Network Integration - Confidential job execution with TEE attestation verification
- 📊 Advanced Contract Wrappers - Complete integration for all 6 smart contracts
- 🧪 Comprehensive Testing - 75+ integration tests covering all workflows
- ⚡ Production Ready - 250+ Type Definitions, 18 Custom Error Classes, gas optimization
Features
- Complete Job Lifecycle Management - Submit, assign, track, and complete AI compute jobs with state validation
- 🛡️ Advanced MEV Protection - Intent batching, sandwich attack prevention, cross-DEX aggregation
- 🔐 Confidential Computing - Phala TEE integration with cryptographic attestation proofs
- Secure Payment Escrow - Type-safe fund management with deposit, release, and refund mechanisms
- Provider Registry & Reputation - Register compute providers, manage stakes, and track reputation scores
- Data NFT Management - Create and manage data NFTs with granular access control and privacy levels
- Address & Balance Utilities - Comprehensive validation, conversion, and formatting utilities
- Gas Estimation - Built-in gas optimization for cost prediction and transaction planning
Installation
npm install polkamesh-sdkQuick Start
import { PolkaMesh } from 'polkamesh-sdk';
const sdk = new PolkaMesh({
rpcUrl: 'wss://rpc1.paseo.popnetwork.xyz',
contractAddresses: {
paymentEscrow: '0x5a86a13ef7fc1c5e58f022be183de015dfb702ae',
aiJobQueue: '0xa44639cd0d0e6c6607491088c9c549e184456122',
computeProviderRegistry: '0x2c6fc00458f198f46ef072e1516b83cd56db7cf5',
dataNFTRegistry: '0x6dc84ddeffccb19ed5285cf3c3d7b03a57a9a4b1',
mevProtection: '5DTPZHSHydkPQZbTFrhnHtZiDER7uoKSzdYHuCUXVAtjajXs',
phalaJobProcessor: '5HrKZAiTSAFcuxda89kSD77ZdygRUkufwRnGKgfGFR4NC2np',
},
});
await sdk.initialize();
// Submit a confidential AI job with MEV protection
const jobQueue = sdk.getAIJobQueue();
const jobId = await jobQueue.submitJob({
description: 'Confidential image classification',
budget: '1000000000000', // 100 DOT in planck units
computeType: 'phala-confidential',
});
console.log('Job submitted:', jobId);Core Modules
PaymentEscrow
Manage job payment escrows and fund transfers.
const escrow = sdk.getPaymentEscrow();
// Deposit funds for a job
await escrow.depositForJob(jobId, amount);
// Release funds to provider
await escrow.releaseToProvider(jobId);
// Check escrow status
const result = await escrow.getEscrow(jobId);AIJobQueue
Submit and manage AI compute jobs.
const jobQueue = sdk.getAIJobQueue();
// Submit a job
const jobId = await jobQueue.submitJob({
description: 'AI task',
budget: '1000000000000',
dataSetId: '1',
computeType: 'GPU',
estimatedRuntime: 3600,
});
// Update job status
await jobQueue.assignProvider(jobId, providerAddress);
await jobQueue.markInProgress(jobId);
await jobQueue.markCompleted(jobId, resultHash);ComputeProviderRegistry
Register as a provider and manage profiles.
const registry = sdk.getComputeProviderRegistry();
// Register as a provider
await registry.registerProvider({
endpoint: 'https://my-provider.com',
initialStake: '10000000000', // 1 DOT
hourlyRate: '50000000000', // 5 DOT/hour
});
// Get provider profile
const profileResult = await registry.getProfile(providerAddress);DataNFTRegistry
Create and manage data NFTs.
const nftRegistry = sdk.getDataNFTRegistry();
// Mint a data NFT
const tokenId = await nftRegistry.mint({
accessPrice: '100000000000', // 10 DOT
isTransferable: true,
privacyLevel: 'Private',
metadata: 'Medical images dataset',
});
// Grant access
await nftRegistry.grantAccess(tokenId, granteeAddress);
// Transfer NFT
await nftRegistry.transfer(tokenId, recipientAddress);MEVProtection
Submit trading intents and protect against MEV attacks.
const mevProtection = sdk.getMEVProtection();
// Submit encrypted trading intent
const intentId = await mevProtection.submitIntent(
'encrypted_trading_intent',
'USDT',
'DOT',
BigInt(1000000000000) // 1000 USDT
);
// Create batch from multiple intents
const batchId = await mevProtection.createBatch([intentId1, intentId2, intentId3], 'hydradx');
// Execute batch with slippage protection
const success = await mevProtection.executeBatch(
batchId,
BigInt(950), // Min output
'1.05' // Max slippage 5%
);
// Get batch statistics
const stats = await mevProtection.getBatchStats(batchId);PhalaJobProcessor
Execute confidential jobs in Trusted Execution Environment.
const phalaProcessor = sdk.getPhalaJobProcessor();
// Submit confidential job
const jobId = await phalaProcessor.submitConfidentialJob(
'encrypted_ai_model_payload',
'client_public_key'
);
// Record TEE attestation proof
const recorded = await phalaProcessor.recordAttestation(
jobId,
'result_hash',
'attestation_proof_from_tee',
'tee_worker_public_key'
);
// Verify attestation
const isValid = await phalaProcessor.verifyAttestation(jobId);
// Mark job as processed
if (isValid) {
await phalaProcessor.markJobProcessed(jobId);
}Utilities
The SDK provides utility functions for common operations:
import {
isValidAddress,
validateAddress,
isValidBalance,
dotsToPlancks,
plancksToDots,
GasEstimates,
} from 'polkamesh-sdk';
// Validate address
if (isValidAddress(userAddress)) {
// Process address
}
// Convert between DOT and planck
const inPlancks = dotsToPlancks(100); // 100 DOT to planck units
const inDots = plancksToDots(inPlancks);
// Get gas estimates
const depositGas = GasEstimates.paymentEscrow.depositForJob();Advanced Examples
Complete MEV-Protected Trading Workflow
// Example: Submit MEV-protected trading intent and execute
const mev = sdk.getMEVProtection();
try {
// Submit encrypted trading intent
const intentId = await mev.submitIntent(
await encryptTradingIntent({
tokenIn: 'USDT',
tokenOut: 'DOT',
amountIn: '1000',
minAmountOut: '95',
}),
'USDT',
'DOT',
BigInt(1000000000000)
);
// Batch with other intents for better execution
const batchId = await mev.createBatch([intentId], 'hydradx');
// Execute with slippage protection
const success = await mev.executeBatch(batchId, BigInt(950), '1.05');
console.log('MEV-protected trade executed:', success);
} catch (error) {
console.error('Trading failed:', error);
}Confidential AI Job with TEE Verification
// Example: Execute AI job in Phala TEE with full attestation
const phala = sdk.getPhalaJobProcessor();
const jobQueue = sdk.getAIJobQueue();
try {
// Submit confidential job to Phala
const confidentialJobId = await phala.submitConfidentialJob(
await encryptJobPayload({
modelType: 'image-classification',
dataset: 'medical-xrays',
parameters: { epochs: 10, batch_size: 32 },
}),
'user_public_key'
);
// Also submit to main job queue for tracking
const jobId = await jobQueue.submitJob({
description: 'Confidential medical AI analysis',
budget: '500000000000',
computeType: 'phala-confidential',
estimatedRuntime: 7200,
});
// Wait for TEE execution and attestation
const attestationValid = await phala.verifyAttestation(confidentialJobId);
if (attestationValid) {
await phala.markJobProcessed(confidentialJobId);
await jobQueue.markCompleted(jobId, 'tee_result_hash');
console.log('Confidential job completed with valid attestation');
}
} catch (error) {
console.error('Confidential job failed:', error);
}Error Handling
The SDK provides specific error types for better error handling:
import {
ValidationError,
ContractCallError,
InsufficientBalanceError,
AttestationError,
MEVExecutionError,
} from 'polkamesh-sdk';
try {
// MEV-protected operation
await sdk.getMEVProtection().submitIntent(intent, 'USDT', 'DOT', amount);
} catch (error) {
if (error instanceof MEVExecutionError) {
console.log('MEV protection failed:', error.message);
} else if (error instanceof AttestationError) {
console.log('TEE attestation invalid:', error.message);
} else if (error instanceof InsufficientBalanceError) {
console.log('Not enough balance');
} else if (error instanceof ValidationError) {
console.log('Validation failed:', error.message);
}
}Contributing
Contributions are welcome! Please follow the existing code style and add tests for new features.
License
Apache License 2.0
