nansen-cli 2.1.0 → 2.3.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/src/wallet.js CHANGED
@@ -1253,8 +1253,17 @@ ENVIRONMENT:
1253
1253
  NANSEN_BASE_RPC Custom Base RPC endpoint
1254
1254
  NANSEN_SOLANA_RPC Custom Solana RPC endpoint
1255
1255
  NANSEN_X402_MAX_AMOUNT Max USD per x402 auto-payment (default 1.00; "unlimited" to disable)
1256
+ NANSEN_X402_SESSION_MAX_AMOUNT
1257
+ Max total USD of x402 auto-payments one CLI process signs and the
1258
+ server doesn't cleanly reject (unset or "unlimited" = no limit; an
1259
+ invalid value refuses every payment; environment only). It resets
1260
+ with every process, so it does not limit spending across separate runs.
1256
1261
  NANSEN_X402_ALLOWED_PAYTO Comma-separated recipient allowlist for x402 auto-payment (optional)
1257
1262
 
1263
+ x402 auto-payments are recorded in ~/.nansen/x402/payments.jsonl (amount, network,
1264
+ asset, recipient, request path and outcome; never signatures, request bodies or
1265
+ query strings).
1266
+
1258
1267
  EXAMPLES:
1259
1268
  NANSEN_WALLET_PASSWORD=mypass nansen wallet create --name trading
1260
1269
  nansen wallet create --name agent-wallet --provider privy
@@ -104,6 +104,36 @@ export async function getWalletConnectAddress(chainType, chainId) {
104
104
  }
105
105
  }
106
106
 
107
+ /**
108
+ * Run a wallet send and mark anything that goes wrong as an ambiguous handoff.
109
+ *
110
+ * Once the wallet has been asked to send, no failure here proves the
111
+ * transaction stayed put. `wcExec` collapses a user rejection, a 120s approval
112
+ * timeout and a failure to launch the binary into the same bare
113
+ * `Error(err.message)`, and the timeout is precisely the case where the user DID
114
+ * approve and the wallet DID broadcast while the subprocess gave up waiting. A
115
+ * reply we cannot parse, or one carrying neither a hash nor signed bytes, says
116
+ * just as little about what the wallet did.
117
+ *
118
+ * Callers must therefore never read one of these as "nothing was sent" and go on
119
+ * to send something else. Marking it here, at the boundary, is what makes that
120
+ * hold for every call site — including ones added later — instead of depending
121
+ * on each `catch` to remember. `isFatalBroadcastError` in trading.js treats the
122
+ * flag as terminal; it is deliberately distinct from `broadcastRuledOut`, which
123
+ * is the opposite claim (the backend stated nothing was sent).
124
+ *
125
+ * @param {() => Promise<T>} fn - the send, from the wallet call through parsing
126
+ * @returns {Promise<T>}
127
+ * @template T
128
+ */
129
+ async function markBroadcastAmbiguous(fn) {
130
+ try {
131
+ return await fn();
132
+ } catch (err) {
133
+ throw Object.assign(err, { broadcastAmbiguous: true });
134
+ }
135
+ }
136
+
107
137
  /**
108
138
  * Send a transaction via WalletConnect.
109
139
  *
@@ -128,14 +158,16 @@ export async function sendTransactionViaWalletConnect(txData, timeoutMs = 120000
128
158
  chainId,
129
159
  };
130
160
 
131
- const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs);
132
- const result = parseWcJson(output);
161
+ return markBroadcastAmbiguous(async () => {
162
+ const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs);
163
+ const result = parseWcJson(output);
133
164
 
134
- if (result.transactionHash) return { txHash: result.transactionHash };
135
- if (result.txHash) return { txHash: result.txHash };
136
- if (result.signedTransaction) return { signedTransaction: result.signedTransaction };
165
+ if (result.transactionHash) return { txHash: result.transactionHash };
166
+ if (result.txHash) return { txHash: result.txHash };
167
+ if (result.signedTransaction) return { signedTransaction: result.signedTransaction };
137
168
 
138
- throw new Error('Unexpected response from walletconnect send-transaction');
169
+ throw new Error('Unexpected response from walletconnect send-transaction');
170
+ });
139
171
  }
140
172
 
141
173
  /**
@@ -186,15 +218,20 @@ export async function sendSolanaTransactionViaWalletConnect(txBase58, timeoutMs
186
218
  chainId: SOLANA_MAINNET_CHAIN,
187
219
  };
188
220
 
189
- const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs);
190
- const result = parseWcJson(output);
221
+ // Marked ambiguous for the same reason as the EVM send: this goes out over the
222
+ // CLI's `send-transaction` verb, so a wallet that signs-and-sends has already
223
+ // broadcast by the time a timeout or an unreadable reply reaches us.
224
+ return markBroadcastAmbiguous(async () => {
225
+ const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs);
226
+ const result = parseWcJson(output);
191
227
 
192
- if (result.signedTransaction) return { signedTransaction: result.signedTransaction };
193
- if (result.signature) return { signature: result.signature };
194
- // Some wallets (e.g. Phantom) return 'transaction' instead of 'signedTransaction'
195
- if (result.transaction) return { signedTransaction: result.transaction };
228
+ if (result.signedTransaction) return { signedTransaction: result.signedTransaction };
229
+ if (result.signature) return { signature: result.signature };
230
+ // Some wallets (e.g. Phantom) return 'transaction' instead of 'signedTransaction'
231
+ if (result.transaction) return { signedTransaction: result.transaction };
196
232
 
197
- throw new Error('Unexpected response from walletconnect Solana sign');
233
+ throw new Error('Unexpected response from walletconnect Solana sign');
234
+ });
198
235
  }
199
236
 
200
237
  /**
@@ -9,20 +9,33 @@ import crypto from 'crypto';
9
9
  import { NansenError, ErrorCode } from './api.js';
10
10
  import { wcExec } from './walletconnect-exec.js';
11
11
  import { getWalletConnectAddress, parseWcJson } from './walletconnect-trading.js';
12
- import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
12
+ import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo, signWithSessionCharge } from './x402-policy.js';
13
+ import { isEvmNetwork } from './x402-evm.js';
14
+ import { rankRequirements } from './x402.js';
15
+ import { hasSufficientEvmPaymentBalance } from './x402-payment-balance.js';
16
+
17
+ /**
18
+ * True for an option this path can sign: scheme=exact with EIP-3009
19
+ * TransferWithAuthorization support (extra.name + extra.version). Like the
20
+ * local EVM signer, only an absent or "eip3009" transfer method is signed as
21
+ * EIP-3009; Permit2 and unknown methods are not compatible.
22
+ */
23
+ function isCompatible(req) {
24
+ const method = req?.extra?.assetTransferMethod;
25
+ return Boolean(
26
+ req?.scheme === 'exact' &&
27
+ req.extra?.name &&
28
+ req.extra?.version &&
29
+ (!method || method === 'eip3009')
30
+ );
31
+ }
13
32
 
14
33
  /**
15
34
  * Select a compatible payment requirement from the accepts array.
16
- * Requires scheme=exact and EIP-3009 TransferWithAuthorization support (extra.name + extra.version).
17
35
  */
18
36
  export function selectPaymentRequirement(accepts) {
19
37
  if (!Array.isArray(accepts) || accepts.length === 0) return null;
20
-
21
- return accepts.find(req =>
22
- req.scheme === 'exact' &&
23
- req.extra?.name &&
24
- req.extra?.version
25
- ) || null;
38
+ return accepts.find(isCompatible) || null;
26
39
  }
27
40
 
28
41
  /**
@@ -138,33 +151,17 @@ function formatPaymentAmount(requirement) {
138
151
  }
139
152
 
140
153
  /**
141
- * Handle x402 payment: check wallet, sign, return Payment-Signature header.
142
- *
143
- * @param {Object} paymentRequirements - Decoded payment requirements from 402 response
144
- * @param {string} requestUrl - The original request URL (for context in errors)
145
- * @returns {string} Base64-encoded Payment-Signature header value
146
- * @throws {NansenError} On failure
154
+ * Prepare one option for signing: policy, chain-scoped session, balance,
155
+ * typed data. Returns { fromAddress, typedData, payment } (payment is the
156
+ * policy decision) or { error } explaining why
157
+ * the option is skipped; `logged` marks an error already reported on stderr.
147
158
  */
148
- export async function handleX402Payment(paymentRequirements) {
149
- // 1. Select compatible payment requirement
150
- const accepts = paymentRequirements.accepts || paymentRequirements;
151
- const requirement = selectPaymentRequirement(Array.isArray(accepts) ? accepts : [accepts]);
152
- if (!requirement) {
153
- const available = (Array.isArray(accepts) ? accepts : []).map(r => r.scheme).join(', ');
154
- throw new NansenError(
155
- `x402 payment required but no compatible payment method found. Available: ${available || 'none'}. Need scheme=exact with EIP-3009 support.`,
156
- ErrorCode.PAYMENT_REQUIRED,
157
- 402
158
- );
159
- }
160
-
161
- // 2. Evaluate payment policy before touching any signing material
159
+ async function prepareRequirement(requirement) {
160
+ // Evaluate payment policy before touching any signing material
162
161
  const decision = evaluatePaymentRequirement(requirement);
163
- if (!decision.ok) {
164
- throw new Error(decision.reason);
165
- }
162
+ if (!decision.ok) return { error: new Error(decision.reason) };
166
163
 
167
- // 3. Resolve the WalletConnect signer scoped to this exact chain. EVM
164
+ // Resolve the WalletConnect signer scoped to this exact chain. EVM
168
165
  // addresses are identical across chains, so "some account exists in the
169
166
  // session" can't prove the session was actually approved for THIS chain --
170
167
  // only the CAIP-2 chain tag can (mirrors getWalletConnectAddress's chainId
@@ -176,28 +173,54 @@ export async function handleX402Payment(paymentRequirements) {
176
173
  // with no chain filter at all.
177
174
  const chainId = parseChainId(requirement.network);
178
175
  if (chainId === null) {
179
- throw new Error(`Refusing to auto-pay: unsupported or missing EVM network ${requirement.network}.`);
176
+ return { error: new Error(`Refusing to auto-pay: unsupported or missing EVM network ${requirement.network}.`) };
180
177
  }
181
178
  const fromAddress = await getWalletConnectAddress('evm', chainId);
182
179
  if (!fromAddress) {
183
- throw new NansenError(
184
- `x402 payment required but no WalletConnect session is active for chain ${requirement.network}. ` +
185
- 'To pay automatically: create a local wallet with `nansen wallet create` (then set NANSEN_WALLET_PASSWORD), ' +
186
- 'or connect an external wallet approved for this chain via the `walletconnect` CLI (`walletconnect connect`).',
187
- ErrorCode.PAYMENT_REQUIRED,
188
- 402
189
- );
180
+ return {
181
+ error: new NansenError(
182
+ `x402 payment required but no WalletConnect session is active for chain ${requirement.network}. ` +
183
+ 'To pay automatically: create a local wallet with `nansen wallet create` (then set NANSEN_WALLET_PASSWORD), ' +
184
+ 'or connect an external wallet approved for this chain via the `walletconnect` CLI (`walletconnect connect`).',
185
+ ErrorCode.PAYMENT_REQUIRED,
186
+ 402
187
+ ),
188
+ };
189
+ }
190
+
191
+ // Don't ask the user to approve a payment the wallet can't cover.
192
+ if (!await hasSufficientEvmPaymentBalance(requirement, fromAddress)) {
193
+ return {
194
+ logged: true,
195
+ error: new NansenError(
196
+ `x402 payment required but the WalletConnect wallet has an insufficient token balance on ${requirement.network}. ` +
197
+ 'Fund the token on this network or use another funded payment option.',
198
+ ErrorCode.PAYMENT_REQUIRED,
199
+ 402
200
+ ),
201
+ };
190
202
  }
191
203
 
192
- // 4. Build EIP-712 typed data
193
- const typedData = buildEIP712TypedData({ fromAddress, requirement });
204
+ try {
205
+ return { fromAddress, typedData: buildEIP712TypedData({ fromAddress, requirement }), payment: decision };
206
+ } catch (error) {
207
+ return { error };
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Ask the connected wallet to sign one option and build its header.
213
+ * A rejected, timed-out, or malformed signature throws: the user was already
214
+ * prompted, so the caller must not prompt again for another option.
215
+ */
216
+ async function signRequirement(requirement, fromAddress, typedData, resource) {
194
217
  const typedDataJson = JSON.stringify(typedData);
195
218
 
196
- // 5. Log payment info to stderr (stdout is for JSON output)
219
+ // Log payment info to stderr (stdout is for JSON output)
197
220
  const amountStr = formatPaymentAmount(requirement);
198
221
  process.stderr.write(`x402: Requesting payment approval (${amountStr})...\n`);
199
222
 
200
- // 6. Sign via walletconnect CLI (120s timeout for user approval)
223
+ // Sign via walletconnect CLI (120s timeout for user approval)
201
224
  let signResult;
202
225
  try {
203
226
  const output = await wcExec('walletconnect', ['sign-typed-data', typedDataJson], 120000);
@@ -217,7 +240,7 @@ export async function handleX402Payment(paymentRequirements) {
217
240
  );
218
241
  }
219
242
 
220
- // 7. Build Payment-Signature header (authorization values must be strings per x402 spec)
243
+ // Build Payment-Signature header (authorization values must be strings per x402 spec)
221
244
  const authorization = {
222
245
  from: fromAddress,
223
246
  to: resolvePayTo(requirement),
@@ -230,10 +253,81 @@ export async function handleX402Payment(paymentRequirements) {
230
253
  const headerValue = buildPaymentSignatureHeader({
231
254
  signature: signResult.signature,
232
255
  authorization,
233
- resource: paymentRequirements.resource || { url: '', description: '', mimeType: '' },
256
+ resource,
234
257
  accepted: requirement,
235
258
  });
236
259
 
237
260
  process.stderr.write(`x402: Payment signed successfully.\n`);
238
261
  return headerValue;
239
262
  }
263
+
264
+ /**
265
+ * Generate WalletConnect payment signatures for every viable option, cheapest
266
+ * first (the same ranking the local wallet uses). Options refused by policy,
267
+ * without a session for their chain, or known to be unfunded are skipped
268
+ * before the user is prompted. Caller tries each until the server accepts one.
269
+ *
270
+ * Throws when nothing can be signed (the last skip reason) or when signing
271
+ * itself fails.
272
+ *
273
+ * Yields the same { signature, network, asset, payment, releaseCharge } shape
274
+ * as createPaymentSignatures() in x402.js.
275
+ *
276
+ * @param {Object} paymentRequirements - Decoded payment requirements from 402 response
277
+ * @param {object} [options] - { onCapRefusal }, called with the reason when the session cap refuses an option
278
+ * @returns {AsyncGenerator<{ signature: string, network: string, asset: string, payment: object, releaseCharge: Function }>}
279
+ */
280
+ export async function* createWalletConnectPaymentSignatures(paymentRequirements, options = {}) {
281
+ const accepts = paymentRequirements.accepts || paymentRequirements;
282
+ const list = Array.isArray(accepts) ? accepts : [accepts];
283
+ const compatible = rankRequirements(list.filter(isCompatible))
284
+ .filter(req => isEvmNetwork(req.network));
285
+ if (compatible.length === 0) {
286
+ const available = list.map(r => r?.scheme).join(', ');
287
+ throw new NansenError(
288
+ `x402 payment required but no compatible payment method found. Available: ${available || 'none'}. Need scheme=exact with EIP-3009 support.`,
289
+ ErrorCode.PAYMENT_REQUIRED,
290
+ 402
291
+ );
292
+ }
293
+
294
+ const resource = paymentRequirements.resource || { url: '', description: '', mimeType: '' };
295
+ let lastError = null;
296
+ let yielded = false;
297
+ for (const requirement of compatible) {
298
+ const { fromAddress, typedData, payment, error, logged } = await prepareRequirement(requirement);
299
+ if (error) {
300
+ if (compatible.length > 1 && !logged) console.error(`[x402] Skipping ${requirement.network} WalletConnect option: ${error.message}`);
301
+ lastError = error;
302
+ continue;
303
+ }
304
+ // The charge comes before the approval prompt, so an over-cap option never prompts.
305
+ const signed = await signWithSessionCharge(payment, () => signRequirement(requirement, fromAddress, typedData, resource));
306
+ if (!signed.ok) {
307
+ console.error(`[x402] Skipping ${requirement.network} WalletConnect option: ${signed.reason}`);
308
+ options.onCapRefusal?.(signed.reason);
309
+ lastError = new Error(signed.reason);
310
+ continue;
311
+ }
312
+ yielded = true;
313
+ yield { signature: signed.value, network: requirement.network, asset: requirement.asset, payment, releaseCharge: signed.release };
314
+ }
315
+ if (!yielded && lastError) throw lastError;
316
+ }
317
+
318
+ /**
319
+ * Handle x402 payment: return the first viable Payment-Signature header.
320
+ * For fallback across options, use createWalletConnectPaymentSignatures().
321
+ * The signature's session-cap charge is never released, so a payment the
322
+ * server rejects still counts against the cap.
323
+ *
324
+ * @param {Object} paymentRequirements - Decoded payment requirements from 402 response
325
+ * @returns {string} Base64-encoded Payment-Signature header value
326
+ * @throws {NansenError} On failure
327
+ */
328
+ export async function handleX402Payment(paymentRequirements) {
329
+ for await (const { signature } of createWalletConnectPaymentSignatures(paymentRequirements)) {
330
+ return signature;
331
+ }
332
+ throw new NansenError('x402 payment required but no WalletConnect payment option could be signed.', ErrorCode.PAYMENT_REQUIRED, 402);
333
+ }
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Local audit log of x402 auto-payments: ~/.nansen/x402/payments.jsonl.
3
+ *
4
+ * One JSON line when a signed payment is sent, and one for its outcome
5
+ * (accepted, rejected or ambiguous), sharing an id. Lines never carry the
6
+ * payment signature, request or response bodies, or the URL's query string.
7
+ *
8
+ * Writes are best-effort: a failure warns once on stderr and never blocks a
9
+ * payment. The log is for auditing; it is not a safety control. A symlinked or
10
+ * hard-linked log, or a symlinked ~/.nansen or x402 directory, is refused
11
+ * rather than followed, so records never land in (or re-permission) another
12
+ * file.
13
+ */
14
+
15
+ import crypto from 'node:crypto';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { authDirectory } from './auth-credentials.js';
19
+ import { openLocalFile } from './local-file.js';
20
+
21
+ let warned = false;
22
+
23
+ /**
24
+ * Throws when no absolute home directory is known, rather than resolving
25
+ * against the working directory (which could be a git checkout).
26
+ */
27
+ export function x402AuditLogPath() {
28
+ return path.join(authDirectory(), 'x402', 'payments.jsonl');
29
+ }
30
+
31
+ export function newPaymentId() {
32
+ return crypto.randomUUID();
33
+ }
34
+
35
+ /**
36
+ * Origin and path only. The query string can carry addresses or other
37
+ * user-supplied values, and a URL that doesn't parse is dropped entirely.
38
+ */
39
+ export function sanitizeRequestUrl(url) {
40
+ try {
41
+ const parsed = new URL(url);
42
+ return `${parsed.origin}${parsed.pathname}`;
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * chmod a descriptor to `mode` only when group or other users have access.
50
+ * A file the user can write but not chmod (owned by another user) is fine
51
+ * as long as it is already private.
52
+ */
53
+ function tightenIfOpen(fd, mode) {
54
+ if (process.platform === 'win32') return;
55
+ if (fs.fstatSync(fd).mode & 0o077) fs.fchmodSync(fd, mode);
56
+ }
57
+
58
+ /**
59
+ * Tighten the x402 directory to 0700 through a descriptor opened without
60
+ * following symlinks, and only when it is still the directory `expected`
61
+ * (checked before the log was opened), so a swapped-in link at the x402
62
+ * directory or ~/.nansen can't redirect the chmod.
63
+ */
64
+ function tightenDirectory(dir, expected) {
65
+ if (process.platform === 'win32') return;
66
+ const { O_RDONLY, O_DIRECTORY, O_NOFOLLOW } = fs.constants;
67
+ const fd = fs.openSync(dir, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
68
+ try {
69
+ const opened = fs.fstatSync(fd);
70
+ if (opened.dev !== expected.dev || opened.ino !== expected.ino) {
71
+ throw new Error(`refusing ${dir}: directory was replaced while writing`);
72
+ }
73
+ tightenIfOpen(fd, 0o700);
74
+ } finally {
75
+ fs.closeSync(fd);
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Run `fn` with a umask of 077, so the paths it creates are exactly 0700/0600
81
+ * whatever the user's umask. A umask such as 0277 would otherwise create a
82
+ * 0500 directory or 0400 file that later records can't be written to.
83
+ * The umask is process-wide, so anything another thread creates in this short
84
+ * synchronous window is only made more private, never less.
85
+ */
86
+ function withPrivateUmask(fn) {
87
+ let previous;
88
+ try {
89
+ previous = process.umask(0o077);
90
+ } catch {
91
+ // Worker threads can't change the umask; fall back to the user's.
92
+ return fn();
93
+ }
94
+ try {
95
+ return fn();
96
+ } finally {
97
+ process.umask(previous);
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Create `dir` if missing (its parent must exist) and refuse anything other
103
+ * than a real directory, so a symlink is never followed into another tree.
104
+ * Returns its lstat.
105
+ */
106
+ function ensureDirectory(dir) {
107
+ try {
108
+ fs.mkdirSync(dir, { mode: 0o700 });
109
+ } catch (err) {
110
+ if (err.code !== 'EEXIST') throw err;
111
+ }
112
+ const stat = fs.lstatSync(dir);
113
+ if (!stat.isDirectory()) {
114
+ throw new Error(`refusing ${dir}: expected a directory without symlinks`);
115
+ }
116
+ return stat;
117
+ }
118
+
119
+ /**
120
+ * Write all of `text` at the end of the log. O_APPEND puts each write at the
121
+ * current end; a short write (nearly full disk) continues with the rest.
122
+ */
123
+ function appendAll(fd, text) {
124
+ const bytes = Buffer.from(text, 'utf8');
125
+ let offset = 0;
126
+ while (offset < bytes.length) {
127
+ const written = fs.writeSync(fd, bytes, offset, bytes.length - offset);
128
+ if (!written) throw new Error('the disk accepted no more bytes');
129
+ offset += written;
130
+ }
131
+ }
132
+
133
+ /**
134
+ * True when the log is non-empty and its last byte isn't a newline, i.e. an
135
+ * earlier write was cut short. The next record then starts on a fresh line
136
+ * instead of being glued onto the broken one.
137
+ */
138
+ function endsMidLine(fd) {
139
+ const { size } = fs.fstatSync(fd);
140
+ if (size === 0) return false;
141
+ const last = Buffer.alloc(1);
142
+ fs.readSync(fd, last, 0, 1, size - 1);
143
+ return last[0] !== 0x0a;
144
+ }
145
+
146
+ /**
147
+ * Append one record. Never throws.
148
+ */
149
+ export function appendPaymentRecord(record) {
150
+ let file = null;
151
+ let fd;
152
+ try {
153
+ file = x402AuditLogPath();
154
+ const dir = path.dirname(file);
155
+ const nansenDir = path.dirname(dir);
156
+ const { O_RDWR, O_APPEND, O_CREAT } = fs.constants;
157
+ let dirStat;
158
+ fd = withPrivateUmask(() => {
159
+ ensureDirectory(nansenDir);
160
+ dirStat = ensureDirectory(dir);
161
+ // Rooted at the home directory, which may itself be a symlink (as /var
162
+ // is on macOS). Refuses a symlink or hard link at the log, a symlinked
163
+ // ~/.nansen or x402 directory, and a path swapped while opening.
164
+ return openLocalFile(file, { root: path.dirname(nansenDir), flags: O_RDWR | O_APPEND | O_CREAT, mode: 0o600 });
165
+ });
166
+ // The open mode only applies when the file is created; tighten an
167
+ // existing file too. Records are never written to a file others can read.
168
+ tightenIfOpen(fd, 0o600);
169
+ tightenDirectory(dir, dirStat);
170
+ const line = `${JSON.stringify({ timestamp: new Date().toISOString(), ...record })}\n`;
171
+ appendAll(fd, endsMidLine(fd) ? `\n${line}` : line);
172
+ } catch (err) {
173
+ if (!warned) {
174
+ warned = true;
175
+ // EACCES/EPERM usually means a run under sudo left root-owned files.
176
+ const hint = file && (err.code === 'EACCES' || err.code === 'EPERM')
177
+ ? ` If it was created by a run under sudo, take it back with: sudo chown -R "$(id -un)" ${path.dirname(file)}`
178
+ : '';
179
+ console.error(`[x402] Warning: could not write the payment audit log${file ? ` ${file}` : ''} (${err.message}). Payments are not blocked.${hint}`);
180
+ }
181
+ } finally {
182
+ if (fd !== undefined) {
183
+ try { fs.closeSync(fd); } catch { /* already reported or harmless */ }
184
+ }
185
+ }
186
+ }
187
+
188
+ /** Test hook: let the next failure warn again. */
189
+ export function resetAuditWarningForTests() {
190
+ warned = false;
191
+ }
@@ -0,0 +1,90 @@
1
+ import { CHAIN_RPCS } from './rpc-urls.js';
2
+ import { resolvePaymentAmount, resolveKnownToken } from './x402-policy.js';
3
+ import { deriveATA, getSolanaRpcUrl } from './x402-svm.js';
4
+
5
+ // RPC endpoint per supported x402 EVM network.
6
+ export const EVM_X402_RPCS = {
7
+ 'eip155:8453': CHAIN_RPCS.base,
8
+ 'eip155:196': CHAIN_RPCS.xlayer,
9
+ 'eip155:56': CHAIN_RPCS.bsc,
10
+ };
11
+
12
+ async function rpcResult(rpc, method, params) {
13
+ const response = await fetch(rpc, {
14
+ method: 'POST',
15
+ headers: { 'Content-Type': 'application/json' },
16
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
17
+ signal: AbortSignal.timeout(5000),
18
+ });
19
+ const data = await response.json();
20
+ if (response.ok === false || data.error) throw new Error('Balance unavailable');
21
+ return data.result;
22
+ }
23
+
24
+ /**
25
+ * Compare a raw balance read with the payment amount. A read that throws is
26
+ * unknown, not zero: let server verification decide.
27
+ */
28
+ async function hasSufficientBalance(requirement, readBalance) {
29
+ const token = resolveKnownToken(requirement.network, requirement.asset);
30
+ const symbol = token?.symbol || 'token';
31
+ const amount = BigInt(resolvePaymentAmount(requirement));
32
+ let balance;
33
+ try {
34
+ balance = await readBalance();
35
+ } catch {
36
+ console.error(`[x402] Unable to check ${symbol} balance on ${requirement.network}; deferring to server verification.`);
37
+ return true;
38
+ }
39
+ if (balance < amount) {
40
+ console.error(
41
+ `[x402] Skipping ${symbol} on ${requirement.network}: insufficient token balance. ` +
42
+ `Fund this token on this network or use another funded payment option.`,
43
+ );
44
+ return false;
45
+ }
46
+ return true;
47
+ }
48
+
49
+ /**
50
+ * Skip known unfunded EVM options before signing. RPC failures remain
51
+ * best-effort: let server verification decide when the balance is unknown.
52
+ */
53
+ export async function hasSufficientEvmPaymentBalance(requirement, address) {
54
+ const rpc = EVM_X402_RPCS[requirement.network];
55
+ if (!rpc) return true;
56
+ return hasSufficientBalance(requirement, async () => {
57
+ const result = await rpcResult(rpc, 'eth_call', [{
58
+ to: requirement.asset,
59
+ data: `0x70a08231${address.replace(/^0x/, '').toLowerCase().padStart(64, '0')}`,
60
+ }, 'latest']);
61
+ if (!/^0x[0-9a-f]+$/i.test(result)) throw new Error('Balance unavailable');
62
+ return BigInt(result);
63
+ });
64
+ }
65
+
66
+ /**
67
+ * Solana counterpart of hasSufficientEvmPaymentBalance. The payment transfers
68
+ * from the payer's associated token account, so only that account counts: a
69
+ * missing ATA is a zero balance, not an unknown one.
70
+ */
71
+ export async function hasSufficientSvmPaymentBalance(requirement, address) {
72
+ let rpc;
73
+ try {
74
+ rpc = getSolanaRpcUrl(requirement.network);
75
+ } catch {
76
+ return true;
77
+ }
78
+ return hasSufficientBalance(requirement, async () => {
79
+ const result = await rpcResult(rpc, 'getTokenAccountsByOwner', [
80
+ address, { mint: requirement.asset }, { encoding: 'jsonParsed' },
81
+ ]);
82
+ if (!Array.isArray(result?.value)) throw new Error('Balance unavailable');
83
+ const ata = deriveATA(address, requirement.asset);
84
+ const account = result.value.find(entry => entry?.pubkey === ata);
85
+ if (!account) return 0n;
86
+ const raw = account.account?.data?.parsed?.info?.tokenAmount?.amount;
87
+ if (typeof raw !== 'string' || !/^\d+$/.test(raw)) throw new Error('Balance unavailable');
88
+ return BigInt(raw);
89
+ });
90
+ }