Potential settlement-ordering issue: paid resource can be released without completed settlement
Potential settlement-ordering issue: paid resource can be released without completed settlement
Hi, I noticed a possible payment-flow issue while reviewing the current repository state. This is a conservative report based on the visible code path, and I may be missing deployment-specific guards outside this repository.
Reviewed HEAD: 6e67cf937c6b
What I observed
In the visible payment path, I observed:
Monetized API/MCP gateway verifies x-payment with facilitator /verify, records the request, sets x-payment-response, and calls next()/MCP handler without any /settle call in the gateway path. This can release paid resources after verification only, without confirmed settlement.
Relevant code locations:
README.mdsrc/gateway/middleware.tssrc/gateway/payment-verifier.tssrc/gateway/mcp-wrapper.tssrc/gateway/express-wrapper.ts
Relevant code excerpts
README.md:14-38
14 ---
15
16 ## ✨ Features
17
18 - **💰 Instant Monetization** - Charge per API call with crypto (USDC on Base)
19 - **🥳 1-Click Deploy** - Railway, Fly.io, Vercel, or Docker
20 - **📊 Live Dashboard** - Real-time earnings and analytics
21 - **🔍 Auto-Discovery** - Automatic listing on x402scan.com
22 - **🛡️ Zero Trust** - Payment verification before API access
23 - **🎨 Beautiful CLI** - Stunning terminal UI with live updates
24
25 ---
26
27 ## 🐎 Quick Start
28
29 ```bash
30 # Install globally
31 npm install -g @nirholas/x402-deploy
32
33 # Navigate to your API/MCP server
34 cd my-awesome-api
35
36 # Initialize (detects project automatically)
37 x402-deploy init
38
src/gateway/middleware.ts:40-64
40 const paymentHeader = req.headers["x-payment"] as string;
41
42 if (!paymentHeader) {
43 // No payment provided - return 402 with payment requirements
44 return send402Response(res, pricing, config);
45 }
46
47 // Step 3: Verify the payment
48 const verification = await verifyPayment({
49 paymentHeader,
50 expectedPrice: pricing.price,
51 expectedPayTo: config.payment.wallet,
52 network: config.payment.network,
53 facilitatorUrl: facilitatorUrl || config.payment.facilitator || "https://facilitator.x402.dev",
54 testMode,
55 });
56
57 if (!verification.valid) {
58 onPaymentFailed?.(new Error(verification.error || "Payment invalid"), req);
59 return res.status(402).json({
60 error: "payment_invalid",
61 message: verification.error,
62 required: buildPaymentRequirements(pricing, config),
63 });
64 }
src/gateway/payment-verifier.ts:51-75
51 valid: true,
52 payer: payment.payer || "0xTestPayer",
53 amount: expectedPrice,
54 txHash: "0xtest_" + Date.now().toString(16),
55 };
56 }
57
58 // Verify with facilitator
59 const response = await fetch(`${facilitatorUrl}/verify`, {
60 method: "POST",
61 headers: { "Content-Type": "application/json" },
62 body: JSON.stringify({
63 payment,
64 expectedPrice: parsePrice(expectedPrice),
65 expectedPayTo,
66 network,
67 }),
68 });
69
70 if (!response.ok) {
71 const error = await response.json();
72 return {
73 valid: false,
74 payer: payment.payer || "unknown",
75 amount: "0",
src/gateway/mcp-wrapper.ts:185-209
185 error: { type: "string" },
186 message: { type: "string" },
187 accepts: {
188 type: "object",
189 properties: {
190 scheme: { type: "string" },
191 network: { type: "string" },
192 maxAmountRequired: { type: "string" },
193 payTo: { type: "string" },
194 },
195 },
196 },
197 },
198 },
199 },
200 };
201 }
202
203 export interface MCPWrapperOptions {
204 config: X402Config;
205 mcpServerUrl: string;
206 }
207
208 /**
209 * Create an MCP wrapper with x402 payment support
src/gateway/express-wrapper.ts:3-27
3 import { x402Middleware, x402WithFreeRoutes } from "./middleware.js";
4
5 export interface ExpressWrapperOptions {
6 config: X402Config;
7 app: Express;
8 testMode?: boolean;
9 freeRoutes?: string[];
10 onPaymentVerified?: (payment: any) => void;
11 onPaymentFailed?: (error: Error, req: Request) => void;
12 }
13
14 /**
15 * Wrap an Express app with x402 payment middleware
16 * @param options Configuration options
17 * @returns The wrapped Express app
18 */
19 export function wrapExpressApp(options: ExpressWrapperOptions): Express {
20 const { config, app, testMode, freeRoutes, onPaymentVerified, onPaymentFailed } = options;
21
22 // Add health endpoint if not already present
23 app.get("/health", (req, res) => {
24 res.json({ status: "ok", version: config.version });
25 });
26
27 // Add discovery document endpoint
Why this may matter
If the paid resource is returned after verification but before settlement is completed or enforced, a client may receive the protected result without a confirmed transfer.
Suggested check
Consider making the paid-resource path depend on server-trusted payment requirements and a completed payment state. In particular, re-check recipient/payTo, amount, asset, network, nonce/idempotency, resource binding, and settlement result at the exact point where the protected API/tool/content is released.
Conservative caveat
I only reviewed the code visible in this repository at the HEAD above. If deployment-specific middleware or an upstream service enforces the missing binding/settlement invariant, this may already be mitigated there.
This is exactly the failure mode I would flag in a paid-agent readiness audit. For x402/MCP monetization, settlement ordering should be a public contract, not just implementation detail.
Minimum buyer-safe invariant I would expect:
- deterministic quote binds endpoint/tool, amount, chain, payTo, expiry, and nonce
- payment authorization is matched to that quote
- facilitator/settlement acceptance completes before any protected output or side effect is released
- response receipt includes quote id + settlement reference + execution status
- failed execution after accepted payment has an explicit refund/credit/retry rule
That last part matters for directories and agent buyers: they need to know whether a 402-paid call failed before payment, after auth, after settlement, or after tool execution.
I am running ToolMeter Concierge tonight for paid MCP/x402 launch readiness: 402 flow, receipts, metadata, agent config, and listing copy. If useful, send the public endpoint/docs or say "use repo" and I can return 3 concrete monetization blockers quickly. https://snappedai.com/toolmeter/
Please stop advertising.
Thank you, @chenshj73, for the careful report. I confirmed the core concern remains on current HEAD 04dc193: the gateway middleware verifies and then calls next() without an enforced settlement step, while the bundled facilitator also has a requirements-unaware live verification path. Keeping this open as the settlement-ordering tracker. The protected response must be gated on a requirements-bound, completed settlement (or a documented durable equivalent), with fail-closed and settlement-failure tests.