@celorodrigues/x402-conformance 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -47,7 +47,7 @@ The same package runs as an MCP stdio server:
47
47
  - Claude Desktop: Settings → Developer → Edit Config (`claude_desktop_config.json`), then restart.
48
48
  - Cursor: `.cursor/mcp.json` in the project, or `~/.cursor/mcp.json`.
49
49
 
50
- Tools: `x402_conformance_check` (free, runs locally), `security_scan` (Base token honeypot / mint-trap / contract risk), `oracle_base`, `sentiment_analysis`, `attest`, `merkle_prove`, plus free `verify_attestation`, `read_ledger`, `merkle_verify`, `pricing`, `health`. Paid tools cost 0.001 USDC on Base (3 free calls/day/IP).
50
+ Tools: `x402_conformance_check` (free, runs locally), `simulate_base_transaction` (free, EVM dry-run via Base RPC with revert reason decoding), `security_scan` (Base token honeypot / mint-trap / contract risk), `oracle_base`, `sentiment_analysis`, `attest`, `merkle_prove`, plus free `verify_attestation`, `read_ledger`, `merkle_verify`, `pricing`, `health`. Paid tools cost 0.001 - 0.05 USDC on Base (3 free calls/day/IP).
51
51
 
52
52
  Optional env: `VALUE_API_BASE` (default `https://api.automaton-sovereign.workers.dev`), `VALUE_API_PAYMENT` (payment tx hash attached to paid calls).
53
53
 
package/bin/cli.js CHANGED
@@ -4,7 +4,7 @@ const args = process.argv.slice(2);
4
4
 
5
5
  // MCP stdio server mode: npx -y @celorodrigues/x402-conformance --mcp
6
6
  if (args.includes('--mcp')) {
7
- require('../mcp-server.js');
7
+ require('../mcp-server.js').startStdio();
8
8
  return;
9
9
  }
10
10
 
package/mcp-server.js CHANGED
@@ -22,6 +22,7 @@ const https = require('https');
22
22
  const { URL } = require('url');
23
23
  const PKG = require('./package.json');
24
24
  const linter = require('./index.js');
25
+ const simulator = require('./tx-simulator.js');
25
26
 
26
27
  const BASE = (process.env.VALUE_API_BASE || 'https://api.automaton-sovereign.workers.dev').replace(/\/+$/, '');
27
28
  const PAYMENT = process.env.VALUE_API_PAYMENT || '';
@@ -49,6 +50,8 @@ function httpJson(method, urlStr, headers, body) {
49
50
  const TOOLS = [
50
51
  { name: 'x402_conformance_check', description: 'FREE, runs locally. Lint any x402 paid endpoint for protocol conformance: HTTP 402 challenge, x402Version, accepts[] (exact scheme), Base network and addresses, EIP-712 domain, and rejection of malformed, forged, expired, underpaid and wrong-recipient EIP-3009 payments. Returns verdict, grade and per-check results.',
51
52
  inputSchema: { type: 'object', properties: { url: { type: 'string', description: 'Full URL of the x402-protected endpoint to check.' } }, required: ['url'] } },
53
+ { name: 'simulate_base_transaction', description: 'FREE, runs locally against Base Mainnet RPC. Dry-run a transaction before sending it: eth_call + eth_estimateGas at the latest block. Predicts whether it will revert and decodes the reason (Error(string), Panic(uint256) codes, custom-error selector, or node rejection such as insufficient funds). Returns { ok, willRevert, revertReason, estimatedGas, returnData }.',
54
+ inputSchema: { type: 'object', properties: { to: { type: 'string', description: 'Target contract or recipient address on Base (0x...).' }, data: { type: 'string', description: 'Calldata as 0x-hex (default 0x for a plain ETH transfer).' }, value: { type: 'string', description: 'ETH value in wei, decimal or 0x-hex (default 0).' }, from: { type: 'string', description: 'Optional sender address; needed for balance/allowance-dependent calls.' } }, required: ['to'] } },
52
55
  { name: 'security_scan', description: 'PAID 0.001 USDC/call, or free trial (3/day/IP). Base token safety analysis: honeypot detection, mint traps, selfdestruct/delegatecall, proxy and tax risks from contract bytecode, with a risk score and signed verdict. On 402, pay the accepts[] terms then retry with the payment tx hash.',
53
56
  inputSchema: { type: 'object', properties: { address: { type: 'string', description: 'Token or contract address on Base (0x...).' }, payment: { type: 'string', description: 'Optional X-PAYMENT base tx hash of the USDC payment.' } }, required: ['address'] } },
54
57
  { name: 'attest', description: 'Create a SIGNED, hash-chained, append-only attestation (verifiable proof-of-existence) for a payload. PAID: 0.001 USDC/call, or free trial (3/day/IP). On 402, pay the accepts[] terms then retry with the payment tx hash.',
@@ -77,63 +80,94 @@ const TOOLS = [
77
80
 
78
81
  function q(o) { return Object.entries(o || {}).filter(([, v]) => v !== undefined && v !== null && v !== '').map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&'); }
79
82
 
80
- async function callTool(name, args) {
83
+ // opts.base / opts.headers let an embedding server (HTTP /mcp) call its own API directly and
84
+ // forward the caller's IP / public host.
85
+ async function callTool(name, args, opts) {
81
86
  args = args || {};
82
- const payHeader = (args.payment || PAYMENT) ? { 'X-PAYMENT': args.payment || PAYMENT } : {};
87
+ opts = opts || {};
88
+ const B = (opts.base || BASE).replace(/\/+$/, '');
89
+ const fwd = opts.headers || {};
90
+ const payHeader = Object.assign({}, fwd, (args.payment || PAYMENT) ? { 'X-PAYMENT': args.payment || PAYMENT } : {});
83
91
  switch (name) {
84
92
  case 'x402_conformance_check': {
85
93
  if (!/^https?:\/\//i.test(args.url || '')) throw new Error('url must be an absolute http(s) URL');
86
94
  return { status: 200, body: await linter.run(args.url) };
87
95
  }
88
- case 'security_scan': return httpJson('GET', BASE + '/v2/security/scan?' + q({ address: args.address }), payHeader);
89
- case 'attest': return httpJson('POST', BASE + '/v2/attest', payHeader, { data: args.data });
90
- case 'verify_attestation': return httpJson('GET', BASE + '/v2/verify?' + q({ index: args.index, dataHash: args.dataHash }));
91
- case 'attestation_pubkey': return httpJson('GET', BASE + '/v2/pubkey');
92
- case 'read_ledger': return httpJson('GET', BASE + '/v2/ledger?' + q({ from: args.from, limit: args.limit }));
93
- case 'oracle_base': return httpJson('GET', BASE + '/v2/oracle/base', payHeader);
94
- case 'merkle_prove': return httpJson('POST', BASE + '/v2/merkle/prove', payHeader, { items: args.items, target: args.target });
95
- case 'merkle_verify': return httpJson('POST', BASE + '/v2/merkle/verify', {}, { item: args.item, proof: args.proof, root: args.root });
96
- case 'sentiment_analysis': return httpJson('GET', BASE + '/v2/sentiment?' + q({ asset: args.asset }), payHeader);
97
- case 'hash_sha256': return httpJson('GET', BASE + '/v1/hash?' + q({ input: args.input }), payHeader);
98
- case 'uuid': return httpJson('GET', BASE + '/v1/uuid', payHeader);
99
- case 'pricing': return httpJson('GET', BASE + '/pricing');
100
- case 'health': return httpJson('GET', BASE + '/health');
96
+ case 'simulate_base_transaction': {
97
+ const r = await simulator.simulate({ to: args.to, data: args.data, value: args.value, from: args.from });
98
+ return { status: r.ok ? 200 : 400, body: r };
99
+ }
100
+ case 'security_scan': return httpJson('GET', B + '/v2/security/scan?' + q({ address: args.address }), payHeader);
101
+ case 'attest': return httpJson('POST', B + '/v2/attest', payHeader, { data: args.data });
102
+ case 'verify_attestation': return httpJson('GET', B + '/v2/verify?' + q({ index: args.index, dataHash: args.dataHash }), fwd);
103
+ case 'attestation_pubkey': return httpJson('GET', B + '/v2/pubkey', fwd);
104
+ case 'read_ledger': return httpJson('GET', B + '/v2/ledger?' + q({ from: args.from, limit: args.limit }), fwd);
105
+ case 'oracle_base': return httpJson('GET', B + '/v2/oracle/base', payHeader);
106
+ case 'merkle_prove': return httpJson('POST', B + '/v2/merkle/prove', payHeader, { items: args.items, target: args.target });
107
+ case 'merkle_verify': return httpJson('POST', B + '/v2/merkle/verify', fwd, { item: args.item, proof: args.proof, root: args.root });
108
+ case 'sentiment_analysis': return httpJson('GET', B + '/v2/sentiment?' + q({ asset: args.asset }), payHeader);
109
+ case 'hash_sha256': return httpJson('GET', B + '/v1/hash?' + q({ input: args.input }), payHeader);
110
+ case 'uuid': return httpJson('GET', B + '/v1/uuid', payHeader);
111
+ case 'pricing': return httpJson('GET', B + '/pricing', fwd);
112
+ case 'health': return httpJson('GET', B + '/health', fwd);
101
113
  default: throw new Error('unknown tool: ' + name);
102
114
  }
103
115
  }
104
116
 
105
- function reply(id, result) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n'); }
106
- function replyErr(id, code, message, data) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message, data } }) + '\n'); }
117
+ const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
107
118
 
108
- let buf = '';
109
- process.stdin.on('data', (chunk) => {
110
- buf += chunk.toString('utf8');
111
- let nl;
112
- while ((nl = buf.indexOf('\n')) >= 0) {
113
- const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1);
114
- if (!line) continue;
115
- let msg; try { msg = JSON.parse(line); } catch (e) { continue; }
116
- if (msg.method === 'initialize') {
117
- reply(msg.id, { protocolVersion: '2024-11-05', capabilities: { tools: {} },
119
+ /**
120
+ * Handles one JSON-RPC 2.0 message. Resolves to the response object, or null for
121
+ * notifications (no id). Shared by the stdio transport and the HTTP /mcp endpoint.
122
+ */
123
+ async function handleMessage(msg, opts) {
124
+ if (!msg || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
125
+ return { jsonrpc: '2.0', id: (msg && msg.id !== undefined) ? msg.id : null, error: { code: -32600, message: 'invalid request' } };
126
+ }
127
+ const isNotification = msg.id === undefined;
128
+ const ok = (result) => isNotification ? null : { jsonrpc: '2.0', id: msg.id, result };
129
+ switch (msg.method) {
130
+ case 'initialize': {
131
+ const asked = msg.params && msg.params.protocolVersion;
132
+ return ok({ protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0], capabilities: { tools: {} },
118
133
  serverInfo: { name: 'automaton-x402', version: PKG.version } });
119
- } else if (msg.method === 'ping') {
120
- reply(msg.id, {});
121
- } else if (msg.method === 'notifications/initialized') {
122
- // no reply
123
- } else if (msg.method === 'tools/list') {
124
- reply(msg.id, { tools: TOOLS });
125
- } else if (msg.method === 'tools/call') {
134
+ }
135
+ case 'ping': return ok({});
136
+ case 'tools/list': return ok({ tools: TOOLS });
137
+ case 'tools/call': {
126
138
  const { name, arguments: a } = msg.params || {};
127
- Promise.resolve().then(() => callTool(name, a)).then((r) => {
128
- const isClosedError = r.status >= 400;
139
+ try {
140
+ if (opts && opts.beforeCall) await opts.beforeCall(name, a || {});
141
+ const r = await callTool(name, a, opts);
142
+ const isErr = r.status >= 400;
129
143
  // MCP expects content[]; surface status + body, and mark 402 as error with actionable text
130
144
  const text = typeof r.body === 'string' ? r.body : JSON.stringify(r.body, null, 2);
131
- const prefix = isClosedError ? ('HTTP ' + r.status + '\n') : '';
132
- reply(msg.id, { content: [{ type: 'text', text: prefix + text }], isError: isClosedError });
133
- }).catch((e) => reply(msg.id, { content: [{ type: 'text', text: 'error: ' + e.message }], isError: true }));
134
- } else if (msg.id !== undefined) {
135
- replyErr(msg.id, -32601, 'method not found: ' + msg.method);
145
+ return ok({ content: [{ type: 'text', text: (isErr ? 'HTTP ' + r.status + '\n' : '') + text }], isError: isErr });
146
+ } catch (e) {
147
+ return ok({ content: [{ type: 'text', text: 'error: ' + e.message }], isError: true });
148
+ }
136
149
  }
150
+ default:
151
+ if (msg.method.startsWith('notifications/')) return null;
152
+ return isNotification ? null : { jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'method not found: ' + msg.method } };
137
153
  }
138
- });
139
- process.stdin.on('end', () => process.exit(0));
154
+ }
155
+
156
+ function startStdio() {
157
+ let buf = '';
158
+ process.stdin.on('data', (chunk) => {
159
+ buf += chunk.toString('utf8');
160
+ let nl;
161
+ while ((nl = buf.indexOf('\n')) >= 0) {
162
+ const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1);
163
+ if (!line) continue;
164
+ let msg; try { msg = JSON.parse(line); } catch (e) { continue; }
165
+ handleMessage(msg).then((r) => { if (r) process.stdout.write(JSON.stringify(r) + '\n'); });
166
+ }
167
+ });
168
+ process.stdin.on('end', () => process.exit(0));
169
+ }
170
+
171
+ module.exports = { TOOLS, callTool, handleMessage, startStdio };
172
+
173
+ if (require.main === module) startStdio();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celorodrigues/x402-conformance",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Zero-dependency CLI, MCP server and testing suite for x402 AI agent micropayment protocol & EIP-3009 compliance",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -9,6 +9,7 @@
9
9
  "files": [
10
10
  "index.js",
11
11
  "mcp-server.js",
12
+ "tx-simulator.js",
12
13
  "bin/",
13
14
  "README.md",
14
15
  "LICENSE",
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+ /**
3
+ * Base Mainnet transaction simulator (zero deps).
4
+ *
5
+ * simulate({ to, data, value, from }) runs eth_call + eth_estimateGas against a Base RPC at a
6
+ * pinned block and predicts whether the tx will revert, decoding Error(string) (0x08c379a0),
7
+ * Panic(uint256) (0x4e487b71) and surfacing custom-error selectors.
8
+ *
9
+ * Returns { ok, willRevert, revertReason, estimatedGas, returnData, ... }.
10
+ * ok true when the simulation ran (RPC answered); false on bad input / RPC failure.
11
+ * willRevert true when the call reverts or the node rejects it (e.g. insufficient funds).
12
+ */
13
+ const https = require('https');
14
+ const http = require('http');
15
+ const { URL } = require('url');
16
+
17
+ const DEFAULT_RPC = process.env.BASE_RPC_URL || 'https://mainnet.base.org';
18
+ const BASE_CHAIN_ID = '0x2105'; // 8453
19
+
20
+ const PANIC_CODES = {
21
+ 0x00: 'generic compiler panic',
22
+ 0x01: 'assertion failed',
23
+ 0x11: 'arithmetic overflow or underflow',
24
+ 0x12: 'division or modulo by zero',
25
+ 0x21: 'invalid enum value',
26
+ 0x22: 'corrupted storage byte array',
27
+ 0x31: 'pop() on empty array',
28
+ 0x32: 'array index out of bounds',
29
+ 0x41: 'out of memory / allocation too large',
30
+ 0x51: 'call to zero-initialized function pointer'
31
+ };
32
+
33
+ function rpcCall(rpcUrl, method, params) {
34
+ return new Promise((resolve, reject) => {
35
+ const u = new URL(rpcUrl);
36
+ const lib = u.protocol === 'http:' ? http : https;
37
+ const payload = JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
38
+ const req = lib.request({ hostname: u.hostname, port: u.port || (u.protocol === 'http:' ? 80 : 443), path: u.pathname + u.search, method: 'POST',
39
+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload), 'User-Agent': 'automaton-simulator/1.0' } }, (res) => {
40
+ let d = ''; res.on('data', (c) => d += c);
41
+ res.on('end', () => {
42
+ let j; try { j = JSON.parse(d); } catch (e) { return reject(new Error('bad_rpc_response (HTTP ' + res.statusCode + ')')); }
43
+ resolve(j); // caller inspects j.result / j.error (a revert arrives as j.error)
44
+ });
45
+ });
46
+ req.on('error', reject);
47
+ req.setTimeout(15000, () => req.destroy(new Error('rpc_timeout')));
48
+ req.write(payload); req.end();
49
+ });
50
+ }
51
+
52
+ function isAddr(a) { return typeof a === 'string' && /^0x[0-9a-fA-F]{40}$/.test(a); }
53
+
54
+ // Accepts wei as decimal string/number, 0x-hex, or bigint. Returns a JSON-RPC quantity.
55
+ function toQuantity(v) {
56
+ if (v === undefined || v === null || v === '' || v === 0 || v === '0') return '0x0';
57
+ let n;
58
+ if (typeof v === 'bigint') n = v;
59
+ else if (typeof v === 'number') { if (!Number.isSafeInteger(v) || v < 0) throw new Error('value must be a non-negative integer (wei)'); n = BigInt(v); }
60
+ else if (typeof v === 'string' && /^0x[0-9a-fA-F]+$/.test(v)) n = BigInt(v);
61
+ else if (typeof v === 'string' && /^\d+$/.test(v)) n = BigInt(v);
62
+ else throw new Error('value must be wei as a decimal or 0x-hex integer');
63
+ if (n < 0n) throw new Error('value must be non-negative');
64
+ return '0x' + n.toString(16);
65
+ }
66
+
67
+ function decodeRevert(hex) {
68
+ const data = typeof hex === 'string' ? hex.toLowerCase() : '';
69
+ if (!data || data === '0x') return { errorType: 'empty', reason: 'reverted without a reason' };
70
+ const sel = data.slice(0, 10);
71
+ const body = data.slice(10);
72
+ try {
73
+ if (sel === '0x08c379a0' && body.length >= 128) {
74
+ const off = Number(BigInt('0x' + body.slice(0, 64))) * 2;
75
+ const len = Number(BigInt('0x' + body.slice(off, off + 64)));
76
+ const str = Buffer.from(body.slice(off + 64, off + 64 + len * 2), 'hex').toString('utf8');
77
+ return { errorType: 'Error(string)', reason: str };
78
+ }
79
+ if (sel === '0x4e487b71' && body.length >= 64) {
80
+ const code = Number(BigInt('0x' + body.slice(0, 64)));
81
+ return { errorType: 'Panic(uint256)', panicCode: '0x' + code.toString(16).padStart(2, '0'),
82
+ reason: 'Panic(0x' + code.toString(16).padStart(2, '0') + '): ' + (PANIC_CODES[code] || 'unknown panic code') };
83
+ }
84
+ } catch (e) { /* fall through to raw selector */ }
85
+ return { errorType: 'custom', selector: sel, reason: 'custom error ' + sel + ' (not ABI-decoded)' };
86
+ }
87
+
88
+ // Node errors carry revert data in error.data (string) or error.data.data depending on client.
89
+ function revertDataOf(err) {
90
+ if (!err) return null;
91
+ const d = err.data;
92
+ if (typeof d === 'string' && /^0x[0-9a-fA-F]*$/.test(d)) return d;
93
+ if (d && typeof d === 'object' && typeof d.data === 'string') return d.data;
94
+ return null;
95
+ }
96
+
97
+ async function simulate(input, opts) {
98
+ input = input || {};
99
+ opts = opts || {};
100
+ const rpcUrl = opts.rpcUrl || DEFAULT_RPC;
101
+ const out = { ok: false, network: 'base', chainId: 8453, willRevert: null, revertReason: null, estimatedGas: null, returnData: null };
102
+
103
+ if (!isAddr(input.to)) { out.error = 'to must be a 0x-prefixed 20-byte address'; return out; }
104
+ if (input.from !== undefined && input.from !== null && input.from !== '' && !isAddr(input.from)) { out.error = 'from must be a 0x-prefixed 20-byte address'; return out; }
105
+ const data = input.data === undefined || input.data === null || input.data === '' ? '0x' : String(input.data);
106
+ if (!/^0x([0-9a-fA-F]{2})*$/.test(data)) { out.error = 'data must be 0x-prefixed even-length hex'; return out; }
107
+ let value; try { value = toQuantity(input.value); } catch (e) { out.error = e.message; return out; }
108
+
109
+ const tx = { to: input.to, data, value };
110
+ if (input.from) tx.from = input.from;
111
+
112
+ let chain, head;
113
+ try {
114
+ [chain, head] = await Promise.all([rpcCall(rpcUrl, 'eth_chainId', []), rpcCall(rpcUrl, 'eth_blockNumber', [])]);
115
+ } catch (e) { out.error = 'rpc_unreachable: ' + e.message; return out; }
116
+ if (!chain.result || String(chain.result).toLowerCase() !== BASE_CHAIN_ID) { out.error = 'rpc is not Base Mainnet (chainId ' + (chain.result || '?') + ')'; return out; }
117
+ if (!head.result) { out.error = 'rpc_error: ' + ((head.error && head.error.message) || 'no block number'); return out; }
118
+ const block = head.result;
119
+ out.blockNumber = parseInt(block, 16);
120
+ out.tx = tx;
121
+
122
+ let call, gas;
123
+ try {
124
+ [call, gas] = await Promise.all([rpcCall(rpcUrl, 'eth_call', [tx, block]), rpcCall(rpcUrl, 'eth_estimateGas', [tx, block])]);
125
+ } catch (e) { out.error = 'rpc_unreachable: ' + e.message; return out; }
126
+
127
+ out.ok = true;
128
+ if (call.error) {
129
+ const rd = revertDataOf(call.error);
130
+ out.willRevert = true;
131
+ out.returnData = rd;
132
+ if (rd) {
133
+ const dec = decodeRevert(rd);
134
+ out.revertReason = dec.reason; out.errorType = dec.errorType;
135
+ if (dec.panicCode) out.panicCode = dec.panicCode;
136
+ if (dec.selector) out.errorSelector = dec.selector;
137
+ } else {
138
+ // No revert payload: node-level rejection (insufficient funds, bad nonce, ...) or bare revert.
139
+ const msg = String(call.error.message || 'execution failed');
140
+ out.revertReason = msg;
141
+ out.errorType = /revert/i.test(msg) ? 'empty' : 'node_rejected';
142
+ }
143
+ } else {
144
+ out.willRevert = false;
145
+ out.returnData = call.result || '0x';
146
+ }
147
+
148
+ if (gas.result) out.estimatedGas = parseInt(gas.result, 16);
149
+ else if (gas.error) {
150
+ out.estimateGasError = String(gas.error.message || 'estimateGas failed');
151
+ // eth_call can pass while estimateGas fails (e.g. gas-dependent logic): still a revert on-chain.
152
+ if (out.willRevert === false) {
153
+ out.willRevert = true;
154
+ const rd = revertDataOf(gas.error);
155
+ const dec = rd ? decodeRevert(rd) : null;
156
+ out.revertReason = dec ? dec.reason : out.estimateGasError;
157
+ out.errorType = dec ? dec.errorType : 'estimate_gas_failed';
158
+ }
159
+ }
160
+ out.success = out.willRevert === false;
161
+ out.simulatedAt = new Date().toISOString();
162
+ return out;
163
+ }
164
+
165
+ module.exports = { simulate, decodeRevert, toQuantity, PANIC_CODES };