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
@@ -2,6 +2,8 @@
2
2
  * x402 payment policy guard.
3
3
  * Decides whether an auto-payment is safe to sign before any signature is produced.
4
4
  * Three layers: known-asset allowlist, optional payTo allowlist, per-payment USD cap.
5
+ * An optional per-process cumulative cap is charged by each signer, through
6
+ * signWithSessionCharge, immediately before it signs.
5
7
  */
6
8
 
7
9
  import { EVM_X402_TOKENS, SVM_X402_TOKENS } from './x402-tokens.js';
@@ -128,8 +130,10 @@ export function resolvePayTo(requirement) {
128
130
 
129
131
  /**
130
132
  * Decide whether an x402 payment requirement is safe to auto-sign.
131
- * Returns { ok: true, usd, symbol } when allowed, or { ok: false, reason }
132
- * with a human-readable, actionable reason when refused.
133
+ * Returns { ok: true, usd, symbol, network, asset, payTo, amountRaw } when
134
+ * allowed (amountRaw is the parsed base-unit amount as a decimal string, so
135
+ * "0x2710" and 1e4 both become "10000"), or
136
+ * { ok: false, reason } with a human-readable, actionable reason when refused.
133
137
  *
134
138
  * Enforces in order: known (network, asset) allowlist, optional payTo
135
139
  * allowlist, per-payment USD cap. Never signs; pure decision.
@@ -179,10 +183,11 @@ export function evaluatePaymentRequirement(requirement) {
179
183
  }
180
184
 
181
185
  let usd;
186
+ let base;
182
187
  try {
183
188
  // BigInt base units → USD. Keep integer/fraction split to avoid float loss
184
189
  // on large values; final Number() is safe for display-scale amounts.
185
- const base = BigInt(amountRaw);
190
+ base = BigInt(amountRaw);
186
191
  // A transfer authorization must be for a positive amount; a negative value
187
192
  // is never legitimate and should never be signed.
188
193
  if (base < 0n) {
@@ -212,5 +217,147 @@ export function evaluatePaymentRequirement(requirement) {
212
217
  };
213
218
  }
214
219
 
215
- return { ok: true, usd, symbol: known.symbol };
220
+ return {
221
+ ok: true,
222
+ usd,
223
+ // A decimal string, not a BigInt, so the decision stays JSON-serializable.
224
+ amountMicroUsd: toMicroUsd(base, known.decimals).toString(),
225
+ symbol: known.symbol,
226
+ network,
227
+ asset,
228
+ payTo,
229
+ amountRaw: base.toString(),
230
+ };
231
+ }
232
+
233
+ // Cumulative USD auto-paid by this process, in integer micro-USD so repeated
234
+ // charges can't drift past an exact cap the way float sums do (0.1 + 0.2).
235
+ // It resets with every process: the cap bounds one invocation (its retries,
236
+ // fallbacks and concurrent requests), not spending across separate runs.
237
+ let sessionSpentMicroUsd = 0n;
238
+ // The cap as first read, so it can't change partway through a run.
239
+ let sessionCap;
240
+
241
+ const MICRO_USD_PER_USD = 1_000_000n;
242
+ const USD_AMOUNT = /^\d+(\.\d+)?$/;
243
+
244
+ /**
245
+ * Token base units → micro-USD, rounded up so a fraction of a micro-dollar is
246
+ * never charged as zero.
247
+ */
248
+ function toMicroUsd(base, decimals) {
249
+ const scale = 10n ** BigInt(decimals);
250
+ return (base * MICRO_USD_PER_USD + scale - 1n) / scale;
251
+ }
252
+
253
+ /** "$0.01", or up to six decimals ("$0.0015") when a sub-cent amount needs them. */
254
+ function formatMicroUsd(micro) {
255
+ const fraction = (micro % MICRO_USD_PER_USD).toString().padStart(6, '0').replace(/0{1,4}$/, '');
256
+ return `$${micro / MICRO_USD_PER_USD}.${fraction}`;
257
+ }
258
+
259
+ /**
260
+ * Parse NANSEN_X402_SESSION_MAX_AMOUNT as a cap in micro-USD.
261
+ * Returns null when the cap is disabled (unset, empty or "unlimited"), or
262
+ * { error } for a value that isn't a plain non-negative decimal: a safety cap
263
+ * the user asked for must not silently turn off because of a typo.
264
+ */
265
+ export function resolveSessionMaxMicroUsd() {
266
+ const env = process.env.NANSEN_X402_SESSION_MAX_AMOUNT;
267
+ if (env === undefined || env.trim() === '') return null;
268
+ const value = env.trim();
269
+ if (value.toLowerCase() === 'unlimited') return null;
270
+ // Plain decimals only: Number() would read "0x10" as $16 and "1e3" as $1000.
271
+ if (!USD_AMOUNT.test(value)) {
272
+ return {
273
+ error:
274
+ `Refusing to auto-pay: NANSEN_X402_SESSION_MAX_AMOUNT="${env}" is not a valid USD amount. ` +
275
+ 'Set it to a number such as 5.00, or unset it to disable the session cap. No signature was produced.',
276
+ };
277
+ }
278
+ const [whole, fraction = ''] = value.split('.');
279
+ // Digits past the sixth decimal are dropped, which can only lower the cap.
280
+ return BigInt(whole) * MICRO_USD_PER_USD + BigInt(fraction.slice(0, 6).padEnd(6, '0'));
281
+ }
282
+
283
+ function sessionMaxMicroUsd() {
284
+ if (sessionCap === undefined) sessionCap = resolveSessionMaxMicroUsd();
285
+ return sessionCap;
286
+ }
287
+
288
+ /**
289
+ * The refusal reason when NANSEN_X402_SESSION_MAX_AMOUNT is invalid, else
290
+ * null. Check it once before any payment work, so the error is reported once
291
+ * and before any balance or blockhash request.
292
+ */
293
+ export function sessionCapConfigError() {
294
+ const cap = sessionMaxMicroUsd();
295
+ return cap !== null && typeof cap === 'object' ? cap.error : null;
296
+ }
297
+
298
+ /**
299
+ * Charge an approved payment against the per-process cumulative cap.
300
+ * Prefer signWithSessionCharge, which also runs the signer and releases the
301
+ * charge when signing fails.
302
+ *
303
+ * `decision` is the { ok: true } result of evaluatePaymentRequirement.
304
+ * Returns { ok: true, release } and adds the amount to the session total, or
305
+ * { ok: false, reason } and leaves the total unchanged.
306
+ */
307
+ export function chargeSessionSpend(decision) {
308
+ const cap = sessionMaxMicroUsd();
309
+ if (cap === null) return { ok: true, release: () => {} };
310
+ if (typeof cap === 'object') return { ok: false, reason: cap.error };
311
+
312
+ if (typeof decision.amountMicroUsd !== 'string' || !/^\d+$/.test(decision.amountMicroUsd)) {
313
+ return { ok: false, reason: 'Refusing to auto-pay: payment amount is unknown, so the session cap cannot be applied. No signature was produced.' };
314
+ }
315
+
316
+ const micro = BigInt(decision.amountMicroUsd);
317
+ const total = sessionSpentMicroUsd + micro;
318
+ if (total > cap) {
319
+ return {
320
+ ok: false,
321
+ reason:
322
+ `Refusing to auto-pay ${formatMicroUsd(micro)} ${decision.symbol}: this process has already auto-paid ` +
323
+ `${formatMicroUsd(sessionSpentMicroUsd)}, and the payment would exceed the ${formatMicroUsd(cap)} ` +
324
+ 'session cap. To authorize, raise it with NANSEN_X402_SESSION_MAX_AMOUNT=<usd> (or unset it to disable). ' +
325
+ 'No signature was produced.',
326
+ };
327
+ }
328
+ sessionSpentMicroUsd = total;
329
+ let released = false;
330
+ const release = () => {
331
+ if (released) return;
332
+ released = true;
333
+ sessionSpentMicroUsd -= micro;
334
+ };
335
+ return { ok: true, release };
336
+ }
337
+
338
+ /**
339
+ * Charge the session cap for an approved payment, then run `sign`. The signer
340
+ * starts in the same tick as the charge, so concurrent requests in one process
341
+ * can't both pass the check. Call it after every async check that could still
342
+ * skip the option.
343
+ *
344
+ * Returns { ok: false, reason } when the cap refuses, without calling `sign`,
345
+ * or { ok: true, value, release }. The charge is released if `sign` throws.
346
+ * The caller calls release() if the server cleanly rejects the payment; any
347
+ * other outcome keeps the charge, so the cap can only over-count.
348
+ */
349
+ export async function signWithSessionCharge(decision, sign) {
350
+ const charge = chargeSessionSpend(decision);
351
+ if (!charge.ok) return charge;
352
+ try {
353
+ return { ok: true, value: await sign(), release: charge.release };
354
+ } catch (err) {
355
+ charge.release();
356
+ throw err;
357
+ }
358
+ }
359
+
360
+ export function resetSessionSpendForTests() {
361
+ sessionSpentMicroUsd = 0n;
362
+ sessionCap = undefined;
216
363
  }
package/src/x402.js CHANGED
@@ -12,8 +12,9 @@ import {
12
12
  getSolanaRpcUrl,
13
13
  } from './x402-svm.js';
14
14
  import { resolvePassword } from './keychain.js';
15
- import { CHAIN_RPCS } from './rpc-urls.js';
16
- import { evaluatePaymentRequirement, resolvePaymentAmount } from './x402-policy.js';
15
+ import { EVM_X402_RPCS, hasSufficientEvmPaymentBalance, hasSufficientSvmPaymentBalance } from './x402-payment-balance.js';
16
+ export { EVM_X402_RPCS } from './x402-payment-balance.js';
17
+ import { evaluatePaymentRequirement, resolvePaymentAmount, signWithSessionCharge } from './x402-policy.js';
17
18
  import { EVM_X402_TOKENS } from './x402-tokens.js';
18
19
  export { EVM_X402_TOKENS } from './x402-tokens.js';
19
20
 
@@ -59,7 +60,7 @@ export function parsePaymentRequirements(response) {
59
60
  * Ties keep the previous behaviour — EVM before Solana, then the server's own
60
61
  * order — so a response whose options cost the same is unaffected.
61
62
  */
62
- function rankRequirements(requirements) {
63
+ export function rankRequirements(requirements) {
63
64
  return requirements
64
65
  .filter(r => isEvmNetwork(r.network) || isSvmNetwork(r.network))
65
66
  .map((requirement, index) => {
@@ -111,15 +112,40 @@ async function hasPermit2Allowance(network, token, owner, amount) {
111
112
 
112
113
  /**
113
114
  * Build a payment signature for a single requirement.
114
- * @returns {string|null} Base64 payment signature, or null on failure
115
+ * @returns {Promise<{ signature: string, payment: object, releaseCharge: Function }|null>}
116
+ * Base64 payment signature, the policy decision that approved it and the
117
+ * release for its session-cap charge, or null on failure
115
118
  */
116
- async function buildPaymentForRequirement(requirement, exported, url) {
119
+ async function buildPaymentForRequirement(requirement, exported, url, onCapRefusal) {
117
120
  const decision = evaluatePaymentRequirement(requirement);
118
121
  if (!decision.ok) {
119
122
  console.error(`[x402] ${decision.reason}`);
120
123
  return null;
121
124
  }
125
+ const signed = await signApprovedRequirement(requirement, exported, url, decision, onCapRefusal);
126
+ return signed ? { signature: signed.value, payment: decision, releaseCharge: signed.release } : null;
127
+ }
128
+
129
+ /**
130
+ * Charge the session cap and run the local signer. Called right before
131
+ * signing, after every async check that could still skip the option.
132
+ */
133
+ async function chargeAndSign(decision, onCapRefusal, sign) {
134
+ const signed = await signWithSessionCharge(decision, sign);
135
+ if (!signed.ok) {
136
+ console.error(`[x402] ${signed.reason}`);
137
+ onCapRefusal?.(signed.reason);
138
+ return null;
139
+ }
140
+ return signed;
141
+ }
122
142
 
143
+ /**
144
+ * Sign a requirement the policy guard already approved.
145
+ * @returns {Promise<{ value: string, release: Function }|null>} Base64 payment
146
+ * signature and its session-cap release, or null when skipped
147
+ */
148
+ async function signApprovedRequirement(requirement, exported, url, decision, onCapRefusal) {
123
149
  // exportWallet returns a null key for a chain the wallet file doesn't hold.
124
150
  // Skip that option with a clear reason instead of failing on the missing key.
125
151
  const rail = isEvmNetwork(requirement.network) ? 'evm' : 'solana';
@@ -133,6 +159,7 @@ async function buildPaymentForRequirement(requirement, exported, url) {
133
159
  }
134
160
 
135
161
  if (isEvmNetwork(requirement.network)) {
162
+ if (!await hasSufficientEvmPaymentBalance(requirement, exported.evm.address)) return null;
136
163
  if ((requirement.extra || {}).assetTransferMethod === 'permit2-exact') {
137
164
  const resolvedAmount = resolvePaymentAmount(requirement);
138
165
  const approved = await hasPermit2Allowance(
@@ -151,24 +178,25 @@ async function buildPaymentForRequirement(requirement, exported, url) {
151
178
  return null;
152
179
  }
153
180
  }
154
- return createEvmPaymentPayload(
181
+ return chargeAndSign(decision, onCapRefusal, () => createEvmPaymentPayload(
155
182
  requirement,
156
183
  exported.evm.privateKey,
157
184
  exported.evm.address,
158
185
  url,
159
- );
186
+ ));
160
187
  }
161
188
 
162
189
  if (isSvmNetwork(requirement.network)) {
190
+ if (!await hasSufficientSvmPaymentBalance(requirement, exported.solana.address)) return null;
163
191
  const rpcUrl = getSolanaRpcUrl(requirement.network);
164
192
  const blockhash = await fetchRecentBlockhash(rpcUrl);
165
- return createSvmPaymentPayload(
193
+ return chargeAndSign(decision, onCapRefusal, () => createSvmPaymentPayload(
166
194
  requirement,
167
195
  exported.solana.privateKey,
168
196
  exported.solana.address,
169
197
  url,
170
198
  blockhash,
171
- );
199
+ ));
172
200
  }
173
201
 
174
202
  return null;
@@ -176,12 +204,16 @@ async function buildPaymentForRequirement(requirement, exported, url) {
176
204
 
177
205
  /**
178
206
  * Generate payment signatures for all viable payment options, in priority order.
179
- * Yields { signature, network } objects. Caller should try each until one succeeds.
207
+ * Yields { signature, network, asset, payment, releaseCharge } objects, where
208
+ * payment is the policy decision that approved the option and releaseCharge
209
+ * returns its session-cap charge (call it when the server cleanly rejects the
210
+ * payment). Caller should try each until one succeeds.
180
211
  *
181
212
  * @param {Response} response - The 402 HTTP response
182
213
  * @param {string} url - The original request URL
183
- * @param {object} options - { password, walletName }
184
- * @returns {AsyncGenerator<{ signature: string, network: string }>}
214
+ * @param {object} options - { password, walletName, onCapRefusal }, where
215
+ * onCapRefusal(reason) is called when the session cap refuses an option
216
+ * @returns {AsyncGenerator<{ signature: string, network: string, asset: string, payment: object, releaseCharge: Function }>}
185
217
  */
186
218
  export async function* createPaymentSignatures(response, url, options = {}) {
187
219
  const requirements = parsePaymentRequirements(response);
@@ -221,8 +253,10 @@ export async function* createPaymentSignatures(response, url, options = {}) {
221
253
 
222
254
  for (const req of ranked) {
223
255
  try {
224
- const sig = await buildPaymentForRequirement(req, exported, url);
225
- if (sig) yield { signature: sig, network: req.network, asset: req.asset };
256
+ const built = await buildPaymentForRequirement(req, exported, url, options.onCapRefusal);
257
+ if (built) {
258
+ yield { signature: built.signature, network: req.network, asset: req.asset, payment: built.payment, releaseCharge: built.releaseCharge };
259
+ }
226
260
  } catch (err) {
227
261
  // This payment option failed to build; say why and try the next one
228
262
  // (otherwise a malformed server option only surfaces as a generic
@@ -235,7 +269,9 @@ export async function* createPaymentSignatures(response, url, options = {}) {
235
269
 
236
270
  /**
237
271
  * Attempt to auto-pay a 402 response (single-shot, returns first viable signature).
238
- * For fallback support, use createPaymentSignatures() instead.
272
+ * For fallback support, use createPaymentSignatures() instead. The signature's
273
+ * session-cap charge is never released, so a payment the server rejects still
274
+ * counts against the cap.
239
275
  *
240
276
  * @param {Response} response - The 402 HTTP response
241
277
  * @param {string} url - The original request URL
@@ -249,13 +285,6 @@ export async function createPaymentSignature(response, url, options = {}) {
249
285
  return null;
250
286
  }
251
287
 
252
- // RPC endpoint per supported x402 EVM network.
253
- export const EVM_X402_RPCS = {
254
- 'eip155:8453': CHAIN_RPCS.base,
255
- 'eip155:196': CHAIN_RPCS.xlayer,
256
- 'eip155:56': CHAIN_RPCS.bsc,
257
- };
258
-
259
288
  function getEvmRpcUrl(network) {
260
289
  return EVM_X402_RPCS[network] || null;
261
290
  }