nansen-cli 1.43.1 → 1.44.1
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 +94 -0
- package/README.md +34 -0
- package/package.json +1 -1
- package/src/api.js +206 -28
- package/src/bridge.js +103 -5
- package/src/cli.js +81 -56
- package/src/commands/alerts.js +56 -16
- package/src/commands/completion.js +652 -0
- package/src/commands/mcp.js +19 -3
- package/src/commands/research.js +199 -25
- package/src/hl-client.js +20 -8
- package/src/limit-order.js +223 -34
- package/src/mcp-verify.js +66 -1
- package/src/perp.js +72 -24
- package/src/query-options.js +32 -0
- package/src/schema.json +642 -133
- package/src/semver.js +26 -0
- package/src/telemetry.js +133 -24
- package/src/trade-validation.js +222 -5
- package/src/trading.js +198 -23
- package/src/update-check.js +13 -6
- package/src/walletconnect-x402.js +25 -4
- package/src/x402-evm.js +8 -4
- package/src/x402-policy.js +16 -1
- package/src/x402-svm.js +9 -7
- package/src/x402-tokens.js +7 -2
- package/src/x402.js +8 -1
package/src/trading.js
CHANGED
|
@@ -87,22 +87,41 @@ export function resolveTokenAddress(symbolOrAddress, chainName) {
|
|
|
87
87
|
* @returns {Promise<*>} Parsed result value
|
|
88
88
|
* @throws {Error} If chain has no configured RPC or the RPC returns an error
|
|
89
89
|
*/
|
|
90
|
+
// Error codes let a broadcasting caller (bridge.js) tell a DEFINITIVE rejection
|
|
91
|
+
// (the node refused the tx — nothing is in flight, safe to retry) apart from an
|
|
92
|
+
// AMBIGUOUS failure (a gateway/transport error that may have dropped the ack
|
|
93
|
+
// AFTER the node accepted the tx), so it can fail closed only on the latter:
|
|
94
|
+
// - RPC_UNCONFIGURED — no URL; thrown before any request leaves the process
|
|
95
|
+
// - RPC_NETWORK_ERROR — request left but no response (reset/timeout): ambiguous
|
|
96
|
+
// - RPC_HTTP_ERROR — non-JSON HTTP response (e.g. a 502 gateway page): ambiguous
|
|
97
|
+
// - RPC_JSON_ERROR — a JSON-RPC { error }: the node definitively rejected it
|
|
90
98
|
export async function evmRpcCall(chain, method, params = []) {
|
|
91
99
|
const rpcUrl = CHAIN_RPCS[chain];
|
|
92
|
-
if (!rpcUrl) throw new Error(`No RPC URL configured for chain: ${chain}`);
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
100
|
+
if (!rpcUrl) throw Object.assign(new Error(`No RPC URL configured for chain: ${chain}`), { code: 'RPC_UNCONFIGURED' });
|
|
101
|
+
let res;
|
|
102
|
+
try {
|
|
103
|
+
res = await fetch(rpcUrl, {
|
|
104
|
+
method: 'POST',
|
|
105
|
+
headers: { 'Content-Type': 'application/json' },
|
|
106
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
|
|
107
|
+
});
|
|
108
|
+
} catch (netErr) {
|
|
109
|
+
// The request left this process but no response came back. A reset or
|
|
110
|
+
// timeout can strike AFTER the node accepted the payload, so a caller that
|
|
111
|
+
// just broadcast a tx cannot assume it was never sent.
|
|
112
|
+
throw Object.assign(new Error(`RPC request to ${chain} failed for ${method}: ${netErr.message}`), { code: 'RPC_NETWORK_ERROR' });
|
|
113
|
+
}
|
|
98
114
|
const text = await res.text();
|
|
99
115
|
let body;
|
|
100
116
|
try {
|
|
101
117
|
body = JSON.parse(text);
|
|
102
118
|
} catch {
|
|
103
|
-
throw
|
|
119
|
+
throw Object.assign(
|
|
120
|
+
new Error(`RPC endpoint returned non-JSON response (HTTP ${res.status}) for ${method}: ${text.slice(0, 100)}`),
|
|
121
|
+
{ code: 'RPC_HTTP_ERROR', status: res.status },
|
|
122
|
+
);
|
|
104
123
|
}
|
|
105
|
-
if (body.error) throw new Error(`RPC error (${method}): ${body.error.message}`);
|
|
124
|
+
if (body.error) throw Object.assign(new Error(`RPC error (${method}): ${body.error.message}`), { code: 'RPC_JSON_ERROR' });
|
|
106
125
|
return body.result;
|
|
107
126
|
}
|
|
108
127
|
|
|
@@ -186,19 +205,72 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
|
|
|
186
205
|
await new Promise(r => setTimeout(r, retryDelayMs));
|
|
187
206
|
}
|
|
188
207
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
208
|
+
let res;
|
|
209
|
+
try {
|
|
210
|
+
res = await fetch(`${TRADING_API_URL}/execute`, {
|
|
211
|
+
method: 'POST',
|
|
212
|
+
headers,
|
|
213
|
+
body: JSON.stringify(params),
|
|
214
|
+
});
|
|
215
|
+
} catch (netErr) {
|
|
216
|
+
// The POST left this process but no response came back (a reset/timeout).
|
|
217
|
+
// That may have struck AFTER the backend received the signed tx and
|
|
218
|
+
// broadcast it — indistinguishable from "never sent" — so treat it as
|
|
219
|
+
// BROADCAST_FAILED, the same fail-closed class as a 502. Retrying re-sends
|
|
220
|
+
// the SAME signed bytes (a byte-identical replay a node dedupes), so a
|
|
221
|
+
// retry here can't itself double-broadcast; only exhausting them fails
|
|
222
|
+
// closed at the caller (isFatalBroadcastError → mark the quote spent).
|
|
223
|
+
lastError = Object.assign(
|
|
224
|
+
new Error(`Execute POST to /execute failed: ${netErr.message}`),
|
|
225
|
+
{ code: 'BROADCAST_FAILED' }
|
|
226
|
+
);
|
|
227
|
+
if (attempt < retries) continue;
|
|
228
|
+
throw lastError;
|
|
229
|
+
}
|
|
194
230
|
|
|
195
|
-
|
|
231
|
+
let text;
|
|
232
|
+
try {
|
|
233
|
+
text = await res.text();
|
|
234
|
+
} catch (bodyErr) {
|
|
235
|
+
// Headers arrived but the body read failed (a truncated/reset response).
|
|
236
|
+
// Like the network case above, the backend may already have broadcast, so
|
|
237
|
+
// fail closed as BROADCAST_FAILED rather than surface a codeless error the
|
|
238
|
+
// candidate loop would treat as nonfatal. A retry re-sends byte-identical
|
|
239
|
+
// bytes a node dedupes.
|
|
240
|
+
lastError = Object.assign(
|
|
241
|
+
new Error(`Execute response body read failed (status ${res.status}): ${bodyErr.message}`),
|
|
242
|
+
{ code: 'BROADCAST_FAILED', status: res.status }
|
|
243
|
+
);
|
|
244
|
+
if (res.status >= 500 && attempt < retries) continue;
|
|
245
|
+
throw lastError;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Parse up front so a JSON body can be preserved as structured details — but
|
|
249
|
+
// the classification below never lets a parseable body downgrade an
|
|
250
|
+
// ambiguous status to its own (nonfatal) code.
|
|
196
251
|
let body;
|
|
252
|
+
let parsed = true;
|
|
197
253
|
try {
|
|
198
254
|
body = JSON.parse(text);
|
|
199
255
|
} catch {
|
|
256
|
+
parsed = false;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ANY 5xx is ambiguous no matter the body SHAPE: the gateway may have
|
|
260
|
+
// forwarded the signed tx upstream before failing (a JSON 502/504 like
|
|
261
|
+
// { code: "UPSTREAM_TIMEOUT" } is exactly that case, and a 500/504 carries
|
|
262
|
+
// the same "forwarded then lost the ack" risk as a 502/503). Classify EVERY
|
|
263
|
+
// 5xx as BROADCAST_FAILED and keep the body only as details — never fall
|
|
264
|
+
// through to the !res.ok branch below, which would surface a nonfatal
|
|
265
|
+
// upstream code and let the candidate loop broadcast the next quote on top
|
|
266
|
+
// of a live tx.
|
|
267
|
+
if (res.status >= 500) {
|
|
268
|
+
// Only append the simulation fee hint for a NON-JSON body. A structured
|
|
269
|
+
// JSON error (e.g. { code: "UPSTREAM_TIMEOUT" }) already explains itself
|
|
270
|
+
// via `details`; tacking "you may be out of SOL" onto a gateway timeout
|
|
271
|
+
// would misdirect the user.
|
|
200
272
|
const chainType = params.chain && CHAIN_MAP[params.chain]?.type;
|
|
201
|
-
const feeHint =
|
|
273
|
+
const feeHint = !parsed
|
|
202
274
|
? chainType === 'solana'
|
|
203
275
|
? ' This often means the transaction failed simulation — check that you have enough SOL for fees (~0.005 SOL minimum).'
|
|
204
276
|
: chainType === 'evm'
|
|
@@ -206,11 +278,22 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
|
|
|
206
278
|
: ''
|
|
207
279
|
: '';
|
|
208
280
|
lastError = Object.assign(
|
|
209
|
-
new Error(`Execute API returned
|
|
210
|
-
{ code: 'BROADCAST_FAILED', status: res.status, details: text.slice(0, 200) }
|
|
281
|
+
new Error(`Execute API returned ${res.status} — treating as an ambiguous broadcast failure; the transaction may already be live.${feeHint}`),
|
|
282
|
+
{ code: 'BROADCAST_FAILED', status: res.status, details: parsed ? body : text.slice(0, 200) }
|
|
283
|
+
);
|
|
284
|
+
// Retry (re-POSTs byte-identical bytes) then fail closed at the caller.
|
|
285
|
+
if (attempt < retries) continue;
|
|
286
|
+
throw lastError;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (!parsed) {
|
|
290
|
+
// Non-JSON on a sub-500 status (a Cloudflare challenge or HTML error
|
|
291
|
+
// page). A clean sub-500 HTTP response is a definitive edge/backend
|
|
292
|
+
// rejection, so it stays nonfatal and leaves the quote reusable.
|
|
293
|
+
lastError = Object.assign(
|
|
294
|
+
new Error(`Execute API returned non-JSON response (status ${res.status}). This may be a Cloudflare challenge or server error.`),
|
|
295
|
+
{ code: 'EXECUTE_ERROR', status: res.status, details: text.slice(0, 200) }
|
|
211
296
|
);
|
|
212
|
-
// Retry on 502/503 (likely transient Cloudflare issues)
|
|
213
|
-
if ((res.status === 502 || res.status === 503) && attempt < retries) continue;
|
|
214
297
|
throw lastError;
|
|
215
298
|
}
|
|
216
299
|
|
|
@@ -434,9 +517,43 @@ export function loadQuote(quoteId) {
|
|
|
434
517
|
if (data.type && data.type !== 'swap') {
|
|
435
518
|
throw new Error(`Quote "${quoteId}" is a ${data.type} quote. Use the matching command (e.g. "nansen bridge execute" for a bridge quote).`);
|
|
436
519
|
}
|
|
520
|
+
if (data.executedAt) {
|
|
521
|
+
// Quotes are single-use: re-signing and re-broadcasting would submit a
|
|
522
|
+
// second, independently valid swap — a fresh EVM nonce or Solana blockhash,
|
|
523
|
+
// not a byte-identical replay a node would reject. Refuse a quote that has
|
|
524
|
+
// already been broadcast, the way loadBridgeQuote does.
|
|
525
|
+
const when = new Date(data.executedAt).toISOString();
|
|
526
|
+
const hashes = (data.broadcasts || []).map(b => b.txHash).filter(Boolean);
|
|
527
|
+
const detail = hashes.length ? ` (${hashes.join(', ')})` : '';
|
|
528
|
+
throw new Error(
|
|
529
|
+
`Quote "${quoteId}" was already executed at ${when}${detail}. The transaction may still be pending — check the explorer before retrying. Request a new quote with "nansen trade quote" to trade again.`,
|
|
530
|
+
);
|
|
531
|
+
}
|
|
437
532
|
return data;
|
|
438
533
|
}
|
|
439
534
|
|
|
535
|
+
// Records that a broadcast has happened. `executedAt` is set on the first call
|
|
536
|
+
// and never moved, so the quote is consumed the instant the swap goes out — a
|
|
537
|
+
// later receipt-wait timeout or a REVERTED/failed outcome must not leave the
|
|
538
|
+
// quote reusable, since retrying would sign and broadcast a second,
|
|
539
|
+
// independently valid swap. Mirrors markBridgeQuoteExecuted (bridge.js).
|
|
540
|
+
export function markQuoteExecuted(quoteId, progress = {}) {
|
|
541
|
+
const filePath = safeQuotesPath(`${quoteId}.json`);
|
|
542
|
+
if (!filePath || !fs.existsSync(filePath)) return;
|
|
543
|
+
try {
|
|
544
|
+
const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
545
|
+
data.executedAt = data.executedAt || Date.now();
|
|
546
|
+
if (progress.broadcast) {
|
|
547
|
+
data.broadcasts = [...(data.broadcasts || []), { ...progress.broadcast, at: Date.now() }];
|
|
548
|
+
}
|
|
549
|
+
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
550
|
+
} catch {
|
|
551
|
+
// Best-effort: if the marker can't be written, the next execute attempt
|
|
552
|
+
// will still proceed, but that's preferable to crashing after a successful
|
|
553
|
+
// broadcast.
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
440
557
|
/**
|
|
441
558
|
* Remove stale files from the quotes dir. Quote files use a 1-hour TTL because
|
|
442
559
|
* the price is stale; tx records use a 30-day TTL because a finalized tx hash
|
|
@@ -811,6 +928,12 @@ export async function waitForReceipt(chain, txHash, timeoutMs = 180000, pollMs =
|
|
|
811
928
|
* - RECEIPT_TIMEOUT — receipt never landed; the tx may still be pending, so
|
|
812
929
|
* retrying would race a second tx against the same nonce
|
|
813
930
|
* (a confirmed on-chain revert is NOT this — it may retry)
|
|
931
|
+
* - BROADCAST_FAILED — /execute returned an uninterpretable response (non-JSON,
|
|
932
|
+
* typically a 502/503 after all retries) AFTER we POSTed
|
|
933
|
+
* the signed tx. A dropped ack is indistinguishable from
|
|
934
|
+
* "never sent", so the backend may already have broadcast
|
|
935
|
+
* it; failing closed here trades a needless re-quote for
|
|
936
|
+
* never trying the next candidate on top of a live tx.
|
|
814
937
|
*
|
|
815
938
|
* @param {Error} err
|
|
816
939
|
* @returns {boolean}
|
|
@@ -818,7 +941,8 @@ export async function waitForReceipt(chain, txHash, timeoutMs = 180000, pollMs =
|
|
|
818
941
|
function isFatalBroadcastError(err) {
|
|
819
942
|
return err?.code === 'TXHASH_MISMATCH'
|
|
820
943
|
|| err?.code === 'INVALID_SIGNED_TX'
|
|
821
|
-
|| err?.code === 'RECEIPT_TIMEOUT'
|
|
944
|
+
|| err?.code === 'RECEIPT_TIMEOUT'
|
|
945
|
+
|| err?.code === 'BROADCAST_FAILED';
|
|
822
946
|
}
|
|
823
947
|
|
|
824
948
|
/**
|
|
@@ -3172,6 +3296,12 @@ EXAMPLES:
|
|
|
3172
3296
|
}
|
|
3173
3297
|
|
|
3174
3298
|
if (wcResult.txHash) {
|
|
3299
|
+
// The wallet already broadcast — the quote is spent right here,
|
|
3300
|
+
// before the receipt wait below can throw RECEIPT_TIMEOUT and
|
|
3301
|
+
// abort this function without ever reaching the shared
|
|
3302
|
+
// executeTransaction() marker further down.
|
|
3303
|
+
markQuoteExecuted(quoteId, { broadcast: { txHash: wcResult.txHash } });
|
|
3304
|
+
|
|
3175
3305
|
// Wallet broadcast — verify on-chain
|
|
3176
3306
|
log(' Verifying on-chain status...');
|
|
3177
3307
|
try {
|
|
@@ -3521,12 +3651,36 @@ EXAMPLES:
|
|
|
3521
3651
|
execParams.requestId = requestId; // Solana Jupiter Ultra
|
|
3522
3652
|
}
|
|
3523
3653
|
|
|
3524
|
-
|
|
3654
|
+
// A retry re-POSTs the signed payload. For a normal swap that's a
|
|
3655
|
+
// byte-identical replay the node dedupes, so retrying an ambiguous
|
|
3656
|
+
// 5xx/network failure can't itself double-broadcast. But a --gasless
|
|
3657
|
+
// Relay swap sends a signed AUTHORIZATION, and Relay's solver
|
|
3658
|
+
// broadcasts its OWN wrapping tx from it (the returned txHash is not
|
|
3659
|
+
// our bytes) — so a re-POST after the solver already picked it up
|
|
3660
|
+
// can't be deduped at the node level and risks a second solve. For
|
|
3661
|
+
// gasless we therefore don't retry: a single POST either succeeds or
|
|
3662
|
+
// fails closed (BROADCAST_FAILED marks the quote spent and aborts).
|
|
3663
|
+
const result = await executeTransaction(execParams, { retries: gasless ? 0 : undefined });
|
|
3525
3664
|
|
|
3526
3665
|
if (result.status === 'Success') {
|
|
3527
3666
|
let txId = result.signature || result.txHash;
|
|
3528
3667
|
let explorerUrl = chainConfig.explorer + txId;
|
|
3529
3668
|
|
|
3669
|
+
// The transaction is on-chain (or in flight) the instant the
|
|
3670
|
+
// Trading API accepts it — the quote is spent here, before the
|
|
3671
|
+
// on-chain verification below can throw RECEIPT_TIMEOUT (or
|
|
3672
|
+
// anything else) and abort this function. Covers local EVM,
|
|
3673
|
+
// Privy EVM, Privy Solana, local/WalletConnect Solana, the
|
|
3674
|
+
// WalletConnect sign-only fallback, and --gasless Relay — every
|
|
3675
|
+
// path that reaches this shared broadcast call.
|
|
3676
|
+
//
|
|
3677
|
+
// Deliberate: a broadcast that later reverts on-chain (the
|
|
3678
|
+
// "Trying next quote" path below) still consumes the quote —
|
|
3679
|
+
// the revert still burned the nonce, so re-signing this same
|
|
3680
|
+
// quote for a retry would race the reverted tx's nonce. This is
|
|
3681
|
+
// intentional, not an oversight.
|
|
3682
|
+
markQuoteExecuted(quoteId, { broadcast: { txHash: txId } });
|
|
3683
|
+
|
|
3530
3684
|
// For EVM: verify the tx actually succeeded on-chain
|
|
3531
3685
|
if (chainType === 'evm') {
|
|
3532
3686
|
log(' Verifying on-chain status...');
|
|
@@ -3629,15 +3783,36 @@ EXAMPLES:
|
|
|
3629
3783
|
} else {
|
|
3630
3784
|
log(`\n ✗ Quote ${quoteName} failed: ${result.status}`);
|
|
3631
3785
|
if (result.error) log(` Error: ${result.error}`);
|
|
3786
|
+
// A non-Success result can still carry a hash — the same
|
|
3787
|
+
// /execute response shape (status: 'Failed' + txHash) is
|
|
3788
|
+
// observed for approval broadcasts in trading.test.js, so a
|
|
3789
|
+
// "Failed" swap isn't provably unbroadcast either. We can't
|
|
3790
|
+
// tell from here whether the hash means the tx actually went
|
|
3791
|
+
// out, but the asymmetry favors marking: a needless re-quote
|
|
3792
|
+
// is cheaper than a silent double broadcast.
|
|
3793
|
+
const failedTxId = result.signature || result.txHash;
|
|
3794
|
+
if (failedTxId) markQuoteExecuted(quoteId, { broadcast: { txHash: failedTxId } });
|
|
3632
3795
|
lastQuoteError = `${quoteName}: ${result.error || result.status}`;
|
|
3633
3796
|
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
3634
3797
|
}
|
|
3635
3798
|
|
|
3636
3799
|
} catch (quoteErr) {
|
|
3800
|
+
// A BROADCAST_FAILED throws out of executeTransaction — BEFORE the
|
|
3801
|
+
// normal markQuoteExecuted runs — so nothing has recorded this quote
|
|
3802
|
+
// as spent. The signed tx may already be live on the backend (a 502
|
|
3803
|
+
// on the ack, not on the send), so fail closed: mark it here so a
|
|
3804
|
+
// later "trade execute --quote <id>" (or an agent auto-retry) is
|
|
3805
|
+
// refused before it re-signs under a fresh nonce. No broadcast hash
|
|
3806
|
+
// is recorded — we don't have one — which yields loadQuote's generic
|
|
3807
|
+
// "may still be pending, check the explorer" message.
|
|
3808
|
+
if (quoteErr?.code === 'BROADCAST_FAILED') {
|
|
3809
|
+
markQuoteExecuted(quoteId);
|
|
3810
|
+
}
|
|
3637
3811
|
// Post-broadcast failures abort the whole execute — never retry the
|
|
3638
3812
|
// next quote once a transaction is already out and its outcome is
|
|
3639
|
-
// unknown (mismatch, underivable local hash,
|
|
3640
|
-
//
|
|
3813
|
+
// unknown (mismatch, underivable local hash, an unconfirmed receipt
|
|
3814
|
+
// timeout, or an ambiguous broadcast failure). See
|
|
3815
|
+
// isFatalBroadcastError.
|
|
3641
3816
|
if (isFatalBroadcastError(quoteErr)) throw quoteErr;
|
|
3642
3817
|
const msg = quoteErr.message || '';
|
|
3643
3818
|
log(` ❌ Quote ${quoteName} failed: ${msg}`);
|
package/src/update-check.js
CHANGED
|
@@ -9,6 +9,7 @@ import fs from 'fs';
|
|
|
9
9
|
import path from 'path';
|
|
10
10
|
import childProcess from 'child_process';
|
|
11
11
|
import { fileURLToPath } from 'url';
|
|
12
|
+
import { compareSemver } from './semver.js';
|
|
12
13
|
|
|
13
14
|
const __filename = fileURLToPath(import.meta.url);
|
|
14
15
|
const CONFIG_DIR = path.join(process.env.HOME || process.env.USERPROFILE || '', '.nansen');
|
|
@@ -19,14 +20,20 @@ const PACKAGE_NAME = 'nansen-cli';
|
|
|
19
20
|
/**
|
|
20
21
|
* Compare two semver strings. Returns true if latest > current.
|
|
21
22
|
* Exported so `nansen doctor` reports upgrade state with identical semantics.
|
|
23
|
+
*
|
|
24
|
+
* Delegates to the shared compareSemver (src/semver.js, also used by `nansen
|
|
25
|
+
* changelog --since`) instead of hand-rolling its own parser. The previous
|
|
26
|
+
* inline parser here had the same bug compareSemver used to have: a version
|
|
27
|
+
* string with fewer than 3 components (e.g. a hand-edited or truncated cache
|
|
28
|
+
* file) parsed its missing component as `undefined`, and `>` is always
|
|
29
|
+
* `false` against `undefined` in both directions — so a partial version
|
|
30
|
+
* always read as "not newer", never "newer". In practice both `latest` (from
|
|
31
|
+
* the npm registry) and `current` (from this package's own version) are
|
|
32
|
+
* always full x.y.z today, so this couldn't misfire yet — but it's the same
|
|
33
|
+
* defect class, so it's fixed the same way rather than left as a landmine.
|
|
22
34
|
*/
|
|
23
35
|
export function isNewer(latest, current) {
|
|
24
|
-
|
|
25
|
-
const [lM, lm, lp] = parse(latest);
|
|
26
|
-
const [cM, cm, cp] = parse(current);
|
|
27
|
-
if (lM !== cM) return lM > cM;
|
|
28
|
-
if (lm !== cm) return lm > cm;
|
|
29
|
-
return lp > cp;
|
|
36
|
+
return compareSemver(latest, current) > 0;
|
|
30
37
|
}
|
|
31
38
|
|
|
32
39
|
const LAST_VERSION_FILE = path.join(CONFIG_DIR, 'last-version.json');
|
|
@@ -8,7 +8,6 @@
|
|
|
8
8
|
import crypto from 'crypto';
|
|
9
9
|
import { NansenError, ErrorCode } from './api.js';
|
|
10
10
|
import { wcExec } from './walletconnect-exec.js';
|
|
11
|
-
import { EVM_CHAIN_IDS } from './chain-ids.js';
|
|
12
11
|
import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
|
|
13
12
|
|
|
14
13
|
/**
|
|
@@ -54,11 +53,33 @@ function parseChainId(network) {
|
|
|
54
53
|
*/
|
|
55
54
|
export function buildEIP712TypedData({ fromAddress, requirement }) {
|
|
56
55
|
const payTo = resolvePayTo(requirement);
|
|
57
|
-
const { asset,
|
|
56
|
+
const { asset, maxTimeoutSeconds } = requirement;
|
|
57
|
+
const extra = requirement.extra || {};
|
|
58
58
|
const amount = resolvePaymentAmount(requirement);
|
|
59
59
|
|
|
60
|
-
|
|
61
|
-
|
|
60
|
+
if (!extra.name || !extra.version) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
'Refusing to sign x402 payment: EIP-712 domain name/version missing from requirement.extra.',
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Chain id comes only from the CAIP-2 network the policy validated — not from
|
|
67
|
+
// a remote extra.chainId override, which could change the signing domain.
|
|
68
|
+
const chainId = parseChainId(requirement.network);
|
|
69
|
+
if (chainId === null) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`Refusing to sign x402 payment: unsupported or missing EVM network ${requirement.network}.`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
// A remote extra.chainId that disagrees with the network is a domain-binding
|
|
75
|
+
// mismatch — refuse rather than sign under either interpretation. A null or
|
|
76
|
+
// empty extra.chainId means "unspecified", not a conflict, so treat it as absent.
|
|
77
|
+
if (extra.chainId != null && extra.chainId !== '' && Number(extra.chainId) !== chainId) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
`Refusing to sign x402 payment: extra.chainId ${extra.chainId} conflicts with ` +
|
|
80
|
+
`network ${requirement.network} (chain id ${chainId}).`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
62
83
|
|
|
63
84
|
const now = Math.floor(Date.now() / 1000);
|
|
64
85
|
const nonce = '0x' + crypto.randomBytes(32).toString('hex');
|
package/src/x402-evm.js
CHANGED
|
@@ -215,12 +215,16 @@ export function createEvmPaymentPayload(requirements, privateKeyHex, walletAddre
|
|
|
215
215
|
throw new Error(`Unsupported assetTransferMethod: ${method}`);
|
|
216
216
|
}
|
|
217
217
|
|
|
218
|
-
// Token name and version from requirements.extra (set by server/facilitator)
|
|
218
|
+
// Token name and version from requirements.extra (set by server/facilitator).
|
|
219
|
+
// Both are required: the EIP-712 domain version varies by token (USDC on Base
|
|
220
|
+
// is "2", USDT0/BSC tokens are "1"), so guessing a default would silently
|
|
221
|
+
// produce an invalid signature. Refuse instead — matches the walletconnect/Privy
|
|
222
|
+
// path in buildEIP712TypedData.
|
|
219
223
|
const tokenName = extra.name;
|
|
220
|
-
const tokenVersion = extra.version
|
|
224
|
+
const tokenVersion = extra.version;
|
|
221
225
|
|
|
222
|
-
if (!tokenName) {
|
|
223
|
-
throw new Error('EIP-712 domain name missing from requirements.extra');
|
|
226
|
+
if (!tokenName || !tokenVersion) {
|
|
227
|
+
throw new Error('EIP-712 domain name/version missing from requirements.extra');
|
|
224
228
|
}
|
|
225
229
|
|
|
226
230
|
// Generate random nonce (32 bytes)
|
package/src/x402-policy.js
CHANGED
|
@@ -7,6 +7,11 @@
|
|
|
7
7
|
import { EVM_X402_TOKENS, SVM_X402_TOKENS } from './x402-tokens.js';
|
|
8
8
|
import { getWalletConfig } from './wallet.js';
|
|
9
9
|
|
|
10
|
+
// The only x402 scheme this client can honour. "exact" = a fixed-amount transfer
|
|
11
|
+
// authorization (EIP-3009 / Permit2 on EVM, SPL TransferChecked on SVM). Any other
|
|
12
|
+
// scheme must be refused before signing, not silently accepted.
|
|
13
|
+
export const SUPPORTED_X402_SCHEMES = new Set(['exact']);
|
|
14
|
+
|
|
10
15
|
/**
|
|
11
16
|
* True for the exact Solana CAIP-2 network prefix ("solana:..."), matching
|
|
12
17
|
* isSvmNetwork() in x402-svm.js. Duplicated here (rather than imported) to
|
|
@@ -36,7 +41,7 @@ export function resolveKnownToken(network, asset) {
|
|
|
36
41
|
return table.find(t => t.token.toLowerCase() === asset.toLowerCase()) || null;
|
|
37
42
|
}
|
|
38
43
|
if (isSvmNetworkString(network)) {
|
|
39
|
-
const table = SVM_X402_TOKENS['solana'
|
|
44
|
+
const table = SVM_X402_TOKENS[network]; // exact CAIP-2 key, not the bare 'solana' prefix
|
|
40
45
|
if (!table) return null;
|
|
41
46
|
return table.find(t => t.token === asset) || null;
|
|
42
47
|
}
|
|
@@ -130,6 +135,16 @@ export function resolvePayTo(requirement) {
|
|
|
130
135
|
* allowlist, per-payment USD cap. Never signs; pure decision.
|
|
131
136
|
*/
|
|
132
137
|
export function evaluatePaymentRequirement(requirement) {
|
|
138
|
+
const scheme = requirement.scheme;
|
|
139
|
+
if (!SUPPORTED_X402_SCHEMES.has(scheme)) {
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
reason:
|
|
143
|
+
`Refusing to auto-pay: unsupported payment scheme ${scheme == null ? '(missing)' : `"${scheme}"`}. ` +
|
|
144
|
+
`Only "exact" is supported. No signature was produced.`,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
133
148
|
const network = requirement.network;
|
|
134
149
|
const asset = requirement.asset;
|
|
135
150
|
const payTo = resolvePayTo(requirement);
|
package/src/x402-svm.js
CHANGED
|
@@ -7,6 +7,7 @@ import crypto from 'crypto';
|
|
|
7
7
|
import { base58Encode, base58DecodePubkey } from './wallet.js';
|
|
8
8
|
import { encodeCompactU16, deriveATA as _deriveATA } from './transfer.js';
|
|
9
9
|
import { resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
|
|
10
|
+
import { SOLANA_MAINNET_NETWORK } from './x402-tokens.js';
|
|
10
11
|
|
|
11
12
|
// ============= Constants =============
|
|
12
13
|
|
|
@@ -329,13 +330,14 @@ export async function fetchRecentBlockhash(rpcUrl = 'https://api.mainnet-beta.so
|
|
|
329
330
|
* Get RPC URL for a Solana network identifier.
|
|
330
331
|
*/
|
|
331
332
|
export function getSolanaRpcUrl(network) {
|
|
332
|
-
if (network
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
return 'https://api.
|
|
333
|
+
if (network === SOLANA_MAINNET_NETWORK) return 'https://api.mainnet-beta.solana.com';
|
|
334
|
+
// Devnet/testnet resolve for tooling (e.g. balance checks), but the x402 pay
|
|
335
|
+
// path never reaches them: SVM_X402_TOKENS is mainnet-only, so the policy layer
|
|
336
|
+
// refuses a devnet/testnet requirement before signing. Adding a non-mainnet
|
|
337
|
+
// token entry would silently enable signing here — revisit this gate if you do.
|
|
338
|
+
if (network === 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1') return 'https://api.devnet.solana.com';
|
|
339
|
+
if (network === 'solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z') return 'https://api.testnet.solana.com';
|
|
340
|
+
throw new Error(`Unsupported Solana network for x402: ${network}`);
|
|
339
341
|
}
|
|
340
342
|
|
|
341
343
|
/**
|
package/src/x402-tokens.js
CHANGED
|
@@ -21,9 +21,14 @@ export const EVM_X402_TOKENS = {
|
|
|
21
21
|
],
|
|
22
22
|
};
|
|
23
23
|
|
|
24
|
-
//
|
|
24
|
+
// Canonical Solana mainnet CAIP-2 id.
|
|
25
|
+
// x402 payment tokens are mainnet mints, so mainnet is the only valid payment network.
|
|
26
|
+
export const SOLANA_MAINNET_NETWORK = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
|
|
27
|
+
|
|
28
|
+
// Known payment tokens on Solana, keyed by exact CAIP-2 network (symmetric with EVM_X402_TOKENS).
|
|
29
|
+
// Unknown or devnet/testnet solana:* ids resolve to no token and are refused by the policy.
|
|
25
30
|
export const SVM_X402_TOKENS = {
|
|
26
|
-
|
|
31
|
+
[SOLANA_MAINNET_NETWORK]: [
|
|
27
32
|
{ token: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', symbol: 'USDC', decimals: 6 },
|
|
28
33
|
],
|
|
29
34
|
};
|
package/src/x402.js
CHANGED
|
@@ -285,7 +285,14 @@ export async function checkX402Balance(network, asset = null) {
|
|
|
285
285
|
}),
|
|
286
286
|
});
|
|
287
287
|
const data = await resp.json();
|
|
288
|
-
|
|
288
|
+
// Use BigInt to avoid precision loss on 18-decimal tokens (BSC stablecoins).
|
|
289
|
+
if (!data.result || data.result === "0x") return { balance: 0, symbol };
|
|
290
|
+
const raw = BigInt(data.result);
|
|
291
|
+
const divisor = 10n ** BigInt(decimals);
|
|
292
|
+
// Fractional part is display-only (.toFixed(2)); sub-cent precision not guaranteed.
|
|
293
|
+
const whole = Number(raw / divisor);
|
|
294
|
+
const frac = Number((raw % divisor) * 10000n / divisor) / 10000;
|
|
295
|
+
return { balance: whole + frac, symbol };
|
|
289
296
|
}
|
|
290
297
|
|
|
291
298
|
return null;
|