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/bridge.js CHANGED
@@ -13,15 +13,18 @@ import * as path from 'node:path';
13
13
  import { CommandError, validateAddress } from './api.js';
14
14
  import { signSecp256k1 } from './crypto.js';
15
15
  import {
16
+ assertEvmFeeWithinCap,
16
17
  convertToBaseUnits,
17
18
  evmRpcCall,
18
19
  getEvmNonce,
19
20
  getQuotesDir,
21
+ parseMaxTxFeeOption,
20
22
  resolveUsdPrice,
21
23
  safeQuotesPath,
22
24
  signEvmTransaction,
23
25
  waitForReceipt,
24
26
  } from './trading.js';
27
+ import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
25
28
  import { screenOrThrow } from './perp.js';
26
29
  import { extractActionErrors } from './hl-client.js';
27
30
  import { encodeApproveCalldata } from './trade-validation.js';
@@ -706,12 +709,16 @@ const ERC20_APPROVE_SELECTOR = '0x095ea7b3';
706
709
  // Keyed by origin chain, in lockstep with the deposit rows of BRIDGE_ROUTES:
707
710
  // widening the EVM deposit side (a new signable origin chain) MUST add that
708
711
  // chain's router here too, or every deposit on the new route fails closed.
709
- const BRIDGE_DEPOSIT_TARGETS = {
712
+ // Exported for a CI guard test that pins every entry to a valid, lowercased
713
+ // 20-byte address — see the invariant note in assertEvmBridgeStepIntent's
714
+ // approve branch (a malformed entry would mis-code a spender-shape error as
715
+ // AMOUNT_MISMATCH, and a non-lowercased one would break the `.has()` lookups).
716
+ export const BRIDGE_DEPOSIT_TARGETS = {
710
717
  base: new Set(['0x4cd00e387622c35bddb9b4c962c136462338bc31']),
711
718
  };
712
719
 
713
720
  // The deposit call selector on that router. Its calldata is a fixed 4-arg ABI
714
- // layout: deposit(address depositor, address token, uint256 amount, bytes32 id).
721
+ // layout: depositErc20(address depositor, address token, uint256 amount, bytes32 id).
715
722
  const BRIDGE_DEPOSIT_SELECTOR = '0xe8017952';
716
723
 
717
724
  // True when calldata is an ERC-20 approve(spender, amount). 0x + 4-byte
@@ -757,14 +764,33 @@ function decodeBridgeDeposit(data) {
757
764
  // than a raw SyntaxError.
758
765
  return null;
759
766
  }
767
+ const idWord = w(3);
768
+ if (!/^[0-9a-fA-F]{64}$/.test(idWord)) return null;
760
769
  return {
761
770
  depositor: '0x' + w(0).slice(24), // last 20 bytes of word 0
762
771
  token: '0x' + w(1).slice(24),
763
772
  amount,
764
- // w(3) is the opaque relay id — intentionally not returned / not bound.
773
+ id: idWord, // opaque relay id word (bytes32), normalized on re-encode
765
774
  };
766
775
  }
767
776
 
777
+ // Re-encode accepted deposit calldata from decoded fields. Normalizes any dirty
778
+ // upper bits in address words (the decoded last-20-bytes are clean; padding them
779
+ // fresh means the output is canonical regardless of the input's upper bits).
780
+ // The relay id word is opaque — lowercased to canonical form; its value is
781
+ // preserved (a bytes32 is binary, so case carries no meaning on-chain).
782
+ // decodeBridgeDeposit already guarantees id is exactly 64 hex chars (it returns
783
+ // null unless data.length === 266 and the id word matches /^[0-9a-fA-F]{64}$/),
784
+ // so the padStart below is a no-op today — kept for symmetry with the other
785
+ // words and to stay correct if that invariant is ever loosened.
786
+ function encodeBridgeDeposit({ depositor, token, amount, id }) {
787
+ return BRIDGE_DEPOSIT_SELECTOR
788
+ + depositor.slice(2).toLowerCase().padStart(64, '0')
789
+ + token.slice(2).toLowerCase().padStart(64, '0')
790
+ + amount.toString(16).padStart(64, '0')
791
+ + id.toLowerCase().padStart(64, '0');
792
+ }
793
+
768
794
  // Bind a server-supplied EVM bridge transaction to the user's intent before
769
795
  // signing. Static only, no RPC. Fails CLOSED — a missing anchor or an
770
796
  // unrecognized target is itself the signal to refuse.
@@ -787,12 +813,21 @@ function requireAmountAnchor(intent, context) {
787
813
  'AMOUNT_MISMATCH',
788
814
  );
789
815
  }
816
+ try {
817
+ return BigInt(intent.requestedAmountBaseUnits);
818
+ } catch {
819
+ throw new CommandError(
820
+ `${context}: reviewed amount ${intent.requestedAmountBaseUnits} is not a valid integer. Refusing to sign. Request a new quote.`,
821
+ 'AMOUNT_MISMATCH',
822
+ );
823
+ }
790
824
  }
791
825
 
792
826
  // Returns { data } — for an approve step, `data` is RE-ENCODED via
793
827
  // encodeApproveCalldata (rejects MAX_UINT256, caps to requestedAmountBaseUnits,
794
- // re-validates the spender width). For a deposit step, `data` is returned
795
- // unchanged after the to/selector allowlist AND the decoded-arg binding pass.
828
+ // re-validates the spender width). For a deposit step, `data` is the canonical
829
+ // re-encoding from encodeBridgeDeposit after the to/selector allowlist AND the
830
+ // decoded-arg binding pass (normalizes dirty upper bits in address words).
796
831
  export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM step') {
797
832
  if (!txData || typeof txData !== 'object' || typeof txData.data !== 'string') {
798
833
  throw new CommandError(`${context}: no transaction data to verify. Request a new quote.`, 'INVALID_INPUT');
@@ -844,7 +879,6 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
844
879
 
845
880
  // AC1: ERC-20 approve → re-scope through the hardened encoder.
846
881
  if (isErc20Approve(txData.data)) {
847
- requireAmountAnchor(intent, context);
848
882
  // The approve call itself must target the origin chain's USDC contract —
849
883
  // otherwise a spender/amount that both look legitimate could still grant
850
884
  // the router an allowance over an unrelated token the wallet holds.
@@ -871,12 +905,30 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
871
905
  'UNEXPECTED_ACTION',
872
906
  );
873
907
  }
874
- // encodeApproveCalldata rejects >= MAX_UINT256 and amount > maxAllowance,
875
- // and re-validates the 20-byte spender width. Cap to the requested input.
876
- const scoped = encodeApproveCalldata(spender, amount, {
877
- maxAllowance: BigInt(intent.requestedAmountBaseUnits),
878
- });
879
- return { data: scoped };
908
+ // Cap to the requested input. The only errors encodeApproveCalldata can
909
+ // throw here are amount-related (zero, unlimited, over-cap): the spender is
910
+ // already validated against BRIDGE_DEPOSIT_TARGETS above, and amount was
911
+ // already parsed as a BigInt by decodeErc20Approve — so AMOUNT_MISMATCH is
912
+ // the correct code for everything that can actually reach the catch.
913
+ // NB: this rests on every BRIDGE_DEPOSIT_TARGETS entry being a valid 20-byte
914
+ // address. If one were ever a zero/malformed address, encodeApproveCalldata's
915
+ // assertValidApprovalSpender would throw a spender-shape error that this catch
916
+ // would mis-code as AMOUNT_MISMATCH — keep that constant's entries valid.
917
+ const maxAllowance = requireAmountAnchor(intent, context);
918
+ try {
919
+ const scoped = encodeApproveCalldata(spender, amount, { maxAllowance });
920
+ return { data: scoped };
921
+ } catch (err) {
922
+ // encodeApproveCalldata messages already end with their own imperative
923
+ // ("Refusing to sign[ an … approval].") — drop it so we don't stack two
924
+ // directives before appending the single actionable next step every
925
+ // sibling refusal ends with.
926
+ const reason = err.message.replace(/\s*Refusing to sign[^.]*\.\s*$/, '');
927
+ throw new CommandError(
928
+ `${context}: ${reason} Request a new quote.`,
929
+ 'AMOUNT_MISMATCH',
930
+ );
931
+ }
880
932
  }
881
933
 
882
934
  // AC2: deposit call → to + selector must both be on the route's allowlist.
@@ -924,8 +976,14 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
924
976
  }
925
977
  // arg2 (amount) must not exceed what the user requested (defense in depth —
926
978
  // the scoped approval already bounds the pull; captures show exact equality).
927
- requireAmountAnchor(intent, context);
928
- if (dep.amount > BigInt(intent.requestedAmountBaseUnits)) {
979
+ if (dep.amount <= 0n) {
980
+ throw new CommandError(
981
+ context + ' would deposit ' + dep.amount + '; deposit amount must be positive. Refusing to sign. Request a new quote.',
982
+ 'AMOUNT_MISMATCH',
983
+ );
984
+ }
985
+ const requestedAmount = requireAmountAnchor(intent, context);
986
+ if (dep.amount > requestedAmount) {
929
987
  throw new CommandError(
930
988
  `${context} would deposit ${dep.amount}, more than the ${intent.requestedAmountBaseUnits} base units you requested. `
931
989
  + `Refusing to sign. Request a new quote.`,
@@ -936,7 +994,7 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
936
994
  // appears on-chain — both are the accepted relayer-trust residual, bounded by
937
995
  // the checks above.
938
996
 
939
- return { data: txData.data };
997
+ return { data: encodeBridgeDeposit(dep) };
940
998
  }
941
999
 
942
1000
  // Validate every EVM step's calldata against intent BEFORE any step is signed
@@ -960,14 +1018,26 @@ export function assertEvmBridgeStepIntent(txData, intent, context = 'Bridge EVM
960
1018
  export function preflightEvmBridgeSteps(steps, intent) {
961
1019
  let approveCount = 0;
962
1020
  let depositCount = 0;
1021
+ let sawDeposit = false;
963
1022
  for (const step of steps) {
964
1023
  for (const item of step.items || []) {
965
1024
  if (item.status === 'complete') continue; // don't re-check / re-count resumed steps
966
1025
  assertEvmBridgeStepIntent(item.data, intent, `Bridge step "${step.id}"`);
967
1026
  // assertEvmBridgeStepIntent above already proved each item is exactly one
968
1027
  // of these two shapes, so this classification is total.
969
- if (isErc20Approve(item.data.data)) approveCount++;
970
- else depositCount++;
1028
+ if (isErc20Approve(item.data.data)) {
1029
+ if (sawDeposit) {
1030
+ throw new CommandError(
1031
+ `Bridge plan has an incomplete approve transaction after the deposit; every incomplete approve must precede the deposit. `
1032
+ + `Refusing to sign — a trailing approve could leave a live router allowance after the deposit is already consumed. Request a new quote.`,
1033
+ 'UNEXPECTED_ACTION',
1034
+ );
1035
+ }
1036
+ approveCount++;
1037
+ } else {
1038
+ sawDeposit = true;
1039
+ depositCount++;
1040
+ }
971
1041
  }
972
1042
  }
973
1043
  if (approveCount > 1 || depositCount !== 1) {
@@ -1161,6 +1231,7 @@ async function processEvmStep(step, { chain, privateKeyHex, signerAddress, log,
1161
1231
  privateKeyHex,
1162
1232
  chain,
1163
1233
  nonce,
1234
+ { label: `bridge step "${step.id}"`, maxTxFeeWei: feeOverrides?.maxTxFeeWei },
1164
1235
  );
1165
1236
 
1166
1237
  log(` Broadcasting ${step.id} on ${chain}...`);
@@ -1456,6 +1527,23 @@ function resolveWalletAddress(walletName) {
1456
1527
  return resolveEvmWallet(walletName, 'Bridging');
1457
1528
  }
1458
1529
 
1530
+ // Bridge quote files persist the address used to build the transaction at this
1531
+ // exact top-level field (see saveBridgeQuote). A dry run can safely use that
1532
+ // public address for screening and transaction preflight without requiring a
1533
+ // configured local wallet, but only after checking it is actually an EVM
1534
+ // address. Missing legacy data falls back to normal wallet resolution.
1535
+ function validateQuotedWalletAddress(quoteId, walletAddress) {
1536
+ if (walletAddress == null || walletAddress === '') return null;
1537
+ const { valid, error } = validateAddress(walletAddress, 'ethereum');
1538
+ if (!valid) {
1539
+ throw new CommandError(
1540
+ `Quote "${quoteId}" is malformed: walletAddress is invalid. ${error} Request a fresh quote with "nansen bridge quote".`,
1541
+ 'INVALID_INPUT',
1542
+ );
1543
+ }
1544
+ return walletAddress.trim();
1545
+ }
1546
+
1459
1547
  // Destination address for --recipient. Validated against the EVM pattern rather
1460
1548
  // than the destination chain's own rules: every supported destination
1461
1549
  // (base/ethereum/arbitrum/hyperliquid) takes an EVM address, and passing
@@ -1495,8 +1583,48 @@ function parseBridgeAmount(raw, amountUnit) {
1495
1583
 
1496
1584
  // ── Command builder ──────────────────────────────────────────────────
1497
1585
 
1586
+ /**
1587
+ * Describe the transfer `bridge execute` is about to sign, for the
1588
+ * confirmation prompt and for --dry-run. Built entirely from the cached quote
1589
+ * and the resolved signer — it touches no wallet material.
1590
+ */
1591
+ export function buildBridgeExecutionPlan({ quoteId, quoteData, signerAddress, overrides }) {
1592
+ const response = quoteData.response || {};
1593
+ const details = response.details || {};
1594
+ const currencyIn = details.currencyIn || {};
1595
+ const currencyOut = details.currencyOut || {};
1596
+ const relayerFee = response.fees?.relayer || {};
1597
+ const steps = response.steps || [];
1598
+ const sendAmount = currencyIn.amountFormatted
1599
+ || (quoteData.requestedAmountBaseUnits != null ? `${quoteData.requestedAmountBaseUnits} base units` : null);
1600
+ // Keep malformed seam inputs out of user-facing plans. formatPlan omits null
1601
+ // rows, but a template literal would otherwise turn an absent signer into a
1602
+ // visible `undefined (same address)` recipient.
1603
+ const planSignerAddress = signerAddress || null;
1604
+
1605
+ return formatPlan(`Bridge plan — ${quoteData.originChain} → ${quoteData.destinationChain}`, [
1606
+ ['Quote', quoteId],
1607
+ ['Type', response.execution_type],
1608
+ ['Send', [sendAmount, currencyIn.currency?.symbol].filter(Boolean).join(' ') || null],
1609
+ ['Receive', currencyOut.amountFormatted ? `~${[currencyOut.amountFormatted, currencyOut.currency?.symbol].filter(Boolean).join(' ')}` : null],
1610
+ ['Fee', relayerFee.amountUsd ? `$${relayerFee.amountUsd}` : null],
1611
+ ['Wallet', planSignerAddress],
1612
+ ['Recipient', quoteData.recipient || (planSignerAddress ? `${planSignerAddress} (same address)` : null)],
1613
+ ['Steps', steps.map(s => `${s.id} (${s.kind})`).join(', ') || null],
1614
+ ['Overrides', overrides || null],
1615
+ ]);
1616
+ }
1617
+
1498
1618
  export function buildBridgeCommands(deps = {}) {
1499
- const { log = console.log } = deps;
1619
+ const {
1620
+ log = console.log,
1621
+ // Injected so the confirmation prompt (and whether there is anyone to
1622
+ // answer it) can be driven in tests without a terminal.
1623
+ promptFn,
1624
+ confirmationLog = log,
1625
+ isTTY = false,
1626
+ env = process.env,
1627
+ } = deps;
1500
1628
 
1501
1629
  return {
1502
1630
  'quote': async (args, apiInstance, flags, options) => {
@@ -1558,6 +1686,17 @@ OPTIONS:
1558
1686
  ? resolveBridgeToken(toTokenRaw, destinationChain)
1559
1687
  : resolveBridgeToken('USDC', destinationChain);
1560
1688
 
1689
+ if (
1690
+ originChain === 'base'
1691
+ && destinationChain === 'hyperliquid'
1692
+ && !isBridgeUsdc(originToken, originChain)
1693
+ ) {
1694
+ throw new CommandError(
1695
+ 'Base -> Hyperliquid bridge deposits currently support USDC only. Use --from-token USDC.',
1696
+ 'INVALID_INPUT',
1697
+ );
1698
+ }
1699
+
1561
1700
  const wallet = resolveWalletAddress(walletName);
1562
1701
 
1563
1702
  // Default: --amount is base units. With --amount-unit, accept a human token
@@ -1660,6 +1799,7 @@ OPTIONS:
1660
1799
  'execute': async (args, apiInstance, flags, options) => {
1661
1800
  const quoteId = options.quote || args[0];
1662
1801
  const walletName = options.wallet;
1802
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
1663
1803
 
1664
1804
  if (!quoteId) {
1665
1805
  throw new CommandError(
@@ -1667,10 +1807,23 @@ OPTIONS:
1667
1807
 
1668
1808
  Execute a cached bridge quote. Signs transactions and broadcasts them.
1669
1809
 
1810
+ OPTIONS:
1811
+ --dry-run Validate and print what would be signed, then stop. Nothing is
1812
+ broadcast and the quote stays usable.
1813
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt
1814
+ only appears when stdin is a terminal; agents, CI and pipes are
1815
+ never prompted, with or without --yes.
1816
+
1817
+ EXIT CODES:
1818
+ 0 the transfer was submitted, or the dry run completed
1819
+ 1 declined at the confirmation prompt, or the execution failed
1820
+
1670
1821
  RECOVERY OPTIONS (EVM deposit legs only):
1671
1822
  --priority-fee Priority fee in gwei, overriding the quoted one
1672
1823
  --max-fee Fee cap in gwei, overriding the computed one
1673
1824
  --nonce Sign at this nonce instead of the next one
1825
+ --max-tx-fee Most one transaction may pay for gas (fee cap x gas limit),
1826
+ in ETH. Default 1; 0 disables the check.
1674
1827
 
1675
1828
  Use these to replace a transaction that is stuck in the mempool: a replacement
1676
1829
  must reuse the stuck nonce and outbid it (roughly +10%), and the fees computed
@@ -1685,6 +1838,11 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1685
1838
  // Fee/nonce overrides. Parsed before the quote is touched so a typo can't
1686
1839
  // consume it, and only applied to EVM legs — an HL withdrawal signs an
1687
1840
  // action with no fee fields at all.
1841
+ // A bare --max-tx-fee lands in flags, not options, so it would otherwise
1842
+ // read as "not given" and silently apply the default cap.
1843
+ if (flags['max-tx-fee']) {
1844
+ throw new CommandError('--max-tx-fee requires a value in ETH (e.g. 0.5), or 0 for no cap.', 'INVALID_INPUT');
1845
+ }
1688
1846
  const feeOverrides = {
1689
1847
  priorityFeeWei: options['priority-fee'] !== undefined
1690
1848
  ? parseGweiToWei(options['priority-fee'], 'priority-fee')
@@ -1692,6 +1850,7 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1692
1850
  maxFeeWei: options['max-fee'] !== undefined
1693
1851
  ? parseGweiToWei(options['max-fee'], 'max-fee')
1694
1852
  : null,
1853
+ maxTxFeeWei: parseMaxTxFeeOption(options['max-tx-fee']),
1695
1854
  };
1696
1855
  let nonceSequence = null;
1697
1856
  if (options.nonce !== undefined) {
@@ -1707,6 +1866,14 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1707
1866
  nonceSequence = { next: parseInt(s, 10) };
1708
1867
  }
1709
1868
 
1869
+ // One rendering of the overrides — shown in the execution plan, and
1870
+ // again when the EVM leg actually applies them.
1871
+ const overridesSummary = [
1872
+ feeOverrides.priorityFeeWei ? `priority fee ${feeOverrides.priorityFeeWei} wei` : null,
1873
+ feeOverrides.maxFeeWei ? `fee cap ${feeOverrides.maxFeeWei} wei` : null,
1874
+ nonceSequence ? `starting nonce ${nonceSequence.next}` : null,
1875
+ ].filter(Boolean).join(', ') || null;
1876
+
1710
1877
  const quoteData = loadBridgeQuote(quoteId);
1711
1878
  // A truncated or hand-edited quote file can be missing `response.steps`
1712
1879
  // entirely; guard before destructuring so the operator gets an actionable
@@ -1734,38 +1901,147 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1734
1901
  );
1735
1902
  }
1736
1903
 
1737
- log(`\n Executing bridge: ${quoteData.originChain} → ${quoteData.destinationChain}`);
1904
+ log(`\n ${guard.dryRun ? 'Checking' : 'Executing'} bridge: ${quoteData.originChain} → ${quoteData.destinationChain}`);
1738
1905
  log(` Type: ${execution_type}`);
1739
1906
  log(` Steps: ${steps.length}`);
1740
1907
 
1741
- // The quote was issued for one wallet, but the signing wallet is resolved
1742
- // separately from --wallet / the current default — which can have changed
1743
- // since. Signing with a different wallet than the quote was built for would
1744
- // screen one address and move funds from another, and the cached tx data
1745
- // (nonce, from) belongs to the quote's wallet regardless. Refuse instead.
1746
- const signer = resolveWalletAddress(walletName);
1908
+ // Dry-run preflight needs only the public address persisted alongside the
1909
+ // quote. Prefer it before touching local wallet configuration; legacy
1910
+ // quotes without the field retain the previous wallet-resolution path.
1911
+ // A real execution always resolves the live signer independently and
1912
+ // binds it to the quote before any credentials are loaded.
1913
+ const quotedWalletAddress = validateQuotedWalletAddress(quoteId, quoteData.walletAddress);
1914
+ const signer = guard.dryRun && quotedWalletAddress
1915
+ ? null
1916
+ : resolveWalletAddress(walletName);
1917
+ const signerAddress = signer?.address || quotedWalletAddress;
1918
+ // resolveEvmWallet and validateQuotedWalletAddress already guarantee this
1919
+ // in production. Keep an explicit boundary before compliance screening
1920
+ // so a malformed injected seam can never turn into screenOrThrow([undefined]).
1921
+ if (!signerAddress) {
1922
+ throw new CommandError(
1923
+ `Quote "${quoteId}" has no valid signer address. Request a fresh quote with "nansen bridge quote".`,
1924
+ 'INVALID_WALLET',
1925
+ );
1926
+ }
1747
1927
  if (
1748
- quoteData.walletAddress &&
1749
- String(signer.address).toLowerCase() !== String(quoteData.walletAddress).toLowerCase()
1928
+ signer &&
1929
+ quotedWalletAddress &&
1930
+ String(signer.address).toLowerCase() !== quotedWalletAddress.toLowerCase()
1750
1931
  ) {
1751
1932
  throw new Error(
1752
- `Bridge quote "${quoteId}" was created for ${quoteData.walletAddress} but the signing wallet is ${signer.address}. Pass --wallet for the quote's wallet, or request a new quote.`,
1933
+ `Bridge quote "${quoteId}" was created for ${quotedWalletAddress} but the signing wallet is ${signer.address}. Pass --wallet for the quote's wallet, or request a new quote.`,
1753
1934
  );
1754
1935
  }
1755
1936
 
1756
1937
  // Re-screen the signer and any distinct recipient immediately before
1757
1938
  // signing. Quotes live up to an hour, and the EVM leg broadcasts directly.
1758
1939
  const screenAddresses = recipient
1759
- && String(recipient).toLowerCase() !== String(signer.address).toLowerCase()
1760
- ? [signer.address, recipient]
1761
- : [signer.address];
1940
+ && String(recipient).toLowerCase() !== String(signerAddress).toLowerCase()
1941
+ ? [signerAddress, recipient]
1942
+ : [signerAddress];
1762
1943
  await screenOrThrow(apiInstance, screenAddresses);
1763
1944
 
1945
+ // These checks use the quote, public signer address, and current EVM fees. A
1946
+ // dry run must execute them before returning at the gate; a real run
1947
+ // preserves the established password/error ordering by executing them
1948
+ // after credentials resolve. Cache the result so each invocation can run
1949
+ // the preflight at most once even if the guard's control flow changes.
1950
+ const preflightPlan = async () => {
1951
+ let evmIntent = null;
1952
+ let hlIntent = null;
1953
+ if (execution_type === 'evm_transaction') {
1954
+ evmIntent = {
1955
+ chain: quoteData.originChain,
1956
+ signerAddress,
1957
+ requestedAmountBaseUnits: quoteData.requestedAmountBaseUnits ?? null,
1958
+ };
1959
+ preflightEvmBridgeSteps(steps, evmIntent);
1960
+ // Check the whole plan before an approval can spend gas or grant an
1961
+ // allowance. Match signing's fee resolution and numeric gas normalization;
1962
+ // the signer checks again if network fees change during execution.
1963
+ for (const step of steps) {
1964
+ for (const item of step.items || []) {
1965
+ if (item.status === 'complete') continue;
1966
+ const txData = item.data;
1967
+ const fees = await resolveEvmStepFees(evmIntent.chain, txData, feeOverrides);
1968
+ assertEvmFeeWithinCap(
1969
+ fees.maxFeePerGas || fees.gasPrice,
1970
+ BigInt(txData.gas || txData.gasLimit || '210000').toString(),
1971
+ `bridge step "${step.id}"`,
1972
+ feeOverrides.maxTxFeeWei,
1973
+ );
1974
+ }
1975
+ }
1976
+ } else if (execution_type === 'hyperliquid_signature') {
1977
+ const currencyIn = quoteData.response.details?.currencyIn;
1978
+ if (quoteData.requestedAmountBaseUnits != null && currencyIn?.amount != null) {
1979
+ let currencyInScaled;
1980
+ let requestedScaled;
1981
+ try {
1982
+ currencyInScaled = BigInt(currencyIn.amount);
1983
+ requestedScaled = BigInt(quoteData.requestedAmountBaseUnits);
1984
+ } catch {
1985
+ throw new CommandError(
1986
+ `Quote input "${currencyIn.amount}" is not a valid amount. Request a new quote.`,
1987
+ 'AMOUNT_MISMATCH',
1988
+ );
1989
+ }
1990
+ if (currencyInScaled !== requestedScaled) {
1991
+ throw new CommandError(
1992
+ `Quote input ${currencyIn.amount} does not match the requested ${quoteData.requestedAmountBaseUnits}. Request a new quote.`,
1993
+ 'AMOUNT_MISMATCH',
1994
+ );
1995
+ }
1996
+ }
1997
+ hlIntent = {
1998
+ reviewedAmountBaseUnits: quoteData.requestedAmountBaseUnits ?? null,
1999
+ hlNetwork: 'Mainnet',
2000
+ signerAddress,
2001
+ };
2002
+ preflightHlBridgeSteps(steps, hlIntent);
2003
+ } else {
2004
+ throw new CommandError(
2005
+ `Quote "${quoteId}" has unsupported execution type "${execution_type}". Request a new quote.`,
2006
+ 'INVALID_INPUT',
2007
+ );
2008
+ }
2009
+ return { evmIntent, hlIntent };
2010
+ };
2011
+
2012
+ // A plan shown for interactive consent must already be known-safe. Match
2013
+ // trade execute: preview and an actual prompt preflight eagerly, while
2014
+ // --yes/non-TTY retain the established ordering (credentials first,
2015
+ // preflight immediately before signing).
2016
+ const shouldPreflightPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
2017
+ let preflightResult = shouldPreflightPlan ? await preflightPlan() : null;
2018
+
2019
+ // ── Acknowledgement gate: --dry-run / --yes ──────────────────────
2020
+ // Placed before the signing credentials are loaded and well before the
2021
+ // first of the quote's steps is signed, so a dry run can sign nothing
2022
+ // and a declined confirmation leaves a multi-step transfer untouched.
2023
+ // See src/execute-guard.js for the TTY rules.
2024
+ const proceed = await guardExecution({
2025
+ plan: buildBridgeExecutionPlan({
2026
+ quoteId,
2027
+ quoteData,
2028
+ signerAddress,
2029
+ overrides: overridesSummary,
2030
+ }),
2031
+ ...guard,
2032
+ promptFn,
2033
+ log,
2034
+ confirmationLog,
2035
+ });
2036
+ if (!proceed) return undefined;
2037
+
1764
2038
  // Signing material for the wallet resolved above — not a second lookup.
1765
2039
  // Resolving twice re-read the wallet file and, worse, could pick a
1766
2040
  // different wallet than the one just screened if the default changed in
1767
2041
  // between.
1768
2042
  const creds = resolveSigningCredentials(signer);
2043
+ preflightResult ??= await preflightPlan();
2044
+ const { evmIntent, hlIntent } = preflightResult;
1769
2045
 
1770
2046
  // Consume the quote at each INDIVIDUAL broadcast, before any receipt wait.
1771
2047
  // A tx can be accepted by the network and then have waitForReceipt time
@@ -1786,23 +2062,10 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1786
2062
  });
1787
2063
 
1788
2064
  if (execution_type === 'evm_transaction') {
1789
- const evmIntent = {
1790
- chain: quoteData.originChain,
1791
- signerAddress: signer.address,
1792
- requestedAmountBaseUnits: quoteData.requestedAmountBaseUnits ?? null,
1793
- };
1794
- // Validate every step's calldata against intent before any step is
1795
- // signed or broadcast — see preflightEvmBridgeSteps for why this can't
1796
- // just be the per-step check processEvmStep already does.
1797
- preflightEvmBridgeSteps(steps, evmIntent);
1798
2065
  // Overrides move real money differently from what was quoted, so say so
1799
2066
  // rather than letting them apply silently.
1800
- if (feeOverrides.priorityFeeWei || feeOverrides.maxFeeWei || nonceSequence) {
1801
- const parts = [];
1802
- if (feeOverrides.priorityFeeWei) parts.push(`priority fee ${feeOverrides.priorityFeeWei} wei`);
1803
- if (feeOverrides.maxFeeWei) parts.push(`fee cap ${feeOverrides.maxFeeWei} wei`);
1804
- if (nonceSequence) parts.push(`starting nonce ${nonceSequence.next}`);
1805
- log(` Overrides: ${parts.join(', ')}`);
2067
+ if (overridesSummary) {
2068
+ log(` Overrides: ${overridesSummary}`);
1806
2069
  }
1807
2070
  for (const [index, step] of steps.entries()) {
1808
2071
  await processEvmStep(step, {
@@ -1818,45 +2081,6 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1818
2081
  markBroadcast(index);
1819
2082
  }
1820
2083
  } else if (execution_type === 'hyperliquid_signature') {
1821
- // Check E: the quote's own currencyIn.amount — the amount it displayed
1822
- // and will send through /perp/bridge/quote — must equal what was
1823
- // actually requested at quote time. The amount cap below (check B) is
1824
- // anchored to requestedAmountBaseUnits directly, not to this display
1825
- // field, so this check is UI-consistency defense-in-depth: it catches a
1826
- // quote whose displayed send amount has drifted from the request,
1827
- // rather than gating the cap itself.
1828
- const currencyIn = quoteData.response.details?.currencyIn;
1829
- if (quoteData.requestedAmountBaseUnits != null && currencyIn?.amount != null) {
1830
- let currencyInScaled, requestedScaled;
1831
- try {
1832
- currencyInScaled = BigInt(currencyIn.amount);
1833
- requestedScaled = BigInt(quoteData.requestedAmountBaseUnits);
1834
- } catch {
1835
- throw new CommandError(
1836
- `Quote input "${currencyIn.amount}" is not a valid amount. Request a new quote.`,
1837
- 'AMOUNT_MISMATCH',
1838
- );
1839
- }
1840
- if (currencyInScaled !== requestedScaled) {
1841
- throw new CommandError(
1842
- `Quote input ${currencyIn.amount} does not match the requested ${quoteData.requestedAmountBaseUnits}. Request a new quote.`,
1843
- 'AMOUNT_MISMATCH',
1844
- );
1845
- }
1846
- }
1847
- const hlIntent = {
1848
- // Anchored to what the CLIENT persisted at quote time from the
1849
- // user's own --amount, not to any server-supplied display field —
1850
- // see assertHlBridgeActionIntent for why.
1851
- reviewedAmountBaseUnits: quoteData.requestedAmountBaseUnits ?? null,
1852
- hlNetwork: 'Mainnet',
1853
- signerAddress: signer.address,
1854
- };
1855
- // Validate every step's payload (both the authorize leg and the HL
1856
- // action leg) before any of them are signed or posted — see
1857
- // preflightHlBridgeSteps for why this can't just be the per-step
1858
- // check the loops below already do.
1859
- preflightHlBridgeSteps(steps, hlIntent);
1860
2084
  if (creds.provider === 'privy') {
1861
2085
  const { PrivyClient } = await import('./privy.js');
1862
2086
  const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);