nansen-cli 2.0.0 → 2.1.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 (55) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +37 -9
  3. package/docs/browser-login.md +13 -7
  4. package/package.json +2 -2
  5. package/scripts/postinstall.js +1 -1
  6. package/skills/nansen-agent-guide/SKILL.md +3 -3
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
  8. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  9. package/skills/nansen-defi-positions/SKILL.md +1 -1
  10. package/skills/nansen-exit-signals/SKILL.md +1 -1
  11. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  12. package/skills/nansen-general-search/SKILL.md +1 -1
  13. package/skills/nansen-holder-analysis/SKILL.md +1 -1
  14. package/skills/nansen-limit-orders/SKILL.md +1 -1
  15. package/skills/nansen-perp-screener/SKILL.md +1 -1
  16. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  20. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  21. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  23. package/skills/nansen-smart-alerts/SKILL.md +1 -1
  24. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  25. package/skills/nansen-smart-money-tracker/SKILL.md +1 -1
  26. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  27. package/skills/nansen-token-research/SKILL.md +1 -1
  28. package/skills/nansen-token-screener/SKILL.md +1 -1
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  30. package/skills/nansen-trading/SKILL.md +1 -1
  31. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  32. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  35. package/skills/nansen-wallet-manager/SKILL.md +1 -1
  36. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  37. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  38. package/skills/nansen-web-searcher/SKILL.md +1 -1
  39. package/src/auth-credentials.js +16 -4
  40. package/src/auth-device.js +1 -1
  41. package/src/auth-login.js +4 -5
  42. package/src/auth-state.js +10 -8
  43. package/src/auth-store-worker.js +4 -3
  44. package/src/auto-paginate.js +31 -15
  45. package/src/bridge.js +105 -77
  46. package/src/cache-inspect.js +3 -7
  47. package/src/cli.js +13 -12
  48. package/src/doctor.js +1 -1
  49. package/src/limit-order.js +1 -1
  50. package/src/local-file.js +75 -0
  51. package/src/schema.json +28 -3
  52. package/src/solana-tx.js +74 -0
  53. package/src/trading.js +76 -40
  54. package/src/wallet.js +16 -35
  55. package/src/x402-svm.js +165 -7
package/src/trading.js CHANGED
@@ -9,9 +9,10 @@ import { rejectBlankOption } from './query-options.js';
9
9
  import crypto from 'crypto';
10
10
  import fs from 'fs';
11
11
  import path from 'path';
12
+ import { readLocalFile, writeLocalFile } from './local-file.js';
12
13
  import { base58Encode, exportWallet, getWalletConfig, showWallet, listWallets } from './wallet.js';
13
14
  import { base58Decode, encodeCompactU16 } from './transfer.js';
14
- import { buildMessageV0, fetchRecentBlockhash } from './x402-svm.js';
15
+ import { buildMessageV0, fetchAddressLookupTables, fetchRecentBlockhash } from './x402-svm.js';
15
16
  import { keccak256, signSecp256k1, rlpEncode } from './crypto.js';
16
17
  import { getWalletConnectAddress, sendTransactionViaWalletConnect, sendSolanaTransactionViaWalletConnect, sendApprovalViaWalletConnect } from './walletconnect-trading.js';
17
18
  import { retrievePassword } from './keychain.js';
@@ -37,6 +38,13 @@ const CHAIN_MAP = {
37
38
  base: { index: '8453', type: 'evm', chainId: 8453, name: 'Base', explorer: 'https://basescan.org/tx/', lifiChainId: '8453' },
38
39
  };
39
40
 
41
+ // CHAIN_MAP is keyed lowercase, but a quote stores the chain exactly as the
42
+ // user typed it (`--chain Base`) — only resolveChain() lowercases on the way
43
+ // through, and direct lookups bypass it.
44
+ function chainConfigFor(name) {
45
+ return name ? CHAIN_MAP[String(name).toLowerCase()] : undefined;
46
+ }
47
+
40
48
  // Extend when adding new EVM chains (e.g. arbitrum WETH, polygon WMATIC)
41
49
  const WRAPPED_NATIVE_TOKENS = {
42
50
  base: { address: '0x4200000000000000000000000000000000000006', symbol: 'WETH', nativeSymbol: 'ETH' },
@@ -135,11 +143,8 @@ export function getQuotesDir() {
135
143
 
136
144
  // Resolve a filename inside the quotes dir, rejecting path traversal.
137
145
  export function safeQuotesPath(filename) {
138
- const base = path.resolve(getQuotesDir());
139
- const target = path.resolve(base, filename);
140
- const relative = path.relative(base, target);
141
- if (relative.startsWith('..') || path.isAbsolute(relative)) return null;
142
- return target;
146
+ if (typeof filename !== 'string' || !filename || filename === '.' || filename === '..' || /[/\\:]/.test(filename) || filename.includes('\0')) return null;
147
+ return path.join(path.resolve(getQuotesDir()), filename);
143
148
  }
144
149
 
145
150
  // ============= Trading API Client =============
@@ -272,7 +277,7 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
272
277
  // JSON error (e.g. { code: "UPSTREAM_TIMEOUT" }) already explains itself
273
278
  // via `details`; tacking "you may be out of SOL" onto a gateway timeout
274
279
  // would misdirect the user.
275
- const chainType = params.chain && CHAIN_MAP[params.chain]?.type;
280
+ const chainType = chainConfigFor(params.chain)?.type;
276
281
  const feeHint = !parsed
277
282
  ? chainType === 'solana'
278
283
  ? ' This often means the transaction failed simulation — check that you have enough SOL for fees (~0.005 SOL minimum).'
@@ -457,7 +462,7 @@ export function loadTxRecord(txHash) {
457
462
  if (!filePath) return null;
458
463
  if (!fs.existsSync(filePath)) return null;
459
464
  try {
460
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
465
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
461
466
  if (Date.now() - data.timestamp > TX_RECORD_TTL_MS) {
462
467
  fs.unlinkSync(filePath);
463
468
  return null;
@@ -516,7 +521,7 @@ export function loadQuote(quoteId) {
516
521
  }
517
522
 
518
523
  function readQuoteFile(filePath, quoteId) {
519
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
524
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
520
525
  if (Date.now() - data.timestamp > 3600000) {
521
526
  fs.unlinkSync(filePath);
522
527
  throw new Error('Quote has expired. Please request a new quote.');
@@ -543,7 +548,7 @@ function readQuoteFile(filePath, quoteId) {
543
548
 
544
549
  function quoteClaimedError(quoteId, claimedPath) {
545
550
  return new Error(
546
- `Quote "${quoteId}" is claimed by another execution (${claimedPath}). If that run is still going, wait for it to finish. If it was interrupted, a swap may or may not have been broadcast: check the wallet on the explorer, then request a new quote with "nansen trade quote". The claimed quote is removed when it expires.`,
551
+ `Quote "${quoteId}" is claimed by another execution (${claimedPath}). If that run is still going, wait for it to finish. If it was interrupted, a transaction may or may not have been broadcast: check the wallet on the explorer, then request a new quote with the matching quote command. The claimed quote is removed when it expires.`,
547
552
  );
548
553
  }
549
554
 
@@ -574,12 +579,14 @@ function quoteClaimedError(quoteId, claimedPath) {
574
579
  * after its 1-hour lifetime.
575
580
  *
576
581
  * @param {string} quoteId
577
- * @returns {{ quote: object, release: (opts?: { handedOff?: boolean }) => void }}
582
+ * @param {function} [readQuote] Validates the claimed quote, including its type.
583
+ * @returns {{ quote: object, release: (opts?: { handedOff?: boolean, keepClaimed?: boolean }) => void }}
578
584
  */
579
- export function claimQuoteForExecution(quoteId) {
585
+ export function claimQuoteForExecution(quoteId, readQuote = readQuoteFile) {
580
586
  const quotePath = safeQuotesPath(`${quoteId}.json`);
581
587
  const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
582
588
  if (!quotePath || !claimedPath) throw new Error(`Invalid quote id "${quoteId}".`);
589
+ if (fs.lstatSync(claimedPath, { throwIfNoEntry: false })) throw quoteClaimedError(quoteId, claimedPath);
583
590
 
584
591
  try {
585
592
  fs.renameSync(quotePath, claimedPath);
@@ -592,19 +599,24 @@ export function claimQuoteForExecution(quoteId) {
592
599
  }
593
600
 
594
601
  let released = false;
595
- const release = ({ handedOff = false } = {}) => {
602
+ const release = ({ handedOff = false, keepClaimed = false } = {}) => {
596
603
  if (released) return;
597
604
  released = true;
605
+ if (keepClaimed) return;
598
606
  try {
599
- if (handedOff && !JSON.parse(fs.readFileSync(claimedPath, 'utf8')).executedAt) return;
607
+ if (handedOff && !JSON.parse(readLocalFile(claimedPath, { root: path.dirname(getQuotesDir()) })).executedAt) return;
600
608
  fs.renameSync(claimedPath, quotePath);
601
609
  } catch { /* gone (expired and cleaned up): nothing to release */ }
602
610
  };
603
611
 
604
612
  try {
605
- return { quote: readQuoteFile(claimedPath, quoteId), release };
613
+ if (process.platform !== 'win32') {
614
+ const fd = fs.openSync(path.dirname(claimedPath), 'r');
615
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
616
+ }
617
+ return { quote: readQuote(claimedPath, quoteId), release };
606
618
  } catch (err) {
607
- // Already executed, expired or not a swap quote: nothing is signed, so
619
+ // Invalid, already executed, or expired: nothing is signed, so
608
620
  // put back whatever is still there.
609
621
  release();
610
622
  throw err;
@@ -624,16 +636,15 @@ export function markQuoteExecuted(quoteId, progress = {}) {
624
636
  : safeQuotesPath(`${quoteId}.json`);
625
637
  if (!filePath || !fs.existsSync(filePath)) return;
626
638
  try {
627
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
639
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
628
640
  data.executedAt = data.executedAt || Date.now();
629
641
  if (progress.broadcast) {
630
642
  data.broadcasts = [...(data.broadcasts || []), { ...progress.broadcast, at: Date.now() }];
631
643
  }
632
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { mode: 0o600 });
644
+ writeLocalFile(filePath, JSON.stringify(data, null, 2), { root: path.dirname(getQuotesDir()) });
633
645
  } catch {
634
- // Best-effort: if the marker can't be written, the next execute attempt
635
- // will still proceed, but that's preferable to crashing after a successful
636
- // broadcast.
646
+ // The execution claim stays in place without a readable marker, so a
647
+ // later execution cannot sign again after an uncertain broadcast.
637
648
  }
638
649
  }
639
650
 
@@ -650,7 +661,7 @@ export function cleanupQuotes() {
650
661
  if (!file.endsWith('.json')) continue;
651
662
  const ttl = file.startsWith('tx-') ? TX_RECORD_TTL_MS : 3600000;
652
663
  try {
653
- const data = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));
664
+ const data = JSON.parse(readLocalFile(path.join(dir, file), { root: path.dirname(dir) }));
654
665
  if (now - data.timestamp > ttl) fs.unlinkSync(path.join(dir, file));
655
666
  } catch { /* ignore */ }
656
667
  }
@@ -749,10 +760,13 @@ function decodeInstructionData(hex) {
749
760
  * — into a signable base64 VersionedTransaction. Some aggregators (Relay's Solana-source
750
761
  * bridge quotes) return this shape instead of a ready-to-sign serialized transaction.
751
762
  *
752
- * Every account is kept static; the address-lookup-table hint is a size optimization,
753
- * not a correctness requirement, so skipping it is valid as long as the compiled
754
- * transaction still fits Solana's packet limit. Full lookup-table compilation is
755
- * unimplemented — throws instead of silently building an oversized/invalid transaction.
763
+ * Accounts stay static whenever the transaction fits Solana's packet limit that way, so
764
+ * the common case needs no extra RPC call and the safety checks see every account. Only
765
+ * a route too large to fit (e.g. a source-chain swap ahead of the bridge deposit) has its
766
+ * addressLookupTableAddresses fetched and used to compress accounts. A table only ever
767
+ * replaces an account with a reference to that same address, and lookup-table entries
768
+ * are immutable once written, so compression doesn't change what the instructions touch.
769
+ * Throws instead of building an oversized/invalid transaction.
756
770
  *
757
771
  * getExpectedSigner is an async thunk resolving to the address of the wallet that is
758
772
  * about to sign. The transaction only ever gets a single signature written into slot 0
@@ -785,6 +799,7 @@ export async function compileRawSolanaTransaction(transaction, rpcUrl, getExpect
785
799
  );
786
800
  }
787
801
 
802
+ const unsignedSize = (message) => 1 + 64 + message.messageBytes.length; // compact-u16(1) + 1 signature slot
788
803
  const preflight = buildMessageV0({ feePayer, instructions, recentBlockhash: SIZE_CHECK_BLOCKHASH });
789
804
  if (preflight.numRequiredSignatures !== 1) {
790
805
  throw new Error(
@@ -792,17 +807,32 @@ export async function compileRawSolanaTransaction(transaction, rpcUrl, getExpect
792
807
  `but only the wallet's own signature can be provided.`
793
808
  );
794
809
  }
795
- const unsignedSize = 1 + 64 + preflight.messageBytes.length; // compact-u16(1) + 1 signature slot
796
- if (unsignedSize > SOLANA_MAX_TX_SIZE) {
797
- throw new Error(
798
- `Solana transaction too large to compile without address-lookup-table support ` +
799
- `(${unsignedSize} bytes > ${SOLANA_MAX_TX_SIZE} limit). This route needs its ` +
800
- `address lookup tables resolved, which isn't supported yet.`
801
- );
810
+
811
+ let addressLookupTables = [];
812
+ let size = unsignedSize(preflight);
813
+ if (size > SOLANA_MAX_TX_SIZE) {
814
+ const hint = transaction.addressLookupTableAddresses;
815
+ const tableAddresses = [...new Set(Array.isArray(hint) ? hint : [])];
816
+ if (tableAddresses.length === 0) {
817
+ throw new Error(
818
+ `Solana transaction too large to compile (${size} bytes > ${SOLANA_MAX_TX_SIZE} limit) and ` +
819
+ `the quote supplied no address lookup tables to compress it. Get a new quote.`
820
+ );
821
+ }
822
+ addressLookupTables = await fetchAddressLookupTables(rpcUrl, tableAddresses);
823
+ size = unsignedSize(buildMessageV0({
824
+ feePayer, instructions, recentBlockhash: SIZE_CHECK_BLOCKHASH, addressLookupTables,
825
+ }));
826
+ if (size > SOLANA_MAX_TX_SIZE) {
827
+ throw new Error(
828
+ `Solana transaction too large to compile (${size} bytes > ${SOLANA_MAX_TX_SIZE} limit) even ` +
829
+ `with its ${tableAddresses.length} address lookup table(s). Get a new quote.`
830
+ );
831
+ }
802
832
  }
803
833
 
804
834
  const recentBlockhash = await fetchRecentBlockhash(rpcUrl);
805
- const { messageBytes } = buildMessageV0({ feePayer, instructions, recentBlockhash });
835
+ const { messageBytes } = buildMessageV0({ feePayer, instructions, recentBlockhash, addressLookupTables });
806
836
  const unsignedTx = Buffer.concat([encodeCompactU16(1), Buffer.alloc(64), messageBytes]);
807
837
  return unsignedTx.toString('base64');
808
838
  }
@@ -847,13 +877,14 @@ export async function normalizeSolanaTransaction(transaction, rpcUrl, getExpecte
847
877
  * @param {string} chain - Chain name
848
878
  * @param {number} nonce - Account nonce
849
879
  * @param {object} [opts]
880
+ * @param {string|number|bigint} [opts.gasLimit] - Resolved gas limit, overriding quote transaction fields
850
881
  * @param {string} [opts.label='swap'] - What is being signed, for the fee-cap error
851
882
  * @param {bigint} [opts.maxTxFeeWei] - Fee cap in wei (--max-tx-fee); 0n disables it
852
883
  * @returns {string} 0x-prefixed signed transaction hex
853
884
  */
854
885
  // Pure EVM encode/sign primitive. Quote authorization and request-intent binding
855
886
  // happen upstream before this function receives transaction calldata.
856
- export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { label = 'swap', maxTxFeeWei = MAX_EVM_TX_FEE_WEI } = {}) {
887
+ export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { gasLimit, label = 'swap', maxTxFeeWei = MAX_EVM_TX_FEE_WEI } = {}) {
857
888
  const chainConfig = CHAIN_MAP[chain];
858
889
  if (!chainConfig || chainConfig.type !== 'evm') {
859
890
  throw new Error(`Unsupported EVM chain: ${chain}`);
@@ -861,7 +892,7 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { label
861
892
 
862
893
  const common = {
863
894
  nonce,
864
- gasLimit: toHex(txData.gas || txData.gasLimit || '210000'),
895
+ gasLimit: toHex(gasLimit ?? (txData.gas || txData.gasLimit || '210000')),
865
896
  to: txData.to,
866
897
  value: toHex(txData.value || '0'),
867
898
  data: txData.data || '0x',
@@ -3122,7 +3153,14 @@ EXAMPLES:
3122
3153
  let swapHandedOff = false;
3123
3154
  try {
3124
3155
  const quoteData = loadQuote(quoteId);
3125
- const chain = quoteData.chain;
3156
+ // The quote command stores the chain exactly as the user typed it
3157
+ // (`--chain Base`), but the lookups downstream — CHAIN_RPCS here above
3158
+ // all — are keyed lowercase, and only resolveChain() normalises on its
3159
+ // own. Without this a capitalised spelling quotes fine and then fails at
3160
+ // execute with "No RPC URL configured for chain: Base", so the quote can
3161
+ // never be used. Normalised once here, which also fixes quotes already
3162
+ // on disk.
3163
+ const chain = quoteData.chain?.toLowerCase();
3126
3164
  const chainConfig = resolveChain(chain);
3127
3165
  const chainType = chainConfig.type;
3128
3166
 
@@ -4417,8 +4455,6 @@ EXAMPLES:
4417
4455
  const txData = currentQuote.transaction;
4418
4456
  const finalGas = await resolveEvmSwapGasLimit(currentQuote, { chain, from: walletAddress });
4419
4457
  logEvmSwapGasResolution(log, currentQuote, txData, finalGas);
4420
- if (txData.gasLimit) txData.gasLimit = String(finalGas);
4421
- else txData.gas = String(finalGas);
4422
4458
 
4423
4459
  log(' Fetching nonce...');
4424
4460
  await new Promise(r => setTimeout(r, 1000));
@@ -4431,7 +4467,7 @@ EXAMPLES:
4431
4467
  exported.evm.privateKey,
4432
4468
  chain,
4433
4469
  nonce,
4434
- { maxTxFeeWei },
4470
+ { gasLimit: finalGas, maxTxFeeWei },
4435
4471
  );
4436
4472
  }
4437
4473
 
package/src/wallet.js CHANGED
@@ -830,20 +830,11 @@ export function buildWalletCommands(deps = {}) {
830
830
  },
831
831
 
832
832
  'list': async () => {
833
- const result = listWallets();
834
- if (result.wallets.length === 0) {
835
- log('No wallets found. Create one with: nansen wallet create');
836
- return;
837
- }
838
- log('');
839
- for (const w of result.wallets) {
840
- const star = w.isDefault ? ' ★' : '';
841
- const providerTag = w.provider === 'privy' ? ' (privy)' : '';
842
- log(` ${w.name}${star}${providerTag}`);
843
- log(` EVM: ${w.evm}`);
844
- log(` Solana: ${w.solana}`);
845
- log('');
846
- }
833
+ // Read-only data: return it so the CLI prints the standard JSON
834
+ // envelope on stdout, in a terminal or a pipe alike. A readable
835
+ // summary here would break agents that capture stderr alongside
836
+ // stdout or run under a pseudo-terminal.
837
+ return listWallets();
847
838
  },
848
839
 
849
840
  'show': async () => {
@@ -851,15 +842,9 @@ export function buildWalletCommands(deps = {}) {
851
842
  if (!name) {
852
843
  throw new CommandError('Usage: nansen wallet show <name>', 'MISSING_ARGS');
853
844
  }
845
+ // Read-only data, returned for the JSON envelope like `wallet list`.
854
846
  try {
855
- const result = showWallet(name);
856
- const star = result.isDefault ? ' ★' : '';
857
- const providerTag = result.provider === 'privy' ? ' (privy)' : '';
858
- log(`\n ${result.name}${star}${providerTag}`);
859
- log(` EVM: ${result.evm}`);
860
- log(` Solana: ${result.solana}`);
861
- log(` Created: ${result.createdAt}\n`);
862
- return;
847
+ return showWallet(name);
863
848
  } catch (err) {
864
849
  throw new CommandError(`❌ ${err.message}`, 'SHOW_FAILED');
865
850
  }
@@ -891,19 +876,15 @@ export function buildWalletCommands(deps = {}) {
891
876
  if (result.provider !== 'local') {
892
877
  throw new Error(`${result.provider} wallets don't support key export. Keys are managed by the provider.`);
893
878
  }
894
- log(`\n Wallet "${result.name}" — private keys are NOT shown by default.\n`);
895
- log(` EVM:`);
896
- log(` Address: ${result.evm}`);
897
- log(` Private Key: [REDACTED]`);
898
- log(` Solana:`);
899
- log(` Address: ${result.solana}`);
900
- log(` Private Key: [REDACTED]`);
901
- log('');
902
- log(' To export the private keys:');
903
- log(` nansen wallet export ${result.name} --file <path> safer: writes a file only you can read (0600)`);
904
- log(` nansen wallet export ${result.name} --reveal prints them in plaintext to stdout`);
905
- log('');
906
- return;
879
+ // Same envelope rule as `wallet show`. The shape follows
880
+ // exportWallet() minus the privateKey fields, which are left out
881
+ // rather than filled with a placeholder a caller could mistake for a key.
882
+ return {
883
+ name: result.name,
884
+ redacted: true,
885
+ evm: { address: result.evm },
886
+ solana: { address: result.solana },
887
+ };
907
888
  } catch (err) {
908
889
  throw new CommandError(`❌ ${err.message}`, 'EXPORT_FAILED');
909
890
  }
package/src/x402-svm.js CHANGED
@@ -9,6 +9,14 @@ import { encodeCompactU16, deriveATA as _deriveATA } from './transfer.js';
9
9
  import { resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
10
10
  import { SOLANA_MAINNET_NETWORK } from './x402-tokens.js';
11
11
  import { CHAIN_RPCS } from './rpc-urls.js';
12
+ import {
13
+ ADDRESS_LOOKUP_TABLE_PROGRAM,
14
+ SLOT_HASHES_SYSVAR,
15
+ SYSVAR_PROGRAM,
16
+ isLookupTableUsable,
17
+ parseAddressLookupTable,
18
+ parseSlotHashes,
19
+ } from './solana-tx.js';
12
20
 
13
21
  // ============= Constants =============
14
22
 
@@ -50,8 +58,13 @@ export function deriveATA(ownerBase58, mintBase58, tokenProgramBase58 = TOKEN_PR
50
58
  * Returns numRequiredSignatures alongside the bytes. Each caller writes a
51
59
  * fixed number of signature slots and asserts this value against it, since a
52
60
  * header that disagrees with the slot count is rejected at broadcast.
61
+ *
62
+ * addressLookupTables ([{ key, addresses }], resolved on-chain by the caller)
63
+ * moves accounts out of the static key list into table lookups. Only accounts
64
+ * that are neither signers nor invoked as a program are eligible — the runtime
65
+ * requires both to be static keys — so the fee payer always stays static.
53
66
  */
54
- export function buildMessageV0({ feePayer, instructions, recentBlockhash, accounts: _accounts }) {
67
+ export function buildMessageV0({ feePayer, instructions, recentBlockhash, addressLookupTables = [] }) {
55
68
  // All unique accounts in order: feePayer first, then signers, then rest
56
69
  const accountMap = new Map();
57
70
  const feePayerKey = feePayer;
@@ -75,10 +88,37 @@ export function buildMessageV0({ feePayer, instructions, recentBlockhash, accoun
75
88
  }
76
89
  }
77
90
 
91
+ // Pull lookup-eligible accounts out of the static list, table by table. An
92
+ // account found in more than one table is loaded from the first.
93
+ const invokedPrograms = new Set(instructions.map(ix => ix.programId));
94
+ const lookups = [];
95
+ const loadedWritable = [];
96
+ const loadedReadonly = [];
97
+ const loaded = new Set();
98
+ for (const table of addressLookupTables) {
99
+ const writableIndexes = [];
100
+ const readonlyIndexes = [];
101
+ table.addresses.forEach((address, index) => {
102
+ const meta = accountMap.get(address);
103
+ if (!meta || meta.isSigner || invokedPrograms.has(address) || loaded.has(address)) return;
104
+ loaded.add(address);
105
+ if (meta.isWritable) {
106
+ writableIndexes.push(index);
107
+ loadedWritable.push(address);
108
+ } else {
109
+ readonlyIndexes.push(index);
110
+ loadedReadonly.push(address);
111
+ }
112
+ });
113
+ if (writableIndexes.length || readonlyIndexes.length) {
114
+ lookups.push({ key: table.key, writableIndexes, readonlyIndexes });
115
+ }
116
+ }
117
+
78
118
  // Sort: signers+writable, signers+readonly, non-signer+writable, non-signer+readonly
79
119
  // feePayer always at index 0
80
120
  const sortedKeys = [feePayerKey];
81
- const rest = [...accountMap.entries()].filter(([k]) => k !== feePayerKey);
121
+ const rest = [...accountMap.entries()].filter(([k]) => k !== feePayerKey && !loaded.has(k));
82
122
 
83
123
  // Signer+writable
84
124
  for (const [k, v] of rest) if (v.isSigner && v.isWritable) sortedKeys.push(k);
@@ -104,9 +144,15 @@ export function buildMessageV0({ feePayer, instructions, recentBlockhash, accoun
104
144
  }
105
145
  }
106
146
 
107
- // Build the account keys index
147
+ // Build the account keys index: static keys, then every table's writable
148
+ // loads, then every table's readonly loads — the order the runtime resolves.
149
+ const allKeys = [...sortedKeys, ...loadedWritable, ...loadedReadonly];
150
+ // Instruction account indexes are single bytes.
151
+ if (allKeys.length > 256) {
152
+ throw new Error(`Solana transaction references ${allKeys.length} accounts; a message can index at most 256.`);
153
+ }
108
154
  const keyIndex = new Map();
109
- sortedKeys.forEach((k, i) => keyIndex.set(k, i));
155
+ allKeys.forEach((k, i) => keyIndex.set(k, i));
110
156
 
111
157
  // Compile instructions
112
158
  const compiledInstructions = instructions.map(ix => {
@@ -146,8 +192,15 @@ export function buildMessageV0({ feePayer, instructions, recentBlockhash, accoun
146
192
  parts.push(ix.data);
147
193
  }
148
194
 
149
- // Address table lookups (empty — all accounts referenced statically above)
150
- parts.push(encodeCompactU16(0));
195
+ // Address table lookups
196
+ parts.push(encodeCompactU16(lookups.length));
197
+ for (const lookup of lookups) {
198
+ parts.push(base58DecodePubkey(lookup.key));
199
+ parts.push(encodeCompactU16(lookup.writableIndexes.length));
200
+ parts.push(Buffer.from(lookup.writableIndexes));
201
+ parts.push(encodeCompactU16(lookup.readonlyIndexes.length));
202
+ parts.push(Buffer.from(lookup.readonlyIndexes));
203
+ }
151
204
 
152
205
  return { messageBytes: Buffer.concat(parts), numRequiredSignatures };
153
206
  }
@@ -252,7 +305,6 @@ export function buildUnsignedSvmTransaction(
252
305
  feePayer: feePayerStr,
253
306
  instructions,
254
307
  recentBlockhash,
255
- accounts: null,
256
308
  });
257
309
  // The header must agree with the signature slots written below. A
258
310
  // server-supplied feePayer equal to the paying wallet collapses the two
@@ -423,6 +475,112 @@ export async function fetchRecentBlockhash(rpcUrl = CHAIN_RPCS.solana) {
423
475
  }
424
476
  }
425
477
 
478
+ /**
479
+ * getMultipleAccounts (base64) with the shared timeout and actionable errors.
480
+ * Returns the accounts in request order and the slot the RPC read them at.
481
+ */
482
+ async function getMultipleAccountsBase64(rpcUrl, addresses, purpose) {
483
+ if (!isHttpUrl(rpcUrl)) {
484
+ throw new Error(
485
+ 'Invalid Solana RPC URL: expected a full http:// or https:// URL. Check NANSEN_SOLANA_RPC.'
486
+ );
487
+ }
488
+
489
+ const controller = new AbortController();
490
+ const timer = setTimeout(() => controller.abort(), SOLANA_RPC_TIMEOUT_MS);
491
+ const rpcError = (detail, cause) => new Error(
492
+ `Solana RPC ${detail} while fetching ${purpose}. Retry or configure a different RPC endpoint.`,
493
+ cause ? { cause } : undefined
494
+ );
495
+ const timeoutError = (cause) => rpcError(`did not respond within ${SOLANA_RPC_TIMEOUT_MS / 1000}s`, cause);
496
+
497
+ let data;
498
+ try {
499
+ let response;
500
+ try {
501
+ response = await fetch(rpcUrl, {
502
+ method: 'POST',
503
+ headers: { 'Content-Type': 'application/json' },
504
+ body: JSON.stringify({
505
+ jsonrpc: '2.0',
506
+ id: 1,
507
+ method: 'getMultipleAccounts',
508
+ params: [addresses, { encoding: 'base64', commitment: 'confirmed' }],
509
+ }),
510
+ signal: controller.signal,
511
+ });
512
+ } catch (err) {
513
+ if (controller.signal.aborted) throw timeoutError(err);
514
+ throw rpcError('was unavailable', err);
515
+ }
516
+ if (!response.ok) throw rpcError(`returned HTTP ${response.status}`);
517
+ try {
518
+ data = await response.json();
519
+ } catch (err) {
520
+ if (controller.signal.aborted) throw timeoutError(err);
521
+ throw rpcError('returned an invalid response', err);
522
+ }
523
+ } finally {
524
+ clearTimeout(timer);
525
+ }
526
+
527
+ if (data?.error) {
528
+ throw rpcError(`failed (${String(data.error.message ?? data.error.code ?? 'unknown RPC error')})`);
529
+ }
530
+ const accounts = data?.result?.value;
531
+ // Each account is matched to its address by position, so a short or padded
532
+ // array would pair an account with the wrong address.
533
+ if (!Array.isArray(accounts) || accounts.length !== addresses.length) {
534
+ throw rpcError('returned an unexpected account list');
535
+ }
536
+ return { accounts, slot: data.result.context?.slot };
537
+ }
538
+
539
+ const accountBytes = (account) =>
540
+ Buffer.from((Array.isArray(account.data) ? account.data[0] : account.data) ?? '', 'base64');
541
+
542
+ /**
543
+ * Fetch and parse address-lookup-table accounts, in the order given.
544
+ *
545
+ * Throws unless every address is a table owned by the lookup-table program
546
+ * that the runtime will still resolve: a quote that names a missing, foreign or
547
+ * deactivated table can't be compiled into a transaction the runtime accepts.
548
+ * A table that is only deactivating is still usable (see isLookupTableUsable);
549
+ * telling the two apart needs the SlotHashes sysvar, which is fetched only when
550
+ * some table has a deactivation slot.
551
+ */
552
+ export async function fetchAddressLookupTables(rpcUrl, addresses) {
553
+ const { accounts } = await getMultipleAccountsBase64(rpcUrl, addresses, 'address lookup tables');
554
+
555
+ const tables = accounts.map((account, i) => {
556
+ const key = addresses[i];
557
+ if (!account) {
558
+ throw new Error(`Address lookup table ${key} not found on-chain. Get a new quote.`);
559
+ }
560
+ if (account.owner !== ADDRESS_LOOKUP_TABLE_PROGRAM) {
561
+ throw new Error(`Account ${key} is not an address lookup table. Get a new quote.`);
562
+ }
563
+ return { key, ...parseAddressLookupTable(accountBytes(account)) };
564
+ });
565
+
566
+ if (tables.some((t) => t.deactivationSlot !== null)) {
567
+ const { accounts: [sysvar], slot } = await getMultipleAccountsBase64(rpcUrl, [SLOT_HASHES_SYSVAR], 'recent slot hashes');
568
+ if (!sysvar || sysvar.owner !== SYSVAR_PROGRAM || !Number.isSafeInteger(slot)) {
569
+ throw new Error(
570
+ 'Solana RPC returned no usable SlotHashes sysvar, so a deactivating address lookup table cannot be checked. Retry or configure a different RPC endpoint.'
571
+ );
572
+ }
573
+ const slotHashes = parseSlotHashes(accountBytes(sysvar));
574
+ for (const table of tables) {
575
+ if (!isLookupTableUsable(table.deactivationSlot, BigInt(slot), slotHashes)) {
576
+ throw new Error(`Address lookup table ${table.key} has been deactivated. Get a new quote.`);
577
+ }
578
+ }
579
+ }
580
+
581
+ return tables.map(({ key, addresses: tableAddresses }) => ({ key, addresses: tableAddresses }));
582
+ }
583
+
426
584
  /**
427
585
  * Get RPC URL for a Solana network identifier.
428
586
  */