nansen-cli 1.45.0 → 2.0.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 (85) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/README.md +158 -18
  3. package/docs/browser-login.md +117 -0
  4. package/package.json +11 -2
  5. package/scripts/postinstall.js +35 -30
  6. package/skills/nansen-agent-guide/SKILL.md +13 -2
  7. package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
  8. package/skills/nansen-dca-tracker/SKILL.md +10 -2
  9. package/skills/nansen-defi-positions/SKILL.md +5 -2
  10. package/skills/nansen-exit-signals/SKILL.md +10 -2
  11. package/skills/nansen-fund-tracker/SKILL.md +10 -2
  12. package/skills/nansen-general-search/SKILL.md +10 -2
  13. package/skills/nansen-holder-analysis/SKILL.md +10 -2
  14. package/skills/nansen-limit-orders/SKILL.md +6 -3
  15. package/skills/nansen-perp-screener/SKILL.md +10 -2
  16. package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
  17. package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
  18. package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
  19. package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
  20. package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
  21. package/skills/nansen-prediction-markets/SKILL.md +10 -2
  22. package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
  23. package/skills/nansen-smart-alerts/SKILL.md +9 -4
  24. package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
  25. package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
  26. package/skills/nansen-smart-money-trend/SKILL.md +10 -2
  27. package/skills/nansen-token-research/SKILL.md +10 -2
  28. package/skills/nansen-token-screener/SKILL.md +14 -4
  29. package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
  30. package/skills/nansen-trading/SKILL.md +27 -2
  31. package/skills/nansen-wallet-batch/SKILL.md +10 -2
  32. package/skills/nansen-wallet-clustering/SKILL.md +10 -2
  33. package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
  34. package/skills/nansen-wallet-keychain-migration/SKILL.md +23 -15
  35. package/skills/nansen-wallet-manager/SKILL.md +26 -10
  36. package/skills/nansen-wallet-profiler/SKILL.md +10 -2
  37. package/skills/nansen-web-fetcher/SKILL.md +5 -2
  38. package/skills/nansen-web-searcher/SKILL.md +5 -2
  39. package/src/api.js +319 -129
  40. package/src/auth-browser.js +16 -0
  41. package/src/auth-credentials.js +73 -0
  42. package/src/auth-device.js +242 -0
  43. package/src/auth-key-input.js +46 -0
  44. package/src/auth-login.js +90 -0
  45. package/src/auth-state.js +487 -0
  46. package/src/auth-store-native.js +20 -0
  47. package/src/auth-store-worker.js +64 -0
  48. package/src/auth-store.js +140 -0
  49. package/src/auto-paginate.js +272 -0
  50. package/src/bridge.js +309 -85
  51. package/src/cache-inspect.js +345 -0
  52. package/src/chain-ids.js +1 -2
  53. package/src/cli.js +779 -286
  54. package/src/commands/agent.js +20 -9
  55. package/src/commands/alerts.js +1 -1
  56. package/src/commands/completion.js +2 -15
  57. package/src/commands/mcp.js +22 -20
  58. package/src/commands/research.js +4 -2
  59. package/src/cost-cache.js +16 -2
  60. package/src/debug.js +348 -0
  61. package/src/doctor.js +22 -45
  62. package/src/ens.js +3 -1
  63. package/src/execute-guard.js +116 -0
  64. package/src/hl-action.js +41 -13
  65. package/src/limit-order.js +9 -1
  66. package/src/mcp-client-config.js +169 -0
  67. package/src/mcp-client-config.json +17 -0
  68. package/src/mcp-verify.js +6 -5
  69. package/src/perp.js +61 -9
  70. package/src/privy.js +12 -12
  71. package/src/query-options.js +38 -6
  72. package/src/response-meta.js +57 -2
  73. package/src/rpc-urls.js +9 -11
  74. package/src/schema.json +309 -30
  75. package/src/semver.js +23 -4
  76. package/src/swap-simulation.js +35 -30
  77. package/src/telemetry.js +20 -0
  78. package/src/trading.js +806 -40
  79. package/src/transfer.js +75 -9
  80. package/src/update-check.js +9 -1
  81. package/src/wallet.js +240 -20
  82. package/src/walletconnect-trading.js +29 -8
  83. package/src/walletconnect-x402.js +9 -5
  84. package/src/x402-svm.js +123 -64
  85. package/src/x402.js +46 -14
package/src/x402-svm.js CHANGED
@@ -8,6 +8,7 @@ import { base58Encode, base58DecodePubkey } from './wallet.js';
8
8
  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
+ import { CHAIN_RPCS } from './rpc-urls.js';
11
12
 
12
13
  // ============= Constants =============
13
14
 
@@ -20,6 +21,16 @@ const _SYSTEM_PROGRAM = '11111111111111111111111111111111';
20
21
  const DEFAULT_COMPUTE_UNIT_LIMIT = 20000;
21
22
  const DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;
22
23
 
24
+ // Upper bound on a single blockhash RPC round-trip. A NANSEN_SOLANA_RPC
25
+ // endpoint that accepts the connection but never answers would otherwise
26
+ // stall the x402 payment fallback loop for Node's default header timeout.
27
+ const SOLANA_RPC_TIMEOUT_MS = 15_000;
28
+
29
+ // An x402 Solana payment is signed by exactly two accounts: the facilitator
30
+ // (feePayer, slot 0) and the paying wallet (slot 1).
31
+ const X402_SVM_SIGNER_COUNT = 2;
32
+ const SIGNATURE_BYTES = 64;
33
+
23
34
  // ============= PDA Derivation =============
24
35
 
25
36
  /**
@@ -36,9 +47,9 @@ export function deriveATA(ownerBase58, mintBase58, tokenProgramBase58 = TOKEN_PR
36
47
  * Build a Solana MessageV0 from accounts and instructions.
37
48
  * feePayer is always placed at account index 0, forced signer+writable,
38
49
  * regardless of whether an instruction references it directly.
39
- * Returns numRequiredSignatures alongside the bytes since it's read back out
40
- * of the header to size the signature-placeholder slots of the wrapping
41
- * unsigned transaction (see callers).
50
+ * Returns numRequiredSignatures alongside the bytes. Each caller writes a
51
+ * fixed number of signature slots and asserts this value against it, since a
52
+ * header that disagrees with the slot count is rejected at broadcast.
42
53
  */
43
54
  export function buildMessageV0({ feePayer, instructions, recentBlockhash, accounts: _accounts }) {
44
55
  // All unique accounts in order: feePayer first, then signers, then rest
@@ -237,20 +248,30 @@ export function buildUnsignedSvmTransaction(
237
248
  },
238
249
  ];
239
250
 
240
- const { messageBytes } = buildMessageV0({
251
+ const { messageBytes, numRequiredSignatures } = buildMessageV0({
241
252
  feePayer: feePayerStr,
242
253
  instructions,
243
254
  recentBlockhash,
244
255
  accounts: null,
245
256
  });
257
+ // The header must agree with the signature slots written below. A
258
+ // server-supplied feePayer equal to the paying wallet collapses the two
259
+ // signers into one, and the transaction would fail sanitization at broadcast.
260
+ if (numRequiredSignatures !== X402_SVM_SIGNER_COUNT) {
261
+ const cause = feePayerStr === walletAddress
262
+ ? `its feePayer is the paying wallet (${walletAddress}) instead of a facilitator account`
263
+ : `its transaction requires ${numRequiredSignatures} signatures instead of ${X402_SVM_SIGNER_COUNT}`;
264
+ throw new Error(
265
+ `Cannot pay this x402 Solana option: ${cause}. ` +
266
+ 'Another payment option will be tried; if none succeeds, pay on another network or report this payment option to Nansen.',
267
+ );
268
+ }
246
269
 
247
270
  // Build transaction: compact-u16(numSignatures) + signatures + message
248
- // 2 signatures: [facilitator placeholder (64 zero bytes), client placeholder (64 zero bytes)]
249
- const numSigs = encodeCompactU16(2);
271
+ // [facilitator placeholder, client placeholder], 64 zero bytes each
250
272
  const txBytes = Buffer.concat([
251
- numSigs,
252
- Buffer.alloc(64), // facilitator placeholder
253
- Buffer.alloc(64), // client placeholder
273
+ encodeCompactU16(X402_SVM_SIGNER_COUNT),
274
+ Buffer.alloc(X402_SVM_SIGNER_COUNT * SIGNATURE_BYTES),
254
275
  messageBytes,
255
276
  ]);
256
277
 
@@ -272,7 +293,7 @@ export function createSvmPaymentPayload(
272
293
  decimals = 6,
273
294
  tokenProgram = TOKEN_PROGRAM,
274
295
  ) {
275
- const { messageBytes } = buildUnsignedSvmTransaction(
296
+ const { messageBytes, txBase64: unsignedTxBase64 } = buildUnsignedSvmTransaction(
276
297
  requirements,
277
298
  walletAddress,
278
299
  recentBlockhash,
@@ -283,14 +304,11 @@ export function createSvmPaymentPayload(
283
304
  // Sign: client signs the full message (with 0x80 version prefix already included)
284
305
  const clientSignature = signEd25519(messageBytes, keypairHex);
285
306
 
286
- // Rebuild transaction with the real client signature at slot 1
287
- const numSigs = encodeCompactU16(2);
288
- const txBytes = Buffer.concat([
289
- numSigs,
290
- Buffer.alloc(64), // facilitator placeholder
291
- clientSignature,
292
- messageBytes,
293
- ]);
307
+ // Write the client signature into slot 1 of the unsigned transaction, so
308
+ // the wire layout is built in one place.
309
+ const txBytes = Buffer.from(unsignedTxBase64, 'base64');
310
+ const clientSlotOffset = encodeCompactU16(X402_SVM_SIGNER_COUNT).length + SIGNATURE_BYTES;
311
+ clientSignature.copy(txBytes, clientSlotOffset);
294
312
 
295
313
  const txBase64 = txBytes.toString('base64');
296
314
 
@@ -308,70 +326,111 @@ export function createSvmPaymentPayload(
308
326
  return Buffer.from(JSON.stringify(payload)).toString('base64');
309
327
  }
310
328
 
329
+ function isHttpUrl(value) {
330
+ if (typeof value !== 'string') return false;
331
+ try {
332
+ const { protocol } = new URL(value);
333
+ return protocol === 'http:' || protocol === 'https:';
334
+ } catch {
335
+ return false;
336
+ }
337
+ }
338
+
311
339
  /**
312
340
  * Fetch recent blockhash from Solana RPC.
341
+ *
342
+ * Defaults to the shared RPC registry so NANSEN_SOLANA_RPC is honoured even
343
+ * for an argless call; every production caller passes the URL explicitly.
313
344
  */
314
- export async function fetchRecentBlockhash(rpcUrl = 'https://api.mainnet-beta.solana.com') {
315
- let response;
316
- try {
317
- response = await fetch(rpcUrl, {
318
- method: 'POST',
319
- headers: { 'Content-Type': 'application/json' },
320
- body: JSON.stringify({
321
- jsonrpc: '2.0',
322
- id: 1,
323
- method: 'getLatestBlockhash',
324
- params: [{ commitment: 'finalized' }],
325
- }),
326
- });
327
- } catch (err) {
345
+ export async function fetchRecentBlockhash(rpcUrl = CHAIN_RPCS.solana) {
346
+ // Validate up front and never echo the raw value. A private RPC URL usually
347
+ // carries an API key in its query string, and Node's own parse failure
348
+ // ("Failed to parse URL from <value>") would otherwise copy it into the
349
+ // error message that the Privy and local-wallet fallback loops print.
350
+ if (!isHttpUrl(rpcUrl)) {
328
351
  throw new Error(
329
- `Solana RPC unavailable while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${String(err.message ?? err)}`,
330
- { cause: err }
352
+ 'Invalid Solana RPC URL: expected a full http:// or https:// URL. Check NANSEN_SOLANA_RPC.'
331
353
  );
332
354
  }
333
355
 
334
- if (!response.ok) {
335
- const text = await response.text().catch(() => '');
336
- throw new Error(
337
- `Solana RPC returned HTTP ${response.status} while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${text.slice(0, 100)}`
338
- );
339
- }
356
+ const controller = new AbortController();
357
+ const timer = setTimeout(() => controller.abort(), SOLANA_RPC_TIMEOUT_MS);
358
+ const timeoutError = (cause) => new Error(
359
+ `Solana RPC did not respond within ${SOLANA_RPC_TIMEOUT_MS / 1000}s while fetching a recent blockhash. Retry or configure a different RPC endpoint.`,
360
+ { cause }
361
+ );
340
362
 
341
- let data;
342
363
  try {
343
- data = await response.json();
344
- } catch {
345
- throw new Error(
346
- 'Solana RPC returned an invalid response while fetching a recent blockhash. Retry or configure a different RPC endpoint.'
347
- );
348
- }
364
+ let response;
365
+ try {
366
+ response = await fetch(rpcUrl, {
367
+ method: 'POST',
368
+ headers: { 'Content-Type': 'application/json' },
369
+ body: JSON.stringify({
370
+ jsonrpc: '2.0',
371
+ id: 1,
372
+ method: 'getLatestBlockhash',
373
+ params: [{ commitment: 'finalized' }],
374
+ }),
375
+ signal: controller.signal,
376
+ });
377
+ } catch (err) {
378
+ if (controller.signal.aborted) throw timeoutError(err);
379
+ throw new Error(
380
+ `Solana RPC unavailable while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${String(err.message ?? err)}`,
381
+ { cause: err }
382
+ );
383
+ }
349
384
 
350
- if (data?.error) {
351
- const detail =
352
- data.error.message != null ? String(data.error.message)
353
- : data.error.code != null ? String(data.error.code)
354
- : 'unknown RPC error';
355
- throw new Error(
356
- `Solana RPC failed while fetching a recent blockhash: ${detail}. Retry or configure a different RPC endpoint.`
357
- );
358
- }
385
+ if (!response.ok) {
386
+ const text = await response.text().catch(() => '');
387
+ throw new Error(
388
+ `Solana RPC returned HTTP ${response.status} while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${text.slice(0, 100)}`
389
+ );
390
+ }
359
391
 
360
- const blockhash = data?.result?.value?.blockhash;
361
- if (typeof blockhash !== 'string' || blockhash.length === 0) {
362
- throw new Error(
363
- 'Solana RPC returned no recent blockhash. Retry or configure a different RPC endpoint.'
364
- );
365
- }
392
+ let data;
393
+ try {
394
+ data = await response.json();
395
+ } catch (err) {
396
+ if (controller.signal.aborted) throw timeoutError(err);
397
+ throw new Error(
398
+ 'Solana RPC returned an invalid response while fetching a recent blockhash. Retry or configure a different RPC endpoint.',
399
+ { cause: err }
400
+ );
401
+ }
366
402
 
367
- return blockhash;
403
+ if (data?.error) {
404
+ const detail =
405
+ data.error.message != null ? String(data.error.message)
406
+ : data.error.code != null ? String(data.error.code)
407
+ : 'unknown RPC error';
408
+ throw new Error(
409
+ `Solana RPC failed while fetching a recent blockhash: ${detail}. Retry or configure a different RPC endpoint.`
410
+ );
411
+ }
412
+
413
+ const blockhash = data?.result?.value?.blockhash;
414
+ if (typeof blockhash !== 'string' || blockhash.length === 0) {
415
+ throw new Error(
416
+ 'Solana RPC returned no recent blockhash. Retry or configure a different RPC endpoint.'
417
+ );
418
+ }
419
+
420
+ return blockhash;
421
+ } finally {
422
+ clearTimeout(timer);
423
+ }
368
424
  }
369
425
 
370
426
  /**
371
427
  * Get RPC URL for a Solana network identifier.
372
428
  */
373
429
  export function getSolanaRpcUrl(network) {
374
- if (network === SOLANA_MAINNET_NETWORK) return 'https://api.mainnet-beta.solana.com';
430
+ // Mainnet goes through the shared registry so NANSEN_SOLANA_RPC applies to
431
+ // x402 blockhash and balance calls the same way it does to every other
432
+ // Solana path (transfer, trading, limit orders). The default is unchanged.
433
+ if (network === SOLANA_MAINNET_NETWORK) return CHAIN_RPCS.solana;
375
434
  // Devnet/testnet resolve for tooling (e.g. balance checks), but the x402 pay
376
435
  // path never reaches them: SVM_X402_TOKENS is mainnet-only, so the policy layer
377
436
  // refuses a devnet/testnet requirement before signing. Adding a non-mainnet
package/src/x402.js CHANGED
@@ -42,20 +42,37 @@ export function parsePaymentRequirements(response) {
42
42
  }
43
43
 
44
44
  /**
45
- * Rank payment requirements. Prefers EVM (gasless) over Solana.
46
- * Returns all supported requirements in priority order.
45
+ * Rank payment requirements cheapest first.
46
+ *
47
+ * A 402 response may offer several options that are all individually valid
48
+ * and within the per-payment cap. The caller signs them in this order and
49
+ * stops at the first the server accepts, so the order decides what the wallet
50
+ * pays: server order alone let a merchant list an expensive option first and
51
+ * be paid it while a cheaper one for the same resource sat in the same
52
+ * response.
53
+ *
54
+ * Price comes from evaluatePaymentRequirement, the same function that later
55
+ * guards the payment, so ranking and policy cannot disagree. An option the
56
+ * policy refuses sorts last rather than being dropped here: the caller logs
57
+ * its reason when it tries and skips it.
58
+ *
59
+ * Ties keep the previous behaviour — EVM before Solana, then the server's own
60
+ * order — so a response whose options cost the same is unaffected.
47
61
  */
48
62
  function rankRequirements(requirements) {
49
- const ranked = [];
50
- // EVM first (gasless for client)
51
- for (const r of requirements) {
52
- if (isEvmNetwork(r.network)) ranked.push(r);
53
- }
54
- // Then Solana
55
- for (const r of requirements) {
56
- if (isSvmNetwork(r.network)) ranked.push(r);
57
- }
58
- return ranked;
63
+ return requirements
64
+ .filter(r => isEvmNetwork(r.network) || isSvmNetwork(r.network))
65
+ .map((requirement, index) => {
66
+ const decision = evaluatePaymentRequirement(requirement);
67
+ return {
68
+ requirement,
69
+ index,
70
+ rail: isEvmNetwork(requirement.network) ? 0 : 1,
71
+ usd: decision.ok && Number.isFinite(decision.usd) ? decision.usd : Number.POSITIVE_INFINITY,
72
+ };
73
+ })
74
+ .sort((a, b) => (a.usd - b.usd) || (a.rail - b.rail) || (a.index - b.index))
75
+ .map(entry => entry.requirement);
59
76
  }
60
77
 
61
78
  // ERC-20 allowance(owner, spender) selector for the Permit2 preflight.
@@ -103,6 +120,18 @@ async function buildPaymentForRequirement(requirement, exported, url) {
103
120
  return null;
104
121
  }
105
122
 
123
+ // exportWallet returns a null key for a chain the wallet file doesn't hold.
124
+ // Skip that option with a clear reason instead of failing on the missing key.
125
+ const rail = isEvmNetwork(requirement.network) ? 'evm' : 'solana';
126
+ if (!exported[rail]?.privateKey || !exported[rail]?.address) {
127
+ const chain = rail === 'evm' ? 'EVM' : 'Solana';
128
+ console.error(
129
+ `[x402] Skipping ${requirement.network} option: wallet "${exported.name}" has no ${chain} key. ` +
130
+ 'Create a wallet with both keys (nansen wallet create) and make it the default (nansen wallet default <name>).',
131
+ );
132
+ return null;
133
+ }
134
+
106
135
  if (isEvmNetwork(requirement.network)) {
107
136
  if ((requirement.extra || {}).assetTransferMethod === 'permit2-exact') {
108
137
  const resolvedAmount = resolvePaymentAmount(requirement);
@@ -194,8 +223,11 @@ export async function* createPaymentSignatures(response, url, options = {}) {
194
223
  try {
195
224
  const sig = await buildPaymentForRequirement(req, exported, url);
196
225
  if (sig) yield { signature: sig, network: req.network, asset: req.asset };
197
- } catch {
198
- // This payment option failed to build, try next
226
+ } catch (err) {
227
+ // This payment option failed to build; say why and try the next one
228
+ // (otherwise a malformed server option only surfaces as a generic
229
+ // payment failure once every option is exhausted).
230
+ console.error(`[x402] Skipping ${req.network} option: ${err?.message || err}`);
199
231
  continue;
200
232
  }
201
233
  }