CAP-402

SDK Reference

Agent SDK Reference

Build autonomous agents that monitor markets, analyze risk, and prepare ready-to-sign transactions. You signβ€”agents do the rest.

Why Use Agents?

Use CaseWithout AgentWith Agent
Price AlertsManually check pricesAgent monitors 24/7, alerts you
TradingResearch β†’ Calculate β†’ ExecuteOne line: trader.smartSwap('SOL', 'USDC', 100)
MEV ProtectionHope you don't get front-runBuilt-in risk analysis + protection
Best ExecutionCompare DEXs manuallyAgent finds best route (DEX or A2A)
PortfolioSpreadsheetsReal-time tracking + P&L

When to Use What

// QUICK OPERATIONS - No setup needed
import { cap402, prepareSwap, findAlpha } from '@cap402/sdk';

await cap402.price('SOL');              // Get price
await prepareSwap('SOL', 'USDC', 10);   // Prepare swap tx
await findAlpha(['SOL', 'ETH']);        // Detect signals

// TRADING AGENT - Continuous monitoring + trading
import { createTradingAgent } from '@cap402/sdk';
const trader = createTradingAgent({ ... });
trader.on('signal', ...);  // React to signals
await trader.start();      // Runs 24/7

// MONITORING AGENT - Watch wallets/protocols
import { createMonitoringAgent } from '@cap402/sdk';
const monitor = createMonitoringAgent({ ... });
monitor.on('alert', ...);  // Get notified

// ANALYTICS AGENT - Collect data + generate reports
import { createAnalyticsAgent } from '@cap402/sdk';
const analytics = createAnalyticsAgent({ ... });
analytics.on('report_generated', ...);

Quick Start

import { cap402 } from '@cap402/sdk';

// One-liner operations
const price = await cap402.price('SOL');           // $143.34
const wallet = await cap402.wallet('address...');
const swap = await cap402.swap('SOL', 'USDC', 10); // dry_run by default

New Capabilities (Jan 2026)

Private AI Inference

Run AI models with encrypted inputs - your data never exposed.

import { createClient } from '@cap402/sdk';

const client = createClient('https://api.cap402.com');

// Private sentiment analysis
const result = await client.invokeCapability('cap.ai.inference.v1', {
  model: 'sentiment-analysis',
  input: 'This product is amazing!',
  privacy_level: 2 // Confidential (Arcium MPC)
});
// { result: { sentiment: 'positive', confidence: 0.92 }, proof: '...' }

// Private embeddings for RAG
const embeddings = await client.invokeCapability('cap.ai.embedding.v1', {
  texts: ['Hello world', 'Goodbye world'],
  privacy_level: 2
});
// { embeddings: [[...], [...]], dimensions: 1536 }

Private KYC Verification

Prove compliance without revealing personal data using zero-knowledge proofs.

// Prove you're 18+ without revealing birthdate
const result = await client.invokeCapability('cap.zk.kyc.v1', {
  verification_type: 'age',
  private_inputs: {
    date_of_birth: '1990-05-15' // NEVER revealed
  },
  public_inputs: {
    min_age: 18
  }
});
// { compliant: true, proof: '0x...', verification_id: 'kyc_abc123' }
// Verifier learns ONLY: "User is 18+" - nothing else

Agent Framework Integrations

Ready-to-use integrations for popular AI agent frameworks.

// LangChain
import { CAP402Toolkit } from '@cap402/sdk/integrations/langchain';
const toolkit = new CAP402Toolkit({ routerUrl: 'https://api.cap402.com' });
const tools = await toolkit.getTools();

// AutoGPT
import { CAP402AutoGPTPlugin } from '@cap402/sdk/integrations/autogpt';
const plugin = new CAP402AutoGPTPlugin();
const commands = plugin.getCommands();

// CrewAI
import { CAP402CrewAgent } from '@cap402/sdk/integrations/crewai';
const agent = new CAP402CrewAgent({
  role: 'Market Analyst',
  capabilities: ['cap.price.lookup.v1', 'cap.ai.inference.v1']
});

Agent Templates

Trading Agent

Monitors prices, generates signals, and prepares ready-to-sign swap transactions.

import { createTradingAgent } from '@cap402/sdk';

const trader = createTradingAgent({
  agent_id: 'sol-trader',
  watched_tokens: ['SOL', 'ETH', 'BTC'],
  mev_protection: true
});

// Agent prepares transactions autonomously
trader.on('signal', async (signal) => {
  const tx = await trader.actOnSignal(signal, 10);
  // tx is ready for your wallet to sign
});

await trader.start();

Prepared Transactions

Agents return ready-to-sign transactions with all details calculated:

const prepared = await trader.prepareSwap('SOL', 'USDC', 10);

// Returns:
{
  instruction_id: 'prep_1705412400_abc123',
  type: 'swap',
  status: 'ready',
  expires_at: 1705412460000,
  
  token_in: 'SOL',
  token_out: 'USDC',
  amount_in: 10,
  expected_out: 1433.40,
  min_out: 1426.23,
  slippage_bps: 50,
  
  dex: 'jupiter',
  mev_risk: 'LOW',
  
  user_action_required: 'sign_and_submit',
  instructions_for_user: 'Swap 10 SOL for ~1433.40 USDC. Sign in wallet.'
}

Monitoring Agent

Tracks wallet balances and protocol health, triggers alerts.

import { createMonitoringAgent } from '@cap402/sdk';

const monitor = createMonitoringAgent({
  agent_id: 'wallet-monitor',
  watched_wallets: ['YOUR_WALLET_ADDRESS'],
  check_interval_ms: 60000,
  alert_channels: [{ type: 'console', enabled: true }]
});

monitor.on('alert', (alert) => {
  console.log(\`\${alert.severity}: \${alert.title}\`);
});

await monitor.start();

Analytics Agent

Collects time-series data, generates reports and insights.

import { createAnalyticsAgent } from '@cap402/sdk';

const analytics = createAnalyticsAgent({
  agent_id: 'market-analytics',
  data_sources: [{
    id: 'sol-price',
    type: 'price',
    capability_id: 'cap.price.lookup.v1',
    inputs: { base_token: 'SOL' },
    interval_ms: 60000,
    enabled: true
  }]
});

analytics.on('report_generated', (report) => {
  console.log('Insights:', report.insights);
});

await analytics.start();

Safety Guardrails

Built-in protection with sensible defaults:

LimitDefaultDescription
Per Transaction$100Maximum USD per single transaction
Per Hour$500Maximum USD spending per hour
Per Day$2,000Maximum USD spending per day
Trades/Hour20Maximum trades per hour
Invocations/Min60Rate limit per minute
import { createSafetyGuardrails, SAFETY_PRESETS } from '@cap402/sdk';

// Use presets: conservative, standard, aggressive
const safety = createSafetyGuardrails(SAFETY_PRESETS.conservative);

// Or customize
const custom = createSafetyGuardrails({
  spending_limits: {
    max_per_transaction: 50,
    max_per_hour: 200
  },
  blocked_tokens: ['SCAM_TOKEN']
});

One-Liner Convenience Methods

Simple methods for common operations:

// Buy token (prepares transaction for signing)
const buyTx = await trader.buy('SOL', 100); // Buy $100 worth of SOL

// Sell token
const sellTx = await trader.sell('SOL', 10); // Sell 10 SOL

// Smart swap - auto-selects best route (DEX vs A2A)
const result = await trader.smartSwap('SOL', 'USDC', 100);
console.log(result.execution_summary);
// "A2A trade via agent-xyz: 100 SOL β†’ 14,334 USDC (0.5% better than DEX)"

// Check if trade is profitable
const check = await trader.isProfitable('SOL', 'USDC', 1000);
console.log(check.recommendation);

// Get portfolio value
const portfolio = await trader.getPortfolioValue();
console.log(\`Total: $\${portfolio.total_usd}\`);

Agent-to-Agent (A2A) Trading

Trade directly with other agents for better prices and liquidity:

// Find trading partners with quotes
const partners = await trader.findTradingPartners('SOL', 'USDC', 100);
console.log(\`Found \${partners.length} partners\`);
console.log(\`Best offer: \${partners[0].quote.amount_out} USDC\`);

// Execute A2A trade
const result = await trader.executeA2ATrade(partners[0].quote);
if (result.status === 'executed') {
  console.log(\`Received: \${result.amount_received} USDC\`);
}

// Auction - agents compete for best price
const auction = await trader.auctionTrade('SOL', 'USDC', 1000);
console.log(\`Winner: \${auction.winner?.agent_id} at \${auction.best_price}\`);

// Swarm trade - split large orders across agents
const swarm = await trader.swarmTrade('SOL', 'USDC', 10000, { minAgents: 3 });
console.log(\`Executed via \${swarm.participants.length} agents\`);
console.log(\`Total received: \${swarm.total_amount_out} USDC\`);

Signal Sharing

// Broadcast signals to other agents
await trader.broadcastSignal(alphaSignal);

// Receive signals from other agents
trader.on('a2a_signal', ({ from, signal }) => {
  console.log(\`Signal from \${from}: \${signal.type} \${signal.token}\`);
});

// Poll for signals
const signals = await trader.pollA2ASignals();

πŸ₯· Stealth Trading Mode

Privacy-first trading with automatic privacy escalation for large trades:

import { createTradingAgent } from '@cap402/sdk';

// Enable stealth mode
const trader = createTradingAgent({
  agent_id: 'stealth-bot',
  watched_tokens: ['SOL', 'ETH'],
  stealth_mode: {
    enabled: true,
    auto_privacy_threshold_usd: 10000,  // Auto-escalate > $10K
    auto_split_threshold_usd: 50000,    // Split orders > $50K
    randomize_timing: true,              // Random delays
    decoy_transactions: false            // Optional decoys
  }
});

// Analyze stealth options before trading
const analysis = await trader.analyzeStealthOptions('SOL', 'USDC', 1000);
console.log(analysis.recommendation);        // 'maximum'
console.log(analysis.mev_risk.level);        // 'HIGH'
console.log(analysis.stealth_options);       // Privacy/cost tradeoffs

// Execute stealth trade
const result = await trader.stealthTrade('SOL', 'USDC', 1000, {
  privacy_level: 'maximum',  // 'standard' | 'enhanced' | 'maximum'
  split_order: true,         // Split into chunks
  max_chunks: 5,             // Number of chunks
  use_decoys: false          // Decoy transactions
});

console.log(result.stealth_features_used);
// ['order_splitting', 'randomized_timing', 'arcium_mpc', 'encrypted_amounts']
console.log(\`MEV Savings: $\${result.mev_savings_usd}\`);
console.log(\`Privacy Cost: $\${result.privacy_cost_usd}\`);

Privacy Levels

LevelMethodProtectionFeatures
standardPrivate RPC40%Hidden from public mempool
enhancedJito Bundle70%Tip protection, atomic execution
maximumArcium MPC95%Encrypted amounts, hidden route, ZK proof

Stealth Features

⚑ Instant Execution

Sub-second trade execution with caching, parallel requests, and smart routing:

// Instant swap - fastest execution
const result = await trader.instantSwap('SOL', 'USDC', 10);
console.log(\`Executed in \${result.latency_ms}ms\`);

// Smart trade - auto-selects best method based on size
// < $100: instant (skip MEV)
// $100-$10K: protected (standard MEV)
// > $10K: stealth (split + max privacy)
const smart = await trader.smartTrade('SOL', 'USDC', 100);
console.log(\`Method: \${smart.method}\`); // 'instant' | 'protected' | 'stealth'

// Race swap - races multiple execution paths
const race = await trader.raceSwap('SOL', 'USDC', 10);
console.log(\`Winner: \${race.winning_method}\`);

// Warm up caches for fastest execution
await trader.warmUp([
  { tokenIn: 'SOL', tokenOut: 'USDC' },
  { tokenIn: 'ETH', tokenOut: 'USDC' }
]);

πŸ“Š Risk Management

Automated stop-loss, take-profit, and trailing stops:

// Stop-loss - sell when price drops below trigger
trader.setStopLoss('SOL', 140, 10, 'USDC');
// Sells 10 SOL if price drops below $140

// Take-profit - sell when price rises above trigger
trader.setTakeProfit('SOL', 200, 10, 'USDC');
// Sells 10 SOL if price rises above $200

// Trailing stop - follows price up, triggers on % drop
trader.setTrailingStop('SOL', 5, 10, 'USDC');
// Sells 10 SOL if price drops 5% from its high

// Cancel orders
trader.cancelOrder(order.order_id);

// Get active orders
const orders = trader.getActiveOrders();

πŸ“… DCA (Dollar Cost Averaging)

Automated recurring buys at regular intervals:

// Start DCA - buy $50 of SOL every hour for 24 hours
const dca = trader.startDCA('SOL', 'USDC', 50, 'hourly', 24);

// Intervals: 'hourly' | 'daily' | 'weekly' | custom ms
trader.startDCA('ETH', 'USDC', 100, 'daily');      // Daily
trader.startDCA('BTC', 'USDC', 500, 'weekly');     // Weekly
trader.startDCA('SOL', 'USDC', 25, 60000);         // Every minute

// Control DCA
trader.pauseDCA(dca.schedule_id);
trader.resumeDCA(dca.schedule_id);
trader.stopDCA(dca.schedule_id);

// Track progress
const schedule = trader.getDCASchedule(dca.schedule_id);
console.log(\`Bought: \${schedule.total_acquired} SOL\`);
console.log(\`Avg price: $\${schedule.avg_price}\`);

πŸ“‹ Limit Orders

Buy or sell at specific prices:

// Limit buy - buy when price drops to limit
trader.limitBuy('SOL', 'USDC', 10, 140);
// Buys 10 SOL when price drops to $140

// Limit sell - sell when price rises to limit
trader.limitSell('SOL', 'USDC', 10, 200);
// Sells 10 SOL when price rises to $200

// Cancel limit orders
trader.cancelLimitOrder(order.order_id);

// Get open limit orders
const limitOrders = trader.getOpenLimitOrders();

βš–οΈ Portfolio Rebalancing

Automatically rebalance to target allocations:

// Rebalance to 60% SOL, 30% ETH, 10% USDC
const result = await trader.rebalance({
  SOL: 60,
  ETH: 30,
  USDC: 10
});

console.log(\`Trades executed: \${result.trades_executed}\`);
console.log('Before:', result.before);
console.log('After:', result.after);

// Dry run - preview without executing
const preview = await trader.rebalance(
  { SOL: 60, ETH: 30, USDC: 10 },
  { dry_run: true, tolerance_percent: 2 }
);

πŸ““ Trade Journal

Track and analyze your trading performance:

// Add notes to trades
trader.addTradeNotes(trade.trade_id, 'Bought on breakout');

// Tag trades for categorization
trader.tagTrade(trade.trade_id, ['momentum', 'breakout']);

// Set strategy
trader.setTradeStrategy(trade.trade_id, 'trend-following', 'MA crossover');

// Filter trades
const momentumTrades = trader.getTradesByTag('momentum');
const trendTrades = trader.getTradesByStrategy('trend-following');

// Get journal summary
const summary = trader.getJournalSummary();
console.log(\`Strategies: \${summary.strategies_used}\`);
console.log(\`By strategy:\`, summary.by_strategy);

// Export to CSV
const csv = trader.exportTradesCSV();
fs.writeFileSync('trades.csv', csv);

πŸ”” Price Alerts

Get notified when prices cross thresholds:

// Alert when SOL goes above $200
trader.setPriceAlert('SOL', 'above', 200, 'SOL broke $200!');

// Alert when price drops below threshold
trader.setPriceAlert('ETH', 'below', 3000);

// With webhook notification
trader.setPriceAlert('SOL', 'above', 200, 'Alert!', 'https://webhook.com');

// Manage alerts
trader.getActivePriceAlerts();
trader.cancelPriceAlert(alert.alert_id);

πŸ“Š Volatility & Market Analysis

Monitor market conditions and volatility:

// Get volatility metrics
const vol = trader.getVolatility('SOL', 60);
console.log(vol.volatility_level); // 'low' | 'medium' | 'high' | 'extreme'

// Market overview
const overview = trader.getMarketOverview();
console.log(overview.market_sentiment); // 'bullish' | 'bearish' | 'neutral'

// Check if conditions are favorable
const check = trader.isTradingFavorable('SOL');
console.log(check.score, check.reasons);

πŸ“ Position Sizing

Calculate optimal position sizes based on risk:

// Risk 2% of portfolio with 5% stop-loss
const size = trader.calculatePositionSize('SOL', 2, 5);
console.log(size.recommended_amount);

// Get risk/reward ratio
const rr = trader.getRiskReward('SOL', 150, 140, 180);
console.log(rr.risk_reward_ratio); // 3:1
console.log(rr.recommendation); // 'good'

πŸ“ˆ Performance Analytics

Detailed trading metrics and statistics:

// Get performance analytics
const analytics = trader.getPerformanceAnalytics();

console.log('Session:', analytics.session);
// { duration_hours, trades_executed, trades_per_hour }

console.log('PnL:', analytics.pnl);
// { realized_usd, unrealized_usd, best_trade_usd, worst_trade_usd }

console.log('Execution:', analytics.execution);
// { avg_latency_ms, p95_latency_ms, success_rate }

console.log('Risk:', analytics.risk);
// { win_rate, avg_win_usd, avg_loss_usd, profit_factor }

// Get latency stats
const latency = trader.getLatencyStats();
console.log(\`Avg: \${latency.avg_ms}ms, P95: \${latency.p95_ms}ms\`);

Alpha Detection

Detect trading opportunities with momentum and reversal signals:

// Detect alpha signals
const alphaSignals = await trader.detectAlpha();

for (const signal of alphaSignals) {
  console.log(\`\${signal.type}: \${signal.token} \${signal.direction}\`);
  console.log(\`  Action: \${signal.suggested_action}\`);
  console.log(\`  Entry: $\${signal.entry_price}\`);
  console.log(\`  Target: $\${signal.target_price}\`);
  console.log(\`  Stop: $\${signal.stop_loss}\`);
  console.log(\`  Confidence: \${signal.confidence}%\`);
}

// Listen for alpha events
trader.on('alpha', (signal) => {
  if (signal.confidence > 70) {
    const tx = await trader.actOnSignal(signal);
    // Ready-to-sign transaction
  }
});

Multi-Agent Orchestration

import { createOrchestrator } from '@cap402/sdk';

const orchestrator = createOrchestrator({
  orchestrator_id: 'trading-swarm',
  max_agents: 5
});

// Parallel execution
const results = await orchestrator.executeParallel([
  { capability_id: 'cap.price.lookup.v1', inputs: { base_token: 'SOL' } },
  { capability_id: 'cap.price.lookup.v1', inputs: { base_token: 'ETH' } }
]);

// Consensus execution
const consensus = await orchestrator.executeWithConsensus(
  'cap.price.lookup.v1',
  { base_token: 'SOL' },
  { min_agreement: 0.5 }
);

Secure A2A Communication

Encrypted messaging with privacy levels and cryptographic verification:

// Establish secure channel with another agent
const session = await trader.establishSecureChannel('agent-xyz', 'confidential');
// { session_id, status: 'established', privacy_level: 'confidential' }

// Send encrypted message
const msg = await trader.sendSecureMessage('agent-xyz', {
  type: 'trade_proposal',
  token: 'SOL',
  amount: 100
}, 'confidential');

// Verify received message
const verification = await trader.verifyMessage(incomingMessage);
if (verification.valid) {
  console.log('Verified payload:', verification.decrypted_payload);
}

// Close secure channel
await trader.closeSecureChannel('agent-xyz');

Privacy Levels

LevelDescriptionUse Case
publicNo encryption, signed onlyBroadcast signals
confidentialEncrypted in transitTrade negotiations
privateZero-knowledge proofsSensitive strategies
maximumFull MPC/FHEHigh-value trades

Fault Tolerance

Built-in retry logic, circuit breakers, and fallback agents:

// Configure fault tolerance
trader.setFaultConfig({
  max_retries: 3,
  retry_delay_ms: 1000,
  timeout_ms: 30000,
  fallback_agents: ['agent-backup-1', 'agent-backup-2'],
  circuit_breaker_threshold: 5
});

// Execute with automatic retries and fallbacks
const result = await trader.executeWithFaultTolerance(
  () => trader.requestQuote('agent-xyz', 'SOL', 'USDC', 100),
  'agent-xyz',
  ['agent-backup']
);

if (result.success) {
  console.log(\`Completed in \${result.attempts} attempts\`);
  if (result.used_fallback) {
    console.log(\`Used fallback: \${result.used_fallback}\`);
  }
}

Cross-Protocol Interoperability

Communicate with agents on other protocols (Google A2A, MCP, custom):

// Register a cross-protocol agent
trader.registerCrossProtocolAgent({
  agent_id: 'google-agent-1',
  protocol: 'a2a_google',
  endpoint: 'https://agent.example.com',
  capabilities: ['swap', 'quote']
});

// Invoke capability on cross-protocol agent
const result = await trader.invokeCrossProtocol(
  'google-agent-1',
  'swap',
  { token_in: 'SOL', token_out: 'USDC', amount: 100 }
);

// Discover agents across all protocols
const agents = await trader.discoverCrossProtocolAgents({
  protocols: ['cap402', 'a2a_google', 'mcp'],
  capability: 'swap'
});

CLI Tools

# Health check
npm run cli health

# List capabilities
npm run cli capabilities

# Invoke a capability
npm run cli invoke cap.price.lookup.v1 '{"base_token":"SOL"}'

# Run examples
npm run example:trading
npm run example:monitor

Zero-Config One-Liners

No setup required for common operations:

import { prepareSwap, bestSwap, findAlpha, findPartners, autoTrader } from '@cap402/sdk';

// Prepare swap without agent setup
const tx = await prepareSwap('SOL', 'USDC', 10);
console.log(tx.summary.headline); // "Swap 10 SOL β†’ ~1,433 USDC"

// Get best execution route (DEX vs A2A)
const result = await bestSwap('SOL', 'USDC', 100);
console.log(result.route, result.execution_summary);

// Detect alpha signals
const signals = await findAlpha(['SOL', 'ETH', 'BTC']);
signals.forEach(s => console.log(s.token, s.direction));

// Find A2A trading partners
const partners = await findPartners('SOL', 'USDC', 100);

// Auto-starting agent with event handlers
const agent = await autoTrader(['SOL', 'ETH'], {
  onSignal: console.log,
  onAlpha: console.log
});

Error Handling

Actionable errors with suggestions and documentation links:

import { CAP402Error, wrapError, isRetryable, getRetryDelay } from '@cap402/sdk';

try {
  await trader.prepareSwap('SOL', 'USDC', 1000000);
} catch (error) {
  if (error instanceof CAP402Error) {
    console.log(error.code);       // 'SPENDING_LIMIT_EXCEEDED'
    console.log(error.suggestion); // 'Adjust limits or use emergencyStop()'
    console.log(error.docs_url);   // 'https://cap402.com/docs/...'
  }
  
  // Check if retryable
  if (isRetryable(error)) {
    const delay = getRetryDelay(error, attempt);
    await sleep(delay);
    // Retry...
  }
}

Error Types

ErrorCodeWhen
NetworkErrorNETWORK_ERRORConnection issues
TimeoutErrorTIMEOUT_ERROROperation timed out
RateLimitErrorRATE_LIMIT_ERRORToo many requests
SlippageExceededErrorSLIPPAGE_EXCEEDEDPrice moved too much
MEVRiskErrorMEV_RISK_HIGHHigh MEV risk detected
QuoteExpiredErrorQUOTE_EXPIREDA2A quote expired
SpendingLimitErrorSPENDING_LIMIT_EXCEEDEDSafety limit hit

Logging & Debugging

import { createLogger, setLogLevel } from '@cap402/sdk';

// Create agent-specific logger
const log = createLogger('my-trader', 'debug');

// Log with categories
log.info('trade', 'Preparing swap', { token: 'SOL', amount: 10 });
log.warn('mev', 'High risk detected', { risk: 'HIGH' });

// Specialized logging
log.trade('execute', { token_in: 'SOL', token_out: 'USDC', amount: 10 });
log.a2a('quote_received', { from_agent: 'agent-xyz', price: 143.34 });
log.signal('buy', 'SOL', { confidence: 85 });

// Timer for performance
log.time('swap');
await trader.prepareSwap('SOL', 'USDC', 10);
log.timeEnd('swap', 'trade', 'Swap prepared');

// Get recent logs
const errors = log.getLogs({ level: 'error', limit: 10 });

// Set global log level
setLogLevel('warn'); // Only warn and error

πŸ”’ Confidential Execution

For trades >$100K, use the confidential execution pipeline (Arcium MPC + Inco FHE + Noir ZK):

// Check if confidential execution is required
const tier = await trader.getExecutionTier(150000);
// { tier: 'confidential', recommendation: 'MANDATORY: Use confidential for MEV protection' }

// Execute with full confidential pipeline
const result = await trader.executeConfidential({
  operation: 'swap',
  amount_usd: 150000,
  inputs: { token_in: 'SOL', token_out: 'USDC' },
  required_proofs: ['balance_threshold']
});

console.log(result.stages_completed);
// ['noir_eligibility', 'inco_encrypt', 'arcium_mpc', 'noir_execution_proof']
console.log(\`Slippage saved: \${result.slippage_saved_bps} bps\`);
console.log(\`Fee: $\${result.fee_usd}\`);

Encrypted Orderbooks (Dark Pools)

// Create encrypted orderbook
const orderbook = await trader.createEncryptedOrderbook('SOL/USDC');

// Submit encrypted order (price/size hidden via FHE)
const order = await trader.submitEncryptedOrder(
  orderbook.orderbook_id,
  'bid',
  145.50,  // price - will be encrypted
  100      // size - will be encrypted
);

// Match orders using FHE comparison (no one sees prices)
const matches = await trader.matchEncryptedOrders(orderbook.orderbook_id);

Private Auctions

// Create sealed-bid auction
const auction = await trader.createPrivateAuction('NFT-123', 1000);

// Submit encrypted bid
const bid = await trader.submitAuctionBid(auction.auction_id, 1500);

// Settle - winner determined without revealing losing bids
const result = await trader.settleAuction(auction.auction_id);
console.log(\`Winner: \${result.winner}\`);

Threshold Signatures

// Multi-party signing (2-of-3)
const signature = await trader.thresholdSign({
  signers: ['agent-1', 'agent-2', 'agent-3'],
  threshold: 2,
  message_hash: '0x...'
});
// No single party sees the full key

Performance Proofs

// Prove performance without revealing strategy
const proof = await trader.provePerformance({
  claim_type: 'win_rate',  // or 'volume', 'profitability'
  metrics: {
    total_trades: 1000,
    profitable_trades: 650,
    total_volume_usd: 5000000,
    total_pnl_usd: 125000
  }
});
// Proof shows win_rate > 50% without revealing exact numbers

Key Principles