@celorodrigues/x402-conformance 2.0.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
@@ -29,6 +29,30 @@ npx @celorodrigues/x402-conformance https://your-service.com/v1/paid --svg > bad
29
29
 
30
30
  ---
31
31
 
32
+ ## ๐Ÿค– MCP Server (Claude Desktop, Cursor)
33
+
34
+ The same package runs as an MCP stdio server:
35
+
36
+ ```json
37
+ {
38
+ "mcpServers": {
39
+ "automaton-x402": {
40
+ "command": "npx",
41
+ "args": ["-y", "@celorodrigues/x402-conformance", "--mcp"]
42
+ }
43
+ }
44
+ }
45
+ ```
46
+
47
+ - Claude Desktop: Settings โ†’ Developer โ†’ Edit Config (`claude_desktop_config.json`), then restart.
48
+ - Cursor: `.cursor/mcp.json` in the project, or `~/.cursor/mcp.json`.
49
+
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
+
52
+ Optional env: `VALUE_API_BASE` (default `https://api.automaton-sovereign.workers.dev`), `VALUE_API_PAYMENT` (payment tx hash attached to paid calls).
53
+
54
+ ---
55
+
32
56
  ## ๐Ÿงช Battery of Checks
33
57
 
34
58
  | Code | Level | Check | Requirement |
package/bin/cli.js CHANGED
@@ -1,14 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
- const engine = require('../index.js');
4
-
5
3
  const args = process.argv.slice(2);
4
+
5
+ // MCP stdio server mode: npx -y @celorodrigues/x402-conformance --mcp
6
+ if (args.includes('--mcp')) {
7
+ require('../mcp-server.js').startStdio();
8
+ return;
9
+ }
10
+
11
+ const engine = require('../index.js');
6
12
  const target = args.find(a => !a.startsWith('--'));
7
13
  const jsonMode = args.includes('--json');
8
14
  const svgMode = args.includes('--svg');
9
15
 
10
16
  if (!target) {
11
17
  console.error('\nUsage: npx @celorodrigues/x402-conformance <endpoint-url> [--json] [--svg]');
18
+ console.error(' npx -y @celorodrigues/x402-conformance --mcp (run as an MCP stdio server)');
12
19
  console.error('Example: npx @celorodrigues/x402-conformance https://api.myservice.com/v1/paid --json\n');
13
20
  process.exit(2);
14
21
  }
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * x402-conformance v2.0.0 -- Autonomous x402 Protocol Conformance Linter & Certification Engine
3
+ * x402-conformance -- Autonomous x402 Protocol Conformance Linter & Certification Engine
4
4
  * Conforms strictly to official Coinbase x402 specifications (v1 and v2 CAIP-2) & EIP-3009.
5
5
  * Author: Automaton-Sovereign (Base: 0x71DEAc098914A009E3720524642A6bE6F65EE528)
6
6
  *
@@ -23,6 +23,7 @@
23
23
  const https = require('https');
24
24
  const http = require('http');
25
25
  const { URL } = require('url');
26
+ const VERSION = require('./package.json').version;
26
27
 
27
28
  function fetchUrl(targetUrl, options = {}) {
28
29
  return new Promise((resolve, reject) => {
@@ -30,7 +31,7 @@ function fetchUrl(targetUrl, options = {}) {
30
31
  const u = new URL(targetUrl);
31
32
  const lib = u.protocol === 'http:' ? http : https;
32
33
  const headers = Object.assign({
33
- 'User-Agent': 'Automaton-x402-Conformance-Linter/2.0.0',
34
+ 'User-Agent': 'Automaton-x402-Conformance-Linter/' + VERSION,
34
35
  'Accept': 'application/json, text/plain, */*'
35
36
  }, options.headers || {});
36
37
 
@@ -271,7 +272,7 @@ function finish(results, targetUrl) {
271
272
 
272
273
  return {
273
274
  suite: '@celorodrigues/x402-conformance',
274
- version: '2.0.0',
275
+ version: VERSION,
275
276
  target: targetUrl,
276
277
  timestamp: new Date().toISOString(),
277
278
  verdict: isConformant ? 'CONFORMANT' : 'NON_CONFORMANT',
package/mcp-server.js ADDED
@@ -0,0 +1,173 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * Automaton-Sovereign Value API โ€” MCP server (stdio transport, zero deps, JSON-RPC 2.0)
5
+ *
6
+ * Exposes the x402-paid Value API as native MCP tools so any MCP-capable agent
7
+ * can call it directly. Paid tools forward the caller's X-PAYMENT tx hash;
8
+ * free tools need nothing.
9
+ *
10
+ * Also exposes the local x402 conformance linter (index.js) as a free tool.
11
+ *
12
+ * Config via env:
13
+ * VALUE_API_BASE base URL of the API (default https://api.automaton-sovereign.workers.dev)
14
+ * VALUE_API_PAYMENT default X-PAYMENT tx hash to attach to paid calls (optional)
15
+ *
16
+ * Usage (Claude Desktop / Cursor MCP config):
17
+ * { "mcpServers": { "automaton-x402": { "command": "npx",
18
+ * "args": ["-y", "@celorodrigues/x402-conformance", "--mcp"] } } }
19
+ */
20
+ const http = require('http');
21
+ const https = require('https');
22
+ const { URL } = require('url');
23
+ const PKG = require('./package.json');
24
+ const linter = require('./index.js');
25
+ const simulator = require('./tx-simulator.js');
26
+
27
+ const BASE = (process.env.VALUE_API_BASE || 'https://api.automaton-sovereign.workers.dev').replace(/\/+$/, '');
28
+ const PAYMENT = process.env.VALUE_API_PAYMENT || '';
29
+
30
+ function httpJson(method, urlStr, headers, body) {
31
+ return new Promise((resolve, reject) => {
32
+ const u = new URL(urlStr);
33
+ const lib = u.protocol === 'http:' ? http : https;
34
+ const payload = body ? (typeof body === 'string' ? body : JSON.stringify(body)) : null;
35
+ const h = Object.assign({ 'Accept': 'application/json', 'User-Agent': 'automaton-mcp/1.0' }, headers || {});
36
+ if (payload) { h['Content-Type'] = 'application/json'; h['Content-Length'] = Buffer.byteLength(payload); }
37
+ const req = lib.request({ hostname: u.hostname, port: u.port || (u.protocol === 'http:' ? 80 : 443), path: u.pathname + u.search, method, headers: h }, (res) => {
38
+ let d = ''; res.on('data', c => d += c);
39
+ res.on('end', () => {
40
+ let parsed = null; try { parsed = JSON.parse(d); } catch (e) {}
41
+ resolve({ status: res.statusCode, headers: res.headers, body: parsed !== null ? parsed : d });
42
+ });
43
+ });
44
+ req.on('error', reject); req.setTimeout(30000, () => req.destroy(new Error('timeout')));
45
+ if (payload) req.write(payload);
46
+ req.end();
47
+ });
48
+ }
49
+
50
+ const TOOLS = [
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.',
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'] } },
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.',
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'] } },
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.',
58
+ inputSchema: { type: 'object', properties: { data: { type: 'string', description: 'Payload to attest (any string).' }, payment: { type: 'string', description: 'Optional X-PAYMENT base tx hash of the USDC payment.' } }, required: ['data'] } },
59
+ { name: 'verify_attestation', description: 'FREE. Verify a ledger entry by index or by data hash: recomputes hash, checks ECDSA signature and chain link.',
60
+ inputSchema: { type: 'object', properties: { index: { type: 'integer' }, dataHash: { type: 'string' } } } },
61
+ { name: 'attestation_pubkey', description: 'FREE. Get the ECDSA P-256 public key (PEM) and keyId used to sign ledger entries.',
62
+ inputSchema: { type: 'object', properties: {} } },
63
+ { name: 'read_ledger', description: 'FREE. Read the attestation ledger (paginated).',
64
+ inputSchema: { type: 'object', properties: { from: { type: 'integer' }, limit: { type: 'integer' } } } },
65
+ { name: 'oracle_base', description: 'PAID 0.001 USDC/call. Get real-time Base L2 gas estimates and asset prices (ETH, USDC, cbBTC, AERO, VIRTUAL) with an ECDSA P-256 digital signature from the sovereign agent.',
66
+ inputSchema: { type: 'object', properties: { payment: { type: 'string', description: 'Optional X-PAYMENT base tx hash of the USDC payment.' } } } },
67
+ { name: 'merkle_prove', description: 'PAID 0.001 USDC/call. Generate a cryptographic Merkle inclusion proof for a list of items and target element.',
68
+ inputSchema: { type: 'object', properties: { items: { type: 'array', items: { type: 'string' }, description: 'Array of items' }, target: { type: 'string', description: 'Target item or index' }, payment: { type: 'string' } }, required: ['items'] } },
69
+ { name: 'merkle_verify', description: 'FREE. Verify a cryptographic Merkle inclusion proof against a root.',
70
+ inputSchema: { type: 'object', properties: { item: { type: 'string' }, proof: { type: 'array', items: { type: 'object' } }, root: { type: 'string' } }, required: ['item', 'proof', 'root'] } },
71
+ { name: 'sentiment_analysis', description: 'PAID 0.001 USDC/call. Web3 token risk, security checks, and sentiment scoring with signed verdict.',
72
+ inputSchema: { type: 'object', properties: { asset: { type: 'string', description: 'Asset symbol (e.g. ETH, AERO, VIRTUAL)' }, payment: { type: 'string' } }, required: ['asset'] } },
73
+ { name: 'hash_sha256', description: 'PAID 0.001 USDC/call. SHA-256 hex of a string.',
74
+ inputSchema: { type: 'object', properties: { input: { type: 'string' }, payment: { type: 'string' } }, required: ['input'] } },
75
+ { name: 'uuid', description: 'PAID 0.001 USDC/call. Generate a UUIDv4.', inputSchema: { type: 'object', properties: { payment: { type: 'string' } } } },
76
+ { name: 'pricing', description: 'FREE. Full pricing terms, endpoints, and payment mechanics.',
77
+ inputSchema: { type: 'object', properties: {} } },
78
+ { name: 'health', description: 'FREE. Service liveness and version.', inputSchema: { type: 'object', properties: {} } }
79
+ ];
80
+
81
+ function q(o) { return Object.entries(o || {}).filter(([, v]) => v !== undefined && v !== null && v !== '').map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&'); }
82
+
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) {
86
+ args = args || {};
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 } : {});
91
+ switch (name) {
92
+ case 'x402_conformance_check': {
93
+ if (!/^https?:\/\//i.test(args.url || '')) throw new Error('url must be an absolute http(s) URL');
94
+ return { status: 200, body: await linter.run(args.url) };
95
+ }
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);
113
+ default: throw new Error('unknown tool: ' + name);
114
+ }
115
+ }
116
+
117
+ const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
118
+
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: {} },
133
+ serverInfo: { name: 'automaton-x402', version: PKG.version } });
134
+ }
135
+ case 'ping': return ok({});
136
+ case 'tools/list': return ok({ tools: TOOLS });
137
+ case 'tools/call': {
138
+ const { name, arguments: a } = msg.params || {};
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;
143
+ // MCP expects content[]; surface status + body, and mark 402 as error with actionable text
144
+ const text = typeof r.body === 'string' ? r.body : JSON.stringify(r.body, null, 2);
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
+ }
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 } };
153
+ }
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,16 +1,19 @@
1
1
  {
2
2
  "name": "@celorodrigues/x402-conformance",
3
- "version": "2.0.0",
4
- "description": "Zero-dependency CLI & testing suite for official x402 AI agent micropayment protocol & EIP-3009 compliance",
3
+ "version": "2.2.0",
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": {
7
7
  "x402-conformance": "bin/cli.js"
8
8
  },
9
9
  "files": [
10
10
  "index.js",
11
+ "mcp-server.js",
12
+ "tx-simulator.js",
11
13
  "bin/",
12
14
  "README.md",
13
- "LICENSE"
15
+ "LICENSE",
16
+ "smithery.yaml"
14
17
  ],
15
18
  "keywords": [
16
19
  "x402",
@@ -21,7 +24,10 @@
21
24
  "micropayments",
22
25
  "usdc",
23
26
  "linter",
24
- "conformance"
27
+ "conformance",
28
+ "mcp",
29
+ "model-context-protocol",
30
+ "claude"
25
31
  ],
26
32
  "author": "Automaton-Sovereign (0x71DEAc098914A009E3720524642A6bE6F65EE528)",
27
33
  "license": "MIT",
package/smithery.yaml ADDED
@@ -0,0 +1,26 @@
1
+ # Smithery configuration: https://smithery.ai/docs/config#smitheryyaml
2
+ # MCP stdio server shipped in the npm package (`x402-conformance --mcp`).
3
+ startCommand:
4
+ type: stdio
5
+ configSchema:
6
+ type: object
7
+ properties:
8
+ valueApiBase:
9
+ type: string
10
+ default: https://api.automaton-sovereign.workers.dev
11
+ description: Base URL of the Automaton-Sovereign Value API used by the paid/free API tools.
12
+ valueApiPayment:
13
+ type: string
14
+ description: Optional x402 payment (Base USDC tx hash) attached as X-PAYMENT to paid tool calls.
15
+ commandFunction:
16
+ |-
17
+ (config) => ({
18
+ command: 'npx',
19
+ args: ['-y', '@celorodrigues/x402-conformance', '--mcp'],
20
+ env: Object.assign(
21
+ { VALUE_API_BASE: config.valueApiBase || 'https://api.automaton-sovereign.workers.dev' },
22
+ config.valueApiPayment ? { VALUE_API_PAYMENT: config.valueApiPayment } : {}
23
+ )
24
+ })
25
+ exampleConfig:
26
+ valueApiBase: https://api.automaton-sovereign.workers.dev
@@ -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 };