nansen-cli 1.45.0 → 2.0.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/README.md +158 -18
  3. package/docs/browser-login.md +117 -0
  4. package/package.json +11 -2
  5. package/scripts/postinstall.js +35 -30
  6. package/skills/nansen-agent-guide/SKILL.md +13 -2
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
  8. package/skills/nansen-dca-tracker/SKILL.md +10 -2
  9. package/skills/nansen-defi-positions/SKILL.md +5 -2
  10. package/skills/nansen-exit-signals/SKILL.md +10 -2
  11. package/skills/nansen-fund-tracker/SKILL.md +10 -2
  12. package/skills/nansen-general-search/SKILL.md +10 -2
  13. package/skills/nansen-holder-analysis/SKILL.md +10 -2
  14. package/skills/nansen-limit-orders/SKILL.md +6 -3
  15. package/skills/nansen-perp-screener/SKILL.md +10 -2
  16. package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
  20. package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
  21. package/skills/nansen-prediction-markets/SKILL.md +10 -2
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
  23. package/skills/nansen-smart-alerts/SKILL.md +9 -4
  24. package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
  25. package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
  26. package/skills/nansen-smart-money-trend/SKILL.md +10 -2
  27. package/skills/nansen-token-research/SKILL.md +10 -2
  28. package/skills/nansen-token-screener/SKILL.md +14 -4
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
  30. package/skills/nansen-trading/SKILL.md +27 -2
  31. package/skills/nansen-wallet-batch/SKILL.md +10 -2
  32. package/skills/nansen-wallet-clustering/SKILL.md +10 -2
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +23 -15
  35. package/skills/nansen-wallet-manager/SKILL.md +26 -10
  36. package/skills/nansen-wallet-profiler/SKILL.md +10 -2
  37. package/skills/nansen-web-fetcher/SKILL.md +5 -2
  38. package/skills/nansen-web-searcher/SKILL.md +5 -2
  39. package/src/api.js +319 -129
  40. package/src/auth-browser.js +16 -0
  41. package/src/auth-credentials.js +73 -0
  42. package/src/auth-device.js +242 -0
  43. package/src/auth-key-input.js +46 -0
  44. package/src/auth-login.js +90 -0
  45. package/src/auth-state.js +487 -0
  46. package/src/auth-store-native.js +20 -0
  47. package/src/auth-store-worker.js +64 -0
  48. package/src/auth-store.js +140 -0
  49. package/src/auto-paginate.js +272 -0
  50. package/src/bridge.js +309 -85
  51. package/src/cache-inspect.js +345 -0
  52. package/src/chain-ids.js +1 -2
  53. package/src/cli.js +779 -286
  54. package/src/commands/agent.js +20 -9
  55. package/src/commands/alerts.js +1 -1
  56. package/src/commands/completion.js +2 -15
  57. package/src/commands/mcp.js +22 -20
  58. package/src/commands/research.js +4 -2
  59. package/src/cost-cache.js +16 -2
  60. package/src/debug.js +348 -0
  61. package/src/doctor.js +22 -45
  62. package/src/ens.js +3 -1
  63. package/src/execute-guard.js +116 -0
  64. package/src/hl-action.js +41 -13
  65. package/src/limit-order.js +9 -1
  66. package/src/mcp-client-config.js +169 -0
  67. package/src/mcp-client-config.json +17 -0
  68. package/src/mcp-verify.js +6 -5
  69. package/src/perp.js +61 -9
  70. package/src/privy.js +12 -12
  71. package/src/query-options.js +38 -6
  72. package/src/response-meta.js +57 -2
  73. package/src/rpc-urls.js +9 -11
  74. package/src/schema.json +309 -30
  75. package/src/semver.js +23 -4
  76. package/src/swap-simulation.js +35 -30
  77. package/src/telemetry.js +20 -0
  78. package/src/trading.js +806 -40
  79. package/src/transfer.js +75 -9
  80. package/src/update-check.js +9 -1
  81. package/src/wallet.js +240 -20
  82. package/src/walletconnect-trading.js +29 -8
  83. package/src/walletconnect-x402.js +9 -5
  84. package/src/x402-svm.js +123 -64
  85. package/src/x402.js +46 -14
package/src/trading.js CHANGED
@@ -17,11 +17,13 @@ import { getWalletConnectAddress, sendTransactionViaWalletConnect, sendSolanaTra
17
17
  import { retrievePassword } from './keychain.js';
18
18
  import { validateQuoteInput, validateBalance, resolvePercentAmount, validateGasBalance, encodeApproveCalldata, assertValidApprovalSpender, assertQuoteMatchesRequest, assertSwapCalldataNotBareTransfer, assertSwapOutcome, assertSolanaInstructionsSafe, assertSolanaSwapOutcome, approvalAmountForSwap, needsAllowanceRevoke, OVERSIZED_ALLOWANCE_MULTIPLIER, EVM_BRIDGE_NATIVE_FEE_SLACK, isBridgeRequest } from './trade-validation.js';
19
19
  import { readCompactU16 } from './solana-tx.js';
20
+ import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
20
21
  export { readCompactU16 };
21
22
  import { CHAIN_RPCS } from './rpc-urls.js';
22
23
  import { simulateAssetChanges, SwapSimulationError, hasSimulationRpc } from './swap-simulation.js';
23
24
  import { simulateSolanaAssetChanges, SolanaSimulationError, hasSolanaSimulationRpc } from './solana-simulation.js';
24
- import { packageVersion, CommandError, telemetryHeaders, loadConfig } from './api.js';
25
+ import { packageVersion, CommandError, telemetryHeaders } from './api.js';
26
+ import { screenOrThrow } from './perp.js';
25
27
 
26
28
  // ============= Constants =============
27
29
 
@@ -506,8 +508,14 @@ export function saveQuote(quoteResponse, chain, signerType = 'local', privyWalle
506
508
  export function loadQuote(quoteId) {
507
509
  const filePath = safeQuotesPath(`${quoteId}.json`);
508
510
  if (!filePath || !fs.existsSync(filePath)) {
511
+ const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
512
+ if (claimedPath && fs.existsSync(claimedPath)) throw quoteClaimedError(quoteId, claimedPath);
509
513
  throw new Error(`Quote "${quoteId}" not found. Quotes expire after 1 hour.`);
510
514
  }
515
+ return readQuoteFile(filePath, quoteId);
516
+ }
517
+
518
+ function readQuoteFile(filePath, quoteId) {
511
519
  const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
512
520
  if (Date.now() - data.timestamp > 3600000) {
513
521
  fs.unlinkSync(filePath);
@@ -533,13 +541,87 @@ export function loadQuote(quoteId) {
533
541
  return data;
534
542
  }
535
543
 
544
+ function quoteClaimedError(quoteId, claimedPath) {
545
+ return new Error(
546
+ `Quote "${quoteId}" is claimed by another execution (${claimedPath}). If that run is still going, wait for it to finish. If it was interrupted, a swap may or may not have been broadcast: check the wallet on the explorer, then request a new quote with "nansen trade quote". The claimed quote is removed when it expires.`,
547
+ );
548
+ }
549
+
550
+ /**
551
+ * Claim a quote for execution, so two concurrent `trade execute --quote <id>`
552
+ * runs cannot both sign and broadcast it.
553
+ *
554
+ * loadQuote's `executedAt` check only rejects a quote that has already been
555
+ * broadcast, and `markQuoteExecuted` writes that marker after the broadcast.
556
+ * Everything in between — sanctions screening, preflight, an approval with up
557
+ * to a 180s receipt wait — is a window in which a second invocation passes the
558
+ * same check. An agent retrying a tool call it believes timed out therefore
559
+ * gets two independently valid swaps; on Solana there is no shared nonce to
560
+ * make the second one fail.
561
+ *
562
+ * The quote file itself is the claim: it is renamed from `<id>.json` to
563
+ * `<id>.executing.json`. rename(2) moves the one inode, so of two runs only one
564
+ * can do it and the other gets ENOENT; no liveness is guessed and nothing is
565
+ * ever taken over. The quote is re-read from the claimed file, so a run that
566
+ * loaded it before another run executed it (for instance while waiting at the
567
+ * confirmation prompt) sees that run's `executedAt` here, before signing.
568
+ *
569
+ * `release({ handedOff })` puts the quote back under its own name when no swap
570
+ * transaction left this process, or when one did and `executedAt` was recorded
571
+ * (loadQuote then refuses it with the broadcast hashes). A swap that was handed
572
+ * off with no recorded marker leaves the quote claimed: a retry is refused
573
+ * rather than risk a second broadcast, and the claim goes away with the quote
574
+ * after its 1-hour lifetime.
575
+ *
576
+ * @param {string} quoteId
577
+ * @returns {{ quote: object, release: (opts?: { handedOff?: boolean }) => void }}
578
+ */
579
+ export function claimQuoteForExecution(quoteId) {
580
+ const quotePath = safeQuotesPath(`${quoteId}.json`);
581
+ const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
582
+ if (!quotePath || !claimedPath) throw new Error(`Invalid quote id "${quoteId}".`);
583
+
584
+ try {
585
+ fs.renameSync(quotePath, claimedPath);
586
+ } catch (err) {
587
+ if (err.code !== 'ENOENT') throw err;
588
+ // Lost the claim, or the quote is gone: loadQuote reports which. If the
589
+ // other run released it in the meantime, still refuse rather than loop.
590
+ loadQuote(quoteId);
591
+ throw quoteClaimedError(quoteId, claimedPath);
592
+ }
593
+
594
+ let released = false;
595
+ const release = ({ handedOff = false } = {}) => {
596
+ if (released) return;
597
+ released = true;
598
+ try {
599
+ if (handedOff && !JSON.parse(fs.readFileSync(claimedPath, 'utf8')).executedAt) return;
600
+ fs.renameSync(claimedPath, quotePath);
601
+ } catch { /* gone (expired and cleaned up): nothing to release */ }
602
+ };
603
+
604
+ try {
605
+ return { quote: readQuoteFile(claimedPath, quoteId), release };
606
+ } catch (err) {
607
+ // Already executed, expired or not a swap quote: nothing is signed, so
608
+ // put back whatever is still there.
609
+ release();
610
+ throw err;
611
+ }
612
+ }
613
+
536
614
  // Records that a broadcast has happened. `executedAt` is set on the first call
537
615
  // and never moved, so the quote is consumed the instant the swap goes out — a
538
616
  // later receipt-wait timeout or a REVERTED/failed outcome must not leave the
539
617
  // quote reusable, since retrying would sign and broadcast a second,
540
618
  // independently valid swap. Mirrors markBridgeQuoteExecuted (bridge.js).
541
619
  export function markQuoteExecuted(quoteId, progress = {}) {
542
- const filePath = safeQuotesPath(`${quoteId}.json`);
620
+ // During an execute the quote lives under its claimed name.
621
+ const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
622
+ const filePath = claimedPath && fs.existsSync(claimedPath)
623
+ ? claimedPath
624
+ : safeQuotesPath(`${quoteId}.json`);
543
625
  if (!filePath || !fs.existsSync(filePath)) return;
544
626
  try {
545
627
  const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
@@ -764,11 +846,14 @@ export async function normalizeSolanaTransaction(transaction, rpcUrl, getExpecte
764
846
  * @param {string} privateKeyHex - 64-char hex (32-byte secp256k1 private key)
765
847
  * @param {string} chain - Chain name
766
848
  * @param {number} nonce - Account nonce
849
+ * @param {object} [opts]
850
+ * @param {string} [opts.label='swap'] - What is being signed, for the fee-cap error
851
+ * @param {bigint} [opts.maxTxFeeWei] - Fee cap in wei (--max-tx-fee); 0n disables it
767
852
  * @returns {string} 0x-prefixed signed transaction hex
768
853
  */
769
854
  // Pure EVM encode/sign primitive. Quote authorization and request-intent binding
770
855
  // happen upstream before this function receives transaction calldata.
771
- export function signEvmTransaction(txData, privateKeyHex, chain, nonce) {
856
+ export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { label = 'swap', maxTxFeeWei = MAX_EVM_TX_FEE_WEI } = {}) {
772
857
  const chainConfig = CHAIN_MAP[chain];
773
858
  if (!chainConfig || chainConfig.type !== 'evm') {
774
859
  throw new Error(`Unsupported EVM chain: ${chain}`);
@@ -784,6 +869,7 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce) {
784
869
  };
785
870
 
786
871
  if (txData.maxFeePerGas) {
872
+ assertEvmFeeWithinCap(txData.maxFeePerGas, common.gasLimit, label, maxTxFeeWei);
787
873
  return signEip1559Transaction({
788
874
  ...common,
789
875
  maxFeePerGas: toHex(txData.maxFeePerGas),
@@ -793,16 +879,161 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce) {
793
879
  }, privateKeyHex);
794
880
  }
795
881
 
796
- // Previously this fell back to a gasPrice of 1 wei, which signs a transaction
797
- // that can never be mined and burns the nonce. Refuse instead: a quote with no
798
- // fee information at all is a bug upstream, not something to sign through.
799
- if (!txData.gasPrice) {
882
+ // A gasPrice-only quote stays a legacy transaction; a quote with no fee
883
+ // information at all is refused (see NO_QUOTE_FEE_MESSAGE).
884
+ if (!txData.gasPrice) throw new Error(NO_QUOTE_FEE_MESSAGE);
885
+
886
+ assertEvmFeeWithinCap(txData.gasPrice, common.gasLimit, label, maxTxFeeWei);
887
+ return signLegacyTransaction({ ...common, gasPrice: toHex(txData.gasPrice) }, privateKeyHex);
888
+ }
889
+
890
+ // Previously the signers fell back to a hardcoded gas price (1 wei here, then
891
+ // 1,000,000 wei = 0.001 gwei in the Privy/approval paths), which signs a
892
+ // transaction that can never be mined and leaves the nonce stuck for every
893
+ // later attempt. Refuse instead: a quote with no fee information at all is a
894
+ // bug upstream, not something to sign through. signEvmTransaction refuses it
895
+ // directly; the Privy swap path and the approval/revoke transactions that
896
+ // precede a swap resolve their fee fields through the two helpers below so the
897
+ // refusal is uniform.
898
+ const NO_QUOTE_FEE_MESSAGE =
899
+ 'Quote supplied no gas price (expected gasPrice or maxFeePerGas), so any signed transaction would be unmineable. Refusing to sign.';
900
+
901
+ // A quote's fee fields are signed verbatim, so a compromised or buggy
902
+ // aggregator response can make the wallet pay an arbitrary tip to the block
903
+ // producer with no revert and no warning. The Solana signer already bounds
904
+ // this (MAX_PRIORITY_FEE_LAMPORTS in trade-validation.js); this is the EVM
905
+ // sibling. It works like geth's --rpc.txfeecap and reth's
906
+ // DEFAULT_TX_FEE_CAP_WEI: maxFeePerGas x gasLimit against an absolute cap of
907
+ // 1 ETH. That product overstates what a transaction actually pays (bridge.js
908
+ // deliberately inflates maxFeePerGas because a generous cap costs nothing), so
909
+ // the cap is a backstop against an anomalous quote, not a price check.
910
+ // --max-tx-fee overrides it, and 0 disables it.
911
+ export const MAX_EVM_TX_FEE_WEI = 1_000_000_000_000_000_000n; // 1 ETH
912
+
913
+ // Gas limit used for every approval/revoke transaction this file signs.
914
+ const APPROVAL_GAS_LIMIT = 100000;
915
+
916
+ // Gas limit resolveEvmSwapGasLimit falls back to when neither the quote nor
917
+ // eth_estimateGas gives one.
918
+ const FALLBACK_SWAP_GAS_LIMIT = 210000;
919
+
920
+ /**
921
+ * Parse a --max-tx-fee value, in ETH, into wei. Converted digit-wise, like
922
+ * parseGweiToWei, so no float rounding is involved. 0 disables the cap.
923
+ *
924
+ * @param {string|undefined} raw - The option value, or undefined when not given
925
+ * @returns {bigint} cap in wei (MAX_EVM_TX_FEE_WEI when not given, 0n = no cap)
926
+ * @throws {CommandError} on anything but a non-negative decimal with at most 18 decimals
927
+ */
928
+ export function parseMaxTxFeeOption(raw) {
929
+ if (raw === undefined || raw === null) return MAX_EVM_TX_FEE_WEI;
930
+ // String() would coerce a repeated or JSON-shaped option into something that
931
+ // parses: `--max-tx-fee '[0]'` becomes "0" and silently disables the cap.
932
+ if (typeof raw !== 'string' && typeof raw !== 'number') {
933
+ throw new CommandError(
934
+ `--max-tx-fee takes a single value in ETH (e.g. 0.5), or 0 for no cap.`,
935
+ 'INVALID_INPUT',
936
+ );
937
+ }
938
+ const s = String(raw).trim();
939
+ const match = /^(\d*)(?:\.(\d{1,18}))?$/.exec(s);
940
+ if (!match || (match[1] === '' && match[2] === undefined)) {
941
+ throw new CommandError(
942
+ `Invalid --max-tx-fee "${raw}". Give the most one transaction may pay for gas, in ETH (e.g. 0.5), or 0 for no cap.`,
943
+ 'INVALID_INPUT',
944
+ );
945
+ }
946
+ const [, int, frac = ''] = match;
947
+ return BigInt(int || '0') * 10n ** 18n + BigInt(frac.padEnd(18, '0'));
948
+ }
949
+
950
+ // Parse a quote quantity (decimal string, 0x-hex string, number or bigint)
951
+ // without letting a malformed value surface as a raw BigInt SyntaxError.
952
+ function parseQuoteQuantity(value, what, label) {
953
+ let parsed = null;
954
+ if (typeof value === 'bigint') parsed = value;
955
+ else if (typeof value === 'number' && Number.isSafeInteger(value)) parsed = BigInt(value);
956
+ else if (typeof value === 'string' && /^(0x[0-9a-fA-F]+|\d+)$/.test(value.trim())) parsed = BigInt(value.trim());
957
+ if (parsed === null || parsed <= 0n) {
958
+ throw new Error(`Quote has an invalid ${what} for this ${label} (${value}); expected a positive integer. Refusing to sign.`);
959
+ }
960
+ return parsed;
961
+ }
962
+
963
+ /**
964
+ * Refuse a transaction whose worst-case gas cost exceeds the fee cap, or whose
965
+ * fee or gas limit is not a positive integer.
966
+ *
967
+ * @param {string|number|bigint} maxFeePerGas - Fee cap per gas, wei (decimal or 0x-hex)
968
+ * @param {string|number|bigint} gasLimit - Gas limit for the transaction
969
+ * @param {string} label - What is being signed, for the error message
970
+ * @param {bigint} [capWei] - Cap in wei (--max-tx-fee); 0n skips the cap
971
+ * @throws {Error} when maxFeePerGas * gasLimit is above the cap
972
+ */
973
+ export function assertEvmFeeWithinCap(maxFeePerGas, gasLimit, label = 'transaction', capWei = MAX_EVM_TX_FEE_WEI) {
974
+ const feePerGas = parseQuoteQuantity(maxFeePerGas, 'fee per gas', label);
975
+ const gas = parseQuoteQuantity(gasLimit, 'gas limit', label);
976
+ if (capWei === 0n) return;
977
+ const worstCase = feePerGas * gas;
978
+ if (worstCase > capWei) {
800
979
  throw new Error(
801
- 'Quote supplied no gas price (expected gasPrice or maxFeePerGas), so any signed transaction would be unmineable. Refusing to sign.',
980
+ `Would pay up to ${worstCase} wei of gas for this ${label} (${feePerGas} wei per gas x ${gas} gas), above the ${capWei} wei fee cap. Refusing to sign. Use --max-tx-fee <eth> to raise the cap, or --max-tx-fee 0 to disable it.`,
802
981
  );
803
982
  }
983
+ }
804
984
 
805
- return signLegacyTransaction({ ...common, gasPrice: toHex(txData.gasPrice) }, privateKeyHex);
985
+ /**
986
+ * Check the swap's fee before any approval is sent for it. The approval is
987
+ * capped against its own 100k gas limit, so without this a quote whose fee
988
+ * passes for the approval but not for the swap would pay for the approval and
989
+ * grant the allowance, and only then be refused. eth_estimateGas can't run yet
990
+ * (without the allowance it reverts), so a quote with no gas fields is checked
991
+ * against the fallback limit; the swap is checked again with the resolved
992
+ * limit when it is signed.
993
+ *
994
+ * @param {object} currentQuote - The quote about to be executed
995
+ * @param {bigint} capWei - Cap in wei (--max-tx-fee)
996
+ */
997
+ export function assertQuotedSwapFeeWithinCap(currentQuote, capWei) {
998
+ const { maxFeePerGas } = resolveQuoteEip1559Fees(currentQuote.transaction);
999
+ const apiGas = parseGasField(currentQuote.gas);
1000
+ const txGas = parseGasField(currentQuote.transaction.gas || currentQuote.transaction.gasLimit);
1001
+ const gas = apiGas > 0 ? apiGas : txGas > 0 ? txGas : FALLBACK_SWAP_GAS_LIMIT;
1002
+ assertEvmFeeWithinCap(maxFeePerGas, gas, 'swap', capWei);
1003
+ }
1004
+
1005
+ /**
1006
+ * Resolve the fee fields for an EIP-1559 (type 2) signer from a quote's
1007
+ * transaction. A legacy-only quote (gasPrice, no maxFeePerGas) is lifted into
1008
+ * type 2 by using gasPrice as the fee cap. A zero priority fee is a valid choice
1009
+ * but not a sane default, so it falls back to the fee cap rather than to
1010
+ * nothing when the quote omits it.
1011
+ *
1012
+ * @param {object} txData - Quote transaction fields
1013
+ * @returns {{ maxFeePerGas: string|number, maxPriorityFeePerGas: string|number }}
1014
+ * @throws {Error} when the quote carries neither maxFeePerGas nor gasPrice
1015
+ */
1016
+ export function resolveQuoteEip1559Fees(txData) {
1017
+ const maxFeePerGas = txData?.maxFeePerGas || txData?.gasPrice;
1018
+ if (!maxFeePerGas) throw new Error(NO_QUOTE_FEE_MESSAGE);
1019
+ return {
1020
+ maxFeePerGas,
1021
+ maxPriorityFeePerGas: txData.maxPriorityFeePerGas || maxFeePerGas,
1022
+ };
1023
+ }
1024
+
1025
+ /**
1026
+ * Resolve the gas price for a legacy (type 0) signer from a quote's
1027
+ * transaction. An EIP-1559-only quote is flattened to its fee cap.
1028
+ *
1029
+ * @param {object} txData - Quote transaction fields
1030
+ * @returns {string|number} gas price in wei
1031
+ * @throws {Error} when the quote carries neither gasPrice nor maxFeePerGas
1032
+ */
1033
+ export function resolveQuoteLegacyGasPrice(txData) {
1034
+ const gasPrice = txData?.gasPrice || txData?.maxFeePerGas;
1035
+ if (!gasPrice) throw new Error(NO_QUOTE_FEE_MESSAGE);
1036
+ return gasPrice;
806
1037
  }
807
1038
 
808
1039
  /**
@@ -1114,10 +1345,10 @@ function toRpcHexValue(value) {
1114
1345
  * @param {string} args.from - the wallet that will sign (the sender simulated)
1115
1346
  * @param {object} args.quote - the quote about to be executed (currentQuote)
1116
1347
  * @param {object} args.quoteData - the loaded quote record (.request, .slippage)
1117
- * @param {string|null} [args.apiKey] - Nansen API key for the hosted endpoint
1348
+ * @param {object} [args.api] - Selected Nansen API client for hosted simulation
1118
1349
  * @param {function} [args.log]
1119
1350
  */
1120
- export async function verifySwapOutcome({ chain, from, quote, quoteData, apiKey = null, log = () => {} }) {
1351
+ export async function verifySwapOutcome({ chain, from, quote, quoteData, api, log = () => {} }) {
1121
1352
  if (CHAIN_MAP[chain?.toLowerCase()]?.type !== 'evm') return { proceed: true }; // EVM-only
1122
1353
  // Cross-chain (bridge): the output token settles on the destination chain,
1123
1354
  // so the source-chain simulation still runs but assertSwapOutcome skips
@@ -1145,7 +1376,7 @@ export async function verifySwapOutcome({ chain, from, quote, quoteData, apiKey
1145
1376
  const sim = await simulateAssetChanges(
1146
1377
  chain,
1147
1378
  { to: tx.to, data: tx.data, value: toRpcHexValue(tx.value) },
1148
- { from, apiKey },
1379
+ { from, api },
1149
1380
  );
1150
1381
  // A cross-chain bridge may pay a fee in native ETH via msg.value on a
1151
1382
  // token-input route; that surfaces as a native sibling outflow which the
@@ -1263,7 +1494,7 @@ export async function resolveEvmSwapGasLimit(currentQuote, { chain, from }) {
1263
1494
  value: txData.value ? '0x' + BigInt(txData.value).toString(16) : '0x0',
1264
1495
  });
1265
1496
  if (estimated) finalGas = Math.ceil(estimated * 1.5);
1266
- if (finalGas === 0) finalGas = 210000;
1497
+ if (finalGas === 0) finalGas = FALLBACK_SWAP_GAS_LIMIT;
1267
1498
  }
1268
1499
  return finalGas;
1269
1500
  }
@@ -1603,16 +1834,22 @@ export function assertUsableSpender(spenderAddress) {
1603
1834
  * @param {bigint|string|number} [maxAllowance] - Hard cap from persisted request intent
1604
1835
  * @param {object} [opts]
1605
1836
  * @param {boolean} [opts.allowZero=false] - Allow a zero-amount revoke approval
1837
+ * @param {bigint} [opts.maxTxFeeWei] - Fee cap in wei (--max-tx-fee); 0n disables it
1606
1838
  * @returns {string} 0x-prefixed signed approval tx hex
1607
1839
  */
1608
1840
  // Approval signing is intentionally narrow: callers pass either the scoped swap
1609
1841
  // amount from approvalAmountForSwap or, for excessive-allowance cleanup, an
1610
1842
  // explicit allowZero revoke. encodeApproveCalldata validates the spender,
1611
1843
  // amount, optional request cap, and final ABI width before signing.
1612
- export function buildApprovalTransaction(tokenAddress, spenderAddress, privateKeyHex, chain, nonce, gasPrice, amount, maxAllowance, { allowZero = false } = {}) {
1844
+ export function buildApprovalTransaction(tokenAddress, spenderAddress, privateKeyHex, chain, nonce, gasPrice, amount, maxAllowance, { allowZero = false, maxTxFeeWei = MAX_EVM_TX_FEE_WEI } = {}) {
1613
1845
  const chainConfig = CHAIN_MAP[chain];
1614
1846
  if (!chainConfig) throw new Error(`Unsupported chain: ${chain}`);
1615
1847
 
1848
+ // An approval broadcast at a placeholder fee never mines and blocks the swap
1849
+ // behind it, so require a real gas price the same way signEvmTransaction does.
1850
+ if (!gasPrice) throw new Error(NO_QUOTE_FEE_MESSAGE);
1851
+ assertEvmFeeWithinCap(gasPrice, APPROVAL_GAS_LIMIT, allowZero ? 'allowance revoke' : 'approval', maxTxFeeWei);
1852
+
1616
1853
  // Scope the approval to the swap's input amount so a malicious or buggy quote
1617
1854
  // can drain at most this one trade, never the wallet's full token balance.
1618
1855
  // encodeApproveCalldata enforces a valid 20-byte spender, a bounded (< MAX)
@@ -1621,8 +1858,8 @@ export function buildApprovalTransaction(tokenAddress, spenderAddress, privateKe
1621
1858
 
1622
1859
  const tx = {
1623
1860
  nonce,
1624
- gasPrice: toHex(gasPrice || '1000000'),
1625
- gasLimit: '0x186a0', // 100000
1861
+ gasPrice: toHex(gasPrice),
1862
+ gasLimit: toHex(APPROVAL_GAS_LIMIT),
1626
1863
  to: tokenAddress,
1627
1864
  value: '0x0',
1628
1865
  data,
@@ -2019,13 +2256,316 @@ export function formatQuote(quote, index) {
2019
2256
  return lines.join('\n');
2020
2257
  }
2021
2258
 
2259
+ // ============= Execution plan (--dry-run / confirmation) =============
2260
+
2261
+ /**
2262
+ * Describe the swap `trade execute` is about to sign, for the confirmation
2263
+ * prompt and for --dry-run. Reads only the cached quote and (on a dry run)
2264
+ * read-only RPC state — it never touches wallet material, so a dry run works
2265
+ * on a locked wallet and cannot sign anything.
2266
+ *
2267
+ * `probe` runs the extra read-only checks that only make sense when the user
2268
+ * asked for a preview: the current ERC-20 allowance and the pre-broadcast
2269
+ * revert simulation. Both degrade to a note if the endpoint is unavailable.
2270
+ */
2271
+ export async function buildTradeExecutionPlan({
2272
+ quoteId,
2273
+ quoteData,
2274
+ quote,
2275
+ chainConfig,
2276
+ quoteIndex = 0,
2277
+ quoteCount = 1,
2278
+ walletAddress = null,
2279
+ gasless = false,
2280
+ noSimulate = false,
2281
+ noVerifyOutcome = false,
2282
+ probe = false,
2283
+ }) {
2284
+ const request = quoteData.request || {};
2285
+ const chain = quoteData.chain;
2286
+ const isNative = isNativeToken(quote.inputMint);
2287
+ const spender = quote.approvalAddress && quote.approvalAddress !== '' && !isNative
2288
+ ? quote.approvalAddress
2289
+ : null;
2290
+
2291
+ let approval = isNative ? 'not required (native token input)' : 'not required';
2292
+ let approvalPending = false;
2293
+ if (spender) {
2294
+ const approveAmt = approvalAmountForSwap({
2295
+ inputAmount: quote.inputAmount || quote.inAmount || '0',
2296
+ swapMode: quoteData.swapMode,
2297
+ slippage: quoteData.slippage,
2298
+ });
2299
+ approval = `required → ${spender} (scoped to ${approveAmt} base units)`;
2300
+ approvalPending = true;
2301
+ if (probe && walletAddress) {
2302
+ try {
2303
+ const existing = await checkErc20Allowance(chain, quote.inputMint, walletAddress, spender);
2304
+ if (existing >= approveAmt) {
2305
+ approval = `already granted to ${spender} (${existing} base units) — no approval transaction needed`;
2306
+ approvalPending = false;
2307
+ } else {
2308
+ approval += `; current allowance is ${existing}`;
2309
+ }
2310
+ } catch (err) {
2311
+ approval += `; current allowance could not be read (${err.message})`;
2312
+ }
2313
+ }
2314
+ }
2315
+
2316
+ // The revert simulation reads the CURRENT chain state, so it is only
2317
+ // meaningful once the router can actually pull the input token. With an
2318
+ // approval still outstanding it would report a revert that the real run
2319
+ // never hits, so say so instead of simulating.
2320
+ let simulation = null;
2321
+ if (probe && chainConfig.type === 'evm') {
2322
+ if (noSimulate) {
2323
+ simulation = 'skipped (--no-simulate)';
2324
+ } else if (gasless) {
2325
+ simulation = 'skipped (--gasless routes through the solver)';
2326
+ } else if (approvalPending) {
2327
+ simulation = 'skipped — runs after the approval transaction lands';
2328
+ } else {
2329
+ try {
2330
+ const tx = quote.transaction || {};
2331
+ const sim = await simulateEvmCall(chain, {
2332
+ from: walletAddress,
2333
+ to: tx.to,
2334
+ data: tx.data,
2335
+ value: tx.value ? '0x' + BigInt(tx.value).toString(16) : '0x0',
2336
+ });
2337
+ simulation = sim.success ? 'passed' : `❌ FAILED: ${sim.reason}`;
2338
+ } catch (err) {
2339
+ simulation = `could not run (${err.message})`;
2340
+ }
2341
+ }
2342
+ }
2343
+
2344
+ const toChain = quoteData.toChain;
2345
+ const route = toChain && toChain !== chain
2346
+ ? `${chainConfig.name} → ${resolveChain(toChain).name}`
2347
+ : chainConfig.name;
2348
+
2349
+ return formatPlan(`Trade plan — ${route}`, [
2350
+ ['Quote', `${quoteId}${quote.aggregator ? ` via ${quote.aggregator}` : ''}${quoteCount > 1 ? ` (quote ${quoteIndex + 1} of ${quoteCount})` : ''}`],
2351
+ ['Sell', `${quote.inAmount ?? quote.inputAmount ?? '?'} base units of ${request.fromToken || quote.inputMint}`],
2352
+ ['Buy', `~${quote.outAmount ?? '?'} base units of ${request.toToken || quote.outputMint}`],
2353
+ ['Max spend', request.maxInputAmount ? `${request.maxInputAmount} base units` : null],
2354
+ ['Wallet', walletAddress || 'the wallet this quote was created for'],
2355
+ ['Recipient', request.recipient || null],
2356
+ ['Trading fee', quote.tradingFeeInUsd ? `$${quote.tradingFeeInUsd}` : null],
2357
+ ['Network fee', quote.networkFeeInUsd ? `$${quote.networkFeeInUsd}` : null],
2358
+ ['Approval', approval],
2359
+ ['Gas', gasless ? 'paid by the solver (--gasless)' : null],
2360
+ ['Simulation', simulation],
2361
+ ['Outcome check', noVerifyOutcome ? 'off (--no-verify-outcome)' : 'on, before broadcast'],
2362
+ ]);
2363
+ }
2364
+
2365
+ /**
2366
+ * Run every execute validation that can be completed from a cached quote,
2367
+ * public signer address, and read-only RPC calls. This intentionally does not
2368
+ * resolve signing credentials, sign, broadcast, or consume the quote.
2369
+ *
2370
+ * Real execution repeats signer binding with the independently resolved live
2371
+ * signer later. The preview uses the immutable signer saved with the request;
2372
+ * this gives --dry-run the same transaction/intent checks without requiring a
2373
+ * wallet password, Privy secret, or WalletConnect session.
2374
+ */
2375
+ async function preflightTradeExecutionCandidate({
2376
+ quoteData,
2377
+ quote,
2378
+ chain,
2379
+ chainConfig,
2380
+ walletAddress,
2381
+ isWalletConnect,
2382
+ gasless,
2383
+ noSimulate,
2384
+ noVerifyOutcome,
2385
+ api,
2386
+ verifiedTargets,
2387
+ log,
2388
+ }) {
2389
+ if (gasless && quote.aggregator !== 'relay') {
2390
+ throw new CommandError(
2391
+ `--gasless is only supported for Relay quotes, not "${quote.aggregator}".`,
2392
+ 'GASLESS_UNSUPPORTED_AGGREGATOR',
2393
+ );
2394
+ }
2395
+ if (gasless && isWalletConnect) {
2396
+ throw new CommandError(
2397
+ 'Gasless swaps are not supported via WalletConnect. Use a local or Privy wallet.',
2398
+ 'GASLESS_UNSUPPORTED_WALLET',
2399
+ );
2400
+ }
2401
+
2402
+ if (!walletAddress) {
2403
+ throw new CommandError(
2404
+ 'The cached quote has no signer address, so it cannot be validated safely. Request a new quote.',
2405
+ 'WALLET_MISMATCH',
2406
+ );
2407
+ }
2408
+
2409
+ if (chainConfig.type === 'solana') {
2410
+ assertCompleteSolanaRequestIntent(quoteData.request);
2411
+ assertQuoteMatchesRequest(quoteData.request, quote, {
2412
+ chain,
2413
+ walletAddress,
2414
+ slippage: quoteData.slippage,
2415
+ });
2416
+ const txBase64 = await normalizeSolanaTransaction(
2417
+ quote.transaction,
2418
+ CHAIN_RPCS.solana,
2419
+ async () => walletAddress,
2420
+ );
2421
+ assertSolanaInstructionsSafe(txBase64, { walletAddress });
2422
+ if (!noVerifyOutcome) {
2423
+ const outcome = await verifySolanaSwapOutcome({
2424
+ chain,
2425
+ walletAddress,
2426
+ txBase64,
2427
+ quote,
2428
+ quoteData,
2429
+ log,
2430
+ });
2431
+ if (!outcome.proceed) {
2432
+ throw new CommandError(
2433
+ `Swap-outcome verification failed: ${outcome.reason}`,
2434
+ 'OUTCOME_VERIFICATION_FAILED',
2435
+ );
2436
+ }
2437
+ }
2438
+ return;
2439
+ }
2440
+
2441
+ await validateSwapTarget(chain, quote.transaction.to, quote.inputMint, { verifiedTargets });
2442
+ assertCompleteEvmRequestIntent(quoteData.request);
2443
+ assertQuoteMatchesRequest(quoteData.request, quote, {
2444
+ chain,
2445
+ walletAddress,
2446
+ slippage: quoteData.slippage,
2447
+ });
2448
+ assertSwapCalldataNotBareTransfer(quote.transaction.data);
2449
+
2450
+ const nativeInput = isNativeToken(quote.inputMint);
2451
+ const txValue = BigInt(quote.transaction.value || '0');
2452
+ if (nativeInput) {
2453
+ const expectedValue = BigInt(quote.inAmount || quote.inputAmount || '0');
2454
+ if (txValue !== expectedValue) {
2455
+ throw new CommandError(
2456
+ `Transaction value mismatch: tx.value=${txValue}, expected=${expectedValue}`,
2457
+ 'AMOUNT_MISMATCH',
2458
+ );
2459
+ }
2460
+ } else {
2461
+ const bridgeFeeAllowed = quoteData?.request
2462
+ && isBridgeRequest(quoteData.request)
2463
+ && txValue <= EVM_BRIDGE_NATIVE_FEE_SLACK;
2464
+ if (txValue > 0n && !bridgeFeeAllowed) {
2465
+ throw new CommandError(
2466
+ `ERC-20 swap has unexpected non-zero tx.value (${txValue}).`,
2467
+ 'AMOUNT_MISMATCH',
2468
+ );
2469
+ }
2470
+ }
2471
+
2472
+ let approvalPending = false;
2473
+ if (quote.approvalAddress && quote.approvalAddress !== '' && !nativeInput) {
2474
+ assertUsableSpender(quote.approvalAddress);
2475
+ const inputAmount = BigInt(quote.inputAmount || quote.inAmount || '0');
2476
+ const approveAmt = approvalAmountForSwap({
2477
+ inputAmount,
2478
+ swapMode: quoteData.swapMode,
2479
+ slippage: quoteData.slippage,
2480
+ });
2481
+ if (approveAmt <= 0n) {
2482
+ throw new CommandError('Quote has a zero input amount, so its approval cannot be scoped safely.', 'INVALID_AMOUNT');
2483
+ }
2484
+ // Exercise the same spender/amount/cap encoder used immediately before a
2485
+ // real approval is signed, but discard the calldata.
2486
+ encodeApproveCalldata(quote.approvalAddress, approveAmt, {
2487
+ maxAllowance: approvalCapForQuote(quoteData),
2488
+ });
2489
+ const existingAllowance = await checkErc20Allowance(
2490
+ chain,
2491
+ quote.inputMint,
2492
+ walletAddress,
2493
+ quote.approvalAddress,
2494
+ );
2495
+ approvalPending = existingAllowance < approveAmt;
2496
+ }
2497
+
2498
+ // These checks require the router to be able to pull the input token. A real
2499
+ // execute runs them after its approval lands; a preview with an outstanding
2500
+ // approval cannot reproduce that future state and reports the deferral in
2501
+ // its plan instead.
2502
+ if (!approvalPending) {
2503
+ if (!noSimulate && !gasless) {
2504
+ const tx = quote.transaction;
2505
+ const sim = await simulateEvmCall(chain, {
2506
+ from: walletAddress,
2507
+ to: tx.to,
2508
+ data: tx.data,
2509
+ value: tx.value ? '0x' + BigInt(tx.value).toString(16) : '0x0',
2510
+ });
2511
+ if (!sim.success) {
2512
+ throw new CommandError(`Pre-broadcast simulation failed: ${sim.reason}`, 'SIMULATION_FAILED');
2513
+ }
2514
+ }
2515
+ if (!noVerifyOutcome) {
2516
+ const outcome = await verifySwapOutcome({
2517
+ chain,
2518
+ from: walletAddress,
2519
+ quote,
2520
+ quoteData,
2521
+ api,
2522
+ log,
2523
+ });
2524
+ if (!outcome.proceed) {
2525
+ throw new CommandError(
2526
+ `Swap-outcome verification failed: ${outcome.reason}`,
2527
+ 'OUTCOME_VERIFICATION_FAILED',
2528
+ );
2529
+ }
2530
+ }
2531
+ await resolveEvmSwapGasLimit(quote, { chain, from: walletAddress });
2532
+ }
2533
+ }
2534
+
2022
2535
  // ============= CLI Command Builder =============
2023
2536
 
2537
+ // Addresses a swap must clear compliance screening for: the wallet that signs
2538
+ // plus any distinct destination wallet. Blanks are dropped and duplicates
2539
+ // removed — case-insensitively for EVM addresses, exactly for base58 (Solana
2540
+ // addresses are case-sensitive, so two strings differing only in case are
2541
+ // different wallets). Exported for tests.
2542
+ export function tradeScreeningAddresses(...addresses) {
2543
+ const seen = new Set();
2544
+ const out = [];
2545
+ for (const raw of addresses) {
2546
+ if (!raw) continue;
2547
+ const address = String(raw);
2548
+ const key = /^0x[0-9a-f]{40}$/i.test(address) ? address.toLowerCase() : address;
2549
+ if (seen.has(key)) continue;
2550
+ seen.add(key);
2551
+ out.push(address);
2552
+ }
2553
+ return out;
2554
+ }
2555
+
2024
2556
  /**
2025
2557
  * Build trading command handlers for CLI integration.
2026
2558
  */
2027
2559
  export function buildTradingCommands(deps = {}) {
2028
- const { log = console.log } = deps;
2560
+ const {
2561
+ log = console.log,
2562
+ // Injected so the confirmation prompt (and whether there is anyone to
2563
+ // answer it) can be driven in tests without a terminal.
2564
+ promptFn,
2565
+ confirmationLog = log,
2566
+ isTTY = false,
2567
+ env = process.env,
2568
+ } = deps;
2029
2569
 
2030
2570
  return {
2031
2571
  'quote': async (args, apiInstance, flags, options) => {
@@ -2094,6 +2634,8 @@ PREREQUISITE:
2094
2634
  A wallet must be configured before using this command (the trading API builds
2095
2635
  a transaction specific to your sender address).
2096
2636
  Set one up with: nansen wallet create
2637
+ API access is required for pre-trade compliance screening.
2638
+ Authenticate with: nansen login (or set NANSEN_API_KEY)
2097
2639
 
2098
2640
  OPTIONS:
2099
2641
  --chain <chain> Source chain: solana, base
@@ -2341,6 +2883,21 @@ CROSS-CHAIN NOTES (when using --to-chain):
2341
2883
  const fromWarning = getWrappedNativeFromWarning(from, chain);
2342
2884
  if (fromWarning) log(` ${fromWarning}`);
2343
2885
 
2886
+ // Every unit conversion above can land on zero base units without
2887
+ // tripping a guard of its own: validateQuoteInput checked the raw
2888
+ // --amount (a positive dollar or percent figure), and the usd and
2889
+ // percent branches pre-round with toFixed() before convertToBaseUnits
2890
+ // sees the value, so its "meaningful digits lost" check never fires.
2891
+ // A zero would be sent to the quote endpoint as a real request.
2892
+ if (!/^\d+$/.test(String(resolvedAmount)) || BigInt(resolvedAmount) === 0n) {
2893
+ const unitSuffix = amountUnit ? ` --amount-unit ${amountUnit}` : '';
2894
+ const scale = resolvedDecimals !== undefined ? ` at ${resolvedDecimals} decimals` : '';
2895
+ throw new CommandError(
2896
+ `Error: --amount ${amount}${unitSuffix} resolves to ${resolvedAmount} base units${scale}, which would quote a swap of nothing. Use a larger amount.`,
2897
+ 'INVALID_INPUT',
2898
+ );
2899
+ }
2900
+
2344
2901
  const params = {
2345
2902
  chainIndex: chainConfig.index,
2346
2903
  fromTokenAddress: from,
@@ -2370,6 +2927,15 @@ CROSS-CHAIN NOTES (when using --to-chain):
2370
2927
  if (maxAutoSlippage != null) params.maxAutoSlippagePercent = maxAutoSlippage;
2371
2928
  if (swapMode !== 'exactIn') params.swapMode = swapMode;
2372
2929
 
2930
+ // Compliance screen before the quote request — the same fail-closed
2931
+ // check `bridge` and `perp` run. Quotes are fetched from the trading
2932
+ // backend directly, so nothing else screens this path; refuse here so a
2933
+ // flagged wallet never receives a signable quote. Screens the signing
2934
+ // wallet plus any distinct destination wallet (--to-wallet or the
2935
+ // auto-derived cross-chain destination). Throws SANCTIONED for a hit
2936
+ // and SCREENING_UNAVAILABLE if the check itself cannot complete.
2937
+ await screenOrThrow(apiInstance, tradeScreeningAddresses(walletAddress, params.toWalletAddress));
2938
+
2373
2939
  const response = await getQuote(params);
2374
2940
 
2375
2941
  if (!response.success || !response.quotes?.length) {
@@ -2507,20 +3073,22 @@ CROSS-CHAIN NOTES (when using --to-chain):
2507
3073
  const noRevokeExcessiveAllowance = flags['no-revoke-excessive-allowance'];
2508
3074
  const noVerifyOutcome = flags['no-verify-outcome'];
2509
3075
  const gasless = Boolean(flags.gasless);
2510
- // Read the API key for the swap-outcome sim endpoint. It's optional (the
2511
- // check degrades to a warning if the endpoint can't authenticate), so a
2512
- // malformed config must not crash an in-progress trade — fall back to null.
2513
- const apiKey = (() => {
2514
- try {
2515
- return loadConfig().apiKey;
2516
- } catch {
2517
- return null;
2518
- }
2519
- })();
3076
+ // Parsed before the quote is touched so a typo can't consume it. A bare
3077
+ // --max-tx-fee lands in flags, not options, so it would otherwise read as
3078
+ // "not given" and silently apply the default cap.
3079
+ if (flags['max-tx-fee']) {
3080
+ throw new CommandError('--max-tx-fee requires a value in ETH (e.g. 0.5), or 0 for no cap.', 'INVALID_INPUT');
3081
+ }
3082
+ const maxTxFeeWei = parseMaxTxFeeOption(options['max-tx-fee']);
3083
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
2520
3084
 
2521
3085
  if (!quoteId) {
2522
3086
  throw new CommandError(`Usage: nansen trade execute --quote <quoteId> [options]
2523
3087
 
3088
+ PREREQUISITE:
3089
+ API access is required for pre-trade compliance screening.
3090
+ Authenticate with: nansen login (or set NANSEN_API_KEY)
3091
+
2524
3092
  OPTIONS:
2525
3093
  --quote <id> Quote ID from 'nansen quote'
2526
3094
  --wallet <name> Wallet name (default: default wallet)
@@ -2529,11 +3097,29 @@ OPTIONS:
2529
3097
  --no-revoke-excessive-allowance
2530
3098
  Skip auto-revoking an oversized/legacy allowance before re-approving
2531
3099
  --gasless Relay-only: have Relay's solver pay gas (no WalletConnect)
3100
+ --max-tx-fee <eth> Most one transaction may pay for gas (fee cap x gas limit).
3101
+ Default 1 ETH; 0 disables the check.
3102
+ --dry-run Validate and print what would be sent, then stop.
3103
+ Nothing is signed or broadcast and the quote stays usable.
3104
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1).
3105
+ The prompt only appears when stdin is a terminal; agents,
3106
+ CI and pipes are never prompted, with or without --yes.
3107
+
3108
+ EXIT CODES:
3109
+ 0 broadcast succeeded, or the dry run completed
3110
+ 1 declined at the confirmation prompt, or the execution failed
2532
3111
 
2533
3112
  EXAMPLES:
2534
- nansen trade execute --quote 1708900000000-abc123`, 'MISSING_ARGS');
3113
+ nansen trade execute --quote 1708900000000-abc123
3114
+ nansen trade execute --quote 1708900000000-abc123 --dry-run
3115
+ nansen trade execute --quote 1708900000000-abc123 --yes`, 'MISSING_ARGS');
2535
3116
  }
2536
3117
 
3118
+ let quoteClaim = null;
3119
+ // Set just before the swap transaction leaves this process (the Trading
3120
+ // API broadcast, or a WalletConnect wallet that may broadcast it), so the
3121
+ // claim is only handed back when no swap can be in flight.
3122
+ let swapHandedOff = false;
2537
3123
  try {
2538
3124
  const quoteData = loadQuote(quoteId);
2539
3125
  const chain = quoteData.chain;
@@ -2565,6 +3151,130 @@ EXAMPLES:
2565
3151
  throw new CommandError('❌ No quotes contain transaction data.\n Ensure userWalletAddress was provided when fetching the quote.', 'NO_TRANSACTION');
2566
3152
  }
2567
3153
 
3154
+ // ── Acknowledgement gate: --dry-run / --yes ──────────────────────
3155
+ // Deliberately placed before any wallet material is loaded and before
3156
+ // the first approval transaction: a dry run needs no password and can
3157
+ // sign nothing, and a declined confirmation cannot have put an
3158
+ // approval on-chain. See src/execute-guard.js for the TTY rules.
3159
+ // Execution falls back across candidates when one fails before a
3160
+ // definitive broadcast. Consent must therefore cover every candidate
3161
+ // that may be signed, rather than displaying only the first one and
3162
+ // silently broadcasting a different fallback quote later.
3163
+ const planCandidates = allQuotes
3164
+ .map((quote, index) => ({ quote, index }))
3165
+ .filter(({ quote, index }) => index >= startIndex && index < endIndex && quote?.transaction);
3166
+ const shouldPreflightPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
3167
+ const planUsesWalletConnect = quoteData.signerType === 'walletconnect'
3168
+ || walletName === 'walletconnect' || walletName === 'wc';
3169
+ if (guard.dryRun) {
3170
+ // The live signer is intentionally unavailable here: dry-run reaches
3171
+ // this gate before wallet material or a WalletConnect session is
3172
+ // resolved. Screen the public signer recorded in the cached request
3173
+ // (or legacy response metadata) plus its distinct recipient for the
3174
+ // preview. Real execution resolves the live signer below and screens
3175
+ // it again immediately before signing.
3176
+ const previewScreenAddresses = tradeScreeningAddresses(
3177
+ quoteData.request?.walletAddress || quoteData.response?.metadata?.userWalletAddress,
3178
+ quoteData.request?.recipient,
3179
+ );
3180
+ if (!previewScreenAddresses.length) {
3181
+ throw new CommandError(
3182
+ `Quote "${quoteId}" does not record which wallet it was built for, so it cannot be screened. Request a fresh quote with "nansen trade quote".`,
3183
+ 'SCREENING_UNAVAILABLE',
3184
+ );
3185
+ }
3186
+ await screenOrThrow(apiInstance, previewScreenAddresses);
3187
+ }
3188
+ const verifiedPlanTargets = new Set();
3189
+ const validatedPlanCandidates = [];
3190
+ let lastPreflightError = null;
3191
+ for (const candidate of planCandidates) {
3192
+ const planWallet = quoteData.request?.walletAddress
3193
+ || quoteData.response?.metadata?.userWalletAddress
3194
+ || candidate.quote.transaction?.from
3195
+ || null;
3196
+ try {
3197
+ if (shouldPreflightPlan) {
3198
+ await preflightTradeExecutionCandidate({
3199
+ quoteData,
3200
+ quote: candidate.quote,
3201
+ chain,
3202
+ chainConfig,
3203
+ walletAddress: planWallet,
3204
+ isWalletConnect: planUsesWalletConnect,
3205
+ gasless,
3206
+ noSimulate,
3207
+ noVerifyOutcome,
3208
+ api: apiInstance,
3209
+ verifiedTargets: verifiedPlanTargets,
3210
+ log,
3211
+ });
3212
+ }
3213
+ validatedPlanCandidates.push(candidate);
3214
+ } catch (error) {
3215
+ lastPreflightError = error;
3216
+ }
3217
+ }
3218
+ if (!validatedPlanCandidates.length) {
3219
+ throw new CommandError(
3220
+ `\n❌ All quotes failed sign-free preflight. Last error: ${lastPreflightError?.message || 'unknown'}\n`,
3221
+ 'ALL_QUOTES_FAILED',
3222
+ );
3223
+ }
3224
+ // Non-interactive/--yes execution never consumes the plan, so avoid
3225
+ // building display strings (and their optional read-only probes) on
3226
+ // that unchanged automation path. guardExecution safely ignores the
3227
+ // empty plan whenever no preview or prompt is active.
3228
+ let plan = '';
3229
+ if (shouldPreflightPlan) {
3230
+ const plans = [];
3231
+ for (const { quote, index } of validatedPlanCandidates) {
3232
+ const planWallet = quoteData.request?.walletAddress
3233
+ || quoteData.response?.metadata?.userWalletAddress
3234
+ || quote.transaction?.from
3235
+ || null;
3236
+ plans.push(await buildTradeExecutionPlan({
3237
+ quoteId,
3238
+ quoteData,
3239
+ quote,
3240
+ chainConfig,
3241
+ quoteIndex: index,
3242
+ quoteCount: allQuotes.length,
3243
+ walletAddress: planWallet,
3244
+ gasless,
3245
+ noSimulate,
3246
+ noVerifyOutcome,
3247
+ probe: true,
3248
+ }));
3249
+ }
3250
+ const fallbackNotice = validatedPlanCandidates.length > 1
3251
+ ? '\n The CLI may try these candidates in order until one broadcasts successfully.'
3252
+ : '';
3253
+ plan = `${plans.join('\n')}${fallbackNotice}`;
3254
+ }
3255
+ // An interactive user only consented to candidates that passed the
3256
+ // sign-free preflight and appeared in this plan. Do not later retry a
3257
+ // candidate omitted after a transient or deterministic preflight
3258
+ // failure; it could otherwise recover and broadcast unseen.
3259
+ const consentedCandidateIndexes = shouldPreflightPlan
3260
+ ? new Set(validatedPlanCandidates.map(({ index }) => index))
3261
+ : null;
3262
+ const proceed = await guardExecution({
3263
+ plan,
3264
+ ...guard,
3265
+ promptFn,
3266
+ log,
3267
+ confirmationLog,
3268
+ });
3269
+ if (!proceed) return undefined;
3270
+
3271
+ // Past this point the run signs and broadcasts. Claim the quote so a
3272
+ // second concurrent execute cannot pass loadQuote's already-executed
3273
+ // check during the window before the first broadcast is recorded. The
3274
+ // claim re-reads the quote, so if another run executed it while this
3275
+ // one waited at the prompt above, this throws before anything is signed.
3276
+ quoteClaim = claimQuoteForExecution(quoteId);
3277
+
2568
3278
  // Determine if this is a WalletConnect or Privy-signed quote
2569
3279
  const isWalletConnect = quoteData.signerType === 'walletconnect'
2570
3280
  || walletName === 'walletconnect' || walletName === 'wc';
@@ -2572,6 +3282,10 @@ EXAMPLES:
2572
3282
 
2573
3283
  let exported = null;
2574
3284
  let privyClient = null;
3285
+ // The wallet resolved before the per-quote loop, for the pre-signing
3286
+ // compliance screen below. Stays null for Privy, whose address is
3287
+ // fetched from the provider inside the loop.
3288
+ let signerAddress = null;
2575
3289
  if (isPrivy) {
2576
3290
  // Privy signing -- import + instantiate once for all quotes
2577
3291
  const { PrivyClient } = await import('./privy.js');
@@ -2604,6 +3318,13 @@ EXAMPLES:
2604
3318
  }
2605
3319
 
2606
3320
  exported = exportWallet(effectiveWalletName, password);
3321
+ signerAddress = chainType === 'solana' ? exported.solana?.address : exported.evm?.address;
3322
+ // A wallet file with no key for this chain can neither sign nor be
3323
+ // screened. Refuse here with the same actionable message the signing
3324
+ // branch gives, rather than a generic "cannot be screened".
3325
+ if (!signerAddress) {
3326
+ throw new Error(`Could not resolve the local wallet's ${chainType === 'solana' ? 'Solana' : 'EVM'} address; cannot confirm the quote was built for this wallet. Refusing to sign.`);
3327
+ }
2607
3328
  } else {
2608
3329
  // Verify WalletConnect session is still active, approved for this
2609
3330
  // chain, and its address matches the quote. Chain-scoped (see
@@ -2628,8 +3349,33 @@ EXAMPLES:
2628
3349
  : wcAddress.toLowerCase().trim() !== quoteWallet.toLowerCase().trim())) {
2629
3350
  throw new CommandError(`Connected wallet (${wcAddress}) doesn't match quote. Get a new quote with --wallet walletconnect`, 'WALLET_MISMATCH');
2630
3351
  }
3352
+ signerAddress = wcAddress;
2631
3353
  }
2632
3354
 
3355
+ // Compliance screen immediately before signing, mirroring `bridge
3356
+ // execute`: a quote stays valid for up to an hour and the signed
3357
+ // transaction is broadcast with no further check, so this is the last
3358
+ // gate before funds move. Every signing branch below refuses to sign
3359
+ // unless the wallet it resolves is `request.walletAddress`
3360
+ // (assertQuoteMatchesRequest), so that wallet — together with the
3361
+ // signer resolved above and any distinct destination wallet — is every
3362
+ // address this run can move funds from or to. Runs once, outside the
3363
+ // per-quote loop, so a refusal is final rather than "try next quote".
3364
+ // Throws SANCTIONED for a hit and SCREENING_UNAVAILABLE if the check
3365
+ // itself cannot complete; nothing is signed in either case.
3366
+ const screenAddresses = tradeScreeningAddresses(
3367
+ signerAddress,
3368
+ quoteData.request?.walletAddress,
3369
+ quoteData.request?.recipient,
3370
+ );
3371
+ if (!screenAddresses.length) {
3372
+ throw new CommandError(
3373
+ `Quote "${quoteId}" does not record which wallet it was built for, so it cannot be screened. Request a fresh quote with "nansen trade quote".`,
3374
+ 'SCREENING_UNAVAILABLE',
3375
+ );
3376
+ }
3377
+ await screenOrThrow(apiInstance, screenAddresses);
3378
+
2633
3379
  let lastQuoteError = null;
2634
3380
  // Swap targets confirmed to carry contract code in this execute run, so a
2635
3381
  // router shared across quotes is verified once, not per quote (see
@@ -2637,6 +3383,7 @@ EXAMPLES:
2637
3383
  const verifiedTargets = new Set();
2638
3384
 
2639
3385
  for (let qi = startIndex; qi < endIndex; qi++) {
3386
+ if (consentedCandidateIndexes && !consentedCandidateIndexes.has(qi)) continue;
2640
3387
  const currentQuote = allQuotes[qi];
2641
3388
  if (!currentQuote) continue;
2642
3389
 
@@ -2783,6 +3530,9 @@ EXAMPLES:
2783
3530
  }
2784
3531
  }
2785
3532
 
3533
+ // Refuse the swap's fee before any approval is paid for it.
3534
+ assertQuotedSwapFeeWithinCap(currentQuote, maxTxFeeWei);
3535
+
2786
3536
  // Handle approval if needed
2787
3537
  // Empty-string approvalAddress is Relay's "no approval needed" sentinel — skip.
2788
3538
  if (currentQuote.approvalAddress && currentQuote.approvalAddress !== '' && !isNative) {
@@ -2808,8 +3558,11 @@ EXAMPLES:
2808
3558
  }
2809
3559
  log(` ✓ Sufficient allowance exists for ${quoteName}, skipping approval`);
2810
3560
  } else {
2811
- const approvalMaxFee = currentQuote.transaction?.maxFeePerGas || currentQuote.transaction?.gasPrice || '1000000';
2812
- const approvalPriorityFee = currentQuote.transaction?.maxPriorityFeePerGas || '1000000';
3561
+ const { maxFeePerGas: approvalMaxFee, maxPriorityFeePerGas: approvalPriorityFee } =
3562
+ resolveQuoteEip1559Fees(currentQuote.transaction);
3563
+ // One check covers the revoke and the approval (same fee, same
3564
+ // gas limit); name whichever is sent first.
3565
+ assertEvmFeeWithinCap(approvalMaxFee, APPROVAL_GAS_LIMIT, shouldRevoke ? 'allowance revoke' : 'approval', maxTxFeeWei);
2813
3566
 
2814
3567
  if (shouldRevoke) {
2815
3568
  log(` ⚠ Existing allowance (${existingAllowance}) for ${quoteName} is excessive (>${OVERSIZED_ALLOWANCE_MULTIPLIER}x this trade) — revoking before re-approving`);
@@ -2821,7 +3574,7 @@ EXAMPLES:
2821
3574
  value: '0x0',
2822
3575
  chain_id: chainConfig.chainId,
2823
3576
  nonce: toHex(revokeNonce),
2824
- gas_limit: toHex(100000),
3577
+ gas_limit: toHex(APPROVAL_GAS_LIMIT),
2825
3578
  max_fee_per_gas: toHex(approvalMaxFee),
2826
3579
  max_priority_fee_per_gas: toHex(approvalPriorityFee),
2827
3580
  });
@@ -2874,7 +3627,7 @@ EXAMPLES:
2874
3627
  value: '0x0',
2875
3628
  chain_id: chainConfig.chainId,
2876
3629
  nonce: toHex(approvalNonce),
2877
- gas_limit: toHex(100000),
3630
+ gas_limit: toHex(APPROVAL_GAS_LIMIT),
2878
3631
  max_fee_per_gas: toHex(approvalMaxFee),
2879
3632
  max_priority_fee_per_gas: toHex(approvalPriorityFee),
2880
3633
  });
@@ -2942,7 +3695,7 @@ EXAMPLES:
2942
3695
  // cheap revert check above); degrades with a warning if no
2943
3696
  // simulation endpoint is available.
2944
3697
  if (!noVerifyOutcome) {
2945
- const outcome = await verifySwapOutcome({ chain, from: walletAddress, quote: currentQuote, quoteData, apiKey, log });
3698
+ const outcome = await verifySwapOutcome({ chain, from: walletAddress, quote: currentQuote, quoteData, api: apiInstance, log });
2946
3699
  if (!outcome.proceed) {
2947
3700
  log(` ❌ ${quoteName} failed swap-outcome verification: ${outcome.reason}`);
2948
3701
  if (qi + 1 < endIndex) log(` Trying next quote...`);
@@ -2959,8 +3712,9 @@ EXAMPLES:
2959
3712
  const nonce = await getEvmNonce(chain, walletAddress);
2960
3713
 
2961
3714
  // Privy signs EIP-1559 (type 2) transactions, so convert gasPrice to EIP-1559 fields
2962
- const maxFee = txData.maxFeePerGas || txData.gasPrice || '1000000';
2963
- const priorityFee = txData.maxPriorityFeePerGas || '1000000';
3715
+ const { maxFeePerGas: maxFee, maxPriorityFeePerGas: priorityFee } = resolveQuoteEip1559Fees(txData);
3716
+
3717
+ assertEvmFeeWithinCap(maxFee, finalGas, 'swap', maxTxFeeWei);
2964
3718
 
2965
3719
  log(' Signing EVM transaction via Privy...');
2966
3720
  const signResult = await privyClient.signEvmTransaction(evmWalletId, {
@@ -3041,6 +3795,7 @@ EXAMPLES:
3041
3795
  } catch (err) {
3042
3796
  throw new Error(`Failed to encode transaction for WalletConnect: ${err.message}`, { cause: err });
3043
3797
  }
3798
+ swapHandedOff = true;
3044
3799
  const wcResult = await sendSolanaTransactionViaWalletConnect(txBase58);
3045
3800
 
3046
3801
  if (wcResult.signedTransaction) {
@@ -3325,7 +4080,7 @@ EXAMPLES:
3325
4080
  // eth_call revert check above; degrades with a warning when no
3326
4081
  // simulation endpoint is set.
3327
4082
  if (!noVerifyOutcome) {
3328
- const outcome = await verifySwapOutcome({ chain, from: wcAddress, quote: currentQuote, quoteData, apiKey, log });
4083
+ const outcome = await verifySwapOutcome({ chain, from: wcAddress, quote: currentQuote, quoteData, api: apiInstance, log });
3329
4084
  if (!outcome.proceed) {
3330
4085
  log(` ❌ ${quoteName} failed swap-outcome verification: ${outcome.reason}`);
3331
4086
  if (qi + 1 < endIndex) log(` Trying next quote...`);
@@ -3341,6 +4096,7 @@ EXAMPLES:
3341
4096
  // Send transaction via WalletConnect
3342
4097
  log(' Sending transaction via WalletConnect...');
3343
4098
  let wcResult;
4099
+ swapHandedOff = true;
3344
4100
  try {
3345
4101
  wcResult = await sendTransactionViaWalletConnect({
3346
4102
  to: txData.to,
@@ -3489,6 +4245,9 @@ EXAMPLES:
3489
4245
  }
3490
4246
  }
3491
4247
 
4248
+ // Refuse the swap's fee before any approval is paid for it.
4249
+ assertQuotedSwapFeeWithinCap(currentQuote, maxTxFeeWei);
4250
+
3492
4251
  // Empty-string approvalAddress is Relay's "no approval needed" sentinel — skip.
3493
4252
  if (currentQuote.approvalAddress && currentQuote.approvalAddress !== '' && !isNative) {
3494
4253
  assertUsableSpender(currentQuote.approvalAddress);
@@ -3514,7 +4273,7 @@ EXAMPLES:
3514
4273
  }
3515
4274
  log(` ✓ Sufficient allowance exists for ${quoteName}, skipping approval`);
3516
4275
  } else {
3517
- const approvalGasPrice = currentQuote.transaction?.gasPrice || currentQuote.transaction?.maxFeePerGas || '1000000';
4276
+ const approvalGasPrice = resolveQuoteLegacyGasPrice(currentQuote.transaction);
3518
4277
 
3519
4278
  if (shouldRevoke) {
3520
4279
  log(` ⚠ Existing allowance (${existingAllowance}) for ${quoteName} is excessive (>${OVERSIZED_ALLOWANCE_MULTIPLIER}x this trade) — revoking before re-approving`);
@@ -3529,7 +4288,7 @@ EXAMPLES:
3529
4288
  approvalGasPrice,
3530
4289
  0n,
3531
4290
  undefined,
3532
- { allowZero: true },
4291
+ { allowZero: true, maxTxFeeWei },
3533
4292
  );
3534
4293
 
3535
4294
  const revokeResult = await executeTransaction({
@@ -3579,6 +4338,7 @@ EXAMPLES:
3579
4338
  approvalGasPrice,
3580
4339
  approveAmt,
3581
4340
  approvalCapForQuote(quoteData),
4341
+ { maxTxFeeWei },
3582
4342
  );
3583
4343
 
3584
4344
  const approvalResult = await executeTransaction({
@@ -3645,7 +4405,7 @@ EXAMPLES:
3645
4405
  // eth_call revert check above; degrades with a warning when no
3646
4406
  // simulation endpoint is set.
3647
4407
  if (!noVerifyOutcome) {
3648
- const outcome = await verifySwapOutcome({ chain, from: walletAddress, quote: currentQuote, quoteData, apiKey, log });
4408
+ const outcome = await verifySwapOutcome({ chain, from: walletAddress, quote: currentQuote, quoteData, api: apiInstance, log });
3649
4409
  if (!outcome.proceed) {
3650
4410
  log(` ❌ ${quoteName} failed swap-outcome verification: ${outcome.reason}`);
3651
4411
  if (qi + 1 < endIndex) log(` Trying next quote...`);
@@ -3670,7 +4430,8 @@ EXAMPLES:
3670
4430
  currentQuote.transaction,
3671
4431
  exported.evm.privateKey,
3672
4432
  chain,
3673
- nonce
4433
+ nonce,
4434
+ { maxTxFeeWei },
3674
4435
  );
3675
4436
  }
3676
4437
 
@@ -3721,6 +4482,7 @@ EXAMPLES:
3721
4482
  // can't be deduped at the node level and risks a second solve. For
3722
4483
  // gasless we therefore don't retry: a single POST either succeeds or
3723
4484
  // fails closed (BROADCAST_FAILED marks the quote spent and aborts).
4485
+ swapHandedOff = true;
3724
4486
  const result = await executeTransaction(execParams, { retries: gasless ? 0 : undefined });
3725
4487
 
3726
4488
  if (result.status === 'Success') {
@@ -3893,6 +4655,10 @@ EXAMPLES:
3893
4655
  let msg = `Error: ${err.message}`;
3894
4656
  if (err.details) msg += `\n Details: ${JSON.stringify(err.details)}`;
3895
4657
  throw new CommandError(msg, err.code || 'EXECUTE_ERROR');
4658
+ } finally {
4659
+ // Hands the quote back only if no swap left this process, or if one
4660
+ // did and its executedAt marker was recorded (see claimQuoteForExecution).
4661
+ if (quoteClaim) quoteClaim.release({ handedOff: swapHandedOff });
3896
4662
  }
3897
4663
  },
3898
4664