nansen-cli 1.46.0 → 2.0.1
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/CHANGELOG.md +122 -0
- package/README.md +157 -14
- package/docs/browser-login.md +123 -0
- package/package.json +11 -2
- package/scripts/postinstall.js +35 -30
- package/skills/nansen-agent-guide/SKILL.md +13 -2
- package/skills/nansen-alerts-webhook-listener/SKILL.md +5 -2
- package/skills/nansen-dca-tracker/SKILL.md +10 -2
- package/skills/nansen-defi-positions/SKILL.md +5 -2
- package/skills/nansen-exit-signals/SKILL.md +10 -2
- package/skills/nansen-fund-tracker/SKILL.md +10 -2
- package/skills/nansen-general-search/SKILL.md +10 -2
- package/skills/nansen-holder-analysis/SKILL.md +10 -2
- package/skills/nansen-limit-orders/SKILL.md +6 -3
- package/skills/nansen-perp-screener/SKILL.md +10 -2
- package/skills/nansen-perp-trader-profile/SKILL.md +10 -2
- package/skills/nansen-polymarket-deep-dive/SKILL.md +10 -2
- package/skills/nansen-polymarket-insider-scan/SKILL.md +10 -2
- package/skills/nansen-polymarket-trader-profile/SKILL.md +10 -2
- package/skills/nansen-portfolio-tracker/SKILL.md +10 -2
- package/skills/nansen-prediction-markets/SKILL.md +10 -2
- package/skills/nansen-sm-cross-chain-flows/SKILL.md +10 -2
- package/skills/nansen-smart-alerts/SKILL.md +9 -4
- package/skills/nansen-smart-money-alpha/SKILL.md +10 -2
- package/skills/nansen-smart-money-tracker/SKILL.md +10 -2
- package/skills/nansen-smart-money-trend/SKILL.md +10 -2
- package/skills/nansen-token-research/SKILL.md +10 -2
- package/skills/nansen-token-screener/SKILL.md +14 -4
- package/skills/nansen-token-transfer-analysis/SKILL.md +10 -2
- package/skills/nansen-trading/SKILL.md +8 -2
- package/skills/nansen-wallet-batch/SKILL.md +10 -2
- package/skills/nansen-wallet-clustering/SKILL.md +10 -2
- package/skills/nansen-wallet-deep-dive/SKILL.md +10 -2
- package/skills/nansen-wallet-keychain-migration/SKILL.md +5 -2
- package/skills/nansen-wallet-manager/SKILL.md +11 -9
- package/skills/nansen-wallet-profiler/SKILL.md +10 -2
- package/skills/nansen-web-fetcher/SKILL.md +5 -2
- package/skills/nansen-web-searcher/SKILL.md +5 -2
- package/src/api.js +202 -104
- package/src/auth-browser.js +16 -0
- package/src/auth-credentials.js +73 -0
- package/src/auth-device.js +242 -0
- package/src/auth-key-input.js +46 -0
- package/src/auth-login.js +89 -0
- package/src/auth-state.js +487 -0
- package/src/auth-store-native.js +20 -0
- package/src/auth-store-worker.js +64 -0
- package/src/auth-store.js +140 -0
- package/src/auto-paginate.js +288 -0
- package/src/bridge.js +126 -21
- package/src/cache-inspect.js +345 -0
- package/src/cli.js +473 -199
- package/src/commands/agent.js +15 -7
- package/src/commands/completion.js +2 -15
- package/src/commands/mcp.js +20 -18
- package/src/cost-cache.js +16 -2
- package/src/debug.js +348 -0
- package/src/doctor.js +22 -45
- package/src/hl-action.js +41 -13
- package/src/limit-order.js +1 -1
- package/src/mcp-client-config.js +169 -0
- package/src/mcp-client-config.json +17 -0
- package/src/mcp-verify.js +6 -5
- package/src/perp.js +41 -0
- package/src/privy.js +12 -12
- package/src/response-meta.js +56 -1
- package/src/rpc-urls.js +9 -11
- package/src/schema.json +185 -8
- package/src/semver.js +23 -4
- package/src/swap-simulation.js +35 -30
- package/src/telemetry.js +20 -0
- package/src/trading.js +266 -29
- package/src/transfer.js +53 -6
- package/src/update-check.js +9 -1
- package/src/wallet.js +107 -17
- package/src/walletconnect-trading.js +24 -5
- package/src/x402-svm.js +123 -64
- package/src/x402.js +46 -14
package/src/response-meta.js
CHANGED
|
@@ -93,6 +93,57 @@ export function readResponseMeta(response) {
|
|
|
93
93
|
return Object.keys(meta).length > 0 ? meta : null;
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
+
/**
|
|
97
|
+
* Combine response metadata from the individual requests in one paginated CLI
|
|
98
|
+
* command. Credit usage/cost is additive, while balance, rate-limit state, and
|
|
99
|
+
* request id keep their normal "freshest response" meaning. Cached pages cost
|
|
100
|
+
* nothing and do not replace the freshest live server metadata.
|
|
101
|
+
*/
|
|
102
|
+
export function aggregatePaginatedResponseMeta(pages) {
|
|
103
|
+
if (!Array.isArray(pages) || pages.length === 0) return null;
|
|
104
|
+
|
|
105
|
+
const livePages = pages.filter(page => !page.cached);
|
|
106
|
+
const metas = livePages.map(page => page.meta);
|
|
107
|
+
const present = metas.filter(Boolean);
|
|
108
|
+
if (livePages.length === 0) {
|
|
109
|
+
return {
|
|
110
|
+
credits: { used: 0, remaining: null, cost: 0 },
|
|
111
|
+
pagination: { pagesFetched: pages.length, livePages: 0, cachedPages: pages.length },
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const latest = present.at(-1) || null;
|
|
116
|
+
const result = latest ? { ...latest } : {};
|
|
117
|
+
|
|
118
|
+
const sumKnown = (key) => {
|
|
119
|
+
// This all-pages guard makes the unchecked access in reduce safe: it only
|
|
120
|
+
// runs when every page has credits[key] and that value is a safe integer.
|
|
121
|
+
if (metas.some(meta => !Number.isSafeInteger(meta?.credits?.[key]))) return null;
|
|
122
|
+
return metas.reduce((sum, meta) => sum + meta.credits[key], 0);
|
|
123
|
+
};
|
|
124
|
+
const used = sumKnown('used');
|
|
125
|
+
const cost = sumKnown('cost');
|
|
126
|
+
const latestCredits = [...present].reverse().find(meta => meta.credits)?.credits;
|
|
127
|
+
if (used !== null || cost !== null || latestCredits) {
|
|
128
|
+
result.credits = {
|
|
129
|
+
used,
|
|
130
|
+
remaining: latestCredits?.remaining ?? null,
|
|
131
|
+
cost,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const notices = {};
|
|
136
|
+
for (const meta of present) Object.assign(notices, meta.notices || {});
|
|
137
|
+
if (Object.keys(notices).length > 0) result.notices = notices;
|
|
138
|
+
|
|
139
|
+
result.pagination = {
|
|
140
|
+
pagesFetched: pages.length,
|
|
141
|
+
livePages: livePages.length,
|
|
142
|
+
cachedPages: pages.length - livePages.length,
|
|
143
|
+
};
|
|
144
|
+
return result;
|
|
145
|
+
}
|
|
146
|
+
|
|
96
147
|
/**
|
|
97
148
|
* Yield notice strings for any server-set advisory headers.
|
|
98
149
|
* Each yields a `⚠️ <message>` line for stderr.
|
|
@@ -123,7 +174,11 @@ export function creditWarning(meta) {
|
|
|
123
174
|
// The cost header is the authoritative charge; used is the fallback.
|
|
124
175
|
const charged = cost ?? used;
|
|
125
176
|
if (charged !== null && charged > 0 && remaining < charged) {
|
|
126
|
-
|
|
177
|
+
const livePages = meta?.pagination?.livePages;
|
|
178
|
+
const costScope = livePages > 1
|
|
179
|
+
? `the aggregate cost of ${livePages} live page requests`
|
|
180
|
+
: 'this call cost';
|
|
181
|
+
return `⚠️ ${remaining} API credit${remaining === 1 ? '' : 's'} left — less than ${costScope} (${charged}). Top up at https://app.nansen.ai/api?tab=api`;
|
|
127
182
|
}
|
|
128
183
|
return null;
|
|
129
184
|
}
|
package/src/rpc-urls.js
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* (nonce, balance, allowance, eth_call revert check) stay on the cheap default.
|
|
24
24
|
*
|
|
25
25
|
* The shipped simulation endpoint is a Nansen-hosted service authenticated with
|
|
26
|
-
* the user's
|
|
26
|
+
* the user's selected Nansen API credential (no secret in this public package): the
|
|
27
27
|
* trace-capable upstream is reached server-side, so the baked default carries no
|
|
28
28
|
* credential. With no NANSEN_BASE_SIM_RPC override, swap-outcome verification
|
|
29
29
|
* uses this default; if the service is ever unreachable it degrades with a
|
|
@@ -60,7 +60,7 @@ export const CHAIN_RPCS = {
|
|
|
60
60
|
};
|
|
61
61
|
|
|
62
62
|
// Zero-config default for the shipped Nansen-hosted simulation endpoint. It
|
|
63
|
-
// authenticates with the user's
|
|
63
|
+
// authenticates with the user's selected Nansen API credential (attached automatically
|
|
64
64
|
// by swap-simulation.js), and the trace-capable upstream is reached server-side —
|
|
65
65
|
// so this URL carries no secret and is safe to bake into a public package. Never
|
|
66
66
|
// embed an RPC URL that carries an inline token here; any embedded secret would
|
|
@@ -89,12 +89,10 @@ export const SIMULATION_RPCS = {
|
|
|
89
89
|
solana: process.env.NANSEN_SOLANA_SIM_RPC || CHAIN_RPCS.solana,
|
|
90
90
|
};
|
|
91
91
|
|
|
92
|
-
//
|
|
93
|
-
//
|
|
94
|
-
//
|
|
95
|
-
|
|
96
|
-
// here deliberately if one is ever introduced.
|
|
97
|
-
const NANSEN_HOSTED_SIM_HOSTS = new Set(['api.nansen.ai']);
|
|
92
|
+
// Explicit API origins that may receive simulation credentials. No wildcard,
|
|
93
|
+
// userinfo or alternate port is trusted. Browser sessions additionally require
|
|
94
|
+
// an exact match with their selected API audience in swap-simulation.js.
|
|
95
|
+
const NANSEN_HOSTED_SIM_ORIGINS = new Set(['https://api.nansen.ai', 'https://api.banansen.dev']);
|
|
98
96
|
|
|
99
97
|
/**
|
|
100
98
|
* Whether a simulation URL is a Nansen-hosted endpoint that may receive the
|
|
@@ -104,14 +102,14 @@ const NANSEN_HOSTED_SIM_HOSTS = new Set(['api.nansen.ai']);
|
|
|
104
102
|
* leak it. So the key is attached ONLY when this returns true — every other
|
|
105
103
|
* endpoint is called anonymously.
|
|
106
104
|
*
|
|
107
|
-
* Trust is:
|
|
105
|
+
* Trust is: exact origin is one of NANSEN_HOSTED_SIM_ORIGINS. Anything else
|
|
108
106
|
* (http, other host, unparseable) is untrusted and gets no key.
|
|
109
107
|
*/
|
|
110
108
|
export function isNansenHostedUrl(url) {
|
|
111
109
|
try {
|
|
112
110
|
const u = new URL(url);
|
|
113
|
-
if (u.
|
|
114
|
-
return
|
|
111
|
+
if (u.username || u.password) return false;
|
|
112
|
+
return NANSEN_HOSTED_SIM_ORIGINS.has(u.origin);
|
|
115
113
|
} catch {
|
|
116
114
|
return false;
|
|
117
115
|
}
|
package/src/schema.json
CHANGED
|
@@ -268,7 +268,7 @@
|
|
|
268
268
|
},
|
|
269
269
|
"bridge": {
|
|
270
270
|
"description": "Move funds between Base and Hyperliquid",
|
|
271
|
-
"notes": "Supported routes: base -> hyperliquid (deposit); hyperliquid -> base, hyperliquid -> ethereum, hyperliquid -> arbitrum (withdrawal). Any other combination is rejected. Deposits broadcast an EVM transaction from the local wallet, so they require a locally signable origin chain; withdrawals sign a Hyperliquid action and never transact on the destination chain.",
|
|
271
|
+
"notes": "Supported routes: base -> hyperliquid (deposit); hyperliquid -> base, hyperliquid -> ethereum, hyperliquid -> arbitrum (withdrawal). Any other combination is rejected. base -> hyperliquid deposits currently support USDC only — a non-USDC --from-token is rejected with INVALID_INPUT before the quote is created. Deposits broadcast an EVM transaction from the local wallet, so they require a locally signable origin chain; withdrawals sign a Hyperliquid action and never transact on the destination chain.",
|
|
272
272
|
"routes": [
|
|
273
273
|
{
|
|
274
274
|
"origin": "base",
|
|
@@ -319,7 +319,7 @@
|
|
|
319
319
|
"from-token": {
|
|
320
320
|
"type": "string",
|
|
321
321
|
"required": true,
|
|
322
|
-
"description": "Source token symbol
|
|
322
|
+
"description": "Source token symbol or address (alias: --token). Base -> Hyperliquid deposits require USDC; a non-USDC token is rejected before the quote is created."
|
|
323
323
|
},
|
|
324
324
|
"to-token": {
|
|
325
325
|
"type": "string",
|
|
@@ -384,6 +384,10 @@
|
|
|
384
384
|
"type": "string",
|
|
385
385
|
"description": "Fee cap in gwei, overriding the computed one (EVM deposit legs only)"
|
|
386
386
|
},
|
|
387
|
+
"max-tx-fee": {
|
|
388
|
+
"type": "string",
|
|
389
|
+
"description": "Most one EVM transaction may pay for gas (fee cap x gas limit), in ETH. Default 1; 0 disables the check."
|
|
390
|
+
},
|
|
387
391
|
"nonce": {
|
|
388
392
|
"type": "string",
|
|
389
393
|
"description": "Sign at this nonce instead of the next one, to replace a stuck transaction (EVM deposit legs only)"
|
|
@@ -423,7 +427,7 @@
|
|
|
423
427
|
}
|
|
424
428
|
},
|
|
425
429
|
"research": {
|
|
426
|
-
"description": "Research and analytics commands. Explicitly blank chain, timeframe, and days options are rejected instead of selecting defaults. Profiler batch rejects blank --delay; trace rejects blank --delay, --depth, and --width.",
|
|
430
|
+
"description": "Research and analytics commands. Explicitly blank chain, timeframe, and days options are rejected instead of selecting defaults. Profiler batch rejects blank --delay; trace rejects blank --delay, --depth, and --width. Browser nansen:api sessions use the same account API permissions and endpoint checks as API keys.",
|
|
427
431
|
"subcommands": {
|
|
428
432
|
"portfolio": {
|
|
429
433
|
"subcommands": {
|
|
@@ -801,9 +805,8 @@
|
|
|
801
805
|
},
|
|
802
806
|
"width": {
|
|
803
807
|
"type": "integer",
|
|
804
|
-
"minimum": 0,
|
|
805
808
|
"default": 10,
|
|
806
|
-
"description": "Counterparties to follow at each hop"
|
|
809
|
+
"description": "Counterparties to follow at each hop (1-50); valid integers outside the range are clamped. Traversal stops expanding after 1000 nodes and reports stats.truncated"
|
|
807
810
|
},
|
|
808
811
|
"days": {
|
|
809
812
|
"type": "integer",
|
|
@@ -1153,6 +1156,10 @@
|
|
|
1153
1156
|
"include-stablecoins": {
|
|
1154
1157
|
"description": "Whether to include stablecoins in screener results (default true on API side)",
|
|
1155
1158
|
"default": true
|
|
1159
|
+
},
|
|
1160
|
+
"search": {
|
|
1161
|
+
"type": "string",
|
|
1162
|
+
"description": "Filter screener candidates client-side by token name, symbol, or exact address. Only the fetched candidate rows are searched (the first 500 by default, more with --limit/--page, every traversed page with --paginate/--all), so the response adds _meta.search: { query, searched, matched, complete }. complete: false means the API had more rows beyond that window and a missing token may simply rank below it; widen with --limit (max 1000) or --paginate, or narrow with --filters. A stderr note repeats this for --fields/--table/--csv/--stream output. With --paginate/--all, the fully traversed candidate pool is filtered after traversal; pagination metadata describes the upstream candidate-page traversal, not the number of matches after filtering."
|
|
1156
1163
|
}
|
|
1157
1164
|
}
|
|
1158
1165
|
},
|
|
@@ -2147,6 +2154,10 @@
|
|
|
2147
2154
|
"type": "boolean",
|
|
2148
2155
|
"description": "Skip swap-outcome verification. That check simulates the swap and confirms the wallet's balance changes match the quote (input spent within your max, expected output received, no other asset moved) before broadcasting; it needs a simulation-capable endpoint (NANSEN_BASE_SIM_RPC on EVM, NANSEN_SOLANA_SIM_RPC on Solana) and degrades with a warning when none is available."
|
|
2149
2156
|
},
|
|
2157
|
+
"max-tx-fee": {
|
|
2158
|
+
"type": "string",
|
|
2159
|
+
"description": "Most one EVM transaction may pay for gas (fee cap x gas limit), in ETH. A quote above it is refused before anything is signed, approvals included. Default 1; 0 disables the check. Not applied to WalletConnect, where the wallet shows the fee."
|
|
2160
|
+
},
|
|
2150
2161
|
"no-revoke-excessive-allowance": {
|
|
2151
2162
|
"type": "boolean",
|
|
2152
2163
|
"description": "Skip revoking an existing on-chain ERC-20 allowance before re-approving when it exceeds 10x this trade's scoped amount. By default, an oversized or legacy allowance is revoked to zero and a fresh trade-scoped allowance is granted. WalletConnect users will see separate wallet prompts for the revoke and re-approval."
|
|
@@ -2443,15 +2454,24 @@
|
|
|
2443
2454
|
},
|
|
2444
2455
|
"account": {
|
|
2445
2456
|
"endpoint": "/api/v1/account",
|
|
2446
|
-
"description": "
|
|
2457
|
+
"description": "Check the effective credential, plan, and remaining credits live. Free, including for a valid zero-credit account. NANSEN_API_KEY overrides saved authentication."
|
|
2447
2458
|
},
|
|
2448
2459
|
"auth": {
|
|
2449
|
-
"description": "Offline authentication status. Reports
|
|
2460
|
+
"description": "Offline authentication status. Reports effective credential source, cached/unverified browser session metadata, API key presence, base URL, and x402 wallet readiness without any network call. Consumes no credits.",
|
|
2450
2461
|
"subcommands": {
|
|
2451
2462
|
"status": {
|
|
2452
2463
|
"description": "Show where credentials come from, entirely offline",
|
|
2453
2464
|
"returns": [
|
|
2454
2465
|
"logged_in",
|
|
2466
|
+
"effective_credential.kind",
|
|
2467
|
+
"effective_credential.source",
|
|
2468
|
+
"effective_credential.validity",
|
|
2469
|
+
"saved_session.account_id",
|
|
2470
|
+
"saved_session.expires_at",
|
|
2471
|
+
"saved_session.expired",
|
|
2472
|
+
"saved_session.validity",
|
|
2473
|
+
"saved_session.storage_access",
|
|
2474
|
+
"saved_session.renewal_state",
|
|
2455
2475
|
"api_key.present",
|
|
2456
2476
|
"api_key.source",
|
|
2457
2477
|
"api_key.masked",
|
|
@@ -2602,7 +2622,7 @@
|
|
|
2602
2622
|
]
|
|
2603
2623
|
},
|
|
2604
2624
|
"install": {
|
|
2605
|
-
"description": "Add the Nansen MCP server to a client's config. Client (positional): claude-code, claude-desktop, or cursor. Uses the API key from `nansen login` / NANSEN_API_KEY; re-run after key rotation to update the entry.",
|
|
2625
|
+
"description": "Add the Nansen MCP server to a client's config. Client (positional): claude-code, claude-desktop, or cursor. Uses the API key from `nansen login --human` / NANSEN_API_KEY; re-run after key rotation to update the entry.",
|
|
2606
2626
|
"args": [
|
|
2607
2627
|
{
|
|
2608
2628
|
"name": "client",
|
|
@@ -2668,6 +2688,95 @@
|
|
|
2668
2688
|
]
|
|
2669
2689
|
}
|
|
2670
2690
|
}
|
|
2691
|
+
},
|
|
2692
|
+
"login": {
|
|
2693
|
+
"description": "Fresh browser approval in every starting state for API-key-equivalent account API permissions (nansen:api). Wallet signing and MCP key export remain separate. Plain login never persists NANSEN_API_KEY; it still overrides commands. Selected sessions renew automatically; uncertain renewal requires fresh login. Browser login is enabled in production; saved sessions need native storage (see docs/browser-login.md).",
|
|
2694
|
+
"options": {
|
|
2695
|
+
"no-browser": {
|
|
2696
|
+
"type": "boolean",
|
|
2697
|
+
"description": "Print the approval URL/code without opening a browser"
|
|
2698
|
+
},
|
|
2699
|
+
"json": {
|
|
2700
|
+
"type": "boolean",
|
|
2701
|
+
"description": "Browser login: NDJSON pending and one terminal event with an interactive terminal; non-TTY exits with a JSON error envelope whose code is NOT_A_TTY. With --api-key-stdin: one saved event with effective_source, environment_key_blank and cleanup."
|
|
2702
|
+
},
|
|
2703
|
+
"human": {
|
|
2704
|
+
"type": "boolean",
|
|
2705
|
+
"description": "Legacy API-key setup: option, environment, then hidden interactive prompt"
|
|
2706
|
+
},
|
|
2707
|
+
"api-key": {
|
|
2708
|
+
"type": "string",
|
|
2709
|
+
"description": "Legacy API key to verify and save; recorded in shell history"
|
|
2710
|
+
},
|
|
2711
|
+
"api-key-stdin": {
|
|
2712
|
+
"type": "boolean",
|
|
2713
|
+
"description": "Read a single API key from a pipe or redirected file (maximum 4096 bytes; input must close within 30 seconds), verify and save it without echoing it. Requires the native lock binding. Cannot combine with --api-key, --human or --no-browser. NANSEN_API_KEY still overrides saved credentials for subsequent commands."
|
|
2714
|
+
}
|
|
2715
|
+
},
|
|
2716
|
+
"returns": {
|
|
2717
|
+
"description": "Operational command. Machine events: pending {verification_uri,user_code,expires_at}; saved {account_id,effective_source,cleanup}; error/cancelled {code,message,cleanup}. Never includes device_code or tokens. Cleanup preserves malformed journals and reports AUTH_JOURNAL_INVALID; unrecognized JSON files remain untouched."
|
|
2718
|
+
}
|
|
2719
|
+
},
|
|
2720
|
+
"logout": {
|
|
2721
|
+
"description": "Clear saved API authentication and attempt browser-family retirement. Preserve wallets and environment keys. Report incomplete local deletion or remote revocation separately. Preserve damaged recovery journals and report auth-operations repair guidance."
|
|
2722
|
+
},
|
|
2723
|
+
"cache": {
|
|
2724
|
+
"description": "Inspect and clear the caches the CLI keeps under ~/.nansen. Reads and deletes local files only: no network call, no credits, and credentials, wallets, saved quotes and config are never changed. CLI startup loads the saved config as usual.",
|
|
2725
|
+
"subcommands": {
|
|
2726
|
+
"stats": {
|
|
2727
|
+
"description": "Report what each cache holds: entry count, bytes on disk, age of the oldest and newest entry, the effective TTL, and how many entries are already expired. Aggregates only — no cached payload, request parameter or cache key is printed.",
|
|
2728
|
+
"options": {
|
|
2729
|
+
"json": {
|
|
2730
|
+
"type": "boolean",
|
|
2731
|
+
"description": "Return the stats as a JSON object instead of a text report"
|
|
2732
|
+
},
|
|
2733
|
+
"cache-ttl": {
|
|
2734
|
+
"type": "integer",
|
|
2735
|
+
"minimum": 0,
|
|
2736
|
+
"maximum": 9007199254740991,
|
|
2737
|
+
"default": 300,
|
|
2738
|
+
"description": "TTL to evaluate the response cache against, matching the TTL a request would use"
|
|
2739
|
+
}
|
|
2740
|
+
},
|
|
2741
|
+
"returns": [
|
|
2742
|
+
"config_dir",
|
|
2743
|
+
"caches[].name",
|
|
2744
|
+
"caches[].description",
|
|
2745
|
+
"caches[].path",
|
|
2746
|
+
"caches[].entries",
|
|
2747
|
+
"caches[].bytes",
|
|
2748
|
+
"caches[].ttl_seconds",
|
|
2749
|
+
"caches[].oldest_age_seconds",
|
|
2750
|
+
"caches[].newest_age_seconds",
|
|
2751
|
+
"caches[].expired_entries",
|
|
2752
|
+
"total_entries",
|
|
2753
|
+
"total_bytes",
|
|
2754
|
+
"hit_miss_recorded"
|
|
2755
|
+
],
|
|
2756
|
+
"examples": [
|
|
2757
|
+
"nansen cache stats",
|
|
2758
|
+
"nansen cache stats --json --pretty",
|
|
2759
|
+
"nansen cache stats --cache-ttl 60"
|
|
2760
|
+
]
|
|
2761
|
+
},
|
|
2762
|
+
"clear": {
|
|
2763
|
+
"description": "Delete cached entries and print exactly what was removed. Takes an explicit target: responses (the default), cost-map, update-check, or all. An unrecognised target removes nothing.",
|
|
2764
|
+
"args": [
|
|
2765
|
+
{
|
|
2766
|
+
"name": "target",
|
|
2767
|
+
"type": "string",
|
|
2768
|
+
"default": "responses",
|
|
2769
|
+
"enum": ["responses", "cost-map", "update-check", "all"],
|
|
2770
|
+
"description": "Which cache to delete"
|
|
2771
|
+
}
|
|
2772
|
+
],
|
|
2773
|
+
"examples": [
|
|
2774
|
+
"nansen cache clear",
|
|
2775
|
+
"nansen cache clear cost-map",
|
|
2776
|
+
"nansen cache clear all"
|
|
2777
|
+
]
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2671
2780
|
}
|
|
2672
2781
|
},
|
|
2673
2782
|
"globalOptions": {
|
|
@@ -2692,6 +2801,17 @@
|
|
|
2692
2801
|
"default": 1,
|
|
2693
2802
|
"description": "1-based page number for list-returning research commands; maps to pagination.page. Supported by smart-money, profiler, token, perp, points, prediction-market, and supported research historical-* commands. Trade, wallet, and operational commands ignore it; token ohlcv, profiler perp-positions, and historical-token-flow-summary do not support pagination. profiler labels defaults to page 1 when omitted."
|
|
2694
2803
|
},
|
|
2804
|
+
"paginate": {
|
|
2805
|
+
"type": "boolean",
|
|
2806
|
+
"description": "Fetch every page of a list-returning command and return one merged response (alias: --all). Starts at --page (default 1) and uses --limit as the page size; stops on a short or empty page, when server pagination metadata (total_pages, total, is_last_page, has_more, or next_page) says the traversal is complete, when a page repeats rows already seen, or after --max-pages requests. Server total metadata is trusted, so a live dataset that changes or reports inconsistent totals during traversal can omit later rows. The merged response keeps the first page's shape (a bare array is wrapped as { data: [...] }) with rows de-duplicated, plus pagination: { page, pages_fetched, next_page, complete } — next_page is null when complete, otherwise the page to resume from. Each page is a separate, separately billed API call. Works with --stream (NDJSON), --table, --format csv and --fields. Commands without pagination are unaffected."
|
|
2807
|
+
},
|
|
2808
|
+
"max-pages": {
|
|
2809
|
+
"type": "integer",
|
|
2810
|
+
"minimum": 1,
|
|
2811
|
+
"maximum": 1000,
|
|
2812
|
+
"default": 10,
|
|
2813
|
+
"description": "Positive safe-integer page-request cap for --paginate/--all. It is parsed and validated only when pagination is active, and is otherwise ignored. Hitting the cap sets pagination.complete to false and pagination.next_page to the page to resume from."
|
|
2814
|
+
},
|
|
2695
2815
|
"no-retry": {
|
|
2696
2816
|
"type": "boolean",
|
|
2697
2817
|
"description": "Disable automatic retry on rate limits/errors"
|
|
@@ -2703,6 +2823,14 @@
|
|
|
2703
2823
|
"default": 3,
|
|
2704
2824
|
"description": "Max retry attempts (non-negative safe integer)"
|
|
2705
2825
|
},
|
|
2826
|
+
"cache": {
|
|
2827
|
+
"type": "boolean",
|
|
2828
|
+
"description": "Serve this invocation from the local response cache and save its result there. Off by default; see the caching section for which commands it applies to"
|
|
2829
|
+
},
|
|
2830
|
+
"no-cache": {
|
|
2831
|
+
"type": "boolean",
|
|
2832
|
+
"description": "Bypass the local response cache for this invocation even when --cache is passed. NANSEN_NO_CACHE=1 does the same without a flag"
|
|
2833
|
+
},
|
|
2706
2834
|
"cache-ttl": {
|
|
2707
2835
|
"type": "integer",
|
|
2708
2836
|
"minimum": 0,
|
|
@@ -2710,6 +2838,10 @@
|
|
|
2710
2838
|
"default": 300,
|
|
2711
2839
|
"description": "Cache TTL in seconds (non-negative safe integer; 0 disables cache reads)"
|
|
2712
2840
|
},
|
|
2841
|
+
"debug": {
|
|
2842
|
+
"type": "boolean",
|
|
2843
|
+
"description": "Trace HTTP request events on stderr: method, redacted URL, response status, time-to-response-headers (TTFB), retry decisions and request id. Also enabled by NANSEN_DEBUG=1. Response timing excludes body download/parsing. Never prints credentials or response bodies."
|
|
2844
|
+
},
|
|
2713
2845
|
"format": {
|
|
2714
2846
|
"type": "string",
|
|
2715
2847
|
"enum": [
|
|
@@ -2723,6 +2855,51 @@
|
|
|
2723
2855
|
"description": "Pre-signed x402 payment signature header"
|
|
2724
2856
|
}
|
|
2725
2857
|
},
|
|
2858
|
+
"caching": {
|
|
2859
|
+
"summary": "Response caching is off by default and opt-in per invocation with --cache. It is a property of the request path, not of individual commands: with --cache on, every read the CLI makes through the Nansen API client is served from and written to the local response cache.",
|
|
2860
|
+
"enableWith": "--cache",
|
|
2861
|
+
"disableWith": ["--no-cache", "NANSEN_NO_CACHE=1"],
|
|
2862
|
+
"ttlOption": "--cache-ttl <seconds>",
|
|
2863
|
+
"defaultTtlSeconds": 300,
|
|
2864
|
+
"cachedCommands": "All research commands (including top-level perp screener and perp leaderboard), plus alerts list and alerts get.",
|
|
2865
|
+
"neverCached": [
|
|
2866
|
+
"account",
|
|
2867
|
+
"web search",
|
|
2868
|
+
"web fetch",
|
|
2869
|
+
"alerts create",
|
|
2870
|
+
"alerts update",
|
|
2871
|
+
"alerts toggle",
|
|
2872
|
+
"alerts delete",
|
|
2873
|
+
"agent",
|
|
2874
|
+
"trade (all subcommands)",
|
|
2875
|
+
"bridge (all subcommands)",
|
|
2876
|
+
"wallet (all subcommands)",
|
|
2877
|
+
"perp trading (order, cancel, close, leverage, transfer, approve-builder-fee, positions, orders, account, meta)",
|
|
2878
|
+
"mcp (all subcommands)"
|
|
2879
|
+
],
|
|
2880
|
+
"inspect": "nansen cache stats",
|
|
2881
|
+
"clear": "nansen cache clear [responses|cost-map|update-check|all]",
|
|
2882
|
+
"caches": [
|
|
2883
|
+
{
|
|
2884
|
+
"name": "responses",
|
|
2885
|
+
"path": "~/.nansen/cache",
|
|
2886
|
+
"ttlSeconds": 300,
|
|
2887
|
+
"description": "API responses saved when --cache is passed; TTL is the effective --cache-ttl"
|
|
2888
|
+
},
|
|
2889
|
+
{
|
|
2890
|
+
"name": "cost-map",
|
|
2891
|
+
"path": "~/.nansen/cost-map.json",
|
|
2892
|
+
"ttlSeconds": 86400,
|
|
2893
|
+
"description": "Per-endpoint credit costs used to report what a call cost"
|
|
2894
|
+
},
|
|
2895
|
+
{
|
|
2896
|
+
"name": "update-check",
|
|
2897
|
+
"path": "~/.nansen/update-check.json",
|
|
2898
|
+
"ttlSeconds": 86400,
|
|
2899
|
+
"description": "Latest published CLI version, for the upgrade notice"
|
|
2900
|
+
}
|
|
2901
|
+
]
|
|
2902
|
+
},
|
|
2726
2903
|
"chains": [
|
|
2727
2904
|
"algorand",
|
|
2728
2905
|
"aptos",
|
package/src/semver.js
CHANGED
|
@@ -13,14 +13,33 @@
|
|
|
13
13
|
* correct way instead of each hand-rolling its own parser.
|
|
14
14
|
*/
|
|
15
15
|
export function compareSemver(a, b) {
|
|
16
|
+
// A prerelease or build suffix ("1.2.10-beta.1", "1.2.10+sha") used to be
|
|
17
|
+
// parsed with Number(), which turned the suffixed component into NaN and
|
|
18
|
+
// then into 0 — so "1.2.10-beta" compared below "1.2.9". Split the suffix
|
|
19
|
+
// off first and read each component as a plain integer. A prerelease ranks
|
|
20
|
+
// below the release it precedes, and build metadata is ignored entirely.
|
|
21
|
+
//
|
|
22
|
+
// Known limitation: prerelease *identity* is not compared, so two
|
|
23
|
+
// prereleases of the same core read as equal ("1.3.0-beta.1" vs
|
|
24
|
+
// "1.3.0-beta.2" is 0). No caller hits that today because every published
|
|
25
|
+
// `latest` has been a plain release — but that's a fact about what we've
|
|
26
|
+
// shipped, not a guarantee the callers make. If the `latest` dist-tag ever
|
|
27
|
+
// points at a prerelease, the update notifier and `doctor` will silently
|
|
28
|
+
// under-report. Full prerelease precedence (SemVer §11) is deliberately
|
|
29
|
+
// out of scope here.
|
|
16
30
|
const parse = v => {
|
|
17
|
-
const
|
|
18
|
-
|
|
31
|
+
const str = String(v).replace(/^v/, '');
|
|
32
|
+
const suffixAt = str.search(/[-+]/);
|
|
33
|
+
const core = suffixAt === -1 ? str : str.slice(0, suffixAt);
|
|
34
|
+
const prerelease = suffixAt !== -1 && str[suffixAt] === '-';
|
|
35
|
+
const parts = core.split('.').map(p => parseInt(p, 10));
|
|
36
|
+
return [parts[0] || 0, parts[1] || 0, parts[2] || 0, prerelease];
|
|
19
37
|
};
|
|
20
|
-
const [aM, am, ap] = parse(a);
|
|
21
|
-
const [bM, bm, bp] = parse(b);
|
|
38
|
+
const [aM, am, ap, aPre] = parse(a);
|
|
39
|
+
const [bM, bm, bp, bPre] = parse(b);
|
|
22
40
|
if (aM !== bM) return aM > bM ? 1 : -1;
|
|
23
41
|
if (am !== bm) return am > bm ? 1 : -1;
|
|
24
42
|
if (ap !== bp) return ap > bp ? 1 : -1;
|
|
43
|
+
if (aPre !== bPre) return aPre ? -1 : 1;
|
|
25
44
|
return 0;
|
|
26
45
|
}
|
package/src/swap-simulation.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* EVM-only: Solana signs the aggregator transaction verbatim and is out of scope.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
+
import { AuthError } from './auth-credentials.js';
|
|
18
19
|
import { SIMULATION_RPCS, isNansenHostedUrl } from './rpc-urls.js';
|
|
19
20
|
|
|
20
21
|
// keccak256("Transfer(address,address,uint256)") — shared by ERC-20 and ERC-721.
|
|
@@ -202,30 +203,27 @@ function buildSimRpcBody(method, params) {
|
|
|
202
203
|
return JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
|
|
203
204
|
}
|
|
204
205
|
|
|
205
|
-
async function postSim(rpcUrl,
|
|
206
|
+
async function postSim(rpcUrl, auth, method, params, timeoutMs) {
|
|
206
207
|
const controller = new AbortController();
|
|
207
208
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
208
209
|
try {
|
|
209
|
-
//
|
|
210
|
-
//
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
210
|
+
// Resolve credentials only for the trusted Nansen origin. Custom RPCs
|
|
211
|
+
// remain anonymous and never open browser custody or receive its tokens.
|
|
212
|
+
const hosted = isNansenHostedUrl(rpcUrl);
|
|
213
|
+
let credentials = {};
|
|
214
|
+
if (hosted && auth.api) {
|
|
215
|
+
if (new URL(rpcUrl).origin !== auth.api.baseUrl) throw new AuthError('AUTH_ORIGIN_MISMATCH', 'Simulation origin differs from the selected API origin. Configure a matching Nansen simulation endpoint.');
|
|
216
|
+
credentials = await auth.api.requestCredentials();
|
|
217
|
+
}
|
|
214
218
|
const res = await fetch(rpcUrl, {
|
|
215
219
|
method: 'POST',
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
// redirect would hand the key to whatever host the response points at.
|
|
219
|
-
// An anonymous call to a user-configured third-party RPC carries nothing
|
|
220
|
-
// to leak, so it keeps following redirects as before.
|
|
221
|
-
redirect: sendApiKey ? 'error' : 'follow',
|
|
222
|
-
headers: {
|
|
223
|
-
'Content-Type': 'application/json',
|
|
224
|
-
...(sendApiKey ? { apikey: apiKey } : {}),
|
|
225
|
-
},
|
|
220
|
+
redirect: Object.keys(credentials).length ? 'error' : 'follow',
|
|
221
|
+
headers: { 'Content-Type': 'application/json', ...credentials },
|
|
226
222
|
body: buildSimRpcBody(method, params),
|
|
227
223
|
signal: controller.signal,
|
|
228
224
|
});
|
|
225
|
+
// Anonymous simulation outages retain the existing warn-and-proceed policy.
|
|
226
|
+
if (hosted && auth.api && auth.api.selection.kind !== 'anonymous' && [401, 403].includes(res.status)) throw new AuthError('SIMULATION_ACCESS_DENIED', 'The selected account cannot access hosted simulation. Check account permissions or log in again.');
|
|
229
227
|
const text = await res.text();
|
|
230
228
|
let body;
|
|
231
229
|
try {
|
|
@@ -254,7 +252,7 @@ async function postSim(rpcUrl, apiKey, method, params, timeoutMs) {
|
|
|
254
252
|
}
|
|
255
253
|
return body;
|
|
256
254
|
} catch (e) {
|
|
257
|
-
if (e instanceof SwapSimulationError) throw e;
|
|
255
|
+
if (e instanceof AuthError || e instanceof SwapSimulationError) throw e;
|
|
258
256
|
if (e.name === 'AbortError') {
|
|
259
257
|
throw new SwapSimulationError('SIM_RPC_ERROR', `Simulation RPC timed out after ${timeoutMs}ms (${method})`);
|
|
260
258
|
}
|
|
@@ -304,7 +302,7 @@ function isRevertError(rpcError) {
|
|
|
304
302
|
return (rpcError?.message || '').toLowerCase().includes('execution reverted');
|
|
305
303
|
}
|
|
306
304
|
|
|
307
|
-
async function simulateViaEthSimulateV1(rpcUrl,
|
|
305
|
+
async function simulateViaEthSimulateV1(rpcUrl, auth, { from, to, data, value }, timeoutMs) {
|
|
308
306
|
const params = [
|
|
309
307
|
{
|
|
310
308
|
blockStateCalls: [
|
|
@@ -319,7 +317,7 @@ async function simulateViaEthSimulateV1(rpcUrl, apiKey, { from, to, data, value
|
|
|
319
317
|
},
|
|
320
318
|
'latest',
|
|
321
319
|
];
|
|
322
|
-
const body = await postSim(rpcUrl,
|
|
320
|
+
const body = await postSim(rpcUrl, auth, 'eth_simulateV1', params, timeoutMs);
|
|
323
321
|
if (body.error) {
|
|
324
322
|
if (isMethodUnsupported(body.error)) {
|
|
325
323
|
throw new SwapSimulationError('NOT_SIM_CAPABLE', `eth_simulateV1 unavailable: ${body.error.message}`);
|
|
@@ -368,13 +366,13 @@ function flattenFrames(root) {
|
|
|
368
366
|
return { logs, frames };
|
|
369
367
|
}
|
|
370
368
|
|
|
371
|
-
async function simulateViaDebugTraceCall(rpcUrl,
|
|
369
|
+
async function simulateViaDebugTraceCall(rpcUrl, auth, { from, to, data, value }, timeoutMs) {
|
|
372
370
|
const params = [
|
|
373
371
|
{ from, to, data: data || '0x', value: value || '0x0' },
|
|
374
372
|
'latest',
|
|
375
373
|
{ tracer: 'callTracer', tracerConfig: { withLog: true } },
|
|
376
374
|
];
|
|
377
|
-
const body = await postSim(rpcUrl,
|
|
375
|
+
const body = await postSim(rpcUrl, auth, 'debug_traceCall', params, timeoutMs);
|
|
378
376
|
if (body.error) {
|
|
379
377
|
if (isMethodUnsupported(body.error)) {
|
|
380
378
|
throw new SwapSimulationError('NOT_SIM_CAPABLE', `debug_traceCall unavailable: ${body.error.message}`);
|
|
@@ -455,11 +453,11 @@ async function simulateViaDebugTraceCall(rpcUrl, apiKey, { from, to, data, value
|
|
|
455
453
|
*
|
|
456
454
|
* @param {string} chain - chain key (only 'base' is wired today)
|
|
457
455
|
* @param {{ to: string, data: string, value?: string }} swapCall - the swap tx
|
|
458
|
-
* @param {{ from: string,
|
|
456
|
+
* @param {{ from: string, api?: object, timeoutMs?: number }} opts
|
|
459
457
|
* @returns {Promise<{ deltas: Record<string,bigint>, approvals: Array<{token,spender,amount}>, nftOut: Array<{standard,token}>, nftApprovals: Array<{standard,token,operator}>, method: string }>}
|
|
460
458
|
* @throws {SwapSimulationError} on any degrade condition or an in-sim revert.
|
|
461
459
|
*/
|
|
462
|
-
export async function simulateAssetChanges(chain, swapCall, { from,
|
|
460
|
+
export async function simulateAssetChanges(chain, swapCall, { from, api, timeoutMs = 20000 } = {}) {
|
|
463
461
|
const rpcUrl = SIMULATION_RPCS[chain];
|
|
464
462
|
if (!rpcUrl) {
|
|
465
463
|
throw new SwapSimulationError('NO_SIM_RPC', `No simulation RPC configured for chain '${chain}'.`);
|
|
@@ -470,14 +468,21 @@ export async function simulateAssetChanges(chain, swapCall, { from, apiKey = nul
|
|
|
470
468
|
|
|
471
469
|
const call = { from, to: swapCall.to, data: swapCall.data, value: swapCall.value };
|
|
472
470
|
|
|
473
|
-
// Primary
|
|
474
|
-
//
|
|
471
|
+
// Primary and method fallback share credential selection, origin checks and
|
|
472
|
+
// error redaction. No transport failure changes account or payment rail.
|
|
475
473
|
try {
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
474
|
+
try {
|
|
475
|
+
return await simulateViaEthSimulateV1(rpcUrl, { api }, call, timeoutMs);
|
|
476
|
+
} catch (error) {
|
|
477
|
+
if (error instanceof SwapSimulationError && error.code === 'NOT_SIM_CAPABLE') {
|
|
478
|
+
return await simulateViaDebugTraceCall(rpcUrl, { api }, call, timeoutMs);
|
|
479
|
+
}
|
|
480
|
+
throw error;
|
|
481
|
+
}
|
|
482
|
+
} catch (error) {
|
|
483
|
+
if (api?.selection?.kind === 'session' && error instanceof SwapSimulationError) {
|
|
484
|
+
throw new SwapSimulationError(error.code, 'Simulation could not verify the swap. Check the selected account access and simulation service.');
|
|
480
485
|
}
|
|
481
|
-
throw
|
|
486
|
+
throw error;
|
|
482
487
|
}
|
|
483
488
|
}
|
package/src/telemetry.js
CHANGED
|
@@ -241,6 +241,26 @@ function commandToPath(command) {
|
|
|
241
241
|
return '/' + String(command).replace(/\s+/g, '/');
|
|
242
242
|
}
|
|
243
243
|
|
|
244
|
+
// Authentication accepts positional extras for compatibility, but none of that
|
|
245
|
+
// input is analytics metadata. Keep this vocabulary closed on both outcomes.
|
|
246
|
+
const AUTH_FLAGS = new Set(['--human', '--api-key', '--api-key-stdin', '--no-browser', '--json']);
|
|
247
|
+
const AUTH_ERRORS = new Set(['PAIRING_CANCELLED', 'PAIRING_DENIED', 'PAIRING_EXPIRED', 'PAIRING_FAILED', 'AUTH_NETWORK_ERROR', 'AUTH_STORE_UNAVAILABLE', 'AUTH_LOCK_UNAVAILABLE', 'AUTH_BUSY', 'AUTH_TIMEOUT', 'AUTH_CANCELLED', 'AUTH_STATE_INVALID', 'AUTH_JOURNAL_INVALID', 'AUTH_CLEANUP_REQUIRED', 'AUTH_SELECTION_CHANGED', 'AUTH_ORIGIN_UNSUPPORTED', 'INVALID_BROWSER_SESSION', 'SESSION_VERIFICATION_FAILED', 'BROWSER_SESSION_SETUP_REQUIRED']);
|
|
248
|
+
export function trackAuthCommand({ command, duration_ms, flags = [], error_code, failed = false }) {
|
|
249
|
+
if (command !== 'login' && command !== 'logout') return Promise.resolve();
|
|
250
|
+
return sendEvent({
|
|
251
|
+
event: failed ? 'cli_command_failed' : 'cli_command_succeeded',
|
|
252
|
+
event_source: getEventSource(), event_id: crypto.randomUUID(), user_id: null,
|
|
253
|
+
anonymous_id: getAnonymousId(), session_id: getSessionId(),
|
|
254
|
+
timestamp: new Date().toISOString(), path: `/${command}`,
|
|
255
|
+
properties: {
|
|
256
|
+
source: `nansen-cli/${cliVersion}`, latency: duration_ms / 1000,
|
|
257
|
+
flags: [...new Set(flags.filter(flag => AUTH_FLAGS.has(flag)))],
|
|
258
|
+
...(failed && { error_code: AUTH_ERRORS.has(error_code) ? error_code : 'AUTH_FAILED' }),
|
|
259
|
+
},
|
|
260
|
+
context: buildContext(),
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
244
264
|
/**
|
|
245
265
|
* Track a CLI command that completed successfully.
|
|
246
266
|
*
|