nansen-cli 2.2.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/CHANGELOG.md +44 -0
- package/README.md +77 -1
- package/package.json +1 -1
- package/skills/nansen-agent-guide/SKILL.md +37 -0
- package/src/api.js +134 -24
- package/src/cli.js +70 -18
- package/src/commands/completion.js +6 -1
- package/src/commands/feedback.js +352 -0
- package/src/feedback-journal.js +86 -0
- package/src/privy.js +55 -37
- package/src/schema.json +128 -16
- package/src/telemetry.js +5 -1
- package/src/trade-validation.js +23 -13
- package/src/trading.js +57 -117
- package/src/wallet.js +9 -0
- package/src/walletconnect-x402.js +140 -46
- package/src/x402-audit.js +191 -0
- package/src/x402-payment-balance.js +90 -0
- package/src/x402-policy.js +151 -4
- package/src/x402.js +51 -22
|
@@ -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
|
+
}
|
package/src/x402-policy.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* x402 payment policy guard.
|
|
3
3
|
* Decides whether an auto-payment is safe to sign before any signature is produced.
|
|
4
4
|
* Three layers: known-asset allowlist, optional payTo allowlist, per-payment USD cap.
|
|
5
|
+
* An optional per-process cumulative cap is charged by each signer, through
|
|
6
|
+
* signWithSessionCharge, immediately before it signs.
|
|
5
7
|
*/
|
|
6
8
|
|
|
7
9
|
import { EVM_X402_TOKENS, SVM_X402_TOKENS } from './x402-tokens.js';
|
|
@@ -128,8 +130,10 @@ export function resolvePayTo(requirement) {
|
|
|
128
130
|
|
|
129
131
|
/**
|
|
130
132
|
* Decide whether an x402 payment requirement is safe to auto-sign.
|
|
131
|
-
* Returns { ok: true, usd, symbol
|
|
132
|
-
*
|
|
133
|
+
* Returns { ok: true, usd, symbol, network, asset, payTo, amountRaw } when
|
|
134
|
+
* allowed (amountRaw is the parsed base-unit amount as a decimal string, so
|
|
135
|
+
* "0x2710" and 1e4 both become "10000"), or
|
|
136
|
+
* { ok: false, reason } with a human-readable, actionable reason when refused.
|
|
133
137
|
*
|
|
134
138
|
* Enforces in order: known (network, asset) allowlist, optional payTo
|
|
135
139
|
* allowlist, per-payment USD cap. Never signs; pure decision.
|
|
@@ -179,10 +183,11 @@ export function evaluatePaymentRequirement(requirement) {
|
|
|
179
183
|
}
|
|
180
184
|
|
|
181
185
|
let usd;
|
|
186
|
+
let base;
|
|
182
187
|
try {
|
|
183
188
|
// BigInt base units → USD. Keep integer/fraction split to avoid float loss
|
|
184
189
|
// on large values; final Number() is safe for display-scale amounts.
|
|
185
|
-
|
|
190
|
+
base = BigInt(amountRaw);
|
|
186
191
|
// A transfer authorization must be for a positive amount; a negative value
|
|
187
192
|
// is never legitimate and should never be signed.
|
|
188
193
|
if (base < 0n) {
|
|
@@ -212,5 +217,147 @@ export function evaluatePaymentRequirement(requirement) {
|
|
|
212
217
|
};
|
|
213
218
|
}
|
|
214
219
|
|
|
215
|
-
return {
|
|
220
|
+
return {
|
|
221
|
+
ok: true,
|
|
222
|
+
usd,
|
|
223
|
+
// A decimal string, not a BigInt, so the decision stays JSON-serializable.
|
|
224
|
+
amountMicroUsd: toMicroUsd(base, known.decimals).toString(),
|
|
225
|
+
symbol: known.symbol,
|
|
226
|
+
network,
|
|
227
|
+
asset,
|
|
228
|
+
payTo,
|
|
229
|
+
amountRaw: base.toString(),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Cumulative USD auto-paid by this process, in integer micro-USD so repeated
|
|
234
|
+
// charges can't drift past an exact cap the way float sums do (0.1 + 0.2).
|
|
235
|
+
// It resets with every process: the cap bounds one invocation (its retries,
|
|
236
|
+
// fallbacks and concurrent requests), not spending across separate runs.
|
|
237
|
+
let sessionSpentMicroUsd = 0n;
|
|
238
|
+
// The cap as first read, so it can't change partway through a run.
|
|
239
|
+
let sessionCap;
|
|
240
|
+
|
|
241
|
+
const MICRO_USD_PER_USD = 1_000_000n;
|
|
242
|
+
const USD_AMOUNT = /^\d+(\.\d+)?$/;
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Token base units → micro-USD, rounded up so a fraction of a micro-dollar is
|
|
246
|
+
* never charged as zero.
|
|
247
|
+
*/
|
|
248
|
+
function toMicroUsd(base, decimals) {
|
|
249
|
+
const scale = 10n ** BigInt(decimals);
|
|
250
|
+
return (base * MICRO_USD_PER_USD + scale - 1n) / scale;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** "$0.01", or up to six decimals ("$0.0015") when a sub-cent amount needs them. */
|
|
254
|
+
function formatMicroUsd(micro) {
|
|
255
|
+
const fraction = (micro % MICRO_USD_PER_USD).toString().padStart(6, '0').replace(/0{1,4}$/, '');
|
|
256
|
+
return `$${micro / MICRO_USD_PER_USD}.${fraction}`;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Parse NANSEN_X402_SESSION_MAX_AMOUNT as a cap in micro-USD.
|
|
261
|
+
* Returns null when the cap is disabled (unset, empty or "unlimited"), or
|
|
262
|
+
* { error } for a value that isn't a plain non-negative decimal: a safety cap
|
|
263
|
+
* the user asked for must not silently turn off because of a typo.
|
|
264
|
+
*/
|
|
265
|
+
export function resolveSessionMaxMicroUsd() {
|
|
266
|
+
const env = process.env.NANSEN_X402_SESSION_MAX_AMOUNT;
|
|
267
|
+
if (env === undefined || env.trim() === '') return null;
|
|
268
|
+
const value = env.trim();
|
|
269
|
+
if (value.toLowerCase() === 'unlimited') return null;
|
|
270
|
+
// Plain decimals only: Number() would read "0x10" as $16 and "1e3" as $1000.
|
|
271
|
+
if (!USD_AMOUNT.test(value)) {
|
|
272
|
+
return {
|
|
273
|
+
error:
|
|
274
|
+
`Refusing to auto-pay: NANSEN_X402_SESSION_MAX_AMOUNT="${env}" is not a valid USD amount. ` +
|
|
275
|
+
'Set it to a number such as 5.00, or unset it to disable the session cap. No signature was produced.',
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
const [whole, fraction = ''] = value.split('.');
|
|
279
|
+
// Digits past the sixth decimal are dropped, which can only lower the cap.
|
|
280
|
+
return BigInt(whole) * MICRO_USD_PER_USD + BigInt(fraction.slice(0, 6).padEnd(6, '0'));
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function sessionMaxMicroUsd() {
|
|
284
|
+
if (sessionCap === undefined) sessionCap = resolveSessionMaxMicroUsd();
|
|
285
|
+
return sessionCap;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* The refusal reason when NANSEN_X402_SESSION_MAX_AMOUNT is invalid, else
|
|
290
|
+
* null. Check it once before any payment work, so the error is reported once
|
|
291
|
+
* and before any balance or blockhash request.
|
|
292
|
+
*/
|
|
293
|
+
export function sessionCapConfigError() {
|
|
294
|
+
const cap = sessionMaxMicroUsd();
|
|
295
|
+
return cap !== null && typeof cap === 'object' ? cap.error : null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Charge an approved payment against the per-process cumulative cap.
|
|
300
|
+
* Prefer signWithSessionCharge, which also runs the signer and releases the
|
|
301
|
+
* charge when signing fails.
|
|
302
|
+
*
|
|
303
|
+
* `decision` is the { ok: true } result of evaluatePaymentRequirement.
|
|
304
|
+
* Returns { ok: true, release } and adds the amount to the session total, or
|
|
305
|
+
* { ok: false, reason } and leaves the total unchanged.
|
|
306
|
+
*/
|
|
307
|
+
export function chargeSessionSpend(decision) {
|
|
308
|
+
const cap = sessionMaxMicroUsd();
|
|
309
|
+
if (cap === null) return { ok: true, release: () => {} };
|
|
310
|
+
if (typeof cap === 'object') return { ok: false, reason: cap.error };
|
|
311
|
+
|
|
312
|
+
if (typeof decision.amountMicroUsd !== 'string' || !/^\d+$/.test(decision.amountMicroUsd)) {
|
|
313
|
+
return { ok: false, reason: 'Refusing to auto-pay: payment amount is unknown, so the session cap cannot be applied. No signature was produced.' };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const micro = BigInt(decision.amountMicroUsd);
|
|
317
|
+
const total = sessionSpentMicroUsd + micro;
|
|
318
|
+
if (total > cap) {
|
|
319
|
+
return {
|
|
320
|
+
ok: false,
|
|
321
|
+
reason:
|
|
322
|
+
`Refusing to auto-pay ${formatMicroUsd(micro)} ${decision.symbol}: this process has already auto-paid ` +
|
|
323
|
+
`${formatMicroUsd(sessionSpentMicroUsd)}, and the payment would exceed the ${formatMicroUsd(cap)} ` +
|
|
324
|
+
'session cap. To authorize, raise it with NANSEN_X402_SESSION_MAX_AMOUNT=<usd> (or unset it to disable). ' +
|
|
325
|
+
'No signature was produced.',
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
sessionSpentMicroUsd = total;
|
|
329
|
+
let released = false;
|
|
330
|
+
const release = () => {
|
|
331
|
+
if (released) return;
|
|
332
|
+
released = true;
|
|
333
|
+
sessionSpentMicroUsd -= micro;
|
|
334
|
+
};
|
|
335
|
+
return { ok: true, release };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Charge the session cap for an approved payment, then run `sign`. The signer
|
|
340
|
+
* starts in the same tick as the charge, so concurrent requests in one process
|
|
341
|
+
* can't both pass the check. Call it after every async check that could still
|
|
342
|
+
* skip the option.
|
|
343
|
+
*
|
|
344
|
+
* Returns { ok: false, reason } when the cap refuses, without calling `sign`,
|
|
345
|
+
* or { ok: true, value, release }. The charge is released if `sign` throws.
|
|
346
|
+
* The caller calls release() if the server cleanly rejects the payment; any
|
|
347
|
+
* other outcome keeps the charge, so the cap can only over-count.
|
|
348
|
+
*/
|
|
349
|
+
export async function signWithSessionCharge(decision, sign) {
|
|
350
|
+
const charge = chargeSessionSpend(decision);
|
|
351
|
+
if (!charge.ok) return charge;
|
|
352
|
+
try {
|
|
353
|
+
return { ok: true, value: await sign(), release: charge.release };
|
|
354
|
+
} catch (err) {
|
|
355
|
+
charge.release();
|
|
356
|
+
throw err;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export function resetSessionSpendForTests() {
|
|
361
|
+
sessionSpentMicroUsd = 0n;
|
|
362
|
+
sessionCap = undefined;
|
|
216
363
|
}
|
package/src/x402.js
CHANGED
|
@@ -12,8 +12,9 @@ import {
|
|
|
12
12
|
getSolanaRpcUrl,
|
|
13
13
|
} from './x402-svm.js';
|
|
14
14
|
import { resolvePassword } from './keychain.js';
|
|
15
|
-
import {
|
|
16
|
-
|
|
15
|
+
import { EVM_X402_RPCS, hasSufficientEvmPaymentBalance, hasSufficientSvmPaymentBalance } from './x402-payment-balance.js';
|
|
16
|
+
export { EVM_X402_RPCS } from './x402-payment-balance.js';
|
|
17
|
+
import { evaluatePaymentRequirement, resolvePaymentAmount, signWithSessionCharge } from './x402-policy.js';
|
|
17
18
|
import { EVM_X402_TOKENS } from './x402-tokens.js';
|
|
18
19
|
export { EVM_X402_TOKENS } from './x402-tokens.js';
|
|
19
20
|
|
|
@@ -59,7 +60,7 @@ export function parsePaymentRequirements(response) {
|
|
|
59
60
|
* Ties keep the previous behaviour — EVM before Solana, then the server's own
|
|
60
61
|
* order — so a response whose options cost the same is unaffected.
|
|
61
62
|
*/
|
|
62
|
-
function rankRequirements(requirements) {
|
|
63
|
+
export function rankRequirements(requirements) {
|
|
63
64
|
return requirements
|
|
64
65
|
.filter(r => isEvmNetwork(r.network) || isSvmNetwork(r.network))
|
|
65
66
|
.map((requirement, index) => {
|
|
@@ -111,15 +112,40 @@ async function hasPermit2Allowance(network, token, owner, amount) {
|
|
|
111
112
|
|
|
112
113
|
/**
|
|
113
114
|
* Build a payment signature for a single requirement.
|
|
114
|
-
* @returns {string
|
|
115
|
+
* @returns {Promise<{ signature: string, payment: object, releaseCharge: Function }|null>}
|
|
116
|
+
* Base64 payment signature, the policy decision that approved it and the
|
|
117
|
+
* release for its session-cap charge, or null on failure
|
|
115
118
|
*/
|
|
116
|
-
async function buildPaymentForRequirement(requirement, exported, url) {
|
|
119
|
+
async function buildPaymentForRequirement(requirement, exported, url, onCapRefusal) {
|
|
117
120
|
const decision = evaluatePaymentRequirement(requirement);
|
|
118
121
|
if (!decision.ok) {
|
|
119
122
|
console.error(`[x402] ${decision.reason}`);
|
|
120
123
|
return null;
|
|
121
124
|
}
|
|
125
|
+
const signed = await signApprovedRequirement(requirement, exported, url, decision, onCapRefusal);
|
|
126
|
+
return signed ? { signature: signed.value, payment: decision, releaseCharge: signed.release } : null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Charge the session cap and run the local signer. Called right before
|
|
131
|
+
* signing, after every async check that could still skip the option.
|
|
132
|
+
*/
|
|
133
|
+
async function chargeAndSign(decision, onCapRefusal, sign) {
|
|
134
|
+
const signed = await signWithSessionCharge(decision, sign);
|
|
135
|
+
if (!signed.ok) {
|
|
136
|
+
console.error(`[x402] ${signed.reason}`);
|
|
137
|
+
onCapRefusal?.(signed.reason);
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
return signed;
|
|
141
|
+
}
|
|
122
142
|
|
|
143
|
+
/**
|
|
144
|
+
* Sign a requirement the policy guard already approved.
|
|
145
|
+
* @returns {Promise<{ value: string, release: Function }|null>} Base64 payment
|
|
146
|
+
* signature and its session-cap release, or null when skipped
|
|
147
|
+
*/
|
|
148
|
+
async function signApprovedRequirement(requirement, exported, url, decision, onCapRefusal) {
|
|
123
149
|
// exportWallet returns a null key for a chain the wallet file doesn't hold.
|
|
124
150
|
// Skip that option with a clear reason instead of failing on the missing key.
|
|
125
151
|
const rail = isEvmNetwork(requirement.network) ? 'evm' : 'solana';
|
|
@@ -133,6 +159,7 @@ async function buildPaymentForRequirement(requirement, exported, url) {
|
|
|
133
159
|
}
|
|
134
160
|
|
|
135
161
|
if (isEvmNetwork(requirement.network)) {
|
|
162
|
+
if (!await hasSufficientEvmPaymentBalance(requirement, exported.evm.address)) return null;
|
|
136
163
|
if ((requirement.extra || {}).assetTransferMethod === 'permit2-exact') {
|
|
137
164
|
const resolvedAmount = resolvePaymentAmount(requirement);
|
|
138
165
|
const approved = await hasPermit2Allowance(
|
|
@@ -151,24 +178,25 @@ async function buildPaymentForRequirement(requirement, exported, url) {
|
|
|
151
178
|
return null;
|
|
152
179
|
}
|
|
153
180
|
}
|
|
154
|
-
return createEvmPaymentPayload(
|
|
181
|
+
return chargeAndSign(decision, onCapRefusal, () => createEvmPaymentPayload(
|
|
155
182
|
requirement,
|
|
156
183
|
exported.evm.privateKey,
|
|
157
184
|
exported.evm.address,
|
|
158
185
|
url,
|
|
159
|
-
);
|
|
186
|
+
));
|
|
160
187
|
}
|
|
161
188
|
|
|
162
189
|
if (isSvmNetwork(requirement.network)) {
|
|
190
|
+
if (!await hasSufficientSvmPaymentBalance(requirement, exported.solana.address)) return null;
|
|
163
191
|
const rpcUrl = getSolanaRpcUrl(requirement.network);
|
|
164
192
|
const blockhash = await fetchRecentBlockhash(rpcUrl);
|
|
165
|
-
return createSvmPaymentPayload(
|
|
193
|
+
return chargeAndSign(decision, onCapRefusal, () => createSvmPaymentPayload(
|
|
166
194
|
requirement,
|
|
167
195
|
exported.solana.privateKey,
|
|
168
196
|
exported.solana.address,
|
|
169
197
|
url,
|
|
170
198
|
blockhash,
|
|
171
|
-
);
|
|
199
|
+
));
|
|
172
200
|
}
|
|
173
201
|
|
|
174
202
|
return null;
|
|
@@ -176,12 +204,16 @@ async function buildPaymentForRequirement(requirement, exported, url) {
|
|
|
176
204
|
|
|
177
205
|
/**
|
|
178
206
|
* Generate payment signatures for all viable payment options, in priority order.
|
|
179
|
-
* Yields { signature, network
|
|
207
|
+
* Yields { signature, network, asset, payment, releaseCharge } objects, where
|
|
208
|
+
* payment is the policy decision that approved the option and releaseCharge
|
|
209
|
+
* returns its session-cap charge (call it when the server cleanly rejects the
|
|
210
|
+
* payment). Caller should try each until one succeeds.
|
|
180
211
|
*
|
|
181
212
|
* @param {Response} response - The 402 HTTP response
|
|
182
213
|
* @param {string} url - The original request URL
|
|
183
|
-
* @param {object} options - { password, walletName }
|
|
184
|
-
*
|
|
214
|
+
* @param {object} options - { password, walletName, onCapRefusal }, where
|
|
215
|
+
* onCapRefusal(reason) is called when the session cap refuses an option
|
|
216
|
+
* @returns {AsyncGenerator<{ signature: string, network: string, asset: string, payment: object, releaseCharge: Function }>}
|
|
185
217
|
*/
|
|
186
218
|
export async function* createPaymentSignatures(response, url, options = {}) {
|
|
187
219
|
const requirements = parsePaymentRequirements(response);
|
|
@@ -221,8 +253,10 @@ export async function* createPaymentSignatures(response, url, options = {}) {
|
|
|
221
253
|
|
|
222
254
|
for (const req of ranked) {
|
|
223
255
|
try {
|
|
224
|
-
const
|
|
225
|
-
if (
|
|
256
|
+
const built = await buildPaymentForRequirement(req, exported, url, options.onCapRefusal);
|
|
257
|
+
if (built) {
|
|
258
|
+
yield { signature: built.signature, network: req.network, asset: req.asset, payment: built.payment, releaseCharge: built.releaseCharge };
|
|
259
|
+
}
|
|
226
260
|
} catch (err) {
|
|
227
261
|
// This payment option failed to build; say why and try the next one
|
|
228
262
|
// (otherwise a malformed server option only surfaces as a generic
|
|
@@ -235,7 +269,9 @@ export async function* createPaymentSignatures(response, url, options = {}) {
|
|
|
235
269
|
|
|
236
270
|
/**
|
|
237
271
|
* Attempt to auto-pay a 402 response (single-shot, returns first viable signature).
|
|
238
|
-
* For fallback support, use createPaymentSignatures() instead.
|
|
272
|
+
* For fallback support, use createPaymentSignatures() instead. The signature's
|
|
273
|
+
* session-cap charge is never released, so a payment the server rejects still
|
|
274
|
+
* counts against the cap.
|
|
239
275
|
*
|
|
240
276
|
* @param {Response} response - The 402 HTTP response
|
|
241
277
|
* @param {string} url - The original request URL
|
|
@@ -249,13 +285,6 @@ export async function createPaymentSignature(response, url, options = {}) {
|
|
|
249
285
|
return null;
|
|
250
286
|
}
|
|
251
287
|
|
|
252
|
-
// RPC endpoint per supported x402 EVM network.
|
|
253
|
-
export const EVM_X402_RPCS = {
|
|
254
|
-
'eip155:8453': CHAIN_RPCS.base,
|
|
255
|
-
'eip155:196': CHAIN_RPCS.xlayer,
|
|
256
|
-
'eip155:56': CHAIN_RPCS.bsc,
|
|
257
|
-
};
|
|
258
|
-
|
|
259
288
|
function getEvmRpcUrl(network) {
|
|
260
289
|
return EVM_X402_RPCS[network] || null;
|
|
261
290
|
}
|