nansen-cli 2.3.0 → 2.5.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 (80) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +61 -38
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +251 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +20 -4
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +17 -14
  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 +9 -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 +5 -2
  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 +23 -2
  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 +11 -5
  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 +282 -124
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-key-input.js +57 -9
  45. package/src/auth-state.js +2 -2
  46. package/src/auth-store-native.js +6 -1
  47. package/src/auth-store-worker.js +1 -1
  48. package/src/auth-store.js +9 -4
  49. package/src/auto-paginate.js +25 -7
  50. package/src/bridge.js +19 -10
  51. package/src/cache-inspect.js +16 -6
  52. package/src/cli.js +272 -114
  53. package/src/commands/agent.js +2 -3
  54. package/src/commands/alerts.js +365 -18
  55. package/src/commands/completion.js +4 -1
  56. package/src/commands/feedback.js +98 -37
  57. package/src/commands/mcp.js +1 -1
  58. package/src/commands/research.js +14 -37
  59. package/src/cost-cache.js +33 -7
  60. package/src/doctor.js +14 -5
  61. package/src/ens.js +14 -5
  62. package/src/error-codes.js +228 -0
  63. package/src/execute-guard.js +8 -3
  64. package/src/input-validation.js +555 -0
  65. package/src/limit-order.js +127 -54
  66. package/src/perp.js +358 -35
  67. package/src/privy.js +90 -15
  68. package/src/query-options.js +47 -8
  69. package/src/response-cache-files.js +65 -0
  70. package/src/response-meta.js +8 -2
  71. package/src/rpc-urls.js +3 -1
  72. package/src/schema.json +1254 -156
  73. package/src/solana-tx.js +4 -0
  74. package/src/telemetry-flags.js +75 -0
  75. package/src/trade-validation.js +167 -8
  76. package/src/trading.js +243 -20
  77. package/src/transfer.js +79 -12
  78. package/src/update-check.js +32 -5
  79. package/src/wallet.js +246 -69
  80. package/src/walletconnect-x402.js +27 -9
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
@@ -319,10 +322,14 @@ function fromStandardResponse(body, chainType) {
319
322
  * `ambiguousBroadcast` is the default for every failure after the signed payload
320
323
  * is handed to fetch. An HTTP status describes the response, not whether the
321
324
  * backend forwarded the transaction before producing it: 408/429 and even an
322
- * intermediary-generated 400/409 can arrive after processing began. Until the
323
- * execute API has a documented, authenticated field that explicitly guarantees
324
- * pre-broadcast rejection, no response from this endpoint may authorize signing
325
- * the next candidate.
325
+ * intermediary-generated 400/409 can arrive after processing began, so no
326
+ * non-2xx response may authorize signing the next candidate.
327
+ *
328
+ * The one exception is the standard route's documented pre-broadcast rejection:
329
+ * a 400 carrying a code from STANDARD_PRE_BROADCAST_CODES and no transaction
330
+ * identifier (see isStandardPreBroadcastRejection). That is the same "failed, no
331
+ * transaction" statement the route makes in a 200 body, so it gets the same
332
+ * treatment.
326
333
  */
327
334
  function ambiguousBroadcast(message, { status, details } = {}) {
328
335
  // Deliberately never carries broadcastRuledOut. BROADCAST_FAILED is classified
@@ -330,6 +337,49 @@ function ambiguousBroadcast(message, { status, details } = {}) {
330
337
  return Object.assign(new Error(message), { code: 'BROADCAST_FAILED', status, details });
331
338
  }
332
339
 
340
+ /**
341
+ * Codes the trading API documents as returned before any broadcast on
342
+ * `/execution/standard`. The route answers them as `400 { code, message }` and
343
+ * releases its single-flight lock on the quote, because the swap never left the
344
+ * backend. Kept as an explicit list rather than a pattern: adding a code here
345
+ * lets the candidate loop sign the next quote after it, so it must be a
346
+ * deliberate edit drawn from the API's own published list.
347
+ *
348
+ * A subset of that list, not a copy. `APPROVAL_BROADCAST_FAILED` is left out:
349
+ * the API returns it only when an approval is bundled into the request, and the
350
+ * CLI never bundles one (approvals go out as their own executeTransaction
351
+ * call). The code also says the swap was not sent, not that the approval was
352
+ * not: the API notes the approval may still sit in a mempool. A response with
353
+ * it is therefore unexpected here and stays ambiguous.
354
+ */
355
+ const STANDARD_PRE_BROADCAST_CODES = Object.freeze([
356
+ 'QUOTE_EXPIRED',
357
+ 'INPUT_TRANSFER_FAILED',
358
+ 'SIMULATION_FAILED',
359
+ 'SIMULATION_MIN_RETURN_NOT_REACHED',
360
+ 'INSUFFICIENT_BALANCE',
361
+ ]);
362
+
363
+ const isAbsentTxId = (value) => value === undefined || value === null || value === '';
364
+
365
+ /**
366
+ * True only for the standard route's documented "never broadcast" answer: a 400
367
+ * whose JSON body names a listed code, carries no transaction identifier and
368
+ * has no `success` other than `false`. Anything short of all of that stays ambiguous.
369
+ */
370
+ function isStandardPreBroadcastRejection(status, parsed, body) {
371
+ return status === 400
372
+ && parsed
373
+ && isReadableBody(body)
374
+ && typeof body.code === 'string'
375
+ && STANDARD_PRE_BROADCAST_CODES.includes(body.code)
376
+ && isAbsentTxId(body.txHash)
377
+ && isAbsentTxId(body.signature)
378
+ // The documented body has no `success`; an explicit `false` says the same.
379
+ // Any other value is not this shape, so it stays ambiguous.
380
+ && (body.success === undefined || body.success === false);
381
+ }
382
+
333
383
  /**
334
384
  * A JSON body the branches below can read fields off. JSON.parse also succeeds
335
385
  * on `null`, an array and a bare string or number, none of which carry the
@@ -521,10 +571,26 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
521
571
  );
522
572
  }
523
573
 
524
- // A non-2xx status does not prove the signed transaction stayed put. The
525
- // backend or an intermediary may have produced the response after forwarding
526
- // it, so preserve any structured error only as diagnostic detail and fail
527
- // closed. Do not allow the candidate loop to sign another transaction.
574
+ // The standard route's documented pre-broadcast rejection. Returned as the
575
+ // same "Failed, no hash" result a 200 `success: false` body produces, so the
576
+ // candidate loop releases the claim and tries the next quote exactly as it
577
+ // already does for that body.
578
+ //
579
+ // First attempt only: a retry follows a 5xx or a dropped connection whose
580
+ // outcome is unknown, and a later "never broadcast" speaks for the retry,
581
+ // not for the earlier POST that may have gone out.
582
+ if (isStandard && attempt === 0 && isStandardPreBroadcastRejection(res.status, parsed, body)) {
583
+ return fromStandardResponse(
584
+ { ...body, success: false, txHash: undefined, signature: undefined },
585
+ chainConfigFor(params.chain)?.type,
586
+ );
587
+ }
588
+
589
+ // Every other non-2xx status does not prove the signed transaction stayed
590
+ // put. The backend or an intermediary may have produced the response after
591
+ // forwarding it, so preserve any structured error only as diagnostic detail
592
+ // and fail closed. Do not allow the candidate loop to sign another
593
+ // transaction.
528
594
  if (!res.ok) {
529
595
  const readableBody = parsed && isReadableBody(body);
530
596
  throw ambiguousBroadcast(
@@ -1477,6 +1543,68 @@ export async function waitForReceipt(chain, txHash, timeoutMs = 180000, pollMs =
1477
1543
  throw timeoutErr;
1478
1544
  }
1479
1545
 
1546
+ // A Solana transaction can only land while its recent blockhash is valid
1547
+ // (150 slots, roughly 60 to 90 seconds). 90s covers that window, so a timeout
1548
+ // usually means the transaction was dropped. It is still reported as
1549
+ // unconfirmed, never as failed: the CLI has not proven it cannot land.
1550
+ export const SOLANA_CONFIRM_TIMEOUT_MS = 90000;
1551
+ // Upper bound on a single status request inside that window.
1552
+ const SOLANA_RPC_REQUEST_TIMEOUT_MS = 10000;
1553
+
1554
+ /**
1555
+ * Wait for a Solana signature to reach `confirmed` commitment. The Solana
1556
+ * counterpart of waitForReceipt. It throws the same two codes, so the swap path
1557
+ * and isFatalBroadcastError treat both chain types alike:
1558
+ * - TX_REVERTED the transaction landed and failed (status `err` is set)
1559
+ * - RECEIPT_TIMEOUT no confirmed status in the window; it may still land
1560
+ *
1561
+ * An `err` seen at `processed` is not trusted: that slot can still be rolled
1562
+ * back, so the poll keeps going until the status is at least `confirmed`.
1563
+ * RPC and network errors are retried until the deadline, like waitForReceipt.
1564
+ *
1565
+ * @param {string} chain - chain key in CHAIN_RPCS (normally 'solana')
1566
+ * @param {string} signature - base58 transaction signature
1567
+ * @param {number} [timeoutMs]
1568
+ * @param {number} [pollMs]
1569
+ * @returns {Promise<object>} the signature status
1570
+ */
1571
+ export async function waitForSolanaSignature(chain, signature, timeoutMs = SOLANA_CONFIRM_TIMEOUT_MS, pollMs = 2000) {
1572
+ const start = Date.now();
1573
+ while (Date.now() - start < timeoutMs) {
1574
+ let status = null;
1575
+ try {
1576
+ // evmRpcCall is a plain JSON-RPC POST to CHAIN_RPCS[chain]; nothing in it
1577
+ // is EVM-specific. Each request is bounded by the time left, so a hung
1578
+ // request cannot outlive the deadline; an abort is a transient failure.
1579
+ const remainingMs = Math.max(1, timeoutMs - (Date.now() - start));
1580
+ const result = await evmRpcCall(chain, 'getSignatureStatuses', [[signature]], {
1581
+ timeoutMs: Math.min(SOLANA_RPC_REQUEST_TIMEOUT_MS, remainingMs),
1582
+ });
1583
+ status = result?.value?.[0] ?? null;
1584
+ } catch {
1585
+ // Transient RPC failure: keep polling until the deadline.
1586
+ }
1587
+ if (status) {
1588
+ // Older nodes omit confirmationStatus and report `confirmations: null`
1589
+ // for a rooted (finalized) transaction.
1590
+ const level = status.confirmationStatus
1591
+ ?? (status.confirmations === null ? 'finalized' : 'processed');
1592
+ if (level === 'confirmed' || level === 'finalized') {
1593
+ if (status.err) {
1594
+ const failErr = new Error(`Transaction failed on-chain: ${JSON.stringify(status.err)}. Signature: ${signature}`);
1595
+ failErr.code = 'TX_REVERTED';
1596
+ throw failErr;
1597
+ }
1598
+ return status;
1599
+ }
1600
+ }
1601
+ await new Promise(r => setTimeout(r, pollMs));
1602
+ }
1603
+ const timeoutErr = new Error(`Transaction not confirmed after ${timeoutMs}ms. Signature: ${signature}`);
1604
+ timeoutErr.code = 'RECEIPT_TIMEOUT';
1605
+ throw timeoutErr;
1606
+ }
1607
+
1480
1608
  /**
1481
1609
  * Post-broadcast outcomes that must abort the whole `execute` rather than fall
1482
1610
  * through to the next quote. Ambiguous failures may conceal a live transaction;
@@ -1567,6 +1695,46 @@ function assertTxHashMatch(signedTxHex, broadcasterTxHash, label = '') {
1567
1695
  return localHash;
1568
1696
  }
1569
1697
 
1698
+ /**
1699
+ * The Solana counterpart of assertTxHashMatch. A Solana transaction id is its
1700
+ * first signature (the fee payer's), so it is read straight out of the signed
1701
+ * bytes: [signatures_count (compact-u16)] [signatures (64 bytes each)...] ...
1702
+ *
1703
+ * Fails closed (TXHASH_MISMATCH) when the execute API reported a different
1704
+ * signature, and with INVALID_SIGNED_TX when none can be read from our bytes.
1705
+ *
1706
+ * @param {string} signedTxBase64 - the signed transaction we sent to /execute
1707
+ * @param {string} broadcasterSignature - the signature /execute returned (may be empty)
1708
+ * @returns {string} our locally-derived base58 signature
1709
+ */
1710
+ function assertSolanaSignatureMatch(signedTxBase64, broadcasterSignature) {
1711
+ let localSignature;
1712
+ try {
1713
+ const txBytes = Buffer.from(signedTxBase64 || '', 'base64');
1714
+ const { value: sigCount, size: sigCountSize } = readCompactU16(txBytes, 0);
1715
+ if (sigCount < 1) throw new Error('transaction has no signature slots');
1716
+ if (txBytes.length < sigCountSize + 64) throw new Error('transaction is too short to hold a signature');
1717
+ localSignature = base58Encode(txBytes.subarray(sigCountSize, sigCountSize + 64));
1718
+ } catch (sigErr) {
1719
+ throw new CommandError(
1720
+ `Aborting: cannot derive a local signature for the transaction this CLI signed: ${sigErr.message}. `
1721
+ + `The transaction may already have been broadcast, so nothing further will run — `
1722
+ + `check your wallet before retrying.`,
1723
+ 'INVALID_SIGNED_TX',
1724
+ );
1725
+ }
1726
+ if (broadcasterSignature && broadcasterSignature !== localSignature) {
1727
+ throw new CommandError(
1728
+ `Aborting: the broadcaster reported transaction ${broadcasterSignature}, but the transaction this CLI signed `
1729
+ + `has signature ${localSignature}. These must match — a mismatch means the confirmation would be for `
1730
+ + `a transaction you did not sign, so nothing has been verified and no further steps will `
1731
+ + `run. Check both signatures on a block explorer to see what was actually broadcast before retrying.`,
1732
+ 'TXHASH_MISMATCH',
1733
+ );
1734
+ }
1735
+ return localSignature;
1736
+ }
1737
+
1570
1738
  /**
1571
1739
  * Confirm a broadcast EVM transaction against the hash we derived locally from
1572
1740
  * the signed bytes — not the hash the broadcaster reported. See
@@ -2724,7 +2892,11 @@ async function preflightTradeExecutionCandidate({
2724
2892
  CHAIN_RPCS.solana,
2725
2893
  async () => walletAddress,
2726
2894
  );
2727
- assertSolanaInstructionsSafe(txBase64, { walletAddress });
2895
+ const safeTx = assertSolanaInstructionsSafe(txBase64, { walletAddress });
2896
+ const feeCheck = await checkSolanaFeeBalance({ parsed: safeTx, walletAddress, log });
2897
+ if (!feeCheck.proceed) {
2898
+ throw new CommandError(`Insufficient SOL for this transaction: ${feeCheck.reason}`, 'INSUFFICIENT_GAS');
2899
+ }
2728
2900
  if (!noVerifyOutcome) {
2729
2901
  const outcome = await verifySolanaSwapOutcome({
2730
2902
  chain,
@@ -3493,7 +3665,9 @@ EXAMPLES:
3493
3665
  // --quote-index pins a specific quote (no fallback)
3494
3666
  let pinIndex = null;
3495
3667
  if (options['quote-index'] != null) {
3496
- pinIndex = parseInt(options['quote-index'], 10);
3668
+ // parseInt alone would read "1.9" or "1abc" as 1 and pin a quote the user did not pick.
3669
+ const rawIndex = String(options['quote-index']).trim();
3670
+ pinIndex = /^\d+$/.test(rawIndex) ? Number(rawIndex) : NaN;
3497
3671
  if (!Number.isInteger(pinIndex) || pinIndex < 0 || pinIndex >= allQuotes.length) {
3498
3672
  throw new CommandError(
3499
3673
  `❌ Invalid --quote-index "${options['quote-index']}". Must be an integer between 0 and ${allQuotes.length - 1}.`,
@@ -3799,7 +3973,19 @@ EXAMPLES:
3799
3973
  // alone wouldn't see. The residual sibling-transfer gap is closed by
3800
3974
  // verifySolanaSwapOutcome below (degrades gracefully when no sim RPC
3801
3975
  // is available, so this static check remains a guard when sim is off).
3802
- assertSolanaInstructionsSafe(txBase64, { walletAddress });
3976
+ const safeTx = assertSolanaInstructionsSafe(txBase64, { walletAddress });
3977
+
3978
+ // Check the wallet can pay this transaction's actual fee.
3979
+ // Runs regardless of --no-verify-outcome: simulation would also
3980
+ // catch an unpayable transaction, but not when it is skipped or
3981
+ // degraded. Warns and proceeds if the balance read fails.
3982
+ const feeCheck = await checkSolanaFeeBalance({ parsed: safeTx, walletAddress, log });
3983
+ if (!feeCheck.proceed) {
3984
+ log(` ❌ ${quoteName} cannot be paid for: ${feeCheck.reason}`);
3985
+ if (qi + 1 < endIndex) log(' Trying next quote...');
3986
+ lastQuoteError = `${quoteName} insufficient SOL: ${feeCheck.reason}`;
3987
+ continue;
3988
+ }
3803
3989
 
3804
3990
  // Verify the swap's simulated on-chain outcome matches intent.
3805
3991
  // Degrades with a warning if no simulation endpoint is available.
@@ -4125,7 +4311,19 @@ EXAMPLES:
4125
4311
  // alone wouldn't see. The residual sibling-transfer gap is closed by
4126
4312
  // verifySolanaSwapOutcome below (degrades gracefully when no sim RPC
4127
4313
  // is available, so this static check remains a guard when sim is off).
4128
- assertSolanaInstructionsSafe(txBase64, { walletAddress: solanaWalletAddress });
4314
+ const safeTx = assertSolanaInstructionsSafe(txBase64, { walletAddress: solanaWalletAddress });
4315
+
4316
+ // Check the wallet can pay this transaction's actual fee.
4317
+ // Runs regardless of --no-verify-outcome: simulation would also
4318
+ // catch an unpayable transaction, but not when it is skipped or
4319
+ // degraded. Warns and proceeds if the balance read fails.
4320
+ const feeCheck = await checkSolanaFeeBalance({ parsed: safeTx, walletAddress: solanaWalletAddress, log });
4321
+ if (!feeCheck.proceed) {
4322
+ log(` ❌ ${quoteName} cannot be paid for: ${feeCheck.reason}`);
4323
+ if (qi + 1 < endIndex) log(' Trying next quote...');
4324
+ lastQuoteError = `${quoteName} insufficient SOL: ${feeCheck.reason}`;
4325
+ continue;
4326
+ }
4129
4327
 
4130
4328
  // Verify the swap's simulated on-chain outcome matches intent.
4131
4329
  // Degrades with a warning if no simulation endpoint is available.
@@ -4947,12 +5145,11 @@ EXAMPLES:
4947
5145
  if (chainType === 'evm') {
4948
5146
  log(` Checking for a receipt anyway — this can take up to 3 minutes and may time out.`);
4949
5147
  } 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.
5148
+ // Solana fails closed here without waiting on the signature
5149
+ // poll below: a broadcast the node refused is the case most
5150
+ // likely to end in that poll's timeout, so stop now with the
5151
+ // more specific error. Nothing here verified anything, so do
5152
+ // not report success.
4956
5153
  //
4957
5154
  // The quote was marked spent above and no candidate fallback
4958
5155
  // runs from here, so this only changes what we REPORT: a
@@ -5004,6 +5201,32 @@ EXAMPLES:
5004
5201
  }
5005
5202
  }
5006
5203
 
5204
+ // For Solana: the execute API's "Success" only says the transaction
5205
+ // was submitted. Solana drops transactions without a trace, and one
5206
+ // that lands can still fail, so ask the chain before reporting
5207
+ // success. Same outcomes and codes as the EVM branch above; both are
5208
+ // fatal (isFatalBroadcastError), so no further quote is tried and
5209
+ // the quote stays marked as spent.
5210
+ if (chainType === 'solana') {
5211
+ log(' Verifying on-chain status...');
5212
+ // Poll the signature of the transaction we signed, not the one
5213
+ // the API reported: a confirmed status for some other
5214
+ // transaction must not count as ours landing.
5215
+ txId = assertSolanaSignatureMatch(signedTransaction, txId);
5216
+ explorerUrl = chainConfig.explorer + txId;
5217
+ try {
5218
+ await waitForSolanaSignature(chain, txId);
5219
+ } catch (statusErr) {
5220
+ if (statusErr.code === 'RECEIPT_TIMEOUT') {
5221
+ 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');
5222
+ }
5223
+ if (statusErr.code === 'TX_REVERTED') {
5224
+ 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');
5225
+ }
5226
+ throw statusErr;
5227
+ }
5228
+ }
5229
+
5007
5230
  log(`\n ✓ Transaction successful!`);
5008
5231
  log(` Status: ${result.status}`);
5009
5232
  log(` ${chainType === 'solana' ? 'Signature' : 'Tx Hash'}: ${txId}`);
package/src/transfer.js CHANGED
@@ -46,6 +46,49 @@ function validateSolanaAddress(address) {
46
46
  } catch { return { valid: false, error: 'Invalid Solana address' }; }
47
47
  }
48
48
 
49
+ // ============= Token Symbols =============
50
+
51
+ // Well-known stablecoin symbols `wallet send --token` accepts in place of a
52
+ // contract address or mint, per chain the command supports. `evm` signs for
53
+ // chain ID 1, so it takes the Ethereum addresses. Base and Solana match the
54
+ // `trade` symbol map (trading.js TOKEN_SYMBOLS), so a symbol means the same
55
+ // token in both commands.
56
+ const ETHEREUM_STABLECOINS = {
57
+ USDC: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
58
+ USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
59
+ };
60
+ const SEND_TOKEN_SYMBOLS = {
61
+ ethereum: ETHEREUM_STABLECOINS,
62
+ evm: ETHEREUM_STABLECOINS,
63
+ base: {
64
+ USDC: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
65
+ USDT: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',
66
+ },
67
+ solana: {
68
+ USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
69
+ USDT: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB',
70
+ },
71
+ };
72
+
73
+ /**
74
+ * Turn a `--token` value into a token address for `chain`. A known symbol
75
+ * (case-insensitive) maps to its address; an address passes through as given.
76
+ * Anything else fails here, before an RPC call, instead of reaching the node as
77
+ * a malformed address (which answered with a bare "Invalid params").
78
+ */
79
+ function resolveSendToken(token, chain) {
80
+ if (token == null) return null;
81
+ const symbols = SEND_TOKEN_SYMBOLS[chain] || {};
82
+ const known = symbols[String(token).toUpperCase()];
83
+ if (known) return known;
84
+ const check = chain === 'solana' ? validateSolanaAddress(token) : validateEvmAddress(token);
85
+ if (check.valid) return token;
86
+ const kind = chain === 'solana' ? 'mint address' : 'contract address';
87
+ const names = Object.keys(symbols);
88
+ const choices = names.length ? `, or one of: ${names.join(', ')}` : '';
89
+ throw new Error(`Unknown token "${token}" on ${chain}. Pass the token's ${kind}${choices}. Omit --token to send the native currency.`);
90
+ }
91
+
49
92
  // ============= Amount Parsing =============
50
93
 
51
94
  function parseAmount(amountStr, decimals) {
@@ -80,7 +123,7 @@ function formatAmount(rawAmount, decimals) {
80
123
 
81
124
  // ============= RPC =============
82
125
 
83
- async function rpcCall(url, method, params = []) {
126
+ async function rpcCall(url, method, params = [], context = {}) {
84
127
  const response = await fetch(url, {
85
128
  method: 'POST',
86
129
  headers: { 'Content-Type': 'application/json' },
@@ -88,7 +131,7 @@ async function rpcCall(url, method, params = []) {
88
131
  });
89
132
  const data = await response.json();
90
133
  if (data.error) {
91
- const err = new Error(friendlyRpcError(data.error, method));
134
+ const err = new Error(friendlyRpcError(data.error, method, context));
92
135
  // Classified from the raw RPC text, before any rewording, so callers can
93
136
  // branch on it without depending on the friendly message's wording.
94
137
  err.transactionWouldFail = isTransactionFailureMessage(data.error);
@@ -119,8 +162,11 @@ function isTransactionFailureMessage(error) {
119
162
  * geth rejects an underfunded transaction with "insufficient funds for gas *
120
163
  * price + value", which used to match the Solana branch and tell a Base or
121
164
  * Ethereum user to top up SOL.
165
+ *
166
+ * `context.nativeSolSend` marks the broadcast of a plain SOL transfer, the only
167
+ * transaction whose account indices this function can interpret.
122
168
  */
123
- function friendlyRpcError(error, method = '') {
169
+ function friendlyRpcError(error, method = '', context = {}) {
124
170
  const msg = error.message || JSON.stringify(error);
125
171
  const lower = msg.toLowerCase();
126
172
  const isEvm = typeof method === 'string' && method.toLowerCase().startsWith('eth_');
@@ -131,6 +177,17 @@ function friendlyRpcError(error, method = '') {
131
177
  if (lower.includes('no record of a prior credit') || lower.includes('accountnotfound')) {
132
178
  return 'Insufficient SOL for transaction fees. Send at least 0.01 SOL to your wallet.';
133
179
  }
180
+ // Solana names the account short of rent by its index in the transaction.
181
+ // Index 0 is this wallet (the fee payer), where topping up is the fix. In a
182
+ // native SOL send any other index is the recipient, which as a new address
183
+ // must receive at least the rent-exempt minimum, so adding SOL to the wallet
184
+ // would not help. SPL transfers lay out their accounts differently (ATAs,
185
+ // mint, token program), so they keep the generic advice below.
186
+ const rentAccount = context.nativeSolSend
187
+ && lower.match(/results in an account \((\d+)\) with insufficient funds for rent/);
188
+ if (rentAccount && rentAccount[1] !== '0') {
189
+ return `The transfer would leave account ${rentAccount[1]} (the recipient of a SOL send) below Solana's rent-exempt minimum. A new address must receive at least 0.00089088 SOL. RPC said: ${msg}`;
190
+ }
134
191
  if (lower.includes('insufficient lamports') || lower.includes('insufficient funds')) {
135
192
  return 'Insufficient SOL balance for this transaction. Top up your wallet with SOL.';
136
193
  }
@@ -293,15 +350,18 @@ async function buildEvmTransaction({ to, amount, token, privateKey, chain, max =
293
350
  }
294
351
 
295
352
  // RLP: [chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, accessList]
353
+ // `to` and `data` are byte strings, not integers: pass Buffers so rlpEncode
354
+ // keeps their leading zero bytes (a hex string has them stripped, which
355
+ // shortened an address such as 0x0000000000085d47... below 20 bytes).
296
356
  const txFields = [
297
357
  bigIntToHex(BigInt(chainId)),
298
358
  bigIntToHex(nonce),
299
359
  bigIntToHex(maxPriorityFee),
300
360
  bigIntToHex(maxFee),
301
361
  bigIntToHex(gasLimit),
302
- txTo,
362
+ Buffer.from(txTo.replace(/^0x/, ''), 'hex'),
303
363
  bigIntToHex(txValue),
304
- txData.length > 0 ? '0x' + txData.toString('hex') : '0x',
364
+ txData,
305
365
  [], // accessList
306
366
  ];
307
367
 
@@ -644,27 +704,27 @@ async function validateErc20Token(rpcUrl, tokenAddress) {
644
704
 
645
705
  // ============= Broadcasting =============
646
706
 
647
- async function broadcastTransaction(signedTx, chain) {
707
+ async function broadcastTransaction(signedTx, chain, token = null) {
648
708
  if (chain === 'solana') {
649
709
  return rpcCall(CHAIN_RPCS.solana, 'sendTransaction', [signedTx, {
650
710
  encoding: 'base64',
651
711
  skipPreflight: false,
652
712
  preflightCommitment: 'confirmed',
653
- }]);
713
+ }], { nativeSolSend: !token });
654
714
  }
655
715
  return rpcCall(CHAIN_RPCS[chain] || CHAIN_RPCS.evm, 'eth_sendRawTransaction', [signedTx]);
656
716
  }
657
717
 
658
718
  // ============= Public API =============
659
719
 
660
- export { parseAmount, formatAmount, signEd25519, encodeCompactU16, base58Decode, base58DecodePubkey, deriveATA, isOnEd25519Curve, validateEvmAddress, validateSolanaAddress, bigIntToHex };
720
+ export { parseAmount, formatAmount, signEd25519, encodeCompactU16, base58Decode, base58DecodePubkey, deriveATA, isOnEd25519Curve, validateEvmAddress, validateSolanaAddress, bigIntToHex, resolveSendToken };
661
721
 
662
722
  /**
663
723
  * Send tokens via Privy server wallet. EVM uses Privy's sendTransaction (handles gas/nonce).
664
724
  * Solana builds unsigned tx, signs via Privy, then broadcasts.
665
725
  */
666
726
  async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walletInfo }) {
667
- const { PrivyClient } = await import('./privy.js');
727
+ const { PrivyClient, assertPrivyWalletAddress } = await import('./privy.js');
668
728
  const client = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
669
729
 
670
730
  if (chain === 'solana') {
@@ -672,6 +732,9 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle
672
732
  const fromAddress = walletInfo.solana;
673
733
  if (!fromAddress) throw new Error('No Solana wallet in this Privy wallet');
674
734
  if (!walletId) throw new Error('No Privy Solana wallet ID found. Re-create the wallet with: nansen wallet create --provider privy');
735
+ if (token && !validateSolanaAddress(token).valid) throw new Error('Invalid Solana token address');
736
+ if (!max && !token) parseAmount(amount, 9);
737
+ await assertPrivyWalletAddress(client, walletId, fromAddress, 'solana');
675
738
 
676
739
  if (max && !token) {
677
740
  const balResult = await rpcCall(CHAIN_RPCS.solana, 'getBalance', [fromAddress, { commitment: 'confirmed' }]);
@@ -697,7 +760,7 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle
697
760
 
698
761
  const signResult = await client.signSolanaTransaction(walletId, unsignedTransaction);
699
762
  const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction;
700
- const txHash = await broadcastTransaction(signedTx, chain);
763
+ const txHash = await broadcastTransaction(signedTx, chain, token);
701
764
  const confirmation = await waitForSolanaConfirmation(CHAIN_RPCS.solana, txHash);
702
765
 
703
766
  return {
@@ -715,6 +778,9 @@ async function sendTokensViaPrivy({ to, amount, chain, token, max, dryRun, walle
715
778
 
716
779
  const chainId = CHAIN_IDS[chain];
717
780
  if (!chainId) throw new Error(`Unsupported chain: ${chain}`);
781
+ if (token && !validateEvmAddress(token).valid) throw new Error('Invalid ERC-20 token address');
782
+ if (!max && !token) parseAmount(amount, 18);
783
+ await assertPrivyWalletAddress(client, walletId, fromAddress, 'evm');
718
784
 
719
785
  let decimals = 18;
720
786
  const rpcUrl = CHAIN_RPCS[chain] || CHAIN_RPCS.evm;
@@ -773,6 +839,7 @@ export async function sendTokens({ to, amount, chain, token = null, wallet = nul
773
839
  const validate = chain === 'solana' ? validateSolanaAddress : validateEvmAddress;
774
840
  const v = validate(to);
775
841
  if (!v.valid) throw new Error(`Invalid recipient: ${v.error}`);
842
+ token = resolveSendToken(token, chain);
776
843
 
777
844
  if (walletconnect) {
778
845
  if (chain === 'solana') {
@@ -864,7 +931,7 @@ export async function sendTokens({ to, amount, chain, token = null, wallet = nul
864
931
  };
865
932
  }
866
933
 
867
- const txHash = await broadcastTransaction(result.signedTransaction, chain);
934
+ const txHash = await broadcastTransaction(result.signedTransaction, chain, token);
868
935
 
869
936
  // Wait for confirmation
870
937
  let confirmation;
@@ -992,7 +1059,7 @@ async function sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRu
992
1059
 
993
1060
  const txHash = await (async () => {
994
1061
  if (wcResult.txHash) return wcResult.txHash;
995
- if (wcResult.signedTransaction) return broadcastTransaction(wcResult.signedTransaction, chain);
1062
+ if (wcResult.signedTransaction) return broadcastTransaction(wcResult.signedTransaction, chain, token);
996
1063
  throw new Error('No transaction hash or signed transaction returned from WalletConnect');
997
1064
  })();
998
1065
 
@@ -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 {}