diff --git a/src/clearinghouse.ts b/src/clearinghouse.ts new file mode 100644 index 0000000..feb910f --- /dev/null +++ b/src/clearinghouse.ts @@ -0,0 +1,123 @@ +import crypto from "node:crypto"; + +export interface ClearinghouseTransaction { + id: string; + userId: string; + toolId: string; + creditsDebited: number; + platformFeeCredits: number; + creatorPayoutCredits: number; + creatorWallet: string; + timestamp: number; + latencyMs: number; +} + +export interface ClearinghouseStats { + totalTransactions: number; + totalCreditsDebited: number; + totalPlatformFees: number; + totalCreatorPayouts: number; + p99LatencyMs: number; +} + +export class EdgeBillingClearinghouse { + private transactions: Map = new Map(); + private userBalances: Map = new Map(); + private creatorBalances: Map = new Map(); + private latencies: number[] = []; + public static readonly PLATFORM_FEE_PERCENTAGE = 0.035; // 3.5% platform cut + + public depositCredits(userId: string, credits: number): number { + const current = this.userBalances.get(userId) || 0; + const updated = current + credits; + this.userBalances.set(userId, updated); + return updated; + } + + public getBalance(userId: string): number { + return this.userBalances.get(userId) || 0; + } + + public getCreatorBalance(creatorWallet: string): number { + return this.creatorBalances.get(creatorWallet) || 0; + } + + /** + * Atomically debits user credits, deductions 3.5% platform cut, and credits tool creator + * Benchmarked to complete in <15ms P99 + */ + public async processToolCallDebit(params: { + userId: string; + toolId: string; + creditsCost: number; + creatorWallet: string; + }): Promise<{ success: boolean; transaction?: ClearinghouseTransaction; error?: string }> { + const startTime = performance.now(); + const currentBalance = this.userBalances.get(params.userId) || 0; + + if (currentBalance < params.creditsCost) { + return { + success: false, + error: `Insufficient Universal MCP Credits. Required: ${params.creditsCost}, Available: ${currentBalance}. Top up at https://ritualdev.in/credits`, + }; + } + + // Deduct user balance + this.userBalances.set(params.userId, currentBalance - params.creditsCost); + + // Calculate 3.5% clearinghouse fee + const platformFee = Math.max(1, Math.round(params.creditsCost * EdgeBillingClearinghouse.PLATFORM_FEE_PERCENTAGE)); + const creatorPayout = params.creditsCost - platformFee; + + // Credit creator balance + const currentCreator = this.creatorBalances.get(params.creatorWallet) || 0; + this.creatorBalances.set(params.creatorWallet, currentCreator + creatorPayout); + + const endTime = performance.now(); + const latencyMs = Number((endTime - startTime).toFixed(3)); + this.latencies.push(latencyMs); + if (this.latencies.length > 500) this.latencies.shift(); + + const transaction: ClearinghouseTransaction = { + id: `tx_${crypto.randomUUID()}`, + userId: params.userId, + toolId: params.toolId, + creditsDebited: params.creditsCost, + platformFeeCredits: platformFee, + creatorPayoutCredits: creatorPayout, + creatorWallet: params.creatorWallet, + timestamp: Date.now(), + latencyMs, + }; + + this.transactions.set(transaction.id, transaction); + + return { + success: true, + transaction, + }; + } + + public getStats(): ClearinghouseStats { + let totalCredits = 0; + let totalFees = 0; + let totalPayouts = 0; + + for (const tx of this.transactions.values()) { + totalCredits += tx.creditsDebited; + totalFees += tx.platformFeeCredits; + totalPayouts += tx.creatorPayoutCredits; + } + + const sorted = [...this.latencies].sort((a, b) => a - b); + const p99 = sorted.length > 0 ? sorted[Math.floor(sorted.length * 0.99)] : 0; + + return { + totalTransactions: this.transactions.size, + totalCreditsDebited: totalCredits, + totalPlatformFees: totalFees, + totalCreatorPayouts: totalPayouts, + p99LatencyMs: p99, + }; + } +} diff --git a/src/index.ts b/src/index.ts index 6d6295d..ab66e2c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,3 +7,6 @@ export * from "./adapters/redis.js"; export * from "./webhooks.js"; export * from "./license.js"; export * from "./capability.js"; +export * from "./clearinghouse.js"; +export * from "./universal-credits.js"; +export * from "./universal-middleware.js"; diff --git a/src/universal-credits.ts b/src/universal-credits.ts new file mode 100644 index 0000000..8918a4c --- /dev/null +++ b/src/universal-credits.ts @@ -0,0 +1,82 @@ +import crypto from "node:crypto"; + +export interface UniversalCreditPack { + id: "STARTER_PACK" | "PRO_PACK" | "ENTERPRISE_PACK"; + name: string; + priceUsd: number; + credits: number; + bonusPercentage: number; +} + +export const UNIVERSAL_CREDIT_PACKS: Record = { + STARTER_PACK: { + id: "STARTER_PACK", + name: "Starter Credits", + priceUsd: 5.0, + credits: 500, + bonusPercentage: 0, + }, + PRO_PACK: { + id: "PRO_PACK", + name: "Pro Developer Credits", + priceUsd: 20.0, + credits: 2500, // 25% bonus credits + bonusPercentage: 25, + }, + ENTERPRISE_PACK: { + id: "ENTERPRISE_PACK", + name: "Enterprise Pool Credits", + priceUsd: 50.0, + credits: 7000, // 40% bonus credits + bonusPercentage: 40, + }, +}; + +export interface SignedCreditVoucher { + voucherId: string; + userId: string; + packId: string; + credits: number; + issuedAt: number; + expiresAt: number; + signature: string; +} + +export class UniversalCreditsManager { + private signingSecret: string; + + constructor(signingSecret?: string) { + this.signingSecret = signingSecret || "ritual-mcp-universal-clearinghouse-secret-key-32b"; + } + + public mintVoucher(userId: string, packId: "STARTER_PACK" | "PRO_PACK" | "ENTERPRISE_PACK"): SignedCreditVoucher { + const pack = UNIVERSAL_CREDIT_PACKS[packId]; + if (!pack) throw new Error(`Invalid credit pack ID: ${packId}`); + + const voucherId = `vouch_${crypto.randomUUID()}`; + const issuedAt = Date.now(); + const expiresAt = issuedAt + 365 * 24 * 60 * 60 * 1000; // 1 year validity + + const payload = `${voucherId}:${userId}:${pack.credits}:${issuedAt}:${expiresAt}`; + const signature = crypto.createHmac("sha256", this.signingSecret).update(payload).digest("hex"); + + return { + voucherId, + userId, + packId, + credits: pack.credits, + issuedAt, + expiresAt, + signature, + }; + } + + public verifyVoucher(voucher: SignedCreditVoucher): boolean { + if (Date.now() > voucher.expiresAt) return false; + + const payload = `${voucher.voucherId}:${voucher.userId}:${voucher.credits}:${voucher.issuedAt}:${voucher.expiresAt}`; + const expectedSig = crypto.createHmac("sha256", this.signingSecret).update(payload).digest("hex"); + + return crypto.timingSafeEqual(Buffer.from(voucher.signature), Buffer.from(expectedSig)); + } +} diff --git a/src/universal-middleware.ts b/src/universal-middleware.ts new file mode 100644 index 0000000..3491422 --- /dev/null +++ b/src/universal-middleware.ts @@ -0,0 +1,95 @@ +import { EdgeBillingClearinghouse } from "./clearinghouse.js"; + +export interface UniversalMonetizeOptions { + toolPriceCredits: Record; + creatorWallet: string; + clearinghouse?: EdgeBillingClearinghouse; + bypassUsers?: string[]; +} + +export interface McpCallRequest { + method: string; + params: { + name: string; + arguments?: Record; + }; + userId?: string; +} + +export interface McpCallResponse { + content?: Array<{ type: string; text: string }>; + isError?: boolean; + error?: { + code: number; + message: string; + data?: unknown; + }; +} + +/** + * 3-Line Developer Integration SDK: + * Wrap any MCP request handler with Universal Pre-Paid MCP Credits monetization + */ +export function withUniversalMcpMonetize Promise>( + handler: T, + options: UniversalMonetizeOptions, +): (req: McpCallRequest) => Promise { + const clearinghouse = options.clearinghouse || new EdgeBillingClearinghouse(); + + return async (req: McpCallRequest): Promise => { + if (req.method !== "tools/call") { + return handler(req); + } + + const toolName = req.params?.name; + const price = options.toolPriceCredits[toolName] || 0; + + // Free tool call + if (price <= 0) { + return handler(req); + } + + const userId = req.userId || "anonymous_agent"; + + // Bypass list for internal testing + if (options.bypassUsers && options.bypassUsers.includes(userId)) { + return handler(req); + } + + // Atomically debit Universal MCP Credits with 3.5% clearinghouse platform fee + const debitResult = await clearinghouse.processToolCallDebit({ + userId, + toolId: toolName, + creditsCost: price, + creatorWallet: options.creatorWallet, + }); + + if (!debitResult.success) { + return { + isError: true, + error: { + code: -32002, // Standard PaywallRequired error + message: debitResult.error || "Insufficient Universal MCP Credits.", + data: { + requiredCredits: price, + tool: toolName, + checkoutUrl: "https://ritualdev.in/credits", + }, + }, + }; + } + + // Execute downstream tool handler + const response = await handler(req); + + // Attach transaction receipt metadata + if (response.content && Array.isArray(response.content) && debitResult.transaction) { + response.content.push({ + type: "text", + text: `\n[Universal MCP Clearinghouse] Debited: ${price} credits | Tx: ${debitResult.transaction.id.substring(0, 11)}...`, + }); + } + + return response; + }; +} diff --git a/tests/clearinghouse-and-universal-credits.test.ts b/tests/clearinghouse-and-universal-credits.test.ts new file mode 100644 index 0000000..65875dd --- /dev/null +++ b/tests/clearinghouse-and-universal-credits.test.ts @@ -0,0 +1,105 @@ +import assert from "node:assert"; +import test from "node:test"; +import { + EdgeBillingClearinghouse, + UniversalCreditsManager, + UNIVERSAL_CREDIT_PACKS, + withUniversalMcpMonetize, +} from "../src/index.js"; + +test("EdgeBillingClearinghouse - Debits credits atomically with 3.5% clearinghouse platform fee in <15ms", async () => { + const clearinghouse = new EdgeBillingClearinghouse(); + const userId = "usr_agent_007"; + const creatorWallet = "wallet_creator_42"; + + // Deposit 1,000 Universal MCP credits + clearinghouse.depositCredits(userId, 1000); + assert.strictEqual(clearinghouse.getBalance(userId), 1000); + + // Process tool call debit of 100 credits + const result = await clearinghouse.processToolCallDebit({ + userId, + toolId: "database_security_scan", + creditsCost: 100, + creatorWallet, + }); + + assert.strictEqual(result.success, true); + assert.ok(result.transaction); + + // Verify 3.5% clearinghouse platform fee ($100 * 0.035 = 4 credits$) + assert.strictEqual(result.transaction.platformFeeCredits, 4); + // Verify creator receives 96 credits + assert.strictEqual(result.transaction.creatorPayoutCredits, 96); + assert.strictEqual(clearinghouse.getCreatorBalance(creatorWallet), 96); + // User balance decremented by 100 + assert.strictEqual(clearinghouse.getBalance(userId), 900); + + // Verify latency is <15ms + const stats = clearinghouse.getStats(); + assert.strictEqual(stats.totalTransactions, 1); + assert.ok(stats.p99LatencyMs < 15.0); +}); + +test("UniversalCreditsManager - Mints and verifies tamper-proof credit vouchers", () => { + const manager = new UniversalCreditsManager(); + const userId = "usr_dev_bob"; + + const voucher = manager.mintVoucher(userId, "PRO_PACK"); + assert.strictEqual(voucher.credits, UNIVERSAL_CREDIT_PACKS.PRO_PACK.credits); + assert.strictEqual(voucher.credits, 2500); + + // Valid signature + assert.strictEqual(manager.verifyVoucher(voucher), true); + + // Tampered voucher + const tampered = { ...voucher, credits: 99999 }; + assert.strictEqual(manager.verifyVoucher(tampered), false); +}); + +test("withUniversalMcpMonetize - 3-Line Developer SDK enfores paywall and debits credits", async () => { + const clearinghouse = new EdgeBillingClearinghouse(); + const userId = "agent_client_1"; + clearinghouse.depositCredits(userId, 20); + + const mockToolHandler = async (req: any) => ({ + content: [{ type: "text", text: `Executed ${req.params.name}` }], + }); + + const monetizedHandler = withUniversalMcpMonetize(mockToolHandler, { + toolPriceCredits: { + "expensive_tool": 15, + "free_tool": 0, + }, + creatorWallet: "wallet_alice", + clearinghouse, + }); + + // Call free tool - passes without debit + const freeRes = await monetizedHandler({ + method: "tools/call", + params: { name: "free_tool" }, + userId, + }); + assert.strictEqual(freeRes.isError, undefined); + assert.strictEqual(clearinghouse.getBalance(userId), 20); + + // Call expensive tool (15 credits) - succeeds and debits + const paidRes = await monetizedHandler({ + method: "tools/call", + params: { name: "expensive_tool" }, + userId, + }); + assert.strictEqual(paidRes.isError, undefined); + assert.strictEqual(clearinghouse.getBalance(userId), 5); + + // Call expensive tool again (costs 15, but balance is 5) - blocked with -32002 + const blockedRes = await monetizedHandler({ + method: "tools/call", + params: { name: "expensive_tool" }, + userId, + }); + assert.strictEqual(blockedRes.isError, true); + assert.strictEqual(blockedRes.error?.code, -32002); + assert.ok(blockedRes.error?.message.includes("Insufficient Universal MCP Credits")); +});