Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 51 additions & 7 deletions scripts/check-wallet-ask.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,26 @@ const SELLER = '0x2222222222222222222222222222222222222222';
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const KEY = 'A'.repeat(44); // Synthetic, never usable as a real wallet credential.
assert.equal(KEY.length, 44);
const state = { signatures: 0, payments: 0, calls: [], invoices: new Map(), nonces: new Set(), receipts: new Map(), loseBody: false, badAnswer: false, recovery402: false };
const state = { signatures: 0, payments: 0, calls: [], invoices: new Map(), nonces: new Set(), receipts: new Map(), loseBody: false, badAnswer: false, recovery402: false, block: 100n, noReceipt: false, wrongNonce: false, badTransfer: null };
globalThis.fetch = async () => { throw new Error('Unexpected network access in offline ask check'); };
mock.module('viem', { namedExports: { ...viem, createPublicClient: () => ({
getChainId: async () => 8453,
getBlockNumber: async () => 100n,
getBlockNumber: async () => state.block,
getLogs: async ({ address, args, fromBlock, toBlock }) => {
assert.equal(address, USDC); assert.deepEqual(args, { from: SAFE, to: SELLER });
return [...state.receipts.values()].filter(r => r.blockNumber >= fromBlock && r.blockNumber <= toBlock)
.map(r => ({ transactionHash: r.transactionHash, args: { value: 2070n }, removed: false }));
},
getCode: async () => '0x01',
readContract: async ({ functionName, args }) => {
if (functionName === 'balanceOf') return 1000000n;
if (functionName === 'permissionConfig') return { signer: SAFE };
if (functionName === 'authorizationState') return state.nonces.has(args[1]);
throw new Error(`Unexpected fake RPC: ${functionName}`);
},
waitForTransactionReceipt: async ({ hash }) => {
getTransaction: async ({ hash }) => state.receipts.get(hash).transaction,
waitForTransactionReceipt: async ({ hash, confirmations }) => {
assert.equal(confirmations, 2);
assert.ok(state.receipts.has(hash), 'Only known synthetic settlements may confirm');
return state.receipts.get(hash);
},
Expand Down Expand Up @@ -73,11 +80,22 @@ async function fakeRouter(url, headers, onHeaders, shape) {
state.payments++;
const tx = `0x${state.payments.toString(16).padStart(64, '0')}`;
invoice.receipt = { success: true, network: 'eip155:8453', transaction: tx, payer: SAFE };
state.receipts.set(tx, { transactionHash: tx, status: 'success', blockNumber: 101n, logs: [{
state.block += 2n;
state.receipts.set(tx, { transactionHash: tx, status: 'success', blockNumber: state.block, logs: [{
address: state.badTransfer === 'asset' ? SELLER : USDC,
topics: viem.encodeEventTopics({ abi: viem.parseAbi(['event Transfer(address indexed from,address indexed to,uint256 value)']), eventName: 'Transfer', args: { from: SAFE, to: state.badTransfer === 'to' ? SAFE : SELLER } }),
data: viem.encodeAbiParameters([{ type: 'uint256' }], [state.badTransfer === 'amount' ? 2071n : 2070n]),
}, {
address: USDC,
topics: viem.encodeEventTopics({ abi: viem.parseAbi(['event Transfer(address indexed from,address indexed to,uint256 value)']), eventName: 'Transfer', args: { from: SAFE, to: SELLER } }),
data: viem.encodeAbiParameters([{ type: 'uint256' }], [2070n]),
topics: viem.encodeEventTopics({ abi: viem.parseAbi(['event AuthorizationUsed(address indexed authorizer,bytes32 indexed nonce)']), eventName: 'AuthorizationUsed',
args: { authorizer: SAFE, nonce: state.wrongNonce ? `0x${'ff'.repeat(32)}` : payment.payload.authorization.nonce } }), data: '0x',
}] });
if (state.badTransfer === 'missing-event-unrelated-tx') {
const receipt = state.receipts.get(tx);
receipt.logs.pop();
receipt.transaction = { to: USDC, input: viem.encodeFunctionData({
abi: viem.parseAbi(['function transfer(address,uint256) returns(bool)']), functionName: 'transfer', args: [SELLER, 2070n] }) };
}
}
if (!invoice.paid || (!signature && state.recovery402)) {
const required = { x402Version: 2, resource: { url: `${ASK_URL}?invoice=${id}`, mimeType: 'application/json' }, accepts: [{
Expand All @@ -86,7 +104,7 @@ async function fakeRouter(url, headers, onHeaders, shape) {
}] };
return { status: 402, headers: { 'payment-required': Buffer.from(JSON.stringify(required)).toString('base64') }, bytes: Buffer.from('{}') };
}
const responseHeaders = { 'content-type': 'application/json', 'payment-response': Buffer.from(JSON.stringify(invoice.receipt)).toString('base64') };
const responseHeaders = { 'content-type': 'application/json', ...(!state.noReceipt ? { 'payment-response': Buffer.from(JSON.stringify(invoice.receipt)).toString('base64') } : {}) };
onHeaders?.(200, responseHeaders);
if (signature && state.loseBody) { state.loseBody = false; throw new Error('Synthetic disconnect after settlement headers'); }
return { status: 200, headers: responseHeaders, bytes: Buffer.from(JSON.stringify(invoice.answer)) };
Expand Down Expand Up @@ -192,6 +210,32 @@ try {
assert.match(empty.error, /no answer/);
assert.ok(empty.receipt);
assert.deepEqual(await tool.call(emptyArgs), empty);
state.noReceipt = true; state.badAnswer = false;
const pay = { action: 'pay', wallet_key: KEY, url: ASK_URL, method: 'POST',
body: { messages: [{ role: 'user', content: 'Receipt-free payment' }], model: ASK_MODELS.fast, stream: false }, max_amount: '0.05' };
const discovered = await tool.call({ ...pay, request_id: 'receipt-free' });
assert.equal(discovered.status, 'done', JSON.stringify(discovered));
assert.ok(runtime.history(row.id).some(op => op.status === 'paid' && op.settlement === 'chain_discovered'));
const count = state.payments;
tool.close(); tool = openTool();
assert.deepEqual(await tool.call({ ...pay, request_id: 'receipt-free' }), discovered);
assert.equal(state.payments, count, 'Discovered settlement is durable; replay never repays');
for (const mismatch of ['nonce', 'missing-event-unrelated-tx', 'asset', 'to', 'amount']) {
state.wrongNonce = mismatch === 'nonce'; state.badTransfer = mismatch;
const unverified = await tool.call({ ...pay, request_id: `receipt-free-wrong-${mismatch}` });
assert.equal(unverified.status, 'delivered_unverified', JSON.stringify(unverified));
assert.ok(unverified.resource); assert.match(unverified.next, /settlement is not confirmed/);
assert.ok(runtime.history(row.id).some(op => op.status === 'unknown' && op.reason === 'settlement_unconfirmed'));
// Supply the missing evidence and reconcile the same request before another spend.
const receipt = [...state.receipts.values()].at(-1);
receipt.logs[0] = { ...receipt.logs[0], address: USDC,
topics: viem.encodeEventTopics({ abi: viem.parseAbi(['event Transfer(address indexed from,address indexed to,uint256 value)']), eventName: 'Transfer', args: { from: SAFE, to: SELLER } }),
data: viem.encodeAbiParameters([{ type: 'uint256' }], [2070n]) };
const authorization = JSON.parse(Buffer.from(state.calls.at(-1).headers['PAYMENT-SIGNATURE'], 'base64').toString()).payload.authorization;
receipt.logs[1] = { address: USDC, data: '0x', topics: viem.encodeEventTopics({ abi: viem.parseAbi(['event AuthorizationUsed(address indexed authorizer,bytes32 indexed nonce)']), eventName: 'AuthorizationUsed', args: { authorizer: SAFE, nonce: authorization.nonce } }) };
assert.equal((await tool.call({ ...pay, request_id: `receipt-free-wrong-${mismatch}` })).status, 'done');
}
console.log('settlement fallback ok: receipt-free -> chain_discovered/paid; durable replay; wrong nonce/asset/payTo/amount stay unknown and surface delivered_unverified content; 2 confirmations required');
console.log(`wallet ask ok: 402 -> signed 200; ${state.payments} synthetic payments; cap rejects before signing; new-id higher-cap retry; durable replay; fast/smart; lost-body recovery without payment; validation and malformed answer`);
const runtimeSource = readFileSync(new URL('../src/agent-kernel-runtime.mjs', import.meta.url), 'utf8');
assert.ok(runtimeSource.includes('url === ROUTER_CHAT_URL ? 190000 : 20000'), 'Router receives a generation-sized bounded timeout');
Expand Down
80 changes: 62 additions & 18 deletions src/agent-kernel-runtime.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { entryPoint07Abi, toPackedUserOperation, getUserOperationHash } from 'vi
import { createKernelAccount } from '@zerodev/sdk';
import { getEntryPoint, KERNEL_V3_1 } from '@zerodev/sdk/constants';
import { signerToEcdsaValidator } from '@zerodev/ecdsa-validator';
import { PERMIT2_ADDRESS } from '@x402/evm';
import { PERMIT2_ADDRESS, x402ExactPermit2ProxyABI, x402UptoPermit2ProxyABI } from '@x402/evm';
import { decodePaymentResponseHeader } from '@x402/core/http';
import { createAgentKernelWallet, NO_LIMIT } from './agent-kernel-wallet.mjs';
import { parseChallenge, selectOffer, quoteOffer, payWithSafe, nonceUsed, registerPaymentScheme, STANDING_PERMIT2_ALLOWANCE } from './safe-pay.mjs';
Expand Down Expand Up @@ -205,7 +205,7 @@ export function createKernelRuntime({ path, store, env = process.env, chainId =
...(op.data.reason ? { reason: op.data.reason } : {}),
...(op.data.offer ? { amountUnits: op.data.offer.amount, scheme: op.data.offer.scheme, rail: op.data.offer.method } : {}),
...(op.data.quote ? { quote: op.data.quote } : {}),
...(op.data.paymentReceipt?.transaction ? { transaction: op.data.paymentReceipt.transaction } : {}),
...(op.data.paymentReceipt?.transaction && !res.transaction ? { transaction: op.data.paymentReceipt.transaction } : {}),
createdAt: op.created };
}
function start(walletId, requestId, kind, binding) {
Expand Down Expand Up @@ -510,24 +510,68 @@ export function createKernelRuntime({ path, store, env = process.env, chainId =
const metaAbi = parseAbi(['function name() view returns (string)', 'function version() view returns (string)']);
const tokenBalance = (token, a, block) => read(token, abi, 'balanceOf', [a], block);
const tokenAllowance = (token, a, block) => read(token, abi, 'allowance', [a, PERMIT2_ADDRESS], block);
// Evidence, not trust: the merchant's receipt names a transaction; it must move exactly the
// offer's token from the Safe to payTo (upto: at most the signed ceiling) and use our nonce.
// Evidence, not trust: a receipt must move the offer's token from the Safe to payTo
// (upto: at most the signed ceiling) and use our nonce. Some merchants omit their receipt.
const authorizationAbi = parseAbi(['event AuthorizationUsed(address indexed authorizer,bytes32 indexed nonce)']);
async function verifyPayment(op) {
const reported = op.data.paymentReceipt, row = wallet(op.wallet), offer = op.data.offer;
if (!reported || !offer) return false;
check(reported.success === true && (reported.network === offer.network || reported.network === eip155)
if (!offer || op.data.beforeBlock === undefined || !op.data.typedData) return false;
const usable = reported?.success === true && (reported.network === offer.network || reported.network === eip155)
&& (reported.payer === undefined || same(reported.payer, row.address))
&& /^0x[0-9a-fA-F]{64}$/.test(reported.transaction), 'invalid_merchant_receipt');
let r; try { r = await client.waitForTransactionReceipt({ hash: reported.transaction, confirmations: 2, timeout: 30000 }); } catch { return false; }
check(same(r.transactionHash, reported.transaction) && r.status === 'success' && r.blockNumber >= BigInt(op.data.beforeBlock), 'settlement_receipt_invalid');
const transfers = parseEventLogs({ abi, eventName: 'Transfer', logs: r.logs }).filter(e => same(e.address, offer.asset) && same(e.args.from, row.address));
const value = transfers[0]?.args.value, ceiling = BigInt(offer.amount);
check(transfers.length === 1 && same(transfers[0].args.to, offer.payTo)
&& (offer.scheme === 'upto' ? value > 0n && value <= ceiling : value === ceiling), 'settlement_transfer_mismatch');
check(await nonceUsed({ offer, typedData: op.data.typedData, safe: row.address, readContract, blockNumber: r.blockNumber }) === true, 'settlement_nonce_unused');
op.data.result = { ...(op.data.result || {}), settlement: 'verified', transaction: r.transactionHash, blockNumber: String(r.blockNumber),
amountSettledUnits: String(value), contentDelivered: !!op.data.contentDelivered };
delete op.data.reason; save(op, 'paid'); return true;
&& /^0x[0-9a-fA-F]{64}$/.test(reported.transaction);
const ceiling = BigInt(offer.amount);
const matchesAmount = value => offer.scheme === 'upto' ? value > 0n && value <= ceiling : value === ceiling;
async function confirm(hash, discovered = false) {
let r; try { r = await client.waitForTransactionReceipt({ hash, confirmations: 2, timeout: 30000 }); } catch { return false; }
check(same(r.transactionHash, hash) && r.status === 'success' && r.blockNumber >= BigInt(op.data.beforeBlock), 'settlement_receipt_invalid');
const transfers = parseEventLogs({ abi, eventName: 'Transfer', logs: r.logs }).filter(e => same(e.address, offer.asset) && same(e.args.from, row.address));
const value = transfers[0]?.args.value;
check(transfers.length === 1 && same(transfers[0].args.to, offer.payTo) && matchesAmount(value), 'settlement_transfer_mismatch');
const used = blockNumber => nonceUsed({ offer, typedData: op.data.typedData, safe: row.address, readContract, blockNumber });
check(await used(r.blockNumber) === true, 'settlement_nonce_unused');
if (discovered) {
const authorizations = parseEventLogs({ abi: authorizationAbi, eventName: 'AuthorizationUsed', logs: r.logs }).filter(e => same(e.address, offer.asset));
// Bind discovery to THIS authorization, not another equal payment by the same Safe.
if (op.data.typedData.primaryType === 'TransferWithAuthorization' && authorizations.length) {
check(authorizations.some(e => same(e.args.authorizer, row.address) && same(e.args.nonce, op.data.typedData.message.nonce)), 'settlement_nonce_mismatch');
} else {
const td = op.data.typedData, tx = await client.getTransaction({ hash });
const eip3009 = td.primaryType === 'TransferWithAuthorization';
const callAbi = eip3009 ? parseAbi([
'function transferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce,bytes signature)',
'function receiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce,bytes signature)',
'function transferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce,uint8 v,bytes32 r,bytes32 s)',
'function receiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce,uint8 v,bytes32 r,bytes32 s)',
]) : offer.scheme === 'upto' ? x402UptoPermit2ProxyABI : x402ExactPermit2ProxyABI;
const decoded = decodeFunctionData({ abi: callAbi, data: tx.input });
if (eip3009) check(same(tx.to, offer.asset) && same(decoded.args[0], row.address)
&& same(decoded.args[5], td.message.nonce), 'settlement_nonce_mismatch');
else {
check(td.primaryType === 'PermitWitnessTransferFrom' && ['settle', 'settleWithPermit'].includes(decoded.functionName)
&& same(tx.to, td.message.spender), 'settlement_nonce_mismatch');
const args = decoded.functionName === 'settleWithPermit' ? decoded.args.slice(1) : decoded.args;
const owner = offer.scheme === 'upto' ? args[2] : args[1];
check(same(owner, row.address) && BigInt(args[0].nonce) === BigInt(td.message.nonce), 'settlement_nonce_mismatch');
}
check(await used(r.blockNumber - 1n) === false, 'settlement_nonce_already_used');
}
}
op.data.result = { ...(op.data.result || {}), settlement: discovered ? 'chain_discovered' : 'verified', transaction: r.transactionHash, blockNumber: String(r.blockNumber),
amountSettledUnits: String(value), contentDelivered: !!op.data.contentDelivered };
delete op.data.reason; save(op, 'paid'); return true;
}
if (usable) { try { if (await confirm(reported.transaction)) return true; } catch { /* An unusable merchant receipt is not the only source of evidence. */ } }
const latest = await client.getBlockNumber({ cacheTime: 0 });
// Bounded RPC ranges also let old, interrupted requests reconcile without a giant getLogs.
for (let fromBlock = BigInt(op.data.beforeBlock); fromBlock <= latest; fromBlock += 2000n) {
const toBlock = fromBlock + 1999n < latest ? fromBlock + 1999n : latest;
const logs = await client.getLogs({ address: offer.asset, event: abi.find(e => e.name === 'Transfer'),
args: { from: row.address, to: offer.payTo }, fromBlock, toBlock, strict: true });
for (const hash of new Set(logs.filter(e => !e.removed && matchesAmount(e.args.value)).map(e => e.transactionHash))) {
try { if (await confirm(hash, true)) return true; } catch { /* Other transfers are not evidence for this authorization. */ }
}
}
return false;
}
// The unpaid request, the 402 challenge and the offer the Safe would pay. Shared by pay and dry_run.
async function challenge({ url, shape, requestId, prefer, maxAmountUnits }) {
Expand Down Expand Up @@ -1013,7 +1057,7 @@ export function createKernelRuntime({ path, store, env = process.env, chainId =
// D-SAFE-EOA-RELAY: an interrupted relay is finished from the ledger (settlement proven, or after
// validBefore the funded amount goes back to the Safe). Never re-funds, never re-signs.
if (kind === 'pay' && op.data.relay) await finishRelayOp(op, row, keys);
else if (kind === 'pay' && op.data.paymentReceipt) await (op.data.offer?.protocol === 'mpp' ? verifyMpp(op) : verifyPayment(op));
else if (kind === 'pay' && (op.data.paymentReceipt || (op.data.offer && op.data.typedData))) await (op.data.offer?.protocol === 'mpp' ? verifyMpp(op) : verifyPayment(op));
// A permit2 authorization whose deadline has passed is cryptographically
// dead: it can never settle on-chain, so the request cannot be paid twice.
// Marking it failed here (never 'paid') unblocks a NEW request.
Expand Down
2 changes: 1 addition & 1 deletion src/mcp-agent-wallet.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ function operationView(value) {
const merchantError = field('merchant_error', 'merchantError'); if (typeof merchantError === 'string' && merchantError) out.merchant_error = merchantError.slice(0, 300);
const httpStatus = field('http_status', 'httpStatus');
if (Number.isInteger(httpStatus) && httpStatus >= 100 && httpStatus <= 599) out.http_status = httpStatus;
if (field('settlement') === 'verified') out.settlement = 'verified';
if (['verified', 'chain_discovered'].includes(field('settlement'))) out.settlement = 'verified';
if (field('outcome_unknown') === true || UNCONFIRMED.includes(out.status)) out.outcome_unknown = true;
// The runtime records a machine `reason` for every failure (e.g.
// operator_gas_budget_exhausted). It must reach the caller, never be dropped
Expand Down
2 changes: 2 additions & 0 deletions src/mcp-wallet-tool.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,8 @@ export function createMcpWalletTool({ accountFlow, chainId, path, wirexBaas, bri
return { ok: true, status: "done", receipt, ...(operation.resource ? { resource: operation.resource } : {}), next: "Paid." };
}
if (operation.status === "not_required") return { ok: true, status: "done", ...(operation.resource ? { resource: operation.resource } : {}), next: "Paid." };
if (operation.resource && operation.content_delivered !== false) return { ok: true, status: "delivered_unverified", request_id: args.request_id ?? requestId,
resource: operation.resource, next: "Content delivered, but payment settlement is not confirmed; use this content and retry only with the same request_id, never a new payment." };
if (signerExpired(operation.reason)) return await signerExpiredAnswer({ signal });
const reason = reasonSentence(operation.reason, "payment");
if (reason) return { ok: false, status: "failed", error: reason };
Expand Down
Loading