nansen-cli 1.45.0 → 1.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/bridge.js CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  signEvmTransaction,
23
23
  waitForReceipt,
24
24
  } from './trading.js';
25
+ import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
25
26
  import { screenOrThrow } from './perp.js';
26
27
  import { extractActionErrors } from './hl-client.js';
27
28
  import { encodeApproveCalldata } from './trade-validation.js';
@@ -1456,6 +1457,23 @@ function resolveWalletAddress(walletName) {
1456
1457
  return resolveEvmWallet(walletName, 'Bridging');
1457
1458
  }
1458
1459
 
1460
+ // Bridge quote files persist the address used to build the transaction at this
1461
+ // exact top-level field (see saveBridgeQuote). A dry run can safely use that
1462
+ // public address for screening and transaction preflight without requiring a
1463
+ // configured local wallet, but only after checking it is actually an EVM
1464
+ // address. Missing legacy data falls back to normal wallet resolution.
1465
+ function validateQuotedWalletAddress(quoteId, walletAddress) {
1466
+ if (walletAddress == null || walletAddress === '') return null;
1467
+ const { valid, error } = validateAddress(walletAddress, 'ethereum');
1468
+ if (!valid) {
1469
+ throw new CommandError(
1470
+ `Quote "${quoteId}" is malformed: walletAddress is invalid. ${error} Request a fresh quote with "nansen bridge quote".`,
1471
+ 'INVALID_INPUT',
1472
+ );
1473
+ }
1474
+ return walletAddress.trim();
1475
+ }
1476
+
1459
1477
  // Destination address for --recipient. Validated against the EVM pattern rather
1460
1478
  // than the destination chain's own rules: every supported destination
1461
1479
  // (base/ethereum/arbitrum/hyperliquid) takes an EVM address, and passing
@@ -1495,8 +1513,48 @@ function parseBridgeAmount(raw, amountUnit) {
1495
1513
 
1496
1514
  // ── Command builder ──────────────────────────────────────────────────
1497
1515
 
1516
+ /**
1517
+ * Describe the transfer `bridge execute` is about to sign, for the
1518
+ * confirmation prompt and for --dry-run. Built entirely from the cached quote
1519
+ * and the resolved signer — it touches no wallet material.
1520
+ */
1521
+ export function buildBridgeExecutionPlan({ quoteId, quoteData, signerAddress, overrides }) {
1522
+ const response = quoteData.response || {};
1523
+ const details = response.details || {};
1524
+ const currencyIn = details.currencyIn || {};
1525
+ const currencyOut = details.currencyOut || {};
1526
+ const relayerFee = response.fees?.relayer || {};
1527
+ const steps = response.steps || [];
1528
+ const sendAmount = currencyIn.amountFormatted
1529
+ || (quoteData.requestedAmountBaseUnits != null ? `${quoteData.requestedAmountBaseUnits} base units` : null);
1530
+ // Keep malformed seam inputs out of user-facing plans. formatPlan omits null
1531
+ // rows, but a template literal would otherwise turn an absent signer into a
1532
+ // visible `undefined (same address)` recipient.
1533
+ const planSignerAddress = signerAddress || null;
1534
+
1535
+ return formatPlan(`Bridge plan — ${quoteData.originChain} → ${quoteData.destinationChain}`, [
1536
+ ['Quote', quoteId],
1537
+ ['Type', response.execution_type],
1538
+ ['Send', [sendAmount, currencyIn.currency?.symbol].filter(Boolean).join(' ') || null],
1539
+ ['Receive', currencyOut.amountFormatted ? `~${[currencyOut.amountFormatted, currencyOut.currency?.symbol].filter(Boolean).join(' ')}` : null],
1540
+ ['Fee', relayerFee.amountUsd ? `$${relayerFee.amountUsd}` : null],
1541
+ ['Wallet', planSignerAddress],
1542
+ ['Recipient', quoteData.recipient || (planSignerAddress ? `${planSignerAddress} (same address)` : null)],
1543
+ ['Steps', steps.map(s => `${s.id} (${s.kind})`).join(', ') || null],
1544
+ ['Overrides', overrides || null],
1545
+ ]);
1546
+ }
1547
+
1498
1548
  export function buildBridgeCommands(deps = {}) {
1499
- const { log = console.log } = deps;
1549
+ const {
1550
+ log = console.log,
1551
+ // Injected so the confirmation prompt (and whether there is anyone to
1552
+ // answer it) can be driven in tests without a terminal.
1553
+ promptFn,
1554
+ confirmationLog = log,
1555
+ isTTY = false,
1556
+ env = process.env,
1557
+ } = deps;
1500
1558
 
1501
1559
  return {
1502
1560
  'quote': async (args, apiInstance, flags, options) => {
@@ -1660,6 +1718,7 @@ OPTIONS:
1660
1718
  'execute': async (args, apiInstance, flags, options) => {
1661
1719
  const quoteId = options.quote || args[0];
1662
1720
  const walletName = options.wallet;
1721
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
1663
1722
 
1664
1723
  if (!quoteId) {
1665
1724
  throw new CommandError(
@@ -1667,6 +1726,17 @@ OPTIONS:
1667
1726
 
1668
1727
  Execute a cached bridge quote. Signs transactions and broadcasts them.
1669
1728
 
1729
+ OPTIONS:
1730
+ --dry-run Validate and print what would be signed, then stop. Nothing is
1731
+ broadcast and the quote stays usable.
1732
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt
1733
+ only appears when stdin is a terminal; agents, CI and pipes are
1734
+ never prompted, with or without --yes.
1735
+
1736
+ EXIT CODES:
1737
+ 0 the transfer was submitted, or the dry run completed
1738
+ 1 declined at the confirmation prompt, or the execution failed
1739
+
1670
1740
  RECOVERY OPTIONS (EVM deposit legs only):
1671
1741
  --priority-fee Priority fee in gwei, overriding the quoted one
1672
1742
  --max-fee Fee cap in gwei, overriding the computed one
@@ -1707,6 +1777,14 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1707
1777
  nonceSequence = { next: parseInt(s, 10) };
1708
1778
  }
1709
1779
 
1780
+ // One rendering of the overrides — shown in the execution plan, and
1781
+ // again when the EVM leg actually applies them.
1782
+ const overridesSummary = [
1783
+ feeOverrides.priorityFeeWei ? `priority fee ${feeOverrides.priorityFeeWei} wei` : null,
1784
+ feeOverrides.maxFeeWei ? `fee cap ${feeOverrides.maxFeeWei} wei` : null,
1785
+ nonceSequence ? `starting nonce ${nonceSequence.next}` : null,
1786
+ ].filter(Boolean).join(', ') || null;
1787
+
1710
1788
  const quoteData = loadBridgeQuote(quoteId);
1711
1789
  // A truncated or hand-edited quote file can be missing `response.steps`
1712
1790
  // entirely; guard before destructuring so the operator gets an actionable
@@ -1734,38 +1812,131 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1734
1812
  );
1735
1813
  }
1736
1814
 
1737
- log(`\n Executing bridge: ${quoteData.originChain} → ${quoteData.destinationChain}`);
1815
+ log(`\n ${guard.dryRun ? 'Checking' : 'Executing'} bridge: ${quoteData.originChain} → ${quoteData.destinationChain}`);
1738
1816
  log(` Type: ${execution_type}`);
1739
1817
  log(` Steps: ${steps.length}`);
1740
1818
 
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);
1819
+ // Dry-run preflight needs only the public address persisted alongside the
1820
+ // quote. Prefer it before touching local wallet configuration; legacy
1821
+ // quotes without the field retain the previous wallet-resolution path.
1822
+ // A real execution always resolves the live signer independently and
1823
+ // binds it to the quote before any credentials are loaded.
1824
+ const quotedWalletAddress = validateQuotedWalletAddress(quoteId, quoteData.walletAddress);
1825
+ const signer = guard.dryRun && quotedWalletAddress
1826
+ ? null
1827
+ : resolveWalletAddress(walletName);
1828
+ const signerAddress = signer?.address || quotedWalletAddress;
1829
+ // resolveEvmWallet and validateQuotedWalletAddress already guarantee this
1830
+ // in production. Keep an explicit boundary before compliance screening
1831
+ // so a malformed injected seam can never turn into screenOrThrow([undefined]).
1832
+ if (!signerAddress) {
1833
+ throw new CommandError(
1834
+ `Quote "${quoteId}" has no valid signer address. Request a fresh quote with "nansen bridge quote".`,
1835
+ 'INVALID_WALLET',
1836
+ );
1837
+ }
1747
1838
  if (
1748
- quoteData.walletAddress &&
1749
- String(signer.address).toLowerCase() !== String(quoteData.walletAddress).toLowerCase()
1839
+ signer &&
1840
+ quotedWalletAddress &&
1841
+ String(signer.address).toLowerCase() !== quotedWalletAddress.toLowerCase()
1750
1842
  ) {
1751
1843
  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.`,
1844
+ `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
1845
  );
1754
1846
  }
1755
1847
 
1756
1848
  // Re-screen the signer and any distinct recipient immediately before
1757
1849
  // signing. Quotes live up to an hour, and the EVM leg broadcasts directly.
1758
1850
  const screenAddresses = recipient
1759
- && String(recipient).toLowerCase() !== String(signer.address).toLowerCase()
1760
- ? [signer.address, recipient]
1761
- : [signer.address];
1851
+ && String(recipient).toLowerCase() !== String(signerAddress).toLowerCase()
1852
+ ? [signerAddress, recipient]
1853
+ : [signerAddress];
1762
1854
  await screenOrThrow(apiInstance, screenAddresses);
1763
1855
 
1856
+ // These checks need only the cached quote and public signer address. A
1857
+ // dry run must execute them before returning at the gate; a real run
1858
+ // preserves the established password/error ordering by executing them
1859
+ // after credentials resolve. Cache the result so each invocation can run
1860
+ // the preflight at most once even if the guard's control flow changes.
1861
+ const preflightPlan = () => {
1862
+ let evmIntent = null;
1863
+ let hlIntent = null;
1864
+ if (execution_type === 'evm_transaction') {
1865
+ evmIntent = {
1866
+ chain: quoteData.originChain,
1867
+ signerAddress,
1868
+ requestedAmountBaseUnits: quoteData.requestedAmountBaseUnits ?? null,
1869
+ };
1870
+ preflightEvmBridgeSteps(steps, evmIntent);
1871
+ } else if (execution_type === 'hyperliquid_signature') {
1872
+ const currencyIn = quoteData.response.details?.currencyIn;
1873
+ if (quoteData.requestedAmountBaseUnits != null && currencyIn?.amount != null) {
1874
+ let currencyInScaled;
1875
+ let requestedScaled;
1876
+ try {
1877
+ currencyInScaled = BigInt(currencyIn.amount);
1878
+ requestedScaled = BigInt(quoteData.requestedAmountBaseUnits);
1879
+ } catch {
1880
+ throw new CommandError(
1881
+ `Quote input "${currencyIn.amount}" is not a valid amount. Request a new quote.`,
1882
+ 'AMOUNT_MISMATCH',
1883
+ );
1884
+ }
1885
+ if (currencyInScaled !== requestedScaled) {
1886
+ throw new CommandError(
1887
+ `Quote input ${currencyIn.amount} does not match the requested ${quoteData.requestedAmountBaseUnits}. Request a new quote.`,
1888
+ 'AMOUNT_MISMATCH',
1889
+ );
1890
+ }
1891
+ }
1892
+ hlIntent = {
1893
+ reviewedAmountBaseUnits: quoteData.requestedAmountBaseUnits ?? null,
1894
+ hlNetwork: 'Mainnet',
1895
+ signerAddress,
1896
+ };
1897
+ preflightHlBridgeSteps(steps, hlIntent);
1898
+ } else {
1899
+ throw new CommandError(
1900
+ `Quote "${quoteId}" has unsupported execution type "${execution_type}". Request a new quote.`,
1901
+ 'INVALID_INPUT',
1902
+ );
1903
+ }
1904
+ return { evmIntent, hlIntent };
1905
+ };
1906
+
1907
+ // A plan shown for interactive consent must already be known-safe. Match
1908
+ // trade execute: preview and an actual prompt preflight eagerly, while
1909
+ // --yes/non-TTY retain the established ordering (credentials first,
1910
+ // preflight immediately before signing).
1911
+ const shouldPreflightPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
1912
+ let preflightResult = shouldPreflightPlan ? preflightPlan() : null;
1913
+
1914
+ // ── Acknowledgement gate: --dry-run / --yes ──────────────────────
1915
+ // Placed before the signing credentials are loaded and well before the
1916
+ // first of the quote's steps is signed, so a dry run can sign nothing
1917
+ // and a declined confirmation leaves a multi-step transfer untouched.
1918
+ // See src/execute-guard.js for the TTY rules.
1919
+ const proceed = await guardExecution({
1920
+ plan: buildBridgeExecutionPlan({
1921
+ quoteId,
1922
+ quoteData,
1923
+ signerAddress,
1924
+ overrides: overridesSummary,
1925
+ }),
1926
+ ...guard,
1927
+ promptFn,
1928
+ log,
1929
+ confirmationLog,
1930
+ });
1931
+ if (!proceed) return undefined;
1932
+
1764
1933
  // Signing material for the wallet resolved above — not a second lookup.
1765
1934
  // Resolving twice re-read the wallet file and, worse, could pick a
1766
1935
  // different wallet than the one just screened if the default changed in
1767
1936
  // between.
1768
1937
  const creds = resolveSigningCredentials(signer);
1938
+ preflightResult ??= preflightPlan();
1939
+ const { evmIntent, hlIntent } = preflightResult;
1769
1940
 
1770
1941
  // Consume the quote at each INDIVIDUAL broadcast, before any receipt wait.
1771
1942
  // A tx can be accepted by the network and then have waitForReceipt time
@@ -1786,23 +1957,10 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1786
1957
  });
1787
1958
 
1788
1959
  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
1960
  // Overrides move real money differently from what was quoted, so say so
1799
1961
  // 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(', ')}`);
1962
+ if (overridesSummary) {
1963
+ log(` Overrides: ${overridesSummary}`);
1806
1964
  }
1807
1965
  for (const [index, step] of steps.entries()) {
1808
1966
  await processEvmStep(step, {
@@ -1818,45 +1976,6 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
1818
1976
  markBroadcast(index);
1819
1977
  }
1820
1978
  } 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
1979
  if (creds.provider === 'privy') {
1861
1980
  const { PrivyClient } = await import('./privy.js');
1862
1981
  const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
package/src/chain-ids.js CHANGED
@@ -19,7 +19,6 @@ export const EVM_CHAIN_IDS = {
19
19
  avalanche: 43114,
20
20
  bnb: 56,
21
21
  linea: 59144,
22
- scroll: 534352,
23
22
  mantle: 5000,
24
23
  };
25
24
 
@@ -30,6 +29,6 @@ export const EVM_CHAIN_IDS = {
30
29
  */
31
30
  export const EVM_CHAINS = [
32
31
  'ethereum', 'arbitrum', 'base', 'bnb', 'polygon', 'optimism',
33
- 'avalanche', 'linea', 'scroll', 'mantle', 'ronin',
32
+ 'avalanche', 'linea', 'mantle',
34
33
  'sei', 'plasma', 'sonic', 'monad', 'hyperevm', 'iotaevm',
35
34
  ];