nansen-cli 2.0.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/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
  }
@@ -104,6 +104,36 @@ export async function getWalletConnectAddress(chainType, chainId) {
104
104
  }
105
105
  }
106
106
 
107
+ /**
108
+ * Run a wallet send and mark anything that goes wrong as an ambiguous handoff.
109
+ *
110
+ * Once the wallet has been asked to send, no failure here proves the
111
+ * transaction stayed put. `wcExec` collapses a user rejection, a 120s approval
112
+ * timeout and a failure to launch the binary into the same bare
113
+ * `Error(err.message)`, and the timeout is precisely the case where the user DID
114
+ * approve and the wallet DID broadcast while the subprocess gave up waiting. A
115
+ * reply we cannot parse, or one carrying neither a hash nor signed bytes, says
116
+ * just as little about what the wallet did.
117
+ *
118
+ * Callers must therefore never read one of these as "nothing was sent" and go on
119
+ * to send something else. Marking it here, at the boundary, is what makes that
120
+ * hold for every call site — including ones added later — instead of depending
121
+ * on each `catch` to remember. `isFatalBroadcastError` in trading.js treats the
122
+ * flag as terminal; it is deliberately distinct from `broadcastRuledOut`, which
123
+ * is the opposite claim (the backend stated nothing was sent).
124
+ *
125
+ * @param {() => Promise<T>} fn - the send, from the wallet call through parsing
126
+ * @returns {Promise<T>}
127
+ * @template T
128
+ */
129
+ async function markBroadcastAmbiguous(fn) {
130
+ try {
131
+ return await fn();
132
+ } catch (err) {
133
+ throw Object.assign(err, { broadcastAmbiguous: true });
134
+ }
135
+ }
136
+
107
137
  /**
108
138
  * Send a transaction via WalletConnect.
109
139
  *
@@ -128,14 +158,16 @@ export async function sendTransactionViaWalletConnect(txData, timeoutMs = 120000
128
158
  chainId,
129
159
  };
130
160
 
131
- const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs);
132
- const result = parseWcJson(output);
161
+ return markBroadcastAmbiguous(async () => {
162
+ const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs);
163
+ const result = parseWcJson(output);
133
164
 
134
- if (result.transactionHash) return { txHash: result.transactionHash };
135
- if (result.txHash) return { txHash: result.txHash };
136
- if (result.signedTransaction) return { signedTransaction: result.signedTransaction };
165
+ if (result.transactionHash) return { txHash: result.transactionHash };
166
+ if (result.txHash) return { txHash: result.txHash };
167
+ if (result.signedTransaction) return { signedTransaction: result.signedTransaction };
137
168
 
138
- throw new Error('Unexpected response from walletconnect send-transaction');
169
+ throw new Error('Unexpected response from walletconnect send-transaction');
170
+ });
139
171
  }
140
172
 
141
173
  /**
@@ -186,15 +218,20 @@ export async function sendSolanaTransactionViaWalletConnect(txBase58, timeoutMs
186
218
  chainId: SOLANA_MAINNET_CHAIN,
187
219
  };
188
220
 
189
- const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs);
190
- const result = parseWcJson(output);
221
+ // Marked ambiguous for the same reason as the EVM send: this goes out over the
222
+ // CLI's `send-transaction` verb, so a wallet that signs-and-sends has already
223
+ // broadcast by the time a timeout or an unreadable reply reaches us.
224
+ return markBroadcastAmbiguous(async () => {
225
+ const output = await wcExec('walletconnect', ['send-transaction', JSON.stringify(payload)], timeoutMs);
226
+ const result = parseWcJson(output);
191
227
 
192
- if (result.signedTransaction) return { signedTransaction: result.signedTransaction };
193
- if (result.signature) return { signature: result.signature };
194
- // Some wallets (e.g. Phantom) return 'transaction' instead of 'signedTransaction'
195
- if (result.transaction) return { signedTransaction: result.transaction };
228
+ if (result.signedTransaction) return { signedTransaction: result.signedTransaction };
229
+ if (result.signature) return { signature: result.signature };
230
+ // Some wallets (e.g. Phantom) return 'transaction' instead of 'signedTransaction'
231
+ if (result.transaction) return { signedTransaction: result.transaction };
196
232
 
197
- throw new Error('Unexpected response from walletconnect Solana sign');
233
+ throw new Error('Unexpected response from walletconnect Solana sign');
234
+ });
198
235
  }
199
236
 
200
237
  /**
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
  */