nansen-cli 2.3.0 → 2.4.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 (71) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +32 -32
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +249 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +17 -1
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
  9. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  10. package/skills/nansen-defi-positions/SKILL.md +1 -1
  11. package/skills/nansen-exit-signals/SKILL.md +2 -2
  12. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  13. package/skills/nansen-general-search/SKILL.md +1 -1
  14. package/skills/nansen-holder-analysis/SKILL.md +2 -2
  15. package/skills/nansen-limit-orders/SKILL.md +1 -1
  16. package/skills/nansen-mpp-payment/SKILL.md +2 -2
  17. package/skills/nansen-perp-screener/SKILL.md +1 -1
  18. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  20. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  21. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  22. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  23. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  24. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  25. package/skills/nansen-smart-alerts/SKILL.md +2 -1
  26. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  27. package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
  28. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  29. package/skills/nansen-token-research/SKILL.md +1 -1
  30. package/skills/nansen-token-screener/SKILL.md +1 -1
  31. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  32. package/skills/nansen-trading/SKILL.md +1 -1
  33. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  34. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  35. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  36. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  37. package/skills/nansen-wallet-manager/SKILL.md +1 -1
  38. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  39. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  40. package/skills/nansen-web-searcher/SKILL.md +1 -1
  41. package/src/api-endpoints.json +1605 -0
  42. package/src/api.js +202 -97
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-state.js +2 -2
  45. package/src/auth-store-native.js +6 -1
  46. package/src/auth-store-worker.js +1 -1
  47. package/src/auth-store.js +9 -4
  48. package/src/bridge.js +19 -10
  49. package/src/cli.js +188 -89
  50. package/src/commands/agent.js +2 -3
  51. package/src/commands/alerts.js +277 -9
  52. package/src/commands/feedback.js +98 -37
  53. package/src/commands/mcp.js +1 -1
  54. package/src/commands/research.js +14 -37
  55. package/src/cost-cache.js +33 -7
  56. package/src/doctor.js +14 -5
  57. package/src/error-codes.js +226 -0
  58. package/src/input-validation.js +551 -0
  59. package/src/limit-order.js +12 -3
  60. package/src/perp.js +2 -1
  61. package/src/privy.js +89 -11
  62. package/src/query-options.js +30 -7
  63. package/src/rpc-urls.js +3 -1
  64. package/src/schema.json +1137 -145
  65. package/src/solana-tx.js +4 -0
  66. package/src/trade-validation.js +167 -8
  67. package/src/trading.js +172 -12
  68. package/src/transfer.js +7 -1
  69. package/src/update-check.js +32 -5
  70. package/src/wallet.js +211 -57
  71. package/src/walletconnect-x402.js +14 -8
package/src/solana-tx.js CHANGED
@@ -28,6 +28,8 @@ export function readCompactU16(buf, offset) {
28
28
  * [compact-u16 sigCount][sigCount * 64-byte signatures][message]) into its
29
29
  * header, static account keys, instructions, and (v0 only) address-table
30
30
  * lookups. `data` on instructions is returned undecoded (raw Buffer).
31
+ * `messageBase64` is the serialized message (everything after the
32
+ * signatures), the form RPC getFeeForMessage takes.
31
33
  */
32
34
  export function parseTransactionMessage(base64) {
33
35
  const bytes = Buffer.from(base64, 'base64');
@@ -41,6 +43,7 @@ export function parseTransactionMessage(base64) {
41
43
  };
42
44
  const { value: numSignatures, size: sigCountSize } = readCompactU16(bytes, 0);
43
45
  let offset = sigCountSize + numSignatures * 64;
46
+ const messageStart = offset;
44
47
 
45
48
  requireBytes(offset, 1);
46
49
  const first = bytes[offset];
@@ -136,6 +139,7 @@ export function parseTransactionMessage(base64) {
136
139
  recentBlockhash,
137
140
  instructions,
138
141
  addressTableLookups,
142
+ messageBase64: bytes.subarray(messageStart).toString('base64'),
139
143
  };
140
144
  }
141
145
 
@@ -41,8 +41,27 @@ const COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';
41
41
  const COMPUTE_BUDGET_SET_UNIT_LIMIT = 2;
42
42
  const COMPUTE_BUDGET_SET_UNIT_PRICE = 3;
43
43
  const SOLANA_MAX_COMPUTE_UNITS = 1_400_000; // Solana's per-transaction compute-unit ceiling — the
44
- // worst-case bound used when a price is set with no
45
- // explicit limit instruction.
44
+ // worst-case bound the priority-fee cap assumes when a
45
+ // price is set with no explicit limit instruction. The
46
+ // runtime clamps any larger requested limit to it.
47
+ // The runtime's default limit when none is set: 200,000 CU per instruction,
48
+ // or 3,000 for a builtin program's instruction (Agave's builtin cost map).
49
+ // Vote is mid-migration to on-chain BPF; counting it as a builtin can only
50
+ // understate the fee, and an unpayable fee is dropped by the leader unsigned
51
+ // and uncharged, whereas overstating it falsely rejects the transaction.
52
+ const SOLANA_DEFAULT_INSTRUCTION_COMPUTE_UNITS = 200_000;
53
+ const SOLANA_DEFAULT_BUILTIN_COMPUTE_UNITS = 3_000;
54
+ const SOLANA_BUILTIN_PROGRAMS = new Set([
55
+ SYSTEM_PROGRAM,
56
+ COMPUTE_BUDGET_PROGRAM,
57
+ 'BPFLoader1111111111111111111111111111111111',
58
+ 'BPFLoader2111111111111111111111111111111111',
59
+ 'BPFLoaderUpgradeab1e11111111111111111111111',
60
+ 'LoaderV411111111111111111111111111111111111',
61
+ 'KeccakSecp256k11111111111111111111111111111',
62
+ 'Ed25519SigVerify111111111111111111111111111',
63
+ 'Vote111111111111111111111111111111111111111',
64
+ ]);
46
65
  const MAX_PRIORITY_FEE_LAMPORTS = 10_000_000n; // 0.01 SOL sanity ceiling on the priority fee a
47
66
  // single trade can be made to pay.
48
67
 
@@ -1800,7 +1819,11 @@ export function assertLimitOrderCancelOutcome(sim, { inputMint, amount } = {}) {
1800
1819
  * against SPL_TOKEN_PROGRAMS/COMPUTE_BUDGET_PROGRAM, so it's rejected outright
1801
1820
  * rather than silently skipped.
1802
1821
  *
1803
- * Throws on any of those patterns. Returns the parsed transaction otherwise.
1822
+ * Throws on any of those patterns. Otherwise returns the parsed transaction
1823
+ * plus `priorityFeeLamports` (0n when no compute-unit price is set), which
1824
+ * checkSolanaFeeBalance compares against the wallet's balance. With no limit
1825
+ * instruction it is priced at the runtime's default limit, not the 1.4M
1826
+ * ceiling the priority-fee cap assumes, so it is not a worst-case bound.
1804
1827
  */
1805
1828
  export function assertSolanaInstructionsSafe(txBase64, { walletAddress } = {}) {
1806
1829
  // Fail closed on a missing wallet address: every authority check below
@@ -1832,6 +1855,7 @@ export function assertSolanaInstructionsSafe(txBase64, { walletAddress } = {}) {
1832
1855
 
1833
1856
  let computeUnitLimit = null;
1834
1857
  let computeUnitPriceMicroLamports = null;
1858
+ let builtinInstructions = 0;
1835
1859
 
1836
1860
  for (const ix of parsed.instructions) {
1837
1861
  const programId = resolveStaticAccount(parsed, ix.programIdIndex);
@@ -1847,6 +1871,7 @@ export function assertSolanaInstructionsSafe(txBase64, { walletAddress } = {}) {
1847
1871
  'Solana transaction invokes a program only resolvable via an address-lookup-table entry, which cannot be safety-classified. Refusing to sign.',
1848
1872
  );
1849
1873
  }
1874
+ if (SOLANA_BUILTIN_PROGRAMS.has(programId)) builtinInstructions++;
1850
1875
 
1851
1876
  if (SPL_TOKEN_PROGRAMS.has(programId)) {
1852
1877
  // No discriminator byte — not a valid SPL Token instruction (the runtime
@@ -1893,17 +1918,151 @@ export function assertSolanaInstructionsSafe(txBase64, { walletAddress } = {}) {
1893
1918
  }
1894
1919
  }
1895
1920
 
1921
+ let priorityFeeLamports = 0n;
1896
1922
  if (computeUnitPriceMicroLamports != null) {
1897
- const units = BigInt(computeUnitLimit ?? SOLANA_MAX_COMPUTE_UNITS);
1898
- const feeLamports = (computeUnitPriceMicroLamports * units) / 1_000_000n;
1899
- if (feeLamports > MAX_PRIORITY_FEE_LAMPORTS) {
1923
+ // The runtime rounds the priority fee up to a whole lamport.
1924
+ const feeAt = (units) =>
1925
+ (computeUnitPriceMicroLamports * BigInt(Math.min(units, SOLANA_MAX_COMPUTE_UNITS)) + 999_999n) / 1_000_000n;
1926
+ // Returned for checkSolanaFeeBalance's fallback. With no limit instruction
1927
+ // it prices the runtime's default limit, so it doesn't reject a transaction
1928
+ // the wallet can afford.
1929
+ const defaultLimit =
1930
+ SOLANA_DEFAULT_INSTRUCTION_COMPUTE_UNITS * (parsed.instructions.length - builtinInstructions) +
1931
+ SOLANA_DEFAULT_BUILTIN_COMPUTE_UNITS * builtinInstructions;
1932
+ priorityFeeLamports = feeAt(computeUnitLimit ?? defaultLimit);
1933
+ // The cap guards against a hostile transaction, so with no limit
1934
+ // instruction it assumes the 1.4M ceiling instead.
1935
+ const worstCaseFeeLamports = computeUnitLimit != null ? priorityFeeLamports : feeAt(SOLANA_MAX_COMPUTE_UNITS);
1936
+ if (worstCaseFeeLamports > MAX_PRIORITY_FEE_LAMPORTS) {
1900
1937
  throw new Error(
1901
- `Solana transaction sets an excessive priority fee (~${feeLamports} lamports, cap ${MAX_PRIORITY_FEE_LAMPORTS}). Refusing to sign.`,
1938
+ `Solana transaction sets an excessive priority fee (~${worstCaseFeeLamports} lamports, cap ${MAX_PRIORITY_FEE_LAMPORTS}). Refusing to sign.`,
1902
1939
  );
1903
1940
  }
1904
1941
  }
1905
1942
 
1906
- return parsed;
1943
+ return { ...parsed, priorityFeeLamports };
1944
+ }
1945
+
1946
+ // Fallback only: the protocol's per-signature base fee, used when the cluster
1947
+ // can't price the message (getFeeForMessage failed or returned null because
1948
+ // the blockhash is unknown to that node). The live figure comes from the
1949
+ // cluster below.
1950
+ const SOLANA_LAMPORTS_PER_SIGNATURE = 5_000n;
1951
+ // Signature-verification precompiles. Each signature they verify is charged
1952
+ // like a transaction signature; the count is the instruction's first data byte.
1953
+ const SOLANA_SIGNATURE_PRECOMPILES = new Set([
1954
+ 'Ed25519SigVerify111111111111111111111111111',
1955
+ 'KeccakSecp256k11111111111111111111111111111',
1956
+ 'Secp256r1SigVerify1111111111111111111111111',
1957
+ ]);
1958
+ // A hung read must not hold the transaction until its blockhash expires.
1959
+ const SOLANA_FEE_CHECK_RPC_TIMEOUT_MS = 10_000;
1960
+ // Account state the check reads. Finalized state lags ~13s, so SOL spent in
1961
+ // that window would still show.
1962
+ const SOLANA_FEE_CHECK_COMMITMENT = 'confirmed';
1963
+
1964
+ function formatLamports(lamports) {
1965
+ const whole = lamports / 1_000_000_000n;
1966
+ const frac = (lamports % 1_000_000_000n).toString().padStart(9, '0').replace(/0+$/, '');
1967
+ return frac ? `${whole}.${frac}` : `${whole}`;
1968
+ }
1969
+
1970
+ async function solanaRpc(rpcUrl, method, params) {
1971
+ const res = await fetch(rpcUrl, {
1972
+ method: 'POST',
1973
+ headers: { 'Content-Type': 'application/json' },
1974
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
1975
+ signal: AbortSignal.timeout(SOLANA_FEE_CHECK_RPC_TIMEOUT_MS),
1976
+ });
1977
+ if (!res.ok) throw new Error(`${method} failed: HTTP ${res.status}`);
1978
+ const body = await res.json();
1979
+ if (body.error || body.result === undefined) {
1980
+ throw new Error(`${method} failed: ${body.error?.message || 'no result'}`);
1981
+ }
1982
+ return body.result;
1983
+ }
1984
+
1985
+ /**
1986
+ * Check, before signing, that the wallet holds enough SOL to pay THIS
1987
+ * transaction's network fee, when the wallet is the fee payer.
1988
+ *
1989
+ * The fee comes from the cluster (getFeeForMessage), so it follows the current
1990
+ * fee schedule and includes the priority fee and precompile signatures. When
1991
+ * the cluster can't price the message, it falls back to the protocol base fee
1992
+ * (5,000 lamports per transaction and precompile signature) plus the priority
1993
+ * fee assertSolanaInstructionsSafe parsed, rounded up.
1994
+ *
1995
+ * Only a missing Solana RPC or a failed balance read skips the check (warns
1996
+ * and returns { proceed: true }).
1997
+ *
1998
+ * Limits, left to simulation (verifySolanaSwapOutcome): SOL the transaction
1999
+ * takes from the wallet beyond the fee (account rent, the swap's SOL input,
2000
+ * transfers) is not counted.
2001
+ *
2002
+ * The quote-time gate (validateGasBalance) can only apply a fixed floor because
2003
+ * the transaction does not exist yet, and validateBalance holds back a fee
2004
+ * buffer only when selling 95% or more of the SOL balance. Simulation also
2005
+ * catches an unpayable transaction, but it is skipped by --no-verify-outcome
2006
+ * and degrades when no simulation RPC is reachable. This check runs on every
2007
+ * path regardless of that flag.
2008
+ *
2009
+ * REQUIRES `parsed` to be the return value of assertSolanaInstructionsSafe.
2010
+ *
2011
+ * @param {object} opts
2012
+ * @param {object} opts.parsed
2013
+ * @param {string} opts.walletAddress
2014
+ * @returns {Promise<{ proceed: boolean, reason?: string }>}
2015
+ */
2016
+ export async function checkSolanaFeeBalance({ parsed, walletAddress, log = () => {} }) {
2017
+ // The fee payer is the first static account. When another account pays (a
2018
+ // sponsored transaction), the fee is not the wallet's to cover.
2019
+ if (parsed.staticAccountKeys[0] !== walletAddress) return { proceed: true };
2020
+
2021
+ const rpcUrl = CHAIN_RPCS.solana;
2022
+ if (!rpcUrl) {
2023
+ log(' ⚠ SOL fee balance check could not run (no Solana RPC endpoint); proceeding without it.');
2024
+ return { proceed: true };
2025
+ }
2026
+
2027
+ let balance;
2028
+ let feeResult;
2029
+ try {
2030
+ [balance, feeResult] = await Promise.all([
2031
+ solanaRpc(rpcUrl, 'getBalance', [walletAddress, { commitment: SOLANA_FEE_CHECK_COMMITMENT }])
2032
+ .then(r => BigInt(r.value)),
2033
+ // A failed fee lookup falls back to the static estimate.
2034
+ solanaRpc(rpcUrl, 'getFeeForMessage', [parsed.messageBase64, { commitment: 'processed' }]).catch(() => null),
2035
+ ]);
2036
+ } catch (e) {
2037
+ log(` ⚠ SOL fee balance check could not run (${e.message}); proceeding without it.`);
2038
+ return { proceed: true };
2039
+ }
2040
+
2041
+ const clusterFee = feeResult?.value;
2042
+ const clusterPriced = Number.isSafeInteger(clusterFee) && clusterFee >= 0;
2043
+ let feeLamports;
2044
+ if (clusterPriced) {
2045
+ feeLamports = BigInt(clusterFee);
2046
+ } else {
2047
+ let precompileSignatures = 0n;
2048
+ for (const ix of parsed.instructions) {
2049
+ if (SOLANA_SIGNATURE_PRECOMPILES.has(resolveStaticAccount(parsed, ix.programIdIndex)) && ix.data.length > 0) {
2050
+ precompileSignatures += BigInt(ix.data[0]);
2051
+ }
2052
+ }
2053
+ feeLamports = SOLANA_LAMPORTS_PER_SIGNATURE * (BigInt(parsed.header.numRequiredSignatures) + precompileSignatures) +
2054
+ parsed.priorityFeeLamports;
2055
+ }
2056
+
2057
+ if (balance < feeLamports) {
2058
+ return {
2059
+ proceed: false,
2060
+ reason: `wallet has ${formatLamports(balance)} SOL but this transaction needs at least ${formatLamports(feeLamports)} SOL ` +
2061
+ `for its ${clusterPriced ? '' : 'estimated '}network fee. Fund ${walletAddress} with SOL and retry.`,
2062
+ };
2063
+ }
2064
+
2065
+ return { proceed: true };
1907
2066
  }
1908
2067
 
1909
2068
  /**
package/src/trading.js CHANGED
@@ -16,7 +16,7 @@ import { buildMessageV0, fetchAddressLookupTables, fetchRecentBlockhash } from '
16
16
  import { keccak256, signSecp256k1, rlpEncode } from './crypto.js';
17
17
  import { getWalletConnectAddress, sendTransactionViaWalletConnect, sendSolanaTransactionViaWalletConnect, sendApprovalViaWalletConnect } from './walletconnect-trading.js';
18
18
  import { retrievePassword } from './keychain.js';
19
- import { validateQuoteInput, validateBalance, resolvePercentAmount, validateGasBalance, encodeApproveCalldata, assertValidApprovalSpender, assertQuoteMatchesRequest, assertSwapCalldataNotBareTransfer, assertSwapOutcome, assertSolanaInstructionsSafe, assertSolanaSwapOutcome, approvalAmountForSwap, needsAllowanceRevoke, OVERSIZED_ALLOWANCE_MULTIPLIER, EVM_BRIDGE_NATIVE_FEE_SLACK, isBridgeRequest } from './trade-validation.js';
19
+ import { validateQuoteInput, validateBalance, resolvePercentAmount, validateGasBalance, encodeApproveCalldata, assertValidApprovalSpender, assertQuoteMatchesRequest, assertSwapCalldataNotBareTransfer, assertSwapOutcome, assertSolanaInstructionsSafe, checkSolanaFeeBalance, assertSolanaSwapOutcome, approvalAmountForSwap, needsAllowanceRevoke, OVERSIZED_ALLOWANCE_MULTIPLIER, EVM_BRIDGE_NATIVE_FEE_SLACK, isBridgeRequest } from './trade-validation.js';
20
20
  import { readCompactU16 } from './solana-tx.js';
21
21
  import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
22
22
  export { readCompactU16 };
@@ -128,7 +128,9 @@ export function resolveTokenAddress(symbolOrAddress, chainName) {
128
128
  // - RPC_NETWORK_ERROR — request left but no response (reset/timeout): ambiguous
129
129
  // - RPC_HTTP_ERROR — non-JSON HTTP response (e.g. a 502 gateway page): ambiguous
130
130
  // - RPC_JSON_ERROR — a JSON-RPC { error }: the node definitively rejected it
131
- export async function evmRpcCall(chain, method, params = []) {
131
+ // `timeoutMs` (optional) aborts a request that has not completed in time; it
132
+ // surfaces as RPC_NETWORK_ERROR. Without it a request has no time limit.
133
+ export async function evmRpcCall(chain, method, params = [], { timeoutMs } = {}) {
132
134
  const rpcUrl = CHAIN_RPCS[chain];
133
135
  if (!rpcUrl) throw Object.assign(new Error(`No RPC URL configured for chain: ${chain}`), { code: 'RPC_UNCONFIGURED' });
134
136
  let res;
@@ -137,6 +139,7 @@ export async function evmRpcCall(chain, method, params = []) {
137
139
  method: 'POST',
138
140
  headers: { 'Content-Type': 'application/json' },
139
141
  body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
142
+ ...(timeoutMs ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
140
143
  });
141
144
  } catch (netErr) {
142
145
  // The request left this process but no response came back. A reset or
@@ -1477,6 +1480,68 @@ export async function waitForReceipt(chain, txHash, timeoutMs = 180000, pollMs =
1477
1480
  throw timeoutErr;
1478
1481
  }
1479
1482
 
1483
+ // A Solana transaction can only land while its recent blockhash is valid
1484
+ // (150 slots, roughly 60 to 90 seconds). 90s covers that window, so a timeout
1485
+ // usually means the transaction was dropped. It is still reported as
1486
+ // unconfirmed, never as failed: the CLI has not proven it cannot land.
1487
+ export const SOLANA_CONFIRM_TIMEOUT_MS = 90000;
1488
+ // Upper bound on a single status request inside that window.
1489
+ const SOLANA_RPC_REQUEST_TIMEOUT_MS = 10000;
1490
+
1491
+ /**
1492
+ * Wait for a Solana signature to reach `confirmed` commitment. The Solana
1493
+ * counterpart of waitForReceipt. It throws the same two codes, so the swap path
1494
+ * and isFatalBroadcastError treat both chain types alike:
1495
+ * - TX_REVERTED the transaction landed and failed (status `err` is set)
1496
+ * - RECEIPT_TIMEOUT no confirmed status in the window; it may still land
1497
+ *
1498
+ * An `err` seen at `processed` is not trusted: that slot can still be rolled
1499
+ * back, so the poll keeps going until the status is at least `confirmed`.
1500
+ * RPC and network errors are retried until the deadline, like waitForReceipt.
1501
+ *
1502
+ * @param {string} chain - chain key in CHAIN_RPCS (normally 'solana')
1503
+ * @param {string} signature - base58 transaction signature
1504
+ * @param {number} [timeoutMs]
1505
+ * @param {number} [pollMs]
1506
+ * @returns {Promise<object>} the signature status
1507
+ */
1508
+ export async function waitForSolanaSignature(chain, signature, timeoutMs = SOLANA_CONFIRM_TIMEOUT_MS, pollMs = 2000) {
1509
+ const start = Date.now();
1510
+ while (Date.now() - start < timeoutMs) {
1511
+ let status = null;
1512
+ try {
1513
+ // evmRpcCall is a plain JSON-RPC POST to CHAIN_RPCS[chain]; nothing in it
1514
+ // is EVM-specific. Each request is bounded by the time left, so a hung
1515
+ // request cannot outlive the deadline; an abort is a transient failure.
1516
+ const remainingMs = Math.max(1, timeoutMs - (Date.now() - start));
1517
+ const result = await evmRpcCall(chain, 'getSignatureStatuses', [[signature]], {
1518
+ timeoutMs: Math.min(SOLANA_RPC_REQUEST_TIMEOUT_MS, remainingMs),
1519
+ });
1520
+ status = result?.value?.[0] ?? null;
1521
+ } catch {
1522
+ // Transient RPC failure: keep polling until the deadline.
1523
+ }
1524
+ if (status) {
1525
+ // Older nodes omit confirmationStatus and report `confirmations: null`
1526
+ // for a rooted (finalized) transaction.
1527
+ const level = status.confirmationStatus
1528
+ ?? (status.confirmations === null ? 'finalized' : 'processed');
1529
+ if (level === 'confirmed' || level === 'finalized') {
1530
+ if (status.err) {
1531
+ const failErr = new Error(`Transaction failed on-chain: ${JSON.stringify(status.err)}. Signature: ${signature}`);
1532
+ failErr.code = 'TX_REVERTED';
1533
+ throw failErr;
1534
+ }
1535
+ return status;
1536
+ }
1537
+ }
1538
+ await new Promise(r => setTimeout(r, pollMs));
1539
+ }
1540
+ const timeoutErr = new Error(`Transaction not confirmed after ${timeoutMs}ms. Signature: ${signature}`);
1541
+ timeoutErr.code = 'RECEIPT_TIMEOUT';
1542
+ throw timeoutErr;
1543
+ }
1544
+
1480
1545
  /**
1481
1546
  * Post-broadcast outcomes that must abort the whole `execute` rather than fall
1482
1547
  * through to the next quote. Ambiguous failures may conceal a live transaction;
@@ -1567,6 +1632,46 @@ function assertTxHashMatch(signedTxHex, broadcasterTxHash, label = '') {
1567
1632
  return localHash;
1568
1633
  }
1569
1634
 
1635
+ /**
1636
+ * The Solana counterpart of assertTxHashMatch. A Solana transaction id is its
1637
+ * first signature (the fee payer's), so it is read straight out of the signed
1638
+ * bytes: [signatures_count (compact-u16)] [signatures (64 bytes each)...] ...
1639
+ *
1640
+ * Fails closed (TXHASH_MISMATCH) when the execute API reported a different
1641
+ * signature, and with INVALID_SIGNED_TX when none can be read from our bytes.
1642
+ *
1643
+ * @param {string} signedTxBase64 - the signed transaction we sent to /execute
1644
+ * @param {string} broadcasterSignature - the signature /execute returned (may be empty)
1645
+ * @returns {string} our locally-derived base58 signature
1646
+ */
1647
+ function assertSolanaSignatureMatch(signedTxBase64, broadcasterSignature) {
1648
+ let localSignature;
1649
+ try {
1650
+ const txBytes = Buffer.from(signedTxBase64 || '', 'base64');
1651
+ const { value: sigCount, size: sigCountSize } = readCompactU16(txBytes, 0);
1652
+ if (sigCount < 1) throw new Error('transaction has no signature slots');
1653
+ if (txBytes.length < sigCountSize + 64) throw new Error('transaction is too short to hold a signature');
1654
+ localSignature = base58Encode(txBytes.subarray(sigCountSize, sigCountSize + 64));
1655
+ } catch (sigErr) {
1656
+ throw new CommandError(
1657
+ `Aborting: cannot derive a local signature for the transaction this CLI signed: ${sigErr.message}. `
1658
+ + `The transaction may already have been broadcast, so nothing further will run — `
1659
+ + `check your wallet before retrying.`,
1660
+ 'INVALID_SIGNED_TX',
1661
+ );
1662
+ }
1663
+ if (broadcasterSignature && broadcasterSignature !== localSignature) {
1664
+ throw new CommandError(
1665
+ `Aborting: the broadcaster reported transaction ${broadcasterSignature}, but the transaction this CLI signed `
1666
+ + `has signature ${localSignature}. These must match — a mismatch means the confirmation would be for `
1667
+ + `a transaction you did not sign, so nothing has been verified and no further steps will `
1668
+ + `run. Check both signatures on a block explorer to see what was actually broadcast before retrying.`,
1669
+ 'TXHASH_MISMATCH',
1670
+ );
1671
+ }
1672
+ return localSignature;
1673
+ }
1674
+
1570
1675
  /**
1571
1676
  * Confirm a broadcast EVM transaction against the hash we derived locally from
1572
1677
  * the signed bytes — not the hash the broadcaster reported. See
@@ -2724,7 +2829,11 @@ async function preflightTradeExecutionCandidate({
2724
2829
  CHAIN_RPCS.solana,
2725
2830
  async () => walletAddress,
2726
2831
  );
2727
- assertSolanaInstructionsSafe(txBase64, { walletAddress });
2832
+ const safeTx = assertSolanaInstructionsSafe(txBase64, { walletAddress });
2833
+ const feeCheck = await checkSolanaFeeBalance({ parsed: safeTx, walletAddress, log });
2834
+ if (!feeCheck.proceed) {
2835
+ throw new CommandError(`Insufficient SOL for this transaction: ${feeCheck.reason}`, 'INSUFFICIENT_GAS');
2836
+ }
2728
2837
  if (!noVerifyOutcome) {
2729
2838
  const outcome = await verifySolanaSwapOutcome({
2730
2839
  chain,
@@ -3493,7 +3602,9 @@ EXAMPLES:
3493
3602
  // --quote-index pins a specific quote (no fallback)
3494
3603
  let pinIndex = null;
3495
3604
  if (options['quote-index'] != null) {
3496
- pinIndex = parseInt(options['quote-index'], 10);
3605
+ // parseInt alone would read "1.9" or "1abc" as 1 and pin a quote the user did not pick.
3606
+ const rawIndex = String(options['quote-index']).trim();
3607
+ pinIndex = /^\d+$/.test(rawIndex) ? Number(rawIndex) : NaN;
3497
3608
  if (!Number.isInteger(pinIndex) || pinIndex < 0 || pinIndex >= allQuotes.length) {
3498
3609
  throw new CommandError(
3499
3610
  `❌ Invalid --quote-index "${options['quote-index']}". Must be an integer between 0 and ${allQuotes.length - 1}.`,
@@ -3799,7 +3910,19 @@ EXAMPLES:
3799
3910
  // alone wouldn't see. The residual sibling-transfer gap is closed by
3800
3911
  // verifySolanaSwapOutcome below (degrades gracefully when no sim RPC
3801
3912
  // is available, so this static check remains a guard when sim is off).
3802
- assertSolanaInstructionsSafe(txBase64, { walletAddress });
3913
+ const safeTx = assertSolanaInstructionsSafe(txBase64, { walletAddress });
3914
+
3915
+ // Check the wallet can pay this transaction's actual fee.
3916
+ // Runs regardless of --no-verify-outcome: simulation would also
3917
+ // catch an unpayable transaction, but not when it is skipped or
3918
+ // degraded. Warns and proceeds if the balance read fails.
3919
+ const feeCheck = await checkSolanaFeeBalance({ parsed: safeTx, walletAddress, log });
3920
+ if (!feeCheck.proceed) {
3921
+ log(` ❌ ${quoteName} cannot be paid for: ${feeCheck.reason}`);
3922
+ if (qi + 1 < endIndex) log(' Trying next quote...');
3923
+ lastQuoteError = `${quoteName} insufficient SOL: ${feeCheck.reason}`;
3924
+ continue;
3925
+ }
3803
3926
 
3804
3927
  // Verify the swap's simulated on-chain outcome matches intent.
3805
3928
  // Degrades with a warning if no simulation endpoint is available.
@@ -4125,7 +4248,19 @@ EXAMPLES:
4125
4248
  // alone wouldn't see. The residual sibling-transfer gap is closed by
4126
4249
  // verifySolanaSwapOutcome below (degrades gracefully when no sim RPC
4127
4250
  // is available, so this static check remains a guard when sim is off).
4128
- assertSolanaInstructionsSafe(txBase64, { walletAddress: solanaWalletAddress });
4251
+ const safeTx = assertSolanaInstructionsSafe(txBase64, { walletAddress: solanaWalletAddress });
4252
+
4253
+ // Check the wallet can pay this transaction's actual fee.
4254
+ // Runs regardless of --no-verify-outcome: simulation would also
4255
+ // catch an unpayable transaction, but not when it is skipped or
4256
+ // degraded. Warns and proceeds if the balance read fails.
4257
+ const feeCheck = await checkSolanaFeeBalance({ parsed: safeTx, walletAddress: solanaWalletAddress, log });
4258
+ if (!feeCheck.proceed) {
4259
+ log(` ❌ ${quoteName} cannot be paid for: ${feeCheck.reason}`);
4260
+ if (qi + 1 < endIndex) log(' Trying next quote...');
4261
+ lastQuoteError = `${quoteName} insufficient SOL: ${feeCheck.reason}`;
4262
+ continue;
4263
+ }
4129
4264
 
4130
4265
  // Verify the swap's simulated on-chain outcome matches intent.
4131
4266
  // Degrades with a warning if no simulation endpoint is available.
@@ -4947,12 +5082,11 @@ EXAMPLES:
4947
5082
  if (chainType === 'evm') {
4948
5083
  log(` Checking for a receipt anyway — this can take up to 3 minutes and may time out.`);
4949
5084
  } else {
4950
- // Solana has no receipt poll below to resolve this. The EVM
4951
- // branch either confirms the hash or fails closed on a timeout;
4952
- // Solana would fall straight through to "✓ Transaction
4953
- // successful!" and exit 0 for a broadcast the node refused, so
4954
- // an agent would record a swap that may never have propagated.
4955
- // Nothing here verified anything, so do not report success.
5085
+ // Solana fails closed here without waiting on the signature
5086
+ // poll below: a broadcast the node refused is the case most
5087
+ // likely to end in that poll's timeout, so stop now with the
5088
+ // more specific error. Nothing here verified anything, so do
5089
+ // not report success.
4956
5090
  //
4957
5091
  // The quote was marked spent above and no candidate fallback
4958
5092
  // runs from here, so this only changes what we REPORT: a
@@ -5004,6 +5138,32 @@ EXAMPLES:
5004
5138
  }
5005
5139
  }
5006
5140
 
5141
+ // For Solana: the execute API's "Success" only says the transaction
5142
+ // was submitted. Solana drops transactions without a trace, and one
5143
+ // that lands can still fail, so ask the chain before reporting
5144
+ // success. Same outcomes and codes as the EVM branch above; both are
5145
+ // fatal (isFatalBroadcastError), so no further quote is tried and
5146
+ // the quote stays marked as spent.
5147
+ if (chainType === 'solana') {
5148
+ log(' Verifying on-chain status...');
5149
+ // Poll the signature of the transaction we signed, not the one
5150
+ // the API reported: a confirmed status for some other
5151
+ // transaction must not count as ours landing.
5152
+ txId = assertSolanaSignatureMatch(signedTransaction, txId);
5153
+ explorerUrl = chainConfig.explorer + txId;
5154
+ try {
5155
+ await waitForSolanaSignature(chain, txId);
5156
+ } catch (statusErr) {
5157
+ if (statusErr.code === 'RECEIPT_TIMEOUT') {
5158
+ throw new CommandError(`\n ⚠ Transaction was submitted but NOT confirmed within the wait window.\n Signature: ${txId}\n Explorer: ${explorerUrl}\n ${statusErr.message}\n\n The transaction may still land. Do NOT assume it failed: check the explorer\n before retrying, because retrying may execute a second swap.`, 'RECEIPT_TIMEOUT');
5159
+ }
5160
+ if (statusErr.code === 'TX_REVERTED') {
5161
+ throw new CommandError(`\n ⚠ Transaction landed but FAILED on-chain!\n Signature: ${txId}\n Explorer: ${explorerUrl}\n Error: ${statusErr.message}\n\n No further quote was attempted. Review the transaction, then request a new quote before retrying.`, 'TX_REVERTED');
5162
+ }
5163
+ throw statusErr;
5164
+ }
5165
+ }
5166
+
5007
5167
  log(`\n ✓ Transaction successful!`);
5008
5168
  log(` Status: ${result.status}`);
5009
5169
  log(` ${chainType === 'solana' ? 'Signature' : 'Tx Hash'}: ${txId}`);
package/src/transfer.js CHANGED
@@ -664,7 +664,7 @@ export { parseAmount, formatAmount, signEd25519, encodeCompactU16, base58Decode,
664
664
  * Solana builds unsigned tx, signs via Privy, then broadcasts.
665
665
  */
666
666
  async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walletInfo }) {
667
- const { PrivyClient } = await import('./privy.js');
667
+ const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
668
668
  const client = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
669
669
 
670
670
  if (chain === 'solana') {
@@ -672,6 +672,9 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle
672
672
  const fromAddress = walletInfo.solana;
673
673
  if (!fromAddress) throw new Error('No Solana wallet in this Privy wallet');
674
674
  if (!walletId) throw new Error('No Privy Solana wallet ID found. Re-create the wallet with: nansen wallet create --provider privy');
675
+ if (token && !validateSolanaAddress(token).valid) throw new Error('Invalid Solana token address');
676
+ if (!max && !token) parseAmount(amount, 9);
677
+ await assertPrivyWalletAddress(client, walletId, fromAddress, 'solana');
675
678
 
676
679
  if (max && !token) {
677
680
  const balResult = await rpcCall(CHAIN_RPCS.solana, 'getBalance', [fromAddress, { commitment: 'confirmed' }]);
@@ -715,6 +718,9 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle
715
718
 
716
719
  const chainId = CHAIN_IDS[chain];
717
720
  if (!chainId) throw new Error(`Unsupported chain: ${chain}`);
721
+ if (token && !validateEvmAddress(token).valid) throw new Error('Invalid ERC-20 token address');
722
+ if (!max && !token) parseAmount(amount, 18);
723
+ await assertPrivyWalletAddress(client, walletId, fromAddress, 'evm');
718
724
 
719
725
  let decimals = 18;
720
726
  const rpcUrl = CHAIN_RPCS[chain] || CHAIN_RPCS.evm;
@@ -44,7 +44,27 @@ export function isNewer(latest, current) {
44
44
  return compareSemver(latest, current) > 0;
45
45
  }
46
46
 
47
- const LAST_VERSION_FILE = path.join(CONFIG_DIR, 'last-version.json');
47
+ /**
48
+ * Return the minimum Node version the latest release requires when the
49
+ * running Node is below it, otherwise null. `enginesNode` is the cached
50
+ * `engines.node` of the latest release; a cache written before it was
51
+ * recorded has none, so this returns null and callers fall back to the plain
52
+ * update notice.
53
+ *
54
+ * Only a single lower bound (">=22", ">=22.14.0") is understood, compared on
55
+ * the full version so ">=22.14.0" rejects v22.0.0. Any other range ("||", "^",
56
+ * upper bounds) also returns null rather than guessing.
57
+ *
58
+ * npm installs the newest version whose engines match the running Node, so on
59
+ * an older Node "npm i -g nansen-cli" resolves back to the installed version.
60
+ */
61
+ export function nodeTooOldFor(enginesNode, nodeVersion = process.version) {
62
+ const match = /^\s*>=\s*v?(\d+(?:\.\d+){0,2})\s*$/.exec(typeof enginesNode === 'string' ? enginesNode : '');
63
+ if (!match || !/^v?\d/.test(String(nodeVersion))) return null;
64
+ return compareSemver(nodeVersion, match[1]) < 0 ? match[1] : null;
65
+ }
66
+
67
+ const LAST_VERSION_FILE =path.join(CONFIG_DIR, 'last-version.json');
48
68
 
49
69
  /**
50
70
  * After an update, show a one-time "what's new" notice on the first run.
@@ -82,16 +102,20 @@ export function getUpgradeNotice(currentVersion) {
82
102
  /**
83
103
  * Read the cached check result and return a notification string (or null).
84
104
  */
85
- export function getUpdateNotification(currentVersion) {
105
+ export function getUpdateNotification(currentVersion, nodeVersion = process.version) {
86
106
  try {
87
107
  if (process.env.NO_UPDATE_NOTIFIER || process.env.CI) return null;
88
108
  if (!fs.existsSync(CACHE_FILE)) return null;
89
109
 
90
110
  const raw = fs.readFileSync(CACHE_FILE, 'utf8');
91
- const { latest } = JSON.parse(raw);
111
+ const { latest, engines } = JSON.parse(raw);
92
112
  if (!latest) return null;
93
113
 
94
114
  if (isNewer(latest, currentVersion)) {
115
+ const neededNode = nodeTooOldFor(engines, nodeVersion);
116
+ if (neededNode) {
117
+ return `Update available: ${currentVersion} → ${latest}, but it requires Node >= ${neededNode} (you have ${nodeVersion}). Install Node >= ${neededNode}, then: npm i -g ${PACKAGE_NAME}`;
118
+ }
95
119
  return `Update available: ${currentVersion} → ${latest} (npm i -g ${PACKAGE_NAME})`;
96
120
  }
97
121
  return null;
@@ -129,12 +153,15 @@ export function buildCheckScript(dir, file, url = REGISTRY_URL) {
129
153
  res.on('data', c => body += c);
130
154
  res.on('end', () => {
131
155
  try {
132
- const { version } = JSON.parse(body);
156
+ const { version, engines } = JSON.parse(body);
133
157
  if (typeof version !== 'string' || version.trim() === '') return;
158
+ // Keep the latest release's Node requirement so the notice can say
159
+ // when a reinstall would not reach it. Omitted when absent.
160
+ const node = engines && typeof engines.node === 'string' ? engines.node : undefined;
134
161
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { mode: 0o700, recursive: true });
135
162
  const tmp = file + '.' + process.pid + '.tmp';
136
163
  try {
137
- fs.writeFileSync(tmp, JSON.stringify({ latest: version, checkedAt: Date.now() }));
164
+ fs.writeFileSync(tmp, JSON.stringify({ latest: version, engines: node, checkedAt: Date.now() }));
138
165
  fs.renameSync(tmp, file);
139
166
  } catch (e) {
140
167
  try { fs.unlinkSync(tmp); } catch {}