7cordon Docs
Complete technical documentation for the AI-powered trust and safety layer for autonomous financial agents. Built on Tether WDK. See the landing page for a visual overview.
Architecture
7cordon is an AI-powered trust and safety layer that sits between autonomous financial agents and blockchain transactions. It uses a multi-level risk analysis pipeline combined with local policy enforcement to protect users from unauthorized or dangerous transactions.
AI Agent
|
"swap 50 USDT for TOKEN-X"
|
+--------+--------+
| 7cordon |
| SDK |
+--------+--------+
|
+-----------+-----------+
| | |
L0 Policy L1 Quick L2 Deep
(instant) (~2-5s) (~10-20s)
policy GoPlus + full risk
engine AI triage assessment
| | |
+-----+-----+-----+-----+
| |
APPROVED BLOCKED
|
+------v------+
| WDK Wallet |
| (execute) |
+------+------+
|
+------v--------+
| Spark Streaming|
| $0.001/sec fee |
+----------------+
Package Structure
7cordon/
├── packages/shared Types, constants, formulas (shared by SDK & API)
│ ├── types/
│ │ ├── analysis.ts RiskLevel, AnalysisResult, GoPlusData
│ │ ├── audit.ts AuditEntry, AuditLog, AuditStats
│ │ ├── policy.ts PolicyConfig, PolicyResult, PolicyViolation
│ │ ├── transaction.ts TransactionRequest, TransactionResult
│ │ └── trust.ts TrustScore, TrustLevel, TrustStats
│ ├── constants.ts Defaults, risk thresholds, cache TTLs
│ └── trust-formula.ts calculateTrustScore()
│
├── packages/sdk Client SDK (runs in agents)
│ ├── guardian.ts Main orchestrator
│ ├── policy/ L0 policy engine
│ ├── trust/ Trust score calculation
│ ├── cache/ LRU cache with file persistence
│ ├── audit/ Append-only audit trail (JSONL)
│ ├── api-client.ts HTTP client to 7cordon API
│ ├── wdk/ WDK wrapper (EVM, Spark)
│ └── mcp/ MCP server for Claude Desktop
│
├── packages/api AI analysis server (Express)
│ ├── server.ts Express app, middleware, routes
│ ├── middleware/auth.ts SHA-256 + timing-safe API key auth
│ ├── middleware/jwt.ts JWT verification middleware
│ ├── routes/ Health, analyze, auth, dashboard
│ ├── analysis/ L1 and L2 analysis pipeline
│ ├── data/ GoPlus, DeFi Llama, Arbiscan
│ └── prompts/ AI prompt templates
│
├── packages/dashboard Svelte 5 + SvelteKit real-time UI
└── packages/demo Demo scenarios and walkthrough
Three-Level Defense Pipeline
Level 0: Policy Engine (L0)
Timing: <1ms • Cost: Free • Location: SDK (local) • Engine: Deterministic rules
Enforced instantly without any AI or network calls. Operates on the fund owner's device using their local policy configuration.
Rules checked:
- Allowed action — only
send,swap,approve,lend,withdraw,bridge - Max transaction amount — single txn cap (default: $100)
- Daily budget — rolling 24h limit (default: $500)
- Weekly budget — rolling 7-day limit (default: $2,000)
- Rate limit — max 5 txns/minute
- Address blacklist — reject known bad recipient addresses
- Token whitelist — only approved tokens (default: USDT, ETH, WBTC, WETH, ARB, USDC)
- Protocol whitelist — only approved protocols (default: Aave, Compound, Uniswap)
Budget persistence: Policy engine restores budget from audit log on startup, preventing restart-based budget bypass.
Level 1: AI Quick Analysis (L1)
Timing: 2-5 seconds • Cost: ~$0.003 USDT • Location: Remote API server • Model: configurable (fast LLM) • Data source: GoPlus API
Quick triage using on-chain security data and lightweight AI analysis. Good for common safe transactions.
Analysis steps:
- Fetch GoPlus token security (honeypot check, holder count, open-source verification)
- Fetch on-chain address reputation (if applicable)
- Run AI prompt: analyze transaction intent + on-chain data
- Return risk assessment
Risk levels: safe, low, medium, high, critical
Escalation to L2 if: Risk level >= medium OR amount > manual approval threshold ($500 default)
Level 2: AI Deep Analysis (L2)
Timing: 10-20 seconds • Cost: ~$0.015 USDT • Location: Remote API server • Model: configurable (reasoning LLM) • Data sources: GoPlus + Arbiscan contract source
Comprehensive threat assessment with full contract code inspection. Used only when L1 flagged suspicious activity or amount is large.
Analysis steps:
- All L1 data (GoPlus, address checks)
- Fetch contract source code from Arbiscan
- Run AI prompt: comprehensive threat assessment with code review
- Identify specific threats (scam token, social engineering, malicious contract, etc.)
- Return detailed explanation and recommendations
Data Flow
Agent
|
└─> guardian.request(TransactionRequest)
|
├─ L0 Policy Check (PolicyEngine.evaluate)
│ └─ BLOCKED? → Return immediately, log to audit, report to API
│
├─ Cache Check (AnalysisCache.get)
│ └─ HIT? → Skip AI, use cached result
│
├─ Start Spark Streaming (if enabled)
│
├─ Remote AI Analysis
│ │
│ └─ POST /analyze to 7cordon API
│ │
│ ├─ Fetch GoPlus data (parallel)
│ ├─ Fetch protocol info (parallel)
│ │
│ ├─ Run L1 Quick Analysis
│ │ └─ Should escalate to L2?
│ │
│ └─ (if escalating) Run L2 Deep Analysis
│ └─ Fetch Arbiscan contract source
│
├─ Stop Spark Streaming
│
├─ Determine Final Status
│ ├─ Approved: low/safe risk + amount <= threshold
│ ├─ Pending: medium risk OR amount > threshold
│ └─ Blocked: high/critical risk OR policy violation
│
├─ Execute Transaction (if approved)
│ └─ WalletManager.send() → WDK → EVM/Spark
│
└─ Log Audit Entry
└─ AuditLogger.append() → .7cordon/audit.jsonl
Data Enrichment Sources
GoPlus API — Token security check: honeypot detection, holder distribution, minting privileges. Address reputation: whether address has been flagged as malicious. Available for EVM chains (Arbitrum, Ethereum, Sepolia).
DeFi Llama API — Protocol metadata: TVL, category (lending, dex, bridge, etc.), supported chains. Used to verify protocol legitimacy and audit status.
Arbiscan API — Contract source code retrieval for deep code review (L2 only). Verifies contract is open-source and can be audited.
Security Model
Key Management
- Seed phrase never persisted to disk
- Consumed during
guardian.init()and immediately released - Used to derive EVM and Spark wallets
- Wallets stored internally and disposed on
guardian.dispose()
API Authentication
- Client sends:
X-Cordon7-Keyheader - Server validates: SHA-256 hash of request body + constant-time comparison
- Prevents timing attacks on API key verification
- Rate limited: 20 req/min on
/analyze, 60 req/min on/dashboard
Input Sanitization (Prompt Injection Defense)
- Regex validation of all fields (amount format, UUID, action enum, etc.)
- String length caps on user-supplied fields
- AI prompt uses field separators and explicit structure to prevent injection
- Schema validation on AI responses (must match expected type signature)
Body size limit: 50KB cap on incoming requests (prevents DoS)
Cache System
Type: In-memory LRU Map with file persistence • Location: .7cordon/analysis-cache.json • Max size: 1,000 entries
Cache keys are built from action, contract address, token, protocol, and recipient address. Amount is NOT included — same token/protocol analyzed once, reused for all amounts.
| Type | TTL |
|---|---|
| Token analysis | 24h |
| Protocol info | 30d |
| Address check | 7d |
File persistence: Debounced write (1s after last set), loaded on startup, expired entries skipped. File mode: 0o600 (owner read/write only).
Budget and Spending Tracking
| Event | Fee |
|---|---|
| L0 policy block | $0 (free) |
| L1 analysis | ~$0.003 USDT |
| L2 analysis | ~$0.015 USDT (includes L1) |
Spark streaming model: While API analyzes, SDK streams $0.001 USDT per second to the 7cordon operator wallet. Safety cap: auto-stops after 60 seconds.
Budget tracking: PolicyEngine stores spend log (timestamp + amount). Daily/weekly budgets calculated as sum of approvals in time window. On restart, budget restored from audit log (prevents restart-based bypass). Spend log pruned to 7-day window.
Trust Score System
Score = (40% x approval_ratio) +
(25% x volume_score) +
(20% x time_score) +
(15% x streak_score)
| Factor | Weight | Calculation | Scale |
|---|---|---|---|
| Approval ratio | 40% | (1 - blocked/total) x 100 | 0-100 |
| Volume | 25% | log10(total_USDT) / 4 x 100 | Log: $0->0, $10K->100 |
| Active time | 20% | log10(hours+1) / 3 x 100 | Log: 0h->0, 1000h->100 |
| Approval streak | 15% | consecutive / 50 x 100 | Linear: 0->0, 50->100 |
| Score | Level | Behavior |
|---|---|---|
| 0-20 | Untrusted | All transactions get L2 analysis |
| 21-40 | Cautious | Most transactions get L1+L2 |
| 41-60 | Moderate | Standard pipeline, L2 only when flagged |
| 61-80 | Trusted | Faster approvals for known patterns |
| 81-100 | Veteran | Maximum efficiency, minimal escalation |
Audit Trail
Format: JSON Lines (JSONL) — one JSON object per line • Location: .7cordon/audit.jsonl • Mode: Append-only (immutable history)
Each entry includes: Request ID, timestamp, transaction details, policy result, analysis result, final status, risk level, explanation, fee paid, and transaction hash (if executed). File permissions: 0o600.
Streaming Payments (Spark)
Agent starts request
↓
7cordon analyzes (3 seconds)
├─ Time 0s: Stream payment #1 ($0.001)
├─ Time 1s: Stream payment #2 ($0.001)
├─ Time 2s: Stream payment #3 ($0.001)
↓ (Analysis completes)
Stop streaming
↓
Total paid: $0.003 for 3-second L1 analysis
Implementation (SparkPayer): Sequential payment loop, one at a time. Each payment sent to the operator's Spark address. Interval: 1 second. Safety cap: 60-second limit. Failure handling: 3 consecutive failures stop streaming.
Error Handling Strategy
- L0 Policy failures: Fast-fail without AI. Fee: $0.
- Network errors: API client timeout 45s. Spark retry: 3 failures. GoPlus/DeFi Llama: best-effort (continue with partial data).
- LLM response validation: Malformed response = critical error, transaction blocked. Risk level re-validated against enum.
- File I/O failures: Audit log write fails = entry stays in memory. Cache write fails = in-memory cache still works.
SDK Guide
The 7cordon SDK is the client-side library that agents integrate to protect their transactions. It provides transaction analysis, policy enforcement, and local wallet management.
Installation
npm install @7cordon/sdk @7cordon/shared
Quick Start
import { createGuardian } from '@7cordon/sdk';
// 1. Create 7cordon instance
const guardian = createGuardian({
apiUrl: 'http://localhost:3000',
apiKey: 'your-api-key',
evmRpcUrl: 'https://arb1.arbitrum.io/rpc',
chain: 'arbitrum',
});
// 2. Initialize with seed phrase
await guardian.init('your twelve word mnemonic phrase here');
// 3. Submit a transaction request
const result = await guardian.request({
id: crypto.randomUUID(),
action: 'swap',
params: {
chain: 'arbitrum',
amount: '50',
fromToken: 'USDT',
toToken: 'WETH',
protocol: 'uniswap',
contractAddress: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',
},
reasoning: 'Portfolio rebalancing to increase ETH exposure',
timestamp: Date.now(),
});
console.log(result.status); // 'approved' | 'blocked' | 'pending_approval'
console.log(result.riskLevel); // 'safe' | 'low' | 'medium' | 'high' | 'critical'
console.log(result.explanation);
// 4. Cleanup
await guardian.dispose();
GuardianConfig
interface GuardianConfig {
// Required
evmRpcUrl: string; // EVM RPC endpoint
chain: Chain; // Target blockchain
apiUrl: string; // 7cordon API server URL
apiKey?: string; // Shared secret (optional with wallet auth)
// Optional: Policy customization
policy?: Partial<PolicyConfig>;
// Optional: Spark streaming payments
enableSparkPayments?: boolean; // Enable $0.001/sec USDT micropayments
guardianSparkAddress?: string; // Operator's Spark address
sparkNetwork?: 'MAINNET' | 'TESTNET';
// Optional: Transaction execution control
analysisOnly?: boolean; // Skip WDK execution (default: false)
// Optional: ERC-4337 gasless transactions
erc4337?: Erc4337Config;
}
Config Examples
Local development:
const guardian = createGuardian({
evmRpcUrl: 'https://arb-sepolia.g.alchemy.com/v2/demo',
chain: 'sepolia',
apiUrl: 'http://localhost:3000',
apiKey: 'test-key-123',
});
Production with Spark payments:
const guardian = createGuardian({
evmRpcUrl: 'https://arb1.arbitrum.io/rpc',
chain: 'arbitrum',
apiUrl: 'https://api.7cordon.xyz',
apiKey: process.env.CORDON7_API_KEY,
enableSparkPayments: true,
guardianSparkAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18',
sparkNetwork: 'MAINNET',
});
Analysis-only mode (no wallet execution):
const guardian = createGuardian({
evmRpcUrl: 'https://arb1.arbitrum.io/rpc',
chain: 'arbitrum',
apiUrl: 'http://localhost:3000',
apiKey: process.env.CORDON7_API_KEY,
analysisOnly: true,
});
Policy Configuration
interface PolicyConfig {
maxTransactionAmount: string; // Single transaction cap (default: "100")
dailyBudget: string; // Rolling 24h limit (default: "500")
weeklyBudget: string; // Rolling 7-day limit (default: "2000")
rateLimit: number; // Max txns/minute (default: 5)
allowedActions: TransactionAction[];
// Default: ['send', 'swap', 'lend', 'withdraw', 'approve', 'bridge']
whitelist: {
addresses: string[];
protocols: string[]; // Default: ['aave', 'compound', 'uniswap']
tokens: string[]; // Default: ['USDT', 'ETH', 'WBTC', 'WETH', 'ARB', 'USDC']
};
blacklist: {
addresses: string[];
};
autoApproveThreshold: string; // Default: "10"
manualApproveThreshold: string; // Default: "500"
}
Restrict to Uniswap only:
const guardian = createGuardian({
// ... other config
policy: {
whitelist: {
protocols: ['uniswap'],
tokens: ['USDT', 'WETH', 'USDC'],
},
},
});
Tight budget for testing:
const guardian = createGuardian({
// ... other config
policy: {
maxTransactionAmount: '10',
dailyBudget: '50',
weeklyBudget: '200',
autoApproveThreshold: '5',
},
});
Initialization Flow
// Step 1: Create instance (no network calls, no keys loaded yet)
const guardian = createGuardian(config);
// Step 2: Initialize with seed phrase (derives wallets, clears seed)
await guardian.init(seedPhrase);
// Step 3: Ready to process transactions
const result = await guardian.request(transactionRequest);
Key property: The seed phrase is never stored. It is consumed during
init()and immediately released.
TransactionRequest Format
interface TransactionRequest {
id: string; // UUID v4
action: TransactionAction; // 'send' | 'swap' | 'approve' | 'lend' | 'withdraw' | 'bridge'
params: TransactionParams;
reasoning: string; // Agent's explanation for the transaction
timestamp: number; // Milliseconds since epoch
}
interface TransactionParams {
chain: Chain; // 'ethereum' | 'arbitrum' | 'polygon' | 'bsc' | 'base' | 'optimism' | 'avalanche' | 'sepolia'
amount: string; // Decimal string (e.g., "50.5")
fromToken?: string; // Source token symbol
toToken?: string; // Destination token symbol
toAddress?: string; // Recipient address (for send)
protocol?: string; // DeFi protocol name
contractAddress?: string; // Smart contract address
data?: string; // Encoded function call (advanced)
}
Request Examples
Simple token send:
const request: TransactionRequest = {
id: crypto.randomUUID(),
action: 'send',
params: {
chain: 'arbitrum',
amount: '50',
fromToken: 'USDT',
toAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18',
},
reasoning: 'Transfer to secondary wallet for gas funding',
timestamp: Date.now(),
};
Swap on DEX:
const request: TransactionRequest = {
id: crypto.randomUUID(),
action: 'swap',
params: {
chain: 'arbitrum',
amount: '100',
fromToken: 'USDT',
toToken: 'WETH',
protocol: 'uniswap',
contractAddress: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',
},
reasoning: 'Portfolio rebalancing',
timestamp: Date.now(),
};
TransactionResult
interface TransactionResult {
requestId: string;
status: 'approved' | 'blocked' | 'pending_approval';
riskLevel: RiskLevel; // 'safe' | 'low' | 'medium' | 'high' | 'critical'
explanation: string;
analysisLevel: AnalysisLevel; // 'L0_policy' | 'L1_quick' | 'L2_deep'
txHash?: string; // Blockchain tx hash (if executed)
feePaid: string; // USDT paid for analysis
duration: number; // Total milliseconds
timestamp: number;
}
| Status | Meaning |
|---|---|
approved | Transaction executed (unless analysisOnly mode) |
blocked | Transaction rejected, not executed |
pending_approval | Analysis complete, awaiting user confirmation |
| Analysis Level | Time | Cost |
|---|---|---|
L0_policy | <1ms | Free |
L1_quick | 2-5s | ~$0.003 |
L2_deep | 10-20s | ~$0.015 |
Policy Engine
// Get current policy config
const config = guardian.getPolicyEngine().getConfig();
console.log(config.maxTransactionAmount); // "100"
console.log(config.whitelist.tokens); // ['USDT', 'ETH', ...]
// Get budget status
const budget = guardian.getPolicyEngine().getBudgetStatus();
console.log(budget.dailySpent); // 250.50
console.log(budget.dailyLimit); // 500
// Update policy at runtime (deep merges)
guardian.getPolicyEngine().updateConfig({
maxTransactionAmount: '200',
whitelist: {
protocols: [...currentProtocols, 'curve'],
},
});
Cache System
The SDK caches analysis results internally using an LRU cache with file persistence. Repeated requests for the same token/protocol/address reuse previous results automatically.
TTLs: Token analysis: 24h, Protocol info: 30d, Address checks: 7d
Trust Score
const trust = guardian.getTrustScore();
console.log(trust.score); // 0-100
console.log(trust.level); // 'untrusted' | 'cautious' | 'moderate' | 'trusted' | 'veteran'
console.log(trust.stats); // { totalTransactions, approvedCount, blockedCount, ... }
Audit Log
// Get most recent 10 entries
const entries = guardian.getAuditLog().getEntries(10);
for (const entry of entries) {
console.log(`${entry.action} $${entry.params.amount} -> ${entry.finalStatus}`);
}
// Get stats
const stats = guardian.getAuditLog().getStats();
// { totalRequests, approved, blocked, pending, totalFeesPaid, averageAnalysisTime }
// Clear log (for testing/reset)
guardian.getAuditLog().clear();
Spark Payment Configuration
const guardian = createGuardian({
// ... other config
enableSparkPayments: true,
guardianSparkAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18',
sparkNetwork: 'MAINNET',
});
How it works: During AI analysis, SDK streams $0.001/sec USDT. Analysis completes, streaming stops. Total fee = seconds x $0.001. Safety: auto-stop after 60s, 3 consecutive failures stop streaming.
ERC-4337 Gasless Transactions
// Sponsored model (paymaster covers gas)
const guardian = createGuardian({
// ... other config
erc4337: {
bundlerUrl: 'https://bundler.example.com/rpc',
paymasterUrl: 'https://paymaster.example.com/rpc',
isSponsored: true,
sponsorshipPolicyId: 'my-policy',
},
});
// Token-based model (pay gas with token)
const guardian = createGuardian({
// ... other config
erc4337: {
bundlerUrl: '...',
paymasterUrl: '...',
paymasterAddress: '0x...',
paymasterTokenAddress: '0x...', // e.g., USDT
},
});
Error Handling
try {
const result = await guardian.request(request);
if (result.status === 'blocked') {
console.warn(`Blocked: ${result.explanation}`);
} else if (result.status === 'pending_approval') {
console.log(`Awaiting approval: ${result.riskLevel}`);
} else {
console.log(`Approved: ${result.txHash}`);
}
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('not initialized')) {
// guardian.init() wasn't called
} else if (error.message.includes('7cordon API')) {
// API server unreachable
}
console.error(`Failed: ${error.message}`);
}
}
Common errors:
Guardian not initialized. Call init() first.7cordon API error 401— invalid or missing API key7cordon API request timed out— API server not respondingInvalid EVM address— malformed address
Integration Examples
With AI Agent (Node.js)
import Anthropic from '@anthropic-ai/sdk';
import { createGuardian } from '@7cordon/sdk';
const client = new Anthropic();
const guardian = createGuardian({
apiUrl: process.env.CORDON7_API_URL,
apiKey: process.env.CORDON7_API_KEY,
evmRpcUrl: process.env.EVM_RPC_URL,
chain: 'arbitrum',
});
await guardian.init(process.env.WDK_SEED_PHRASE);
async function executeTransaction(description: string) {
const message = await client.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
system: `You are an autonomous agent. Analyze the user's request
and construct a transaction. Return JSON.`,
messages: [{ role: 'user', content: description }],
});
const txData = JSON.parse(message.content[0].text);
const result = await guardian.request({
id: crypto.randomUUID(),
action: txData.action,
params: txData.params,
reasoning: txData.reasoning,
timestamp: Date.now(),
});
console.log(`Status: ${result.status}, Risk: ${result.riskLevel}`);
return result;
}
await executeTransaction('Swap 50 USDT for WETH');
await guardian.dispose();
Production Checklist
- API URL uses HTTPS (not localhost)
- API key loaded from environment variables
- Seed phrase loaded from secure storage (not hardcoded)
- Error handling implemented for all
request()calls dispose()called on shutdown- Policy configured for your use case
- Budget limits set appropriately
- Spark payments funded if enabled
- Rate limiting understood (20 req/min on API)
- Audit logs reviewed regularly
API Reference
The 7cordon API server handles multi-level risk analysis (L1 quick, L2 deep) with AI, integrates external data sources (GoPlus, DeFi Llama, Arbiscan), and serves a dashboard for real-time monitoring.
Server Setup
# Start with default configuration
npm run dev:api
# or with custom port
PORT=3001 npm run dev:api
Environment Variables
# Required
ANTHROPIC_API_KEY=sk-ant-... # Claude API key
CORDON7_API_KEY=your-shared-secret # API authentication
# Optional
PORT=3000 # Server port (default: 3000)
NODE_ENV=development|production
CORS_ORIGIN=http://localhost:4000
ARBISCAN_API_KEY=... # Contract source retrieval
Authentication
All protected endpoints require the X-Cordon7-Key header.
- Client sends
X-Cordon7-Key: <api-key>header - Server SHA-256 hashes the request body
- Server performs timing-safe constant-time comparison
- Prevents timing attacks on API key verification
curl -X POST http://localhost:3000/analyze \
-H "X-Cordon7-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{...}'
Rate Limiting
| Endpoint | Window | Limit | Purpose |
|---|---|---|---|
/analyze | 60s | 20 req/min | AI analysis (expensive) |
/dashboard/report | 60s | 60 req/min | SDK reporting (light) |
| All others | 60s | Standard | General requests |
POST /analyze
POST Auth Required 20 req/min
Submit a transaction for AI risk analysis.
Request body
{
"request": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"action": "swap",
"params": {
"chain": "arbitrum",
"amount": "50",
"fromToken": "USDT",
"toToken": "WETH",
"protocol": "uniswap",
"contractAddress": "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"
},
"reasoning": "Portfolio rebalancing",
"timestamp": 1710000000000
},
"trustScore": 42
}
Response (200 OK)
{
"requestId": "550e8400-...",
"level": "L1_quick",
"riskLevel": "low",
"approved": true,
"explanation": "Verified token swap on audited protocol.",
"details": {
"threats": [],
"goplus": {
"isHoneypot": false,
"isOpenSource": true,
"holderCount": 15000,
"lpAmount": "500000",
"isMintable": false,
"isProxy": false,
"maliciousAddress": false
},
"protocol": {
"name": "Uniswap",
"tvl": 5200000000,
"category": "dex",
"chains": ["ethereum", "arbitrum", "polygon"]
}
},
"duration": 2340
}
Error Responses
| Status | Error | Cause |
|---|---|---|
| 400 | Invalid request schema | Missing/malformed field |
| 401 | Unauthorized | Missing/invalid API key |
| 429 | Too many requests | Rate limit exceeded |
| 500 | Analysis failed | Internal server error |
GET /health
GET No Auth
{
"status": "ok",
"version": "0.1.0",
"uptime": 3600000
}
GET /dashboard/stats
GET No Auth
{
"totalRequests": 42,
"approved": 38,
"blocked": 4,
"pending": 0,
"totalFeesPaid": "0.042000",
"averageAnalysisTime": 3200
}
GET /dashboard/entries
GET No Auth
Paginated audit entries (newest first).
| Parameter | Type | Default | Max |
|---|---|---|---|
limit | number | 50 | 100 |
offset | number | 0 | unbounded |
GET /dashboard/trust
GET No Auth
{
"score": 65,
"level": "trusted",
"stats": {
"totalTransactions": 42,
"approvedCount": 38,
"blockedCount": 4,
"blockedRatio": 0.095,
"totalVolume": "1234.56",
"activeTime": 3600,
"consecutiveApproved": 12
}
}
GET /dashboard/policy
GET No Auth
{
"config": {
"maxTransactionAmount": "100",
"dailyBudget": "500",
"weeklyBudget": "2000",
"rateLimit": 5,
"allowedActions": ["send", "swap", "approve", "lend", "withdraw", "bridge"],
"whitelist": {
"addresses": [],
"protocols": ["aave", "compound", "uniswap"],
"tokens": ["USDT", "ETH", "WBTC", "WETH", "ARB", "USDC"]
},
"blacklist": { "addresses": [] },
"autoApproveThreshold": "10",
"manualApproveThreshold": "500"
},
"budget": {
"dailySpent": 250.50,
"weeklySpent": 750.00,
"dailyLimit": 500,
"weeklyLimit": 2000
}
}
POST /dashboard/report
POST Auth Required 60 req/min
SDK reports the final analysis decision (including L0 blocks that never reach /analyze). Fire-and-forget.
{
"requestId": "550e8400-...",
"finalStatus": "approved",
"riskLevel": "low",
"level": "L1_quick",
"explanation": "Verified token swap...",
"duration": 2340,
"action": "swap",
"amount": "50",
"chain": "arbitrum",
"protocol": "uniswap",
"fromToken": "USDT",
"toToken": "WETH"
}
Response: { "ok": true }
Data Enrichment
GoPlus Integration
Fetches token security and address reputation data. Integrated into /analyze (L1 and L2). On error: best-effort (continues with partial data).
{
"isHoneypot": false,
"isOpenSource": true,
"holderCount": 15000,
"lpAmount": "500000.00",
"isMintable": false,
"isProxy": false,
"maliciousAddress": false
}
DeFi Llama Integration
Protocol metadata for risk assessment. On error: best-effort.
{
"name": "Uniswap",
"tvl": 5200000000,
"category": "dex",
"chains": ["ethereum", "arbitrum", "polygon", "optimism"]
}
Arbiscan Integration
Contract source code for deep analysis. L2 only (on escalation). Fetches full source code, compiler version, verification status.
Response Schemas
interface AnalysisResult {
requestId: string;
level: 'L0_policy' | 'L1_quick' | 'L2_deep';
riskLevel: 'safe' | 'low' | 'medium' | 'high' | 'critical';
approved: boolean;
explanation: string;
details: AnalysisDetails;
duration: number;
}
interface AnalysisDetails {
goplus?: GoPlusData;
protocol?: ProtocolData;
aiReasoning?: string;
threats: ThreatInfo[];
}
type ThreatType =
| 'scam_token'
| 'malicious_contract'
| 'unknown_address'
| 'reasoning_mismatch'
| 'overspending'
| 'unaudited_protocol'
| 'honeypot'
| 'unlimited_approval'
| 'rate_limit_exceeded';
Testing with cURL
# Analyze transaction
curl -X POST http://localhost:3000/analyze \
-H "X-Cordon7-Key: test-key" \
-H "Content-Type: application/json" \
-d '{ "request": { "id": "'$(uuidgen)'", "action": "send", "params": { "chain": "arbitrum", "amount": "50", "toAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18" }, "reasoning": "Test transfer", "timestamp": '$(date +%s000)' }, "trustScore": 50 }'
# Get dashboard stats
curl http://localhost:3000/dashboard/stats
# Get recent entries
curl 'http://localhost:3000/dashboard/entries?limit=10&offset=0'
# Get trust score
curl http://localhost:3000/dashboard/trust
CORS Configuration
# Single origin
CORS_ORIGIN=https://app.example.com
# Multiple origins (comma-separated)
CORS_ORIGIN=https://app.example.com,https://dashboard.example.com
Body size limit: 50KB. Security headers: Helmet.js (nosniff, DENY frame, XSS protection, CSP).
WDK Module
7cordon provides a native WDK middleware module that integrates directly with @tetherto/wdk via the official registerMiddleware() API. One line of code adds AI-powered transaction analysis to any WDK wallet.
Installation
npm install @7cordon/wdk-module @7cordon/sdk @7cordon/shared
The module also requires a running 7cordon API server (see API Server section).
Usage
import WDK from '@tetherto/wdk'
import WalletManagerEvm from '@tetherto/wdk-wallet-evm'
import { guardianMiddleware } from '@7cordon/wdk-module'
const wdk = new WDK(seedPhrase)
.registerWallet('ethereum', WalletManagerEvm, {
provider: 'https://eth.drpc.org',
})
.registerMiddleware('ethereum', guardianMiddleware({
apiUrl: 'http://localhost:3000',
apiKey: process.env.CORDON7_API_KEY,
chain: 'ethereum',
}))
// All transactions now go through 7cordon
const account = await wdk.getAccount('ethereum', 0)
await account.sendTransaction({ to: '0x...', value: 1000000000000000000n })
// ^ 7cordon intercepts: L0 policy check -> L1/L2 AI analysis -> execute or block
The middleware wraps sendTransaction() and transfer() on every account derived via getAccount(). Works with any WDK wallet module (EVM, ERC-4337, etc.).
Configuration
| Option | Type | Required | Description |
|---|---|---|---|
apiUrl | string | Yes | 7cordon API server URL |
apiKey | string | Yes | API authentication key |
chain | string | No | Blockchain identifier: ethereum, arbitrum, sepolia (default: ethereum) |
policy | object | No | L0 policy config for local checks (maxTransaction, dailyBudget, etc.) |
defaultReasoning | string | No | Default reasoning string for audit trail |
onAnalysis | function | No | Callback fired after each analysis: (request, result) => void |
Error Handling
import { GuardianBlockedError } from '@7cordon/wdk-module'
try {
await account.sendTransaction({ to, value })
} catch (error) {
if (error instanceof GuardianBlockedError) {
console.log(error.message) // "[7cordon] Transaction blocked: ..."
console.log(error.riskLevel) // "high" | "critical" | "medium"
console.log(error.analysisLevel) // "L0_policy" | "L1_quick" | "L2_deep"
console.log(error.details) // GoPlus data, threats, etc.
}
}
Blocked transactions throw GuardianBlockedError with the full risk assessment. Approved transactions proceed to the original WDK method transparently.
With L0 Policy Engine
// Add local policy checks (instant, no API call needed)
.registerMiddleware('ethereum', guardianMiddleware({
apiUrl: 'http://localhost:3000',
apiKey: process.env.CORDON7_API_KEY,
policy: {
maxTransaction: 100, // $100 max per transaction
dailyBudget: 500, // $500 daily limit
weeklyBudget: 2000, // $2000 weekly limit
},
}))
When policy is set, L0 checks run locally before the API call. Transactions exceeding limits are blocked instantly without incurring AI analysis costs.
MCP Integration
Model Context Protocol is a standardized interface for AI agents to interact with external tools. 7cordon implements an MCP server that exposes 4 tools for Claude Desktop and other MCP clients.
Starting the MCP Server
npm run mcp
This loads .env, initializes 7cordon SDK, starts MCP stdio server, and waits for client connections.
Required Environment Variables
CORDON7_API_KEY=test-key-123
ANTHROPIC_API_KEY=sk-ant-...
EVM_RPC_URL=https://arb1.arbitrum.io/rpc
WDK_SEED_PHRASE=your twelve word mnemonic here
Claude Desktop Integration
Step 1: Edit claude_desktop_config.json
| Platform | Location |
|---|---|
| macOS | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
| Linux | ~/.config/Claude/claude_desktop_config.json |
Step 2: Add 7cordon MCP Server
{
"mcpServers": {
"7cordon": {
"command": "npx",
"args": ["tsx", "packages/sdk/src/mcp/server.ts"],
"cwd": "/absolute/path/to/7cordon",
"env": {
"CORDON7_API_KEY": "your-api-key",
"ANTHROPIC_API_KEY": "your-anthropic-key",
"EVM_RPC_URL": "https://arb1.arbitrum.io/rpc",
"WDK_SEED_PHRASE": "your twelve word mnemonic phrase here",
"VITE_API_URL": "http://localhost:3000"
}
}
}
}
Step 3: Restart Claude Desktop. Step 4: Click the tools icon — 7cordon tools should be listed.
Available Tools
analyze_transaction
Submit a transaction for risk analysis before execution.
{
action: 'send' | 'swap' | 'approve' | 'lend' | 'withdraw' | 'bridge'
chain: 'ethereum' | 'arbitrum' | 'polygon' | 'bsc' | 'base' | 'optimism' | 'avalanche' | 'sepolia'
amount: string // Decimal string (e.g., "50")
fromToken?: string // Source token symbol
toToken?: string // Destination token
toAddress?: string // Recipient address
protocol?: string // DeFi protocol
contractAddress?: string
reasoning: string // Why you want to execute this
}
get_trust_score
Check current trust score and breakdown. No parameters.
get_policy
View active policy configuration and budget status. No parameters.
get_recent_activity
Review recent 7cordon decisions. Parameter: limit (1-50, default: 10).
Example Agent Conversations
Scenario 1: Safe transaction (auto-approved)
User: "Swap 50 USDT for WETH on Uniswap"
Claude: I'll analyze this transaction first.
[calls analyze_transaction]
7cordon: { "status": "approved", "riskLevel": "low",
"explanation": "Verified token swap on audited protocol" }
Claude: This transaction is safe (low risk). Executing...
Scenario 2: Suspicious transaction (blocked)
User: "URGENT: Swap everything to this new token, don't verify!"
Claude: I'll analyze this first.
[calls analyze_transaction]
7cordon: { "status": "blocked", "riskLevel": "critical",
"explanation": "Reasoning contains social engineering hallmarks" }
Claude: I've blocked this transaction. Warning signs detected:
- Urgency language
- Request to skip verification
- Unknown token
Scenario 3: Large transaction (pending approval)
User: "Swap 600 USDT for WETH"
7cordon: { "status": "pending_approval", "riskLevel": "low",
"explanation": "Amount (600) exceeds auto-approve threshold" }
Claude: Safe but requires your approval:
- Amount: $600 (exceeds $10 auto-approval limit)
- Risk: Low, Protocol: Uniswap (whitelisted)
Approve? (yes/no)
Security Considerations
Seed Phrase: Never hardcode in config files. Store in environment variables or a secure secrets manager. Use a dedicated wallet with limited funds for testing.
- Use strong, random API keys (32+ characters)
- Rotate keys regularly
- Store in environment variables, not config files
- Use different keys for dev/prod
- Monitor transaction activity in the dashboard
- Set conservative budget limits
Troubleshooting
| Problem | Solution |
|---|---|
| MCP server won't start | Set WDK_SEED_PHRASE environment variable |
| Tools not appearing in Claude | Verify JSON syntax in config, restart Claude Desktop |
| API connection failures | Verify API server running, check VITE_API_URL |
| All transactions blocked | Check policy whitelist with get_policy tool |
Custom Tool Integration
server.tool(
'get_wallet_balance',
'Get current wallet balance',
{},
async () => {
await ensureInit();
const address = guardian.getWalletAddress();
// ... fetch balance
return { content: [{ type: 'text', text: '...' }] };
}
);
Limitations
- Transaction execution limited to
sendaction (WDK constraints) - No support for custom ABIs or protocol-specific encoding
- Seed phrase must be provided (no hardware wallet support yet)
analysisOnlymode active (transactions analyzed but not executed)
Deployment
Prerequisites
- Node.js: 18+ (20+ recommended)
- npm: 9+
- Git: For cloning
Optional: Docker, pm2, systemd
Local Development Setup
Step 1: Clone and Install
git clone https://github.com/shipooor/7cordon.git
cd 7cordon
npm install
Step 2: Configure Environment
cp .env.example .env
nano .env
# Required
ANTHROPIC_API_KEY=sk-ant-...
CORDON7_API_KEY=test-key-123
EVM_RPC_URL=https://arb1.arbitrum.io/rpc
# Optional
PORT=3000
NODE_ENV=development
VITE_API_URL=http://localhost:3000
ARBISCAN_API_KEY=...
Step 3: Build All Packages
npm run build
Step 4: Start Services
# Terminal 1 - API Server
npm run dev:api # http://localhost:3000
# Terminal 2 - Dashboard
npm run dev:dashboard # http://localhost:5173
# Terminal 3 - Demo
npm run dev:demo # Runs 6 demo scenarios
# Terminal 4 - MCP Server (optional)
npm run mcp # stdio for Claude Desktop
# Verify
curl http://localhost:3000/health
Monitoring Dashboard
7cordon includes a real-time monitoring dashboard for tracking your agents' activity. It shows transaction stats, trust score, budget usage, policy configuration, and a live activity feed.
Start the dashboard
# Make sure the API server is running first
npm run dev:api
# In a separate terminal
npm run dev:dashboard # http://localhost:5173
The dashboard connects to your local API server and auto-refreshes every 5 seconds. It reads from the /dashboard/* endpoints (read-only, no auth required for self-hosted).
What you'll see
- Stats: total requests, approved, blocked, pending, avg analysis time
- Trust Score: 0-100 gauge based on transaction history
- Budget: daily and weekly spend vs limits
- Policy: max per tx, auto-approve threshold, rate limits, whitelisted tokens and protocols
- Recent Activity: live feed of all analyzed transactions with status, risk level, and AI explanation
Note: The dashboard is for self-hosted deployments. In the future 7cordon Network, the dashboard will be available at 7cordon.xyz with wallet-based auth, where each agent owner sees only their own data.
npm Scripts
| Script | Purpose |
|---|---|
npm run dev:api | Start API server (watch mode) |
npm run dev:dashboard | Start dashboard (dev server) |
npm run dev:demo | Run demo scenarios |
npm run mcp | Start MCP server |
npm run build | Build all packages (production) |
npm run lint | Run ESLint |
npm run type-check | TypeScript check |
npm run clean | Remove build artifacts |
Production Deployment
Step 1: Server Setup
ssh user@server.example.com
git clone https://github.com/shipooor/7cordon.git
cd 7cordon
npm install --production
Step 2: Environment
cat > .env << EOF
NODE_ENV=production
ANTHROPIC_API_KEY=sk-ant-...
CORDON7_API_KEY=$(openssl rand -hex 32)
EVM_RPC_URL=https://arb1.arbitrum.io/rpc
PORT=3000
CORS_ORIGIN=https://app.example.com
EOF
chmod 600 .env
Step 3: Build and Start with PM2
npm run build
npm install -g pm2
# Create ecosystem file
cat > ecosystem.config.cjs << 'EOF'
module.exports = {
apps: [
{
name: '7cordon-api',
script: 'node',
args: 'packages/api/dist/index.js',
env: { NODE_ENV: 'production' },
autorestart: true,
},
{
name: '7cordon-dashboard',
script: 'npx',
args: 'serve packages/dashboard/build -l 5173',
env: { NODE_ENV: 'production' },
autorestart: true,
}
]
};
EOF
pm2 start ecosystem.config.cjs
pm2 startup
pm2 save
Step 4: Reverse Proxy (nginx)
server {
listen 443 ssl http2;
server_name api.example.com;
ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Step 5: SSL (Let's Encrypt)
sudo apt install certbot python3-certbot-nginx
sudo certbot certonly --standalone -d api.example.com
sudo systemctl enable certbot.timer
Docker Deployment
FROM node:20-alpine
WORKDIR /app
COPY package*.json package-lock.json ./
COPY packages/shared packages/shared
COPY packages/api packages/api
RUN npm install --production && npm run build
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/health', (r) => { if (r.statusCode !== 200) throw new Error(r.statusCode) })"
CMD ["node", "packages/api/dist/index.js"]
docker build -t 7cordon-api:latest .
docker run -d --name 7cordon-api -p 3000:3000 \
-e ANTHROPIC_API_KEY=sk-ant-... \
-e CORDON7_API_KEY=test-key \
-e EVM_RPC_URL=https://arb1.arbitrum.io/rpc \
7cordon-api:latest
Docker Compose
version: '3.8'
services:
api:
build: { context: ., dockerfile: Dockerfile.api }
ports: ["3000:3000"]
environment:
NODE_ENV: production
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY}
CORDON7_API_KEY: ${CORDON7_API_KEY}
EVM_RPC_URL: ${EVM_RPC_URL}
restart: unless-stopped
dashboard:
build: { context: ., dockerfile: Dockerfile.dashboard }
ports: ["5173:3000"]
environment:
VITE_API_URL: http://api:3000
depends_on: [api]
restart: unless-stopped
Systemd Service
[Unit]
Description=7cordon API
After=network.target
[Service]
Type=simple
User=7cordon
WorkingDirectory=/opt/7cordon
EnvironmentFile=/opt/7cordon/.env
ExecStart=/usr/bin/node /opt/7cordon/packages/api/dist/index.js
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Environment Variable Reference
API Server
| Variable | Required | Default | Description |
|---|---|---|---|
NODE_ENV | No | development | Environment mode |
PORT | No | 3000 | API server port |
ANTHROPIC_API_KEY | Yes | — | Claude API key |
CORDON7_API_KEY | Yes | — | Shared secret |
EVM_RPC_URL | No | — | EVM RPC endpoint |
CORS_ORIGIN | No | localhost:4000 | CORS origins |
ARBISCAN_API_KEY | No | — | Contract source |
SDK / MCP
| Variable | Required | Default | Description |
|---|---|---|---|
VITE_API_URL | No | localhost:3000 | API server URL |
EVM_RPC_URL | Yes | — | EVM RPC endpoint |
WDK_SEED_PHRASE | MCP | — | BIP-39 mnemonic |
ENABLE_SPARK_PAYMENTS | No | false | Streaming payments |
CORDON7_SPARK_ADDRESS | No | — | Spark address |
Scaling Considerations
- Horizontal: Load balance API instances with nginx/haproxy. Redis for shared cache. Database for audit trail.
- Vertical: Increase RAM for larger cache. Faster CPU for AI analysis.
- Cost optimization: Cache aggressively (24h TTL). Batch Spark payments.
Key Metrics to Track
- API response time (target: <5s for L1)
- Error rate (target: <0.1%)
- Cache hit ratio (target: >80%)
- Audit log size (daily/weekly growth)
Troubleshooting
| Problem | Solution |
|---|---|
| Port already in use | lsof -i :3000 then kill, or use PORT=3001 |
| CORS errors | Set CORS_ORIGIN to frontend URL |
| API 401 error | Check X-Cordon7-Key header matches CORDON7_API_KEY |
| Memory growing | Check cache bounds (max 1000), consider DB persistence |
Backup and Recovery
# Daily backup
cp .7cordon/audit.jsonl /backups/audit-$(date +%Y%m%d).jsonl
# With compression
tar czf /backups/7cordon-$(date +%Y%m%d).tar.gz .7cordon/
# Restore
cp /backups/audit-20260315.jsonl .7cordon/audit.jsonl
Network Model
7cordon is fully open source. Anyone can clone the repo and run it on their own server. The code is not the moat — the network is.
Self-hosted Mode
Clone, configure, run. Full 7cordon pipeline works in isolation:
- L0 policy engine, L1 quick analysis, L2 deep analysis
- Your own API keys (Anthropic for Claude, GoPlus for on-chain data)
- Local audit log, local analysis cache, local trust scoring
- Complete control over policy rules and whitelists
- Zero dependencies on 7cordon infrastructure
Limitation: every token, contract, and address is analyzed from scratch. No shared knowledge. Your instance learns only from its own history.
7cordon Network (roadmap)
The next evolution: connect to the 7cordon Network via MCP or API and unlock collective intelligence. Analysis payments flow through Spark — the network sustains itself. The features below are planned, not yet implemented.
Shared Threat Database
When any 7cordon node flags a token as malicious, the verdict propagates to the entire network:
- Scam tokens, honeypots, rug-pull contracts — flagged once, blocked everywhere
- Malicious addresses (known drainers, phishing wallets) shared in real-time
- Social engineering patterns (urgency language, "skip verification" instructions) learned from blocked transactions across all nodes
More users = more threat data = better protection for everyone. A self-hosted instance starts with zero knowledge. A network node starts with the collective experience of every previous analysis.
Global Analysis Cache
Self-hosted 7cordon caches results locally. If you analyze WETH on Uniswap, the result is cached on your machine. Another self-hosted instance analyzes the same token from scratch, paying for AI again.
On the network, analysis results are shared:
- Token already verified by 200 network nodes? Your analysis is instant and free
- Protocol already deep-analyzed (L2) this week? You get the cached result, no AI cost
- Only novel tokens/contracts trigger fresh analysis — the rest is served from the global cache
At scale, this reduces AI costs by 80-90% compared to isolated instances.
Cross-agent Pattern Detection
A single 7cordon instance sees one agent's transactions. The network sees all of them:
- Coordinated attacks: same scam contract targeting 5 different agents in 10 minutes — an isolated node sees one attempt, the network sees the pattern
- Volume anomalies: a token suddenly appears in 50 analysis requests — either legitimate hype or coordinated pump. The network can distinguish based on threat signals
- Zero-day protection: new exploit hits the first node, all subsequent nodes are warned within seconds
Reputation Scores
The network maintains global reputation scores for:
- Addresses: how many times has this address appeared in approved vs blocked transactions across all nodes?
- Tokens: aggregated GoPlus data + AI analysis results from hundreds of independent checks
- Protocols: TVL trends, audit history, incident reports from the entire network
- Agents: cross-platform trust scores — an agent trusted on one 7cordon node can carry reputation to another
A new token with zero reputation on your isolated instance might already have 500 data points on the network — instantly informing 7cordon's risk assessment.
Business Model
Internal working document. Open questions to be resolved before production launch.
Current Model (Demo)
Per-second Spark streaming: $0.001 USDT/sec during AI analysis.
- L0 policy checks: free (no AI)
- L1 Quick: ~3-4 sec = $0.003-0.004 revenue
- L1+L2 escalation: ~18-22 sec = $0.018-0.022 revenue
Measured Costs (E2E, March 2026)
| Level | Input tokens | Output tokens | AI cost | Time |
|---|---|---|---|---|
| L1 (Quick) | 380-450 | 165-310 | $0.001-0.002 | 2-4s |
| L2 (Deep) | ~900 | ~960 | $0.017 | 17-20s |
| L1+L2 combined | ~1300 | ~1270 | ~$0.019 | 20-22s |
Known Problems
1. Conflict of Interest (per-second model)
Revenue = time x rate. 7cordon is incentivized to be slow or over-escalate to L2. Longer analysis = more Spark payments = more revenue.
2. Amount Disconnect
7cordon analyzes a request, not the execution. An agent can ask "is it safe to send $1?" — get approval — then send $1M. Percentage-of-amount model is broken for this reason.
3. Cache = Free Ride
SDK caches analysis results locally (LRU, TTL-based). Cache hits skip the API entirely — zero revenue. ~80% of agent queries are repetitive, meaning 80% of requests generate zero revenue.
4. Fixed Fee Risk
Fixed fee per level guarantees predictable pricing but exposes to cost spikes: Anthropic price changes, outlier max-token requests, retries on error. Worst case L1+L2: $0.055 (a fixed fee of $0.035 would be a loss).
Candidate Models
A. Cost-Plus (post-analysis settlement)
fee = max(min_fee, actual_ai_cost * (1 + margin))
min_fee = $0.001 (covers cache hits, L0 checks)
margin = 40-50%
Always profitable (margin is percentage-based). Transparent. Scales with model pricing changes automatically. Cache hits earn min_fee at 100% margin.
B. Hybrid (base + per-second with cap)
fee = max(base_fee, seconds * rate), capped at max_fee
L1: max($0.003, sec * $0.001), cap $0.01
L2: max($0.015, sec * $0.001), cap $0.05
C. Subscription Tiers
Free: L0 policy checks only, no AI
Basic: 100 L1 analyses/month, $5/month
Pro: unlimited L1 + 50 L2/month, $20/month
Enterprise: unlimited, custom models, SLA
D. Value-Based (insurance model)
Flat fee per agent per day ($0.10/day) regardless of query count. Simple, predictable, doesn't scale with usage.
Spark Integration Considerations
| Model | Spark streaming | Single Spark payment | Notes |
|---|---|---|---|
| Per-second | Native fit | N/A | Current demo |
| Cost-plus | Awkward (unknown fee) | After analysis | Need estimate + settlement |
| Fixed fee | Stream fixed amount | Before or after | Simple but rigid |
| Subscription | N/A | Monthly payment | Not micro-payment |
Hackathon demo: Per-second streaming showcases Spark best. Production: Cost-plus with post-analysis Spark settlement is most sustainable.
Cache Monetization
Cache reduces revenue to zero for ~80% of requests. Recommendation: min_fee ($0.001 per cache hit at 100% margin).
100 queries/day, 80% cache hit:
80 cache hits * $0.001 = $0.08 (cost: $0)
16 L1 fresh * $0.003 = $0.048 (cost: $0.032)
4 L2 fresh * $0.027 = $0.108 (cost: $0.076)
Total revenue: $0.236, total cost: $0.108
Margin: 54%
Decision Matrix
| Criteria | Per-second | Cost-plus | Fixed fee | Subscription |
|---|---|---|---|---|
| Always profitable | No | Yes | No | Depends |
| No conflict of interest | No | Yes | Yes | Yes |
| Spark showcase | Best | OK | OK | Poor |
| Simple to implement | Yes | Medium | Yes | Medium |
| Handles price changes | No | Yes | No | Partial |
| Cache monetization | No | With min_fee | With min_fee | N/A |
| User predictability | Low | Low | High | High |