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
package/src/trading.js
CHANGED
|
@@ -357,8 +357,8 @@ function assertUsableTxId(body, chainType) {
|
|
|
357
357
|
const check = (field, label, isValid) => {
|
|
358
358
|
const value = body[field];
|
|
359
359
|
// Absent is not malformed. Whether an identifier is REQUIRED depends on the
|
|
360
|
-
// execution mode (
|
|
361
|
-
//
|
|
360
|
+
// execution mode (Solana has no locally derived hash), so that call stays
|
|
361
|
+
// at the call site.
|
|
362
362
|
if (value === undefined || value === null || value === '') return;
|
|
363
363
|
if (typeof value !== 'string' || !isValid(value)) {
|
|
364
364
|
throw ambiguousBroadcast(
|
|
@@ -1652,7 +1652,7 @@ function toRpcHexValue(value) {
|
|
|
1652
1652
|
* guards: the cheap eth_call sim answers "will it revert", this answers "does the
|
|
1653
1653
|
* outcome match intent" (see assertSwapOutcome in trade-validation.js).
|
|
1654
1654
|
*
|
|
1655
|
-
* EVM-only, and on its own gate independent of --no-simulate
|
|
1655
|
+
* EVM-only, and on its own gate independent of --no-simulate. Runs for
|
|
1656
1656
|
* cross-chain bridges too — assertSwapOutcome skips only the output-arrival
|
|
1657
1657
|
* assertion internally, since the output lands on the destination chain and a
|
|
1658
1658
|
* source-chain simulation can't observe it; the input-outflow and no-sibling-
|
|
@@ -2601,7 +2601,6 @@ export async function buildTradeExecutionPlan({
|
|
|
2601
2601
|
quoteIndex = 0,
|
|
2602
2602
|
quoteCount = 1,
|
|
2603
2603
|
walletAddress = null,
|
|
2604
|
-
gasless = false,
|
|
2605
2604
|
noSimulate = false,
|
|
2606
2605
|
noVerifyOutcome = false,
|
|
2607
2606
|
probe = false,
|
|
@@ -2646,8 +2645,6 @@ export async function buildTradeExecutionPlan({
|
|
|
2646
2645
|
if (probe && chainConfig.type === 'evm') {
|
|
2647
2646
|
if (noSimulate) {
|
|
2648
2647
|
simulation = 'skipped (--no-simulate)';
|
|
2649
|
-
} else if (gasless) {
|
|
2650
|
-
simulation = 'skipped (--gasless routes through the solver)';
|
|
2651
2648
|
} else if (approvalPending) {
|
|
2652
2649
|
simulation = 'skipped — runs after the approval transaction lands';
|
|
2653
2650
|
} else {
|
|
@@ -2681,7 +2678,6 @@ export async function buildTradeExecutionPlan({
|
|
|
2681
2678
|
['Trading fee', quote.tradingFeeInUsd ? `$${quote.tradingFeeInUsd}` : null],
|
|
2682
2679
|
['Network fee', quote.networkFeeInUsd ? `$${quote.networkFeeInUsd}` : null],
|
|
2683
2680
|
['Approval', approval],
|
|
2684
|
-
['Gas', gasless ? 'paid by the solver (--gasless)' : null],
|
|
2685
2681
|
['Simulation', simulation],
|
|
2686
2682
|
['Outcome check', noVerifyOutcome ? 'off (--no-verify-outcome)' : 'on, before broadcast'],
|
|
2687
2683
|
]);
|
|
@@ -2703,27 +2699,12 @@ async function preflightTradeExecutionCandidate({
|
|
|
2703
2699
|
chain,
|
|
2704
2700
|
chainConfig,
|
|
2705
2701
|
walletAddress,
|
|
2706
|
-
isWalletConnect,
|
|
2707
|
-
gasless,
|
|
2708
2702
|
noSimulate,
|
|
2709
2703
|
noVerifyOutcome,
|
|
2710
2704
|
api,
|
|
2711
2705
|
verifiedTargets,
|
|
2712
2706
|
log,
|
|
2713
2707
|
}) {
|
|
2714
|
-
if (gasless && quote.aggregator !== 'relay') {
|
|
2715
|
-
throw new CommandError(
|
|
2716
|
-
`--gasless is only supported for Relay quotes, not "${quote.aggregator}".`,
|
|
2717
|
-
'GASLESS_UNSUPPORTED_AGGREGATOR',
|
|
2718
|
-
);
|
|
2719
|
-
}
|
|
2720
|
-
if (gasless && isWalletConnect) {
|
|
2721
|
-
throw new CommandError(
|
|
2722
|
-
'Gasless swaps are not supported via WalletConnect. Use a local or Privy wallet.',
|
|
2723
|
-
'GASLESS_UNSUPPORTED_WALLET',
|
|
2724
|
-
);
|
|
2725
|
-
}
|
|
2726
|
-
|
|
2727
2708
|
if (!walletAddress) {
|
|
2728
2709
|
throw new CommandError(
|
|
2729
2710
|
'The cached quote has no signer address, so it cannot be validated safely. Request a new quote.',
|
|
@@ -2825,7 +2806,7 @@ async function preflightTradeExecutionCandidate({
|
|
|
2825
2806
|
// approval cannot reproduce that future state and reports the deferral in
|
|
2826
2807
|
// its plan instead.
|
|
2827
2808
|
if (!approvalPending) {
|
|
2828
|
-
if (!noSimulate
|
|
2809
|
+
if (!noSimulate) {
|
|
2829
2810
|
const tx = quote.transaction;
|
|
2830
2811
|
const sim = await simulateEvmCall(chain, {
|
|
2831
2812
|
from: walletAddress,
|
|
@@ -3331,10 +3312,8 @@ CROSS-CHAIN NOTES (when using --to-chain):
|
|
|
3331
3312
|
response.quotes.forEach((q, i) => log(formatQuote(q, i)));
|
|
3332
3313
|
|
|
3333
3314
|
// Gas balance validation — check that the wallet has enough native token for gas.
|
|
3334
|
-
// High-value trades (>= $10) can use gasless/solver-paid routes and bypass this check.
|
|
3335
3315
|
try {
|
|
3336
|
-
|
|
3337
|
-
await validateGasBalance({ chain, walletAddress, tradeValueUsd });
|
|
3316
|
+
await validateGasBalance({ chain, walletAddress });
|
|
3338
3317
|
} catch (gasErr) {
|
|
3339
3318
|
throw new CommandError(`Error: ${gasErr.message}`, 'INSUFFICIENT_GAS');
|
|
3340
3319
|
}
|
|
@@ -3397,7 +3376,18 @@ CROSS-CHAIN NOTES (when using --to-chain):
|
|
|
3397
3376
|
const noSimulate = flags['no-simulate'];
|
|
3398
3377
|
const noRevokeExcessiveAllowance = flags['no-revoke-excessive-allowance'];
|
|
3399
3378
|
const noVerifyOutcome = flags['no-verify-outcome'];
|
|
3400
|
-
|
|
3379
|
+
// --gasless is gone. The deprecated broadcast route it posted to validates
|
|
3380
|
+
// its body strictly and has never accepted `gasless` or `steps`, so every
|
|
3381
|
+
// gasless swap was rejected with "Unrecognized keys" before broadcast, on
|
|
3382
|
+
// every chain. Rejected loudly rather than ignored: a script that still
|
|
3383
|
+
// passes it asked the solver to pay, and silently paying its own gas
|
|
3384
|
+
// instead is not a substitution we should make for it.
|
|
3385
|
+
if (flags.gasless) {
|
|
3386
|
+
throw new CommandError(
|
|
3387
|
+
'--gasless has been removed: the backend never accepted gasless swaps from the CLI, so the flag failed before broadcast on every chain. Re-run without it — the wallet pays its own gas.',
|
|
3388
|
+
'GASLESS_REMOVED',
|
|
3389
|
+
);
|
|
3390
|
+
}
|
|
3401
3391
|
// Parsed before the quote is touched so a typo can't consume it. A bare
|
|
3402
3392
|
// --max-tx-fee lands in flags, not options, so it would otherwise read as
|
|
3403
3393
|
// "not given" and silently apply the default cap.
|
|
@@ -3421,7 +3411,6 @@ OPTIONS:
|
|
|
3421
3411
|
--no-verify-outcome Skip swap-outcome verification (balance-delta check)
|
|
3422
3412
|
--no-revoke-excessive-allowance
|
|
3423
3413
|
Skip auto-revoking an oversized/legacy allowance before re-approving
|
|
3424
|
-
--gasless Relay-only: have Relay's solver pay gas (no WalletConnect)
|
|
3425
3414
|
--max-tx-fee <eth> Most one transaction may pay for gas (fee cap x gas limit).
|
|
3426
3415
|
Default 1 ETH; 0 disables the check.
|
|
3427
3416
|
--dry-run Validate and print what would be sent, then stop.
|
|
@@ -3475,13 +3464,10 @@ EXAMPLES:
|
|
|
3475
3464
|
// Resolved once here, before any signing, so an unrecognised route value
|
|
3476
3465
|
// aborts the command instead of surfacing mid-loop as a per-quote failure.
|
|
3477
3466
|
const configuredRoute = executionRoute();
|
|
3478
|
-
//
|
|
3479
|
-
//
|
|
3480
|
-
//
|
|
3481
|
-
|
|
3482
|
-
// broadcast call because the WalletConnect branch — which may never reach
|
|
3483
|
-
// that call — also has to know which route is in force.
|
|
3484
|
-
const swapRoute = gasless ? 'legacy' : configuredRoute;
|
|
3467
|
+
// Named apart from configuredRoute because the WalletConnect branch —
|
|
3468
|
+
// which may never reach the broadcast call — also has to know which route
|
|
3469
|
+
// is in force.
|
|
3470
|
+
const swapRoute = configuredRoute;
|
|
3485
3471
|
|
|
3486
3472
|
// The standard route keys its per-quote single-flight lock on the backend
|
|
3487
3473
|
// quote id, so a submission without one claims duplicate protection and
|
|
@@ -3537,8 +3523,6 @@ EXAMPLES:
|
|
|
3537
3523
|
.map((quote, index) => ({ quote, index }))
|
|
3538
3524
|
.filter(({ quote, index }) => index >= startIndex && index < endIndex && quote?.transaction);
|
|
3539
3525
|
const shouldPreflightPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
|
|
3540
|
-
const planUsesWalletConnect = quoteData.signerType === 'walletconnect'
|
|
3541
|
-
|| walletName === 'walletconnect' || walletName === 'wc';
|
|
3542
3526
|
if (guard.dryRun) {
|
|
3543
3527
|
// The live signer is intentionally unavailable here: dry-run reaches
|
|
3544
3528
|
// this gate before wallet material or a WalletConnect session is
|
|
@@ -3574,8 +3558,6 @@ EXAMPLES:
|
|
|
3574
3558
|
chain,
|
|
3575
3559
|
chainConfig,
|
|
3576
3560
|
walletAddress: planWallet,
|
|
3577
|
-
isWalletConnect: planUsesWalletConnect,
|
|
3578
|
-
gasless,
|
|
3579
3561
|
noSimulate,
|
|
3580
3562
|
noVerifyOutcome,
|
|
3581
3563
|
api: apiInstance,
|
|
@@ -3614,7 +3596,6 @@ EXAMPLES:
|
|
|
3614
3596
|
quoteIndex: index,
|
|
3615
3597
|
quoteCount: allQuotes.length,
|
|
3616
3598
|
walletAddress: planWallet,
|
|
3617
|
-
gasless,
|
|
3618
3599
|
noSimulate,
|
|
3619
3600
|
noVerifyOutcome,
|
|
3620
3601
|
probe: true,
|
|
@@ -3770,20 +3751,6 @@ EXAMPLES:
|
|
|
3770
3751
|
}
|
|
3771
3752
|
|
|
3772
3753
|
const isRelay = currentQuote.aggregator === 'relay';
|
|
3773
|
-
if (gasless) {
|
|
3774
|
-
if (!isRelay) {
|
|
3775
|
-
throw new CommandError(
|
|
3776
|
-
`--gasless is only supported for Relay quotes. Selected quote ${quoteName} is from "${currentQuote.aggregator}". Re-run with --quote-index to pin a Relay quote, or omit --gasless.`,
|
|
3777
|
-
'GASLESS_UNSUPPORTED_AGGREGATOR'
|
|
3778
|
-
);
|
|
3779
|
-
}
|
|
3780
|
-
if (isWalletConnect) {
|
|
3781
|
-
throw new CommandError(
|
|
3782
|
-
'Gasless swaps are not supported via WalletConnect (mobile wallets typically auto-broadcast, breaking the gasless flow). Use a local or Privy wallet.',
|
|
3783
|
-
'GASLESS_UNSUPPORTED_WALLET'
|
|
3784
|
-
);
|
|
3785
|
-
}
|
|
3786
|
-
}
|
|
3787
3754
|
|
|
3788
3755
|
log(`\nExecuting trade on ${chainConfig.name}...`);
|
|
3789
3756
|
if (endIndex - startIndex > 1) {
|
|
@@ -4060,7 +4027,7 @@ EXAMPLES:
|
|
|
4060
4027
|
}
|
|
4061
4028
|
|
|
4062
4029
|
// Pre-flight simulation
|
|
4063
|
-
if (!noSimulate
|
|
4030
|
+
if (!noSimulate) {
|
|
4064
4031
|
const sim = await simulateEvmCall(chain, {
|
|
4065
4032
|
from: walletAddress,
|
|
4066
4033
|
to: currentQuote.transaction.to,
|
|
@@ -4076,8 +4043,8 @@ EXAMPLES:
|
|
|
4076
4043
|
}
|
|
4077
4044
|
|
|
4078
4045
|
// Verify the swap's simulated on-chain outcome matches intent.
|
|
4079
|
-
// Its own gate (runs even when --no-simulate
|
|
4080
|
-
//
|
|
4046
|
+
// Its own gate (runs even when --no-simulate skips the cheap
|
|
4047
|
+
// revert check above); degrades with a warning if no
|
|
4081
4048
|
// simulation endpoint is available.
|
|
4082
4049
|
if (!noVerifyOutcome) {
|
|
4083
4050
|
const outcome = await verifySwapOutcome({ chain, from: walletAddress, quote: currentQuote, quoteData, api: apiInstance, log });
|
|
@@ -4469,7 +4436,7 @@ EXAMPLES:
|
|
|
4469
4436
|
}
|
|
4470
4437
|
|
|
4471
4438
|
// Pre-flight simulation
|
|
4472
|
-
if (!noSimulate
|
|
4439
|
+
if (!noSimulate) {
|
|
4473
4440
|
const txData = currentQuote.transaction;
|
|
4474
4441
|
const sim = await simulateEvmCall(chain, {
|
|
4475
4442
|
from: wcAddress,
|
|
@@ -4486,8 +4453,8 @@ EXAMPLES:
|
|
|
4486
4453
|
}
|
|
4487
4454
|
|
|
4488
4455
|
// Verify the swap's simulated on-chain outcome matches intent. Its
|
|
4489
|
-
// own gate: runs even when --no-simulate
|
|
4490
|
-
//
|
|
4456
|
+
// own gate: runs even when --no-simulate skips the cheap eth_call
|
|
4457
|
+
// revert check above; degrades with a warning when no
|
|
4491
4458
|
// simulation endpoint is set.
|
|
4492
4459
|
if (!noVerifyOutcome) {
|
|
4493
4460
|
const outcome = await verifySwapOutcome({ chain, from: wcAddress, quote: currentQuote, quoteData, api: apiInstance, log });
|
|
@@ -4831,7 +4798,7 @@ EXAMPLES:
|
|
|
4831
4798
|
// Pre-flight simulation (EVM only) — catch logic reverts before spending gas
|
|
4832
4799
|
// Runs AFTER approval so eth_call sees the current allowance state
|
|
4833
4800
|
// Simulates WITHOUT gas limit to check swap logic; gas re-estimation is separate
|
|
4834
|
-
if (!noSimulate
|
|
4801
|
+
if (!noSimulate) {
|
|
4835
4802
|
const txData = currentQuote.transaction;
|
|
4836
4803
|
const sim = await simulateEvmCall(chain, {
|
|
4837
4804
|
from: walletAddress,
|
|
@@ -4848,8 +4815,8 @@ EXAMPLES:
|
|
|
4848
4815
|
}
|
|
4849
4816
|
|
|
4850
4817
|
// Verify the swap's simulated on-chain outcome matches intent. Its
|
|
4851
|
-
// own gate: runs even when --no-simulate
|
|
4852
|
-
//
|
|
4818
|
+
// own gate: runs even when --no-simulate skips the cheap eth_call
|
|
4819
|
+
// revert check above; degrades with a warning when no
|
|
4853
4820
|
// simulation endpoint is set.
|
|
4854
4821
|
if (!noVerifyOutcome) {
|
|
4855
4822
|
const outcome = await verifySwapOutcome({ chain, from: walletAddress, quote: currentQuote, quoteData, api: apiInstance, log });
|
|
@@ -4880,11 +4847,11 @@ EXAMPLES:
|
|
|
4880
4847
|
);
|
|
4881
4848
|
}
|
|
4882
4849
|
|
|
4883
|
-
log(
|
|
4850
|
+
log(' Broadcasting...');
|
|
4884
4851
|
const execParams = {
|
|
4885
4852
|
signedTransaction,
|
|
4886
4853
|
chain,
|
|
4887
|
-
simulate: !noSimulate
|
|
4854
|
+
simulate: !noSimulate,
|
|
4888
4855
|
};
|
|
4889
4856
|
|
|
4890
4857
|
// The backend quote id, resolved with the route above. The per-quote
|
|
@@ -4900,8 +4867,8 @@ EXAMPLES:
|
|
|
4900
4867
|
if (quoteIdForExecute) {
|
|
4901
4868
|
execParams.quoteId = quoteIdForExecute;
|
|
4902
4869
|
}
|
|
4903
|
-
// The backend's /execute schema is strict; sending fields it doesn't
|
|
4904
|
-
// for the (chain × aggregator
|
|
4870
|
+
// The backend's /execute schema is strict; sending fields it doesn't
|
|
4871
|
+
// expect for the (chain × aggregator) combination causes 502s or
|
|
4905
4872
|
// "Unrecognized keys" rejections. The matrix we've validated against the
|
|
4906
4873
|
// live backend:
|
|
4907
4874
|
// - EVM signed (any aggregator): no aggregator/requestId fields.
|
|
@@ -4910,29 +4877,14 @@ EXAMPLES:
|
|
|
4910
4877
|
// intent resolution.
|
|
4911
4878
|
// - Solana signed (Relay): omit requestId — backend tries to look it up
|
|
4912
4879
|
// as a Jupiter intent and 502s.
|
|
4913
|
-
|
|
4914
|
-
// - Gasless (Solana): currently rejected by the backend ("Unrecognized
|
|
4915
|
-
// keys"); we still send the gasless envelope and let the backend
|
|
4916
|
-
// surface the error so users notice when support lands.
|
|
4917
|
-
if (gasless) {
|
|
4918
|
-
execParams.aggregator = 'relay';
|
|
4919
|
-
execParams.gasless = true;
|
|
4920
|
-
const gaslessRequestId = requestId || currentQuote.metadata?.requestId;
|
|
4921
|
-
if (gaslessRequestId) execParams.requestId = gaslessRequestId;
|
|
4922
|
-
if (currentQuote.metadata?.steps) execParams.steps = currentQuote.metadata.steps;
|
|
4923
|
-
} else if (requestId && !isRelay) {
|
|
4880
|
+
if (requestId && !isRelay) {
|
|
4924
4881
|
execParams.requestId = requestId; // Solana Jupiter Ultra
|
|
4925
4882
|
}
|
|
4926
4883
|
|
|
4927
|
-
// A retry re-POSTs the signed payload.
|
|
4928
|
-
//
|
|
4929
|
-
// 5xx/network failure
|
|
4930
|
-
//
|
|
4931
|
-
// broadcasts its OWN wrapping tx from it (the returned txHash is not
|
|
4932
|
-
// our bytes) — so a re-POST after the solver already picked it up
|
|
4933
|
-
// can't be deduped at the node level and risks a second solve. For
|
|
4934
|
-
// gasless we therefore don't retry: a single POST either succeeds or
|
|
4935
|
-
// fails closed (BROADCAST_FAILED marks the quote spent and aborts).
|
|
4884
|
+
// A retry re-POSTs the signed payload. Every remaining execution mode
|
|
4885
|
+
// sends our own signed bytes, so that is a byte-identical replay the
|
|
4886
|
+
// node dedupes: retrying an ambiguous 5xx/network failure cannot itself
|
|
4887
|
+
// double-broadcast.
|
|
4936
4888
|
if (swapRoute === 'standard') {
|
|
4937
4889
|
// Attribution and cross-chain fields the standard route reads from
|
|
4938
4890
|
// the body. Attached only here because the legacy schema rejects
|
|
@@ -4946,19 +4898,17 @@ EXAMPLES:
|
|
|
4946
4898
|
}
|
|
4947
4899
|
|
|
4948
4900
|
swapHandedOff = true;
|
|
4949
|
-
const result = await executeTransaction(execParams, {
|
|
4901
|
+
const result = await executeTransaction(execParams, { route: swapRoute, attemptId });
|
|
4950
4902
|
|
|
4951
4903
|
if (result.status === 'Success') {
|
|
4952
|
-
const gaslessEvm = gasless && chainType === 'evm';
|
|
4953
4904
|
// `signature` is a Solana field. Reading it on EVM let a stray one
|
|
4954
4905
|
// win over the real `txHash` and reach the explorer URL and the
|
|
4955
4906
|
// persisted broadcast marker; executeTransaction has already
|
|
4956
4907
|
// validated the shape of whichever field is used here.
|
|
4957
4908
|
let txId = chainType === 'evm' ? result.txHash : (result.signature || result.txHash);
|
|
4958
|
-
if (
|
|
4959
|
-
const executionType = gaslessEvm ? 'gasless EVM' : 'Solana';
|
|
4909
|
+
if (chainType === 'solana' && !txId) {
|
|
4960
4910
|
throw ambiguousBroadcast(
|
|
4961
|
-
`The execute API reported success for ${quoteName} without a
|
|
4911
|
+
`The execute API reported success for ${quoteName} without a Solana transaction identifier. The broadcast cannot be verified, so no further quote will be tried. Check the wallet on the explorer before retrying.`,
|
|
4962
4912
|
{ details: result },
|
|
4963
4913
|
);
|
|
4964
4914
|
}
|
|
@@ -4968,9 +4918,9 @@ EXAMPLES:
|
|
|
4968
4918
|
// Trading API accepts it — the quote is spent here, before the
|
|
4969
4919
|
// on-chain verification below can throw RECEIPT_TIMEOUT (or
|
|
4970
4920
|
// anything else) and abort this function. Covers local EVM,
|
|
4971
|
-
// Privy EVM, Privy Solana, local/WalletConnect Solana
|
|
4972
|
-
// WalletConnect sign-only fallback
|
|
4973
|
-
//
|
|
4921
|
+
// Privy EVM, Privy Solana, local/WalletConnect Solana and the
|
|
4922
|
+
// WalletConnect sign-only fallback — every path that reaches this
|
|
4923
|
+
// shared broadcast call.
|
|
4974
4924
|
//
|
|
4975
4925
|
// Deliberate: a broadcast that later reverts on-chain still
|
|
4976
4926
|
// consumes the quote and ends this invocation. The user must
|
|
@@ -5020,30 +4970,20 @@ EXAMPLES:
|
|
|
5020
4970
|
// For EVM: verify the tx actually succeeded on-chain
|
|
5021
4971
|
if (chainType === 'evm') {
|
|
5022
4972
|
log(' Verifying on-chain status...');
|
|
5023
|
-
//
|
|
5024
|
-
//
|
|
5025
|
-
// must surface as itself — not as the "REVERTED on-chain" diagnostic
|
|
5026
|
-
// catch is reserved for.
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
|
|
5030
|
-
|
|
5031
|
-
txId = evmTxHash(signedTransaction);
|
|
5032
|
-
} catch (hashErr) {
|
|
5033
|
-
throw new CommandError(`Cannot derive local tx hash for ${quoteName}: ${hashErr.message}`, 'INVALID_SIGNED_TX');
|
|
5034
|
-
}
|
|
5035
|
-
explorerUrl = chainConfig.explorer + txId;
|
|
4973
|
+
// Derive our local hash up front, OUTSIDE the receipt-poll try
|
|
4974
|
+
// below. A hex-validation failure here means no poll ever ran, so it
|
|
4975
|
+
// must surface as itself — not as the "REVERTED on-chain" diagnostic
|
|
4976
|
+
// that catch is reserved for.
|
|
4977
|
+
try {
|
|
4978
|
+
txId = evmTxHash(signedTransaction);
|
|
4979
|
+
} catch (hashErr) {
|
|
4980
|
+
throw new CommandError(`Cannot derive local tx hash for ${quoteName}: ${hashErr.message}`, 'INVALID_SIGNED_TX');
|
|
5036
4981
|
}
|
|
4982
|
+
explorerUrl = chainConfig.explorer + txId;
|
|
5037
4983
|
try {
|
|
5038
|
-
|
|
5039
|
-
|
|
5040
|
-
|
|
5041
|
-
if (result.txHash) await waitForReceipt(chain, result.txHash);
|
|
5042
|
-
} else {
|
|
5043
|
-
const { hash } = await confirmEvmBroadcast(chain, signedTransaction, result.txHash);
|
|
5044
|
-
txId = hash;
|
|
5045
|
-
explorerUrl = chainConfig.explorer + txId;
|
|
5046
|
-
}
|
|
4984
|
+
const { hash } = await confirmEvmBroadcast(chain, signedTransaction, result.txHash);
|
|
4985
|
+
txId = hash;
|
|
4986
|
+
explorerUrl = chainConfig.explorer + txId;
|
|
5047
4987
|
} catch (receiptErr) {
|
|
5048
4988
|
// A receipt TIMEOUT is not a confirmed revert: the tx was
|
|
5049
4989
|
// broadcast and may still be pending under our nonce. Retrying
|
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
|
|
@@ -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
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
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
|
-
|
|
149
|
-
//
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
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
|
-
|
|
193
|
-
|
|
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
|
-
//
|
|
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
|
-
//
|
|
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
|
-
//
|
|
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
|
|
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
|
+
}
|