nansen-cli 1.46.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +157 -14
  3. package/docs/browser-login.md +123 -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 +8 -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 +5 -2
  35. package/skills/nansen-wallet-manager/SKILL.md +11 -9
  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 +202 -104
  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 +89 -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 +288 -0
  50. package/src/bridge.js +126 -21
  51. package/src/cache-inspect.js +345 -0
  52. package/src/cli.js +473 -199
  53. package/src/commands/agent.js +15 -7
  54. package/src/commands/completion.js +2 -15
  55. package/src/commands/mcp.js +20 -18
  56. package/src/cost-cache.js +16 -2
  57. package/src/debug.js +348 -0
  58. package/src/doctor.js +22 -45
  59. package/src/hl-action.js +41 -13
  60. package/src/limit-order.js +1 -1
  61. package/src/mcp-client-config.js +169 -0
  62. package/src/mcp-client-config.json +17 -0
  63. package/src/mcp-verify.js +6 -5
  64. package/src/perp.js +41 -0
  65. package/src/privy.js +12 -12
  66. package/src/response-meta.js +56 -1
  67. package/src/rpc-urls.js +9 -11
  68. package/src/schema.json +185 -8
  69. package/src/semver.js +23 -4
  70. package/src/swap-simulation.js +35 -30
  71. package/src/telemetry.js +20 -0
  72. package/src/trading.js +266 -29
  73. package/src/transfer.js +53 -6
  74. package/src/update-check.js +9 -1
  75. package/src/wallet.js +107 -17
  76. package/src/walletconnect-trading.js +24 -5
  77. package/src/x402-svm.js +123 -64
  78. package/src/x402.js +46 -14
package/src/trading.js CHANGED
@@ -22,7 +22,7 @@ export { readCompactU16 };
22
22
  import { CHAIN_RPCS } from './rpc-urls.js';
23
23
  import { simulateAssetChanges, SwapSimulationError, hasSimulationRpc } from './swap-simulation.js';
24
24
  import { simulateSolanaAssetChanges, SolanaSimulationError, hasSolanaSimulationRpc } from './solana-simulation.js';
25
- import { packageVersion, CommandError, telemetryHeaders, loadConfig } from './api.js';
25
+ import { packageVersion, CommandError, telemetryHeaders } from './api.js';
26
26
  import { screenOrThrow } from './perp.js';
27
27
 
28
28
  // ============= Constants =============
@@ -508,8 +508,14 @@ export function saveQuote(quoteResponse, chain, signerType = 'local', privyWalle
508
508
  export function loadQuote(quoteId) {
509
509
  const filePath = safeQuotesPath(`${quoteId}.json`);
510
510
  if (!filePath || !fs.existsSync(filePath)) {
511
+ const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
512
+ if (claimedPath && fs.existsSync(claimedPath)) throw quoteClaimedError(quoteId, claimedPath);
511
513
  throw new Error(`Quote "${quoteId}" not found. Quotes expire after 1 hour.`);
512
514
  }
515
+ return readQuoteFile(filePath, quoteId);
516
+ }
517
+
518
+ function readQuoteFile(filePath, quoteId) {
513
519
  const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
514
520
  if (Date.now() - data.timestamp > 3600000) {
515
521
  fs.unlinkSync(filePath);
@@ -535,13 +541,87 @@ export function loadQuote(quoteId) {
535
541
  return data;
536
542
  }
537
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
+
538
614
  // Records that a broadcast has happened. `executedAt` is set on the first call
539
615
  // and never moved, so the quote is consumed the instant the swap goes out — a
540
616
  // later receipt-wait timeout or a REVERTED/failed outcome must not leave the
541
617
  // quote reusable, since retrying would sign and broadcast a second,
542
618
  // independently valid swap. Mirrors markBridgeQuoteExecuted (bridge.js).
543
619
  export function markQuoteExecuted(quoteId, progress = {}) {
544
- 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`);
545
625
  if (!filePath || !fs.existsSync(filePath)) return;
546
626
  try {
547
627
  const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
@@ -766,11 +846,14 @@ export async function normalizeSolanaTransaction(transaction, rpcUrl, getExpecte
766
846
  * @param {string} privateKeyHex - 64-char hex (32-byte secp256k1 private key)
767
847
  * @param {string} chain - Chain name
768
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
769
852
  * @returns {string} 0x-prefixed signed transaction hex
770
853
  */
771
854
  // Pure EVM encode/sign primitive. Quote authorization and request-intent binding
772
855
  // happen upstream before this function receives transaction calldata.
773
- export function signEvmTransaction(txData, privateKeyHex, chain, nonce) {
856
+ export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { label = 'swap', maxTxFeeWei = MAX_EVM_TX_FEE_WEI } = {}) {
774
857
  const chainConfig = CHAIN_MAP[chain];
775
858
  if (!chainConfig || chainConfig.type !== 'evm') {
776
859
  throw new Error(`Unsupported EVM chain: ${chain}`);
@@ -786,6 +869,7 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce) {
786
869
  };
787
870
 
788
871
  if (txData.maxFeePerGas) {
872
+ assertEvmFeeWithinCap(txData.maxFeePerGas, common.gasLimit, label, maxTxFeeWei);
789
873
  return signEip1559Transaction({
790
874
  ...common,
791
875
  maxFeePerGas: toHex(txData.maxFeePerGas),
@@ -799,6 +883,7 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce) {
799
883
  // information at all is refused (see NO_QUOTE_FEE_MESSAGE).
800
884
  if (!txData.gasPrice) throw new Error(NO_QUOTE_FEE_MESSAGE);
801
885
 
886
+ assertEvmFeeWithinCap(txData.gasPrice, common.gasLimit, label, maxTxFeeWei);
802
887
  return signLegacyTransaction({ ...common, gasPrice: toHex(txData.gasPrice) }, privateKeyHex);
803
888
  }
804
889
 
@@ -813,6 +898,110 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce) {
813
898
  const NO_QUOTE_FEE_MESSAGE =
814
899
  'Quote supplied no gas price (expected gasPrice or maxFeePerGas), so any signed transaction would be unmineable. Refusing to sign.';
815
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) {
979
+ throw new Error(
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.`,
981
+ );
982
+ }
983
+ }
984
+
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
+
816
1005
  /**
817
1006
  * Resolve the fee fields for an EIP-1559 (type 2) signer from a quote's
818
1007
  * transaction. A legacy-only quote (gasPrice, no maxFeePerGas) is lifted into
@@ -1156,10 +1345,10 @@ function toRpcHexValue(value) {
1156
1345
  * @param {string} args.from - the wallet that will sign (the sender simulated)
1157
1346
  * @param {object} args.quote - the quote about to be executed (currentQuote)
1158
1347
  * @param {object} args.quoteData - the loaded quote record (.request, .slippage)
1159
- * @param {string|null} [args.apiKey] - Nansen API key for the hosted endpoint
1348
+ * @param {object} [args.api] - Selected Nansen API client for hosted simulation
1160
1349
  * @param {function} [args.log]
1161
1350
  */
1162
- export async function verifySwapOutcome({ chain, from, quote, quoteData, apiKey = null, log = () => {} }) {
1351
+ export async function verifySwapOutcome({ chain, from, quote, quoteData, api, log = () => {} }) {
1163
1352
  if (CHAIN_MAP[chain?.toLowerCase()]?.type !== 'evm') return { proceed: true }; // EVM-only
1164
1353
  // Cross-chain (bridge): the output token settles on the destination chain,
1165
1354
  // so the source-chain simulation still runs but assertSwapOutcome skips
@@ -1187,7 +1376,7 @@ export async function verifySwapOutcome({ chain, from, quote, quoteData, apiKey
1187
1376
  const sim = await simulateAssetChanges(
1188
1377
  chain,
1189
1378
  { to: tx.to, data: tx.data, value: toRpcHexValue(tx.value) },
1190
- { from, apiKey },
1379
+ { from, api },
1191
1380
  );
1192
1381
  // A cross-chain bridge may pay a fee in native ETH via msg.value on a
1193
1382
  // token-input route; that surfaces as a native sibling outflow which the
@@ -1305,7 +1494,7 @@ export async function resolveEvmSwapGasLimit(currentQuote, { chain, from }) {
1305
1494
  value: txData.value ? '0x' + BigInt(txData.value).toString(16) : '0x0',
1306
1495
  });
1307
1496
  if (estimated) finalGas = Math.ceil(estimated * 1.5);
1308
- if (finalGas === 0) finalGas = 210000;
1497
+ if (finalGas === 0) finalGas = FALLBACK_SWAP_GAS_LIMIT;
1309
1498
  }
1310
1499
  return finalGas;
1311
1500
  }
@@ -1645,19 +1834,21 @@ export function assertUsableSpender(spenderAddress) {
1645
1834
  * @param {bigint|string|number} [maxAllowance] - Hard cap from persisted request intent
1646
1835
  * @param {object} [opts]
1647
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
1648
1838
  * @returns {string} 0x-prefixed signed approval tx hex
1649
1839
  */
1650
1840
  // Approval signing is intentionally narrow: callers pass either the scoped swap
1651
1841
  // amount from approvalAmountForSwap or, for excessive-allowance cleanup, an
1652
1842
  // explicit allowZero revoke. encodeApproveCalldata validates the spender,
1653
1843
  // amount, optional request cap, and final ABI width before signing.
1654
- 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 } = {}) {
1655
1845
  const chainConfig = CHAIN_MAP[chain];
1656
1846
  if (!chainConfig) throw new Error(`Unsupported chain: ${chain}`);
1657
1847
 
1658
1848
  // An approval broadcast at a placeholder fee never mines and blocks the swap
1659
1849
  // behind it, so require a real gas price the same way signEvmTransaction does.
1660
1850
  if (!gasPrice) throw new Error(NO_QUOTE_FEE_MESSAGE);
1851
+ assertEvmFeeWithinCap(gasPrice, APPROVAL_GAS_LIMIT, allowZero ? 'allowance revoke' : 'approval', maxTxFeeWei);
1661
1852
 
1662
1853
  // Scope the approval to the swap's input amount so a malicious or buggy quote
1663
1854
  // can drain at most this one trade, never the wallet's full token balance.
@@ -1668,7 +1859,7 @@ export function buildApprovalTransaction(tokenAddress, spenderAddress, privateKe
1668
1859
  const tx = {
1669
1860
  nonce,
1670
1861
  gasPrice: toHex(gasPrice),
1671
- gasLimit: '0x186a0', // 100000
1862
+ gasLimit: toHex(APPROVAL_GAS_LIMIT),
1672
1863
  to: tokenAddress,
1673
1864
  value: '0x0',
1674
1865
  data,
@@ -2191,7 +2382,7 @@ async function preflightTradeExecutionCandidate({
2191
2382
  gasless,
2192
2383
  noSimulate,
2193
2384
  noVerifyOutcome,
2194
- apiKey,
2385
+ api,
2195
2386
  verifiedTargets,
2196
2387
  log,
2197
2388
  }) {
@@ -2327,7 +2518,7 @@ async function preflightTradeExecutionCandidate({
2327
2518
  from: walletAddress,
2328
2519
  quote,
2329
2520
  quoteData,
2330
- apiKey,
2521
+ api,
2331
2522
  log,
2332
2523
  });
2333
2524
  if (!outcome.proceed) {
@@ -2692,6 +2883,21 @@ CROSS-CHAIN NOTES (when using --to-chain):
2692
2883
  const fromWarning = getWrappedNativeFromWarning(from, chain);
2693
2884
  if (fromWarning) log(` ${fromWarning}`);
2694
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
+
2695
2901
  const params = {
2696
2902
  chainIndex: chainConfig.index,
2697
2903
  fromTokenAddress: from,
@@ -2867,17 +3073,14 @@ CROSS-CHAIN NOTES (when using --to-chain):
2867
3073
  const noRevokeExcessiveAllowance = flags['no-revoke-excessive-allowance'];
2868
3074
  const noVerifyOutcome = flags['no-verify-outcome'];
2869
3075
  const gasless = Boolean(flags.gasless);
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']);
2870
3083
  const guard = resolveExecuteGuard(flags, { env, isTTY });
2871
- // Read the API key for the swap-outcome sim endpoint. It's optional (the
2872
- // check degrades to a warning if the endpoint can't authenticate), so a
2873
- // malformed config must not crash an in-progress trade — fall back to null.
2874
- const apiKey = (() => {
2875
- try {
2876
- return loadConfig().apiKey;
2877
- } catch {
2878
- return null;
2879
- }
2880
- })();
2881
3084
 
2882
3085
  if (!quoteId) {
2883
3086
  throw new CommandError(`Usage: nansen trade execute --quote <quoteId> [options]
@@ -2894,6 +3097,8 @@ OPTIONS:
2894
3097
  --no-revoke-excessive-allowance
2895
3098
  Skip auto-revoking an oversized/legacy allowance before re-approving
2896
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.
2897
3102
  --dry-run Validate and print what would be sent, then stop.
2898
3103
  Nothing is signed or broadcast and the quote stays usable.
2899
3104
  --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1).
@@ -2910,6 +3115,11 @@ EXAMPLES:
2910
3115
  nansen trade execute --quote 1708900000000-abc123 --yes`, 'MISSING_ARGS');
2911
3116
  }
2912
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;
2913
3123
  try {
2914
3124
  const quoteData = loadQuote(quoteId);
2915
3125
  const chain = quoteData.chain;
@@ -2995,7 +3205,7 @@ EXAMPLES:
2995
3205
  gasless,
2996
3206
  noSimulate,
2997
3207
  noVerifyOutcome,
2998
- apiKey,
3208
+ api: apiInstance,
2999
3209
  verifiedTargets: verifiedPlanTargets,
3000
3210
  log,
3001
3211
  });
@@ -3058,6 +3268,13 @@ EXAMPLES:
3058
3268
  });
3059
3269
  if (!proceed) return undefined;
3060
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
+
3061
3278
  // Determine if this is a WalletConnect or Privy-signed quote
3062
3279
  const isWalletConnect = quoteData.signerType === 'walletconnect'
3063
3280
  || walletName === 'walletconnect' || walletName === 'wc';
@@ -3313,6 +3530,9 @@ EXAMPLES:
3313
3530
  }
3314
3531
  }
3315
3532
 
3533
+ // Refuse the swap's fee before any approval is paid for it.
3534
+ assertQuotedSwapFeeWithinCap(currentQuote, maxTxFeeWei);
3535
+
3316
3536
  // Handle approval if needed
3317
3537
  // Empty-string approvalAddress is Relay's "no approval needed" sentinel — skip.
3318
3538
  if (currentQuote.approvalAddress && currentQuote.approvalAddress !== '' && !isNative) {
@@ -3340,6 +3560,9 @@ EXAMPLES:
3340
3560
  } else {
3341
3561
  const { maxFeePerGas: approvalMaxFee, maxPriorityFeePerGas: approvalPriorityFee } =
3342
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);
3343
3566
 
3344
3567
  if (shouldRevoke) {
3345
3568
  log(` ⚠ Existing allowance (${existingAllowance}) for ${quoteName} is excessive (>${OVERSIZED_ALLOWANCE_MULTIPLIER}x this trade) — revoking before re-approving`);
@@ -3351,7 +3574,7 @@ EXAMPLES:
3351
3574
  value: '0x0',
3352
3575
  chain_id: chainConfig.chainId,
3353
3576
  nonce: toHex(revokeNonce),
3354
- gas_limit: toHex(100000),
3577
+ gas_limit: toHex(APPROVAL_GAS_LIMIT),
3355
3578
  max_fee_per_gas: toHex(approvalMaxFee),
3356
3579
  max_priority_fee_per_gas: toHex(approvalPriorityFee),
3357
3580
  });
@@ -3404,7 +3627,7 @@ EXAMPLES:
3404
3627
  value: '0x0',
3405
3628
  chain_id: chainConfig.chainId,
3406
3629
  nonce: toHex(approvalNonce),
3407
- gas_limit: toHex(100000),
3630
+ gas_limit: toHex(APPROVAL_GAS_LIMIT),
3408
3631
  max_fee_per_gas: toHex(approvalMaxFee),
3409
3632
  max_priority_fee_per_gas: toHex(approvalPriorityFee),
3410
3633
  });
@@ -3472,7 +3695,7 @@ EXAMPLES:
3472
3695
  // cheap revert check above); degrades with a warning if no
3473
3696
  // simulation endpoint is available.
3474
3697
  if (!noVerifyOutcome) {
3475
- 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 });
3476
3699
  if (!outcome.proceed) {
3477
3700
  log(` ❌ ${quoteName} failed swap-outcome verification: ${outcome.reason}`);
3478
3701
  if (qi + 1 < endIndex) log(` Trying next quote...`);
@@ -3491,6 +3714,8 @@ EXAMPLES:
3491
3714
  // Privy signs EIP-1559 (type 2) transactions, so convert gasPrice to EIP-1559 fields
3492
3715
  const { maxFeePerGas: maxFee, maxPriorityFeePerGas: priorityFee } = resolveQuoteEip1559Fees(txData);
3493
3716
 
3717
+ assertEvmFeeWithinCap(maxFee, finalGas, 'swap', maxTxFeeWei);
3718
+
3494
3719
  log(' Signing EVM transaction via Privy...');
3495
3720
  const signResult = await privyClient.signEvmTransaction(evmWalletId, {
3496
3721
  to: txData.to,
@@ -3570,6 +3795,7 @@ EXAMPLES:
3570
3795
  } catch (err) {
3571
3796
  throw new Error(`Failed to encode transaction for WalletConnect: ${err.message}`, { cause: err });
3572
3797
  }
3798
+ swapHandedOff = true;
3573
3799
  const wcResult = await sendSolanaTransactionViaWalletConnect(txBase58);
3574
3800
 
3575
3801
  if (wcResult.signedTransaction) {
@@ -3854,7 +4080,7 @@ EXAMPLES:
3854
4080
  // eth_call revert check above; degrades with a warning when no
3855
4081
  // simulation endpoint is set.
3856
4082
  if (!noVerifyOutcome) {
3857
- 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 });
3858
4084
  if (!outcome.proceed) {
3859
4085
  log(` ❌ ${quoteName} failed swap-outcome verification: ${outcome.reason}`);
3860
4086
  if (qi + 1 < endIndex) log(` Trying next quote...`);
@@ -3870,6 +4096,7 @@ EXAMPLES:
3870
4096
  // Send transaction via WalletConnect
3871
4097
  log(' Sending transaction via WalletConnect...');
3872
4098
  let wcResult;
4099
+ swapHandedOff = true;
3873
4100
  try {
3874
4101
  wcResult = await sendTransactionViaWalletConnect({
3875
4102
  to: txData.to,
@@ -4018,6 +4245,9 @@ EXAMPLES:
4018
4245
  }
4019
4246
  }
4020
4247
 
4248
+ // Refuse the swap's fee before any approval is paid for it.
4249
+ assertQuotedSwapFeeWithinCap(currentQuote, maxTxFeeWei);
4250
+
4021
4251
  // Empty-string approvalAddress is Relay's "no approval needed" sentinel — skip.
4022
4252
  if (currentQuote.approvalAddress && currentQuote.approvalAddress !== '' && !isNative) {
4023
4253
  assertUsableSpender(currentQuote.approvalAddress);
@@ -4058,7 +4288,7 @@ EXAMPLES:
4058
4288
  approvalGasPrice,
4059
4289
  0n,
4060
4290
  undefined,
4061
- { allowZero: true },
4291
+ { allowZero: true, maxTxFeeWei },
4062
4292
  );
4063
4293
 
4064
4294
  const revokeResult = await executeTransaction({
@@ -4108,6 +4338,7 @@ EXAMPLES:
4108
4338
  approvalGasPrice,
4109
4339
  approveAmt,
4110
4340
  approvalCapForQuote(quoteData),
4341
+ { maxTxFeeWei },
4111
4342
  );
4112
4343
 
4113
4344
  const approvalResult = await executeTransaction({
@@ -4174,7 +4405,7 @@ EXAMPLES:
4174
4405
  // eth_call revert check above; degrades with a warning when no
4175
4406
  // simulation endpoint is set.
4176
4407
  if (!noVerifyOutcome) {
4177
- 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 });
4178
4409
  if (!outcome.proceed) {
4179
4410
  log(` ❌ ${quoteName} failed swap-outcome verification: ${outcome.reason}`);
4180
4411
  if (qi + 1 < endIndex) log(` Trying next quote...`);
@@ -4199,7 +4430,8 @@ EXAMPLES:
4199
4430
  currentQuote.transaction,
4200
4431
  exported.evm.privateKey,
4201
4432
  chain,
4202
- nonce
4433
+ nonce,
4434
+ { maxTxFeeWei },
4203
4435
  );
4204
4436
  }
4205
4437
 
@@ -4250,6 +4482,7 @@ EXAMPLES:
4250
4482
  // can't be deduped at the node level and risks a second solve. For
4251
4483
  // gasless we therefore don't retry: a single POST either succeeds or
4252
4484
  // fails closed (BROADCAST_FAILED marks the quote spent and aborts).
4485
+ swapHandedOff = true;
4253
4486
  const result = await executeTransaction(execParams, { retries: gasless ? 0 : undefined });
4254
4487
 
4255
4488
  if (result.status === 'Success') {
@@ -4422,6 +4655,10 @@ EXAMPLES:
4422
4655
  let msg = `Error: ${err.message}`;
4423
4656
  if (err.details) msg += `\n Details: ${JSON.stringify(err.details)}`;
4424
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 });
4425
4662
  }
4426
4663
  },
4427
4664
 
package/src/transfer.js CHANGED
@@ -87,17 +87,47 @@ async function rpcCall(url, method, params = []) {
87
87
  body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
88
88
  });
89
89
  const data = await response.json();
90
- if (data.error) throw new Error(friendlyRpcError(data.error));
90
+ if (data.error) {
91
+ const err = new Error(friendlyRpcError(data.error, method));
92
+ // Classified from the raw RPC text, before any rewording, so callers can
93
+ // branch on it without depending on the friendly message's wording.
94
+ err.transactionWouldFail = isTransactionFailureMessage(data.error);
95
+ throw err;
96
+ }
91
97
  return data.result;
92
98
  }
93
99
 
100
+ /**
101
+ * True when an RPC error says the transaction itself cannot succeed
102
+ * (insufficient funds, execution reverted), as opposed to the node failing
103
+ * to answer.
104
+ */
105
+ function isTransactionFailureMessage(error) {
106
+ const lower = String(error?.message || JSON.stringify(error)).toLowerCase();
107
+ return lower.includes('insufficient funds')
108
+ || lower.includes('insufficient lamports')
109
+ // geth/op-geth phrase every EVM revert as "execution reverted[: reason]";
110
+ // a bare "reverted" would also catch unrelated wording.
111
+ || lower.includes('execution reverted');
112
+ }
113
+
94
114
  /**
95
115
  * Convert raw RPC errors into actionable messages.
116
+ *
117
+ * rpcCall serves both rails, so the method name decides which chain's advice
118
+ * applies: EVM JSON-RPC methods are `eth_*`, Solana's are bare camelCase.
119
+ * geth rejects an underfunded transaction with "insufficient funds for gas *
120
+ * price + value", which used to match the Solana branch and tell a Base or
121
+ * Ethereum user to top up SOL.
96
122
  */
97
- function friendlyRpcError(error) {
123
+ function friendlyRpcError(error, method = '') {
98
124
  const msg = error.message || JSON.stringify(error);
99
125
  const lower = msg.toLowerCase();
126
+ const isEvm = typeof method === 'string' && method.toLowerCase().startsWith('eth_');
100
127
 
128
+ if (isEvm && lower.includes('insufficient funds')) {
129
+ return `Insufficient native balance to cover gas and value for this transaction. Top up the wallet with the chain's native gas token (ETH on most EVM chains). RPC said: ${msg}`;
130
+ }
101
131
  if (lower.includes('no record of a prior credit') || lower.includes('accountnotfound')) {
102
132
  return 'Insufficient SOL for transaction fees. Send at least 0.01 SOL to your wallet.';
103
133
  }
@@ -118,6 +148,17 @@ function friendlyRpcError(error) {
118
148
  }
119
149
 
120
150
 
151
+ /**
152
+ * eth_estimateGas fails for two very different reasons: the node could not run
153
+ * the estimate (transient — fall back to a default gas limit), or it ran the
154
+ * call and the transaction cannot succeed (insufficient funds, execution
155
+ * reverted). Broadcasting the second kind with a default gas limit only burns
156
+ * gas on a transaction the node already said will fail, so let it propagate.
157
+ */
158
+ function isDoomedTransactionError(err) {
159
+ return err?.transactionWouldFail === true;
160
+ }
161
+
121
162
  function bigIntToHex(n) {
122
163
  if (n === 0n) return '0x';
123
164
  const hex = n.toString(16);
@@ -214,7 +255,10 @@ async function buildEvmTransaction({ to, amount, token, privateKey, chain, max =
214
255
  { from, to, value: '0x1' },
215
256
  ]);
216
257
  estGasLimit = BigInt(dummyEstimate) * 120n / 100n;
217
- } catch {
258
+ } catch (err) {
259
+ // A node that rejects even a 1-wei transfer to this recipient is
260
+ // telling us the send cannot succeed; do not paper over it.
261
+ if (isDoomedTransactionError(err)) throw err;
218
262
  estGasLimit = 21000n;
219
263
  }
220
264
  // Reserve: L2 gas (gasLimit * maxFee) + L1 data fee buffer
@@ -242,7 +286,8 @@ async function buildEvmTransaction({ to, amount, token, privateKey, chain, max =
242
286
  const gasEstimate = await rpcCall(rpcUrl, 'eth_estimateGas', [estimateParams]);
243
287
  // Add 20% buffer for safety
244
288
  gasLimit = BigInt(gasEstimate) * 120n / 100n;
245
- } catch {
289
+ } catch (err) {
290
+ if (isDoomedTransactionError(err)) throw err;
246
291
  // Fallback to safe defaults if estimation fails
247
292
  gasLimit = token ? 100000n : 21000n;
248
293
  }
@@ -896,7 +941,8 @@ async function sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRu
896
941
  { from: wcAddress, to, value: '0x1' },
897
942
  ]);
898
943
  estGasLimit = BigInt(dummyEstimate) * 120n / 100n;
899
- } catch {
944
+ } catch (err) {
945
+ if (isDoomedTransactionError(err)) throw err;
900
946
  estGasLimit = 21000n;
901
947
  }
902
948
  const feeHistory = await rpcCall(rpcUrl, 'eth_feeHistory', [4, 'latest', [50]]);
@@ -930,7 +976,8 @@ async function sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRu
930
976
  if (txValue && txValue !== '0') estimateParams.value = '0x' + BigInt(txValue).toString(16);
931
977
  const gasEstimate = await rpcCall(rpcUrl, 'eth_estimateGas', [estimateParams]);
932
978
  gasLimit = (BigInt(gasEstimate) * 120n / 100n).toString(); // 20% buffer
933
- } catch {
979
+ } catch (err) {
980
+ if (isDoomedTransactionError(err)) throw err;
934
981
  gasLimit = token ? '100000' : '21000'; // fallback
935
982
  }
936
983