nansen-cli 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +109 -33
  3. package/docs/auth.md +56 -0
  4. package/docs/browser-login.md +101 -7
  5. package/docs/error-codes.md +249 -0
  6. package/package.json +10 -4
  7. package/skills/nansen-agent-guide/SKILL.md +54 -1
  8. package/skills/nansen-alerts-webhook-listener/SKILL.md +1 -1
  9. package/skills/nansen-dca-tracker/SKILL.md +1 -1
  10. package/skills/nansen-defi-positions/SKILL.md +1 -1
  11. package/skills/nansen-exit-signals/SKILL.md +2 -2
  12. package/skills/nansen-fund-tracker/SKILL.md +1 -1
  13. package/skills/nansen-general-search/SKILL.md +1 -1
  14. package/skills/nansen-holder-analysis/SKILL.md +2 -2
  15. package/skills/nansen-limit-orders/SKILL.md +1 -1
  16. package/skills/nansen-mpp-payment/SKILL.md +2 -2
  17. package/skills/nansen-perp-screener/SKILL.md +1 -1
  18. package/skills/nansen-perp-trader-profile/SKILL.md +1 -1
  19. package/skills/nansen-polymarket-deep-dive/SKILL.md +1 -1
  20. package/skills/nansen-polymarket-insider-scan/SKILL.md +1 -1
  21. package/skills/nansen-polymarket-trader-profile/SKILL.md +1 -1
  22. package/skills/nansen-portfolio-tracker/SKILL.md +1 -1
  23. package/skills/nansen-prediction-markets/SKILL.md +1 -1
  24. package/skills/nansen-sm-cross-chain-flows/SKILL.md +1 -1
  25. package/skills/nansen-smart-alerts/SKILL.md +2 -1
  26. package/skills/nansen-smart-money-alpha/SKILL.md +1 -1
  27. package/skills/nansen-smart-money-tracker/SKILL.md +8 -7
  28. package/skills/nansen-smart-money-trend/SKILL.md +1 -1
  29. package/skills/nansen-token-research/SKILL.md +1 -1
  30. package/skills/nansen-token-screener/SKILL.md +1 -1
  31. package/skills/nansen-token-transfer-analysis/SKILL.md +1 -1
  32. package/skills/nansen-trading/SKILL.md +1 -1
  33. package/skills/nansen-wallet-batch/SKILL.md +1 -1
  34. package/skills/nansen-wallet-clustering/SKILL.md +1 -1
  35. package/skills/nansen-wallet-deep-dive/SKILL.md +1 -1
  36. package/skills/nansen-wallet-keychain-migration/SKILL.md +1 -1
  37. package/skills/nansen-wallet-manager/SKILL.md +1 -1
  38. package/skills/nansen-wallet-profiler/SKILL.md +1 -1
  39. package/skills/nansen-web-fetcher/SKILL.md +1 -1
  40. package/skills/nansen-web-searcher/SKILL.md +1 -1
  41. package/src/api-endpoints.json +1605 -0
  42. package/src/api.js +336 -121
  43. package/src/auth-credentials.js +1 -0
  44. package/src/auth-state.js +2 -2
  45. package/src/auth-store-native.js +6 -1
  46. package/src/auth-store-worker.js +1 -1
  47. package/src/auth-store.js +9 -4
  48. package/src/bridge.js +19 -10
  49. package/src/cli.js +258 -107
  50. package/src/commands/agent.js +2 -3
  51. package/src/commands/alerts.js +277 -9
  52. package/src/commands/completion.js +6 -1
  53. package/src/commands/feedback.js +413 -0
  54. package/src/commands/mcp.js +1 -1
  55. package/src/commands/research.js +14 -37
  56. package/src/cost-cache.js +33 -7
  57. package/src/doctor.js +14 -5
  58. package/src/error-codes.js +226 -0
  59. package/src/feedback-journal.js +86 -0
  60. package/src/input-validation.js +551 -0
  61. package/src/limit-order.js +12 -3
  62. package/src/perp.js +2 -1
  63. package/src/privy.js +144 -48
  64. package/src/query-options.js +30 -7
  65. package/src/rpc-urls.js +3 -1
  66. package/src/schema.json +1254 -150
  67. package/src/solana-tx.js +4 -0
  68. package/src/telemetry.js +5 -1
  69. package/src/trade-validation.js +190 -21
  70. package/src/trading.js +229 -129
  71. package/src/transfer.js +7 -1
  72. package/src/update-check.js +32 -5
  73. package/src/wallet.js +220 -57
  74. package/src/walletconnect-x402.js +152 -52
  75. package/src/x402-audit.js +191 -0
  76. package/src/x402-payment-balance.js +90 -0
  77. package/src/x402-policy.js +151 -4
  78. package/src/x402.js +51 -22
package/src/privy.js CHANGED
@@ -9,9 +9,10 @@
9
9
  import fs from "fs";
10
10
  import path from "path";
11
11
  import { parsePaymentRequirements } from "./x402.js";
12
+ import { hasSufficientEvmPaymentBalance, hasSufficientSvmPaymentBalance } from "./x402-payment-balance.js";
12
13
  import { isEvmNetwork } from "./x402-evm.js";
13
- import { mkdirPrivateSync, readWalletJson, writeWalletJsonAtomic } from "./wallet.js";
14
- import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from "./x402-policy.js";
14
+ import { mkdirPrivateSync, readWalletJson, withWalletLock, writeWalletJsonAtomic } from "./wallet.js";
15
+ import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo, signWithSessionCharge } from "./x402-policy.js";
15
16
  import {
16
17
  isSvmNetwork,
17
18
  getSolanaRpcUrl,
@@ -151,6 +152,54 @@ export class PrivyClient {
151
152
 
152
153
  // ============= Helpers =============
153
154
 
155
+ function extractPrivyWalletAddress(response) {
156
+ return response?.address
157
+ ?? response?.data?.address
158
+ ?? response?.wallet?.address
159
+ ?? response?.data?.wallet?.address
160
+ ?? null;
161
+ }
162
+
163
+ /**
164
+ * Resolve a Privy wallet ID and bind it to the address stored locally before
165
+ * any preview, screening, or signing can rely on that address.
166
+ */
167
+ export async function assertPrivyWalletAddress(client, walletId, expectedAddress, chainType) {
168
+ if (chainType !== 'evm' && chainType !== 'solana') {
169
+ throw new Error(`Unsupported Privy wallet chain type: ${chainType}`);
170
+ }
171
+ const label = chainType === 'solana' ? 'Solana' : 'EVM';
172
+ if (!walletId) {
173
+ throw new Error(`No Privy ${label} wallet ID found. Re-create the wallet with: nansen wallet create --provider privy`);
174
+ }
175
+ if (!expectedAddress) {
176
+ throw new Error(`No ${label} address is stored for this Privy wallet. Re-create the wallet with: nansen wallet create --provider privy`);
177
+ }
178
+
179
+ const response = await client.getWallet(walletId);
180
+ const authoritativeAddress = extractPrivyWalletAddress(response);
181
+ const validAddress = chainType === 'evm'
182
+ ? /^0x[0-9a-f]{40}$/i
183
+ : /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
184
+ if (typeof authoritativeAddress !== 'string' || !validAddress.test(authoritativeAddress)) {
185
+ throw new Error(`Privy returned no valid ${label} address for the selected wallet ID. Re-create the wallet with: nansen wallet create --provider privy`);
186
+ }
187
+ if (typeof expectedAddress !== 'string' || !validAddress.test(expectedAddress)) {
188
+ throw new Error(`The locally stored Privy ${label} address is invalid. Re-create the wallet with: nansen wallet create --provider privy`);
189
+ }
190
+
191
+ const matches = chainType === 'evm'
192
+ ? authoritativeAddress.toLowerCase() === String(expectedAddress).toLowerCase()
193
+ : authoritativeAddress === expectedAddress;
194
+ if (!matches) {
195
+ throw new Error(
196
+ `The selected Privy wallet ID does not match the locally stored ${label} address. Re-create the wallet with: nansen wallet create --provider privy`,
197
+ );
198
+ }
199
+
200
+ return authoritativeAddress;
201
+ }
202
+
154
203
  function getClient() {
155
204
  return new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
156
205
  }
@@ -194,18 +243,48 @@ export async function createPrivyWalletPair(name) {
194
243
 
195
244
  mkdirPrivateSync(walletsDir);
196
245
 
197
- // Write config before wallet file so a crash doesn't leave an orphan without a default entry
198
- const configPath = path.join(walletsDir, "config.json");
199
- let config = { defaultWallet: null, passwordHash: null };
200
- if (fs.existsSync(configPath)) {
201
- config = readWalletJson(configPath);
202
- }
203
- if (!config.defaultWallet) {
204
- config.defaultWallet = name;
205
- writeWalletJsonAtomic(configPath, config);
246
+ // Only the local save is locked; the Privy calls above stay outside it. So
247
+ // re-check the name here: another command may have taken it meanwhile.
248
+ const deleteRemote = async () => {
249
+ try { await client.deleteWallet(evmResult.id); } catch { /* best effort */ }
250
+ try { await client.deleteWallet(solanaResult.id); } catch { /* best effort */ }
251
+ };
252
+ let saved;
253
+ try {
254
+ saved = withWalletLock(() => {
255
+ if (fs.existsSync(walletFile)) return false;
256
+
257
+ const configPath = path.join(walletsDir, "config.json");
258
+ let config = { defaultWallet: null, passwordHash: null };
259
+ if (fs.existsSync(configPath)) {
260
+ config = readWalletJson(configPath);
261
+ }
262
+
263
+ // Wallet file first, as createWallet does: if the config write then
264
+ // fails, the file is removed, so config never names a missing wallet.
265
+ writeWalletJsonAtomic(walletFile, walletData);
266
+ if (!config.defaultWallet) {
267
+ config.defaultWallet = name;
268
+ try {
269
+ writeWalletJsonAtomic(configPath, config);
270
+ } catch (err) {
271
+ fs.rmSync(walletFile, { force: true });
272
+ throw err;
273
+ }
274
+ }
275
+ return true;
276
+ });
277
+ } catch (err) {
278
+ // Busy lock or unreadable config: nothing local references the new
279
+ // Privy wallets, so remove them rather than orphan them.
280
+ await deleteRemote();
281
+ throw err;
206
282
  }
207
283
 
208
- writeWalletJsonAtomic(walletFile, walletData);
284
+ if (!saved) {
285
+ await deleteRemote();
286
+ throw new Error(`Wallet "${name}" already exists`);
287
+ }
209
288
 
210
289
  return walletData;
211
290
  }
@@ -280,13 +359,15 @@ async function getPrivySolanaWallet(client) {
280
359
 
281
360
  /**
282
361
  * Generate payment signatures for x402 using Privy server wallets.
283
- * Same yield contract as createPaymentSignatures() in x402.js: { signature, network }
362
+ * Same yield contract as createPaymentSignatures() in x402.js:
363
+ * { signature, network, asset, payment, releaseCharge }
284
364
  *
285
365
  * @param {Response} response - The 402 HTTP response
286
366
  * @param {string} url - The original request URL
287
- * @returns {AsyncGenerator<{ signature: string, network: string }>}
367
+ * @param {object} [options] - { onCapRefusal }, called with the reason when the session cap refuses an option
368
+ * @returns {AsyncGenerator<{ signature: string, network: string, asset: string, payment: object, releaseCharge: Function }>}
288
369
  */
289
- export async function* createPrivyPaymentSignatures(response, url) {
370
+ export async function* createPrivyPaymentSignatures(response, url, options = {}) {
290
371
  const requirements = parsePaymentRequirements(response);
291
372
  if (!requirements || requirements.length === 0) return;
292
373
 
@@ -304,34 +385,40 @@ export async function* createPrivyPaymentSignatures(response, url) {
304
385
  continue;
305
386
  }
306
387
  try {
388
+ if (!await hasSufficientEvmPaymentBalance(requirement, evmWallet.address)) continue;
307
389
  const typedData = buildEIP712TypedData({
308
390
  fromAddress: evmWallet.address,
309
391
  requirement,
310
392
  });
311
393
 
312
- const signResult = await client.ethSignTypedDataV4(
313
- evmWallet.id,
314
- typedData
315
- );
316
- const signature = signResult.data?.signature || signResult.signature;
317
-
318
- const authorization = {
319
- from: evmWallet.address,
320
- to: resolvePayTo(requirement),
321
- value: resolvePaymentAmount(requirement).toString(),
322
- validAfter: typedData.message.validAfter.toString(),
323
- validBefore: typedData.message.validBefore.toString(),
324
- nonce: typedData.message.nonce,
325
- };
326
-
327
- const header = buildPaymentSignatureHeader({
328
- signature,
329
- authorization,
330
- resource: { url, description: "", mimeType: "" },
331
- accepted: requirement,
394
+ const signed = await signWithSessionCharge(decision, async () => {
395
+ const signResult = await client.ethSignTypedDataV4(evmWallet.id, typedData);
396
+ const signature = signResult.data?.signature || signResult.signature;
397
+ if (!signature) throw new Error('Privy returned no signature');
398
+
399
+ const authorization = {
400
+ from: evmWallet.address,
401
+ to: resolvePayTo(requirement),
402
+ value: resolvePaymentAmount(requirement).toString(),
403
+ validAfter: typedData.message.validAfter.toString(),
404
+ validBefore: typedData.message.validBefore.toString(),
405
+ nonce: typedData.message.nonce,
406
+ };
407
+
408
+ return buildPaymentSignatureHeader({
409
+ signature,
410
+ authorization,
411
+ resource: { url, description: "", mimeType: "" },
412
+ accepted: requirement,
413
+ });
332
414
  });
415
+ if (!signed.ok) {
416
+ console.error(`[x402] ${signed.reason}`);
417
+ options.onCapRefusal?.(signed.reason);
418
+ continue;
419
+ }
333
420
 
334
- yield { signature: header, network: requirement.network };
421
+ yield { signature: signed.value, network: requirement.network, asset: requirement.asset, payment: decision, releaseCharge: signed.release };
335
422
  } catch (err) {
336
423
  console.error(`[x402] Privy EVM signing failed for ${requirement.network}: ${err.message}`);
337
424
  continue;
@@ -354,6 +441,7 @@ export async function* createPrivyPaymentSignatures(response, url) {
354
441
  continue;
355
442
  }
356
443
  try {
444
+ if (!await hasSufficientSvmPaymentBalance(requirement, solWallet.address)) continue;
357
445
  const rpcUrl = getSolanaRpcUrl(requirement.network);
358
446
  const recentBlockhash = await fetchRecentBlockhash(rpcUrl);
359
447
 
@@ -363,20 +451,28 @@ export async function* createPrivyPaymentSignatures(response, url) {
363
451
  recentBlockhash,
364
452
  );
365
453
 
366
- const signResult = await client.signSolanaTransaction(solWallet.id, txBase64);
367
- const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction;
368
-
369
- const payload = {
370
- x402Version: 2,
371
- payload: { transaction: signedTx },
372
- accepted: requirement,
373
- };
374
- if (url) {
375
- payload.resource = { url };
454
+ const signed = await signWithSessionCharge(svmDecision, async () => {
455
+ const signResult = await client.signSolanaTransaction(solWallet.id, txBase64);
456
+ const signedTx = signResult.data?.signed_transaction || signResult.signed_transaction;
457
+ if (!signedTx) throw new Error('Privy returned no signed transaction');
458
+
459
+ const payload = {
460
+ x402Version: 2,
461
+ payload: { transaction: signedTx },
462
+ accepted: requirement,
463
+ };
464
+ if (url) {
465
+ payload.resource = { url };
466
+ }
467
+ return Buffer.from(JSON.stringify(payload)).toString("base64");
468
+ });
469
+ if (!signed.ok) {
470
+ console.error(`[x402] ${signed.reason}`);
471
+ options.onCapRefusal?.(signed.reason);
472
+ continue;
376
473
  }
377
474
 
378
- const header = Buffer.from(JSON.stringify(payload)).toString("base64");
379
- yield { signature: header, network: requirement.network };
475
+ yield { signature: signed.value, network: requirement.network, asset: requirement.asset, payment: svmDecision, releaseCharge: signed.release };
380
476
  } catch (err) {
381
477
  console.error(`[x402] Privy Solana signing failed for ${requirement.network}: ${err.message}`);
382
478
  continue;
@@ -7,17 +7,31 @@
7
7
  */
8
8
 
9
9
  import { NansenError, CommandError, ErrorCode } from './api.js';
10
+ import { normalizeFilterAddresses } from './input-validation.js';
10
11
 
12
+ /**
13
+ * The request `pagination` object for --page/--limit, or undefined when
14
+ * neither is given. Both must be positive whole numbers: --page 0 used to be
15
+ * clamped to 1 silently (API-1081).
16
+ */
11
17
  export function buildPagination(options) {
12
18
  if (options.limit === undefined && options.page === undefined) return undefined;
13
- const perPage = options.limit === undefined ? undefined : Number(options.limit);
14
- if (perPage !== undefined && (!Number.isInteger(perPage) || perPage < 1)) {
15
- throw new NansenError('--limit must be a positive integer', ErrorCode.INVALID_PARAMS);
19
+ const pagination = { page: 1 };
20
+ if (options.page !== undefined) {
21
+ const page = Number(options.page);
22
+ if (typeof options.page === 'boolean' || String(options.page).trim() === '' || !Number.isSafeInteger(page) || page < 1) {
23
+ throw new NansenError('--page must be a positive integer', ErrorCode.INVALID_PARAMS);
24
+ }
25
+ pagination.page = page;
26
+ }
27
+ if (options.limit !== undefined) {
28
+ const perPage = Number(options.limit);
29
+ if (typeof options.limit === 'boolean' || String(options.limit).trim() === '' || !Number.isSafeInteger(perPage) || perPage < 1) {
30
+ throw new NansenError('--limit must be a positive integer', ErrorCode.INVALID_PARAMS);
31
+ }
32
+ pagination.per_page = perPage;
16
33
  }
17
- return {
18
- page: Math.max(1, parseInt(options.page, 10) || 1),
19
- per_page: perPage,
20
- };
34
+ return pagination;
21
35
  }
22
36
 
23
37
  // Parse simple sort syntax: "field:direction" or "field" (defaults to DESC)
@@ -85,6 +99,15 @@ export function parseObjectOption(val, name) {
85
99
  return val;
86
100
  }
87
101
 
102
+ /**
103
+ * `--filters '<json>'` as a plain object with every EVM address lowercased.
104
+ * The API stores EVM addresses lowercase, so a checksummed address matched no
105
+ * rows and the command returned an empty success (API-1081).
106
+ */
107
+ export function parseFiltersOption(val) {
108
+ return normalizeFilterAddresses(parseObjectOption(val, 'filters'));
109
+ }
110
+
88
111
  /** Reject explicit blank strings before a handler selects an omitted-option default. */
89
112
  export function rejectBlankOption(value, name, example) {
90
113
  if (typeof value === 'string' && value.trim() === '') {
package/src/rpc-urls.js CHANGED
@@ -37,7 +37,9 @@
37
37
  * working while new code uses the standardised NANSEN_BASE_RPC name.
38
38
  */
39
39
 
40
- const DEFAULT_EVM_RPC = 'https://eth.public-rpc.com';
40
+ // eth.public-rpc.com started requiring an API key (HTTP 403), which broke every
41
+ // `wallet send --chain ethereum|evm` that had no NANSEN_EVM_RPC override.
42
+ const DEFAULT_EVM_RPC = 'https://ethereum-rpc.publicnode.com';
41
43
  const DEFAULT_BASE_RPC = 'https://mainnet.base.org';
42
44
  const DEFAULT_BSC_RPC = 'https://bsc-dataseed.binance.org';
43
45
  const DEFAULT_XLAYER_RPC = 'https://rpc.xlayer.tech';