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.
- package/CHANGELOG.md +172 -0
- package/README.md +158 -18
- package/docs/browser-login.md +117 -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 +27 -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 +23 -15
- package/skills/nansen-wallet-manager/SKILL.md +26 -10
- 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 +319 -129
- 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 +90 -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 +272 -0
- package/src/bridge.js +309 -85
- package/src/cache-inspect.js +345 -0
- package/src/chain-ids.js +1 -2
- package/src/cli.js +779 -286
- package/src/commands/agent.js +20 -9
- package/src/commands/alerts.js +1 -1
- package/src/commands/completion.js +2 -15
- package/src/commands/mcp.js +22 -20
- package/src/commands/research.js +4 -2
- package/src/cost-cache.js +16 -2
- package/src/debug.js +348 -0
- package/src/doctor.js +22 -45
- package/src/ens.js +3 -1
- package/src/execute-guard.js +116 -0
- package/src/hl-action.js +41 -13
- package/src/limit-order.js +9 -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 +61 -9
- package/src/privy.js +12 -12
- package/src/query-options.js +38 -6
- package/src/response-meta.js +57 -2
- package/src/rpc-urls.js +9 -11
- package/src/schema.json +309 -30
- package/src/semver.js +23 -4
- package/src/swap-simulation.js +35 -30
- package/src/telemetry.js +20 -0
- package/src/trading.js +806 -40
- package/src/transfer.js +75 -9
- package/src/update-check.js +9 -1
- package/src/wallet.js +240 -20
- package/src/walletconnect-trading.js +29 -8
- package/src/walletconnect-x402.js +9 -5
- package/src/x402-svm.js +123 -64
- package/src/x402.js +46 -14
package/src/perp.js
CHANGED
|
@@ -20,8 +20,10 @@ import {
|
|
|
20
20
|
buildUsdClassTransferAction,
|
|
21
21
|
l1Eip712,
|
|
22
22
|
userSignedEip712,
|
|
23
|
+
validateTpsl,
|
|
23
24
|
} from './hl-action.js';
|
|
24
25
|
import { submitExchange } from './hl-client.js';
|
|
26
|
+
import { hlApiUrl, hlNetwork } from './hl-env.js';
|
|
25
27
|
import { trackPerpOrderCompleted } from './telemetry.js';
|
|
26
28
|
import { resolveEvmWallet, resolvePrivateKey } from './wallet-signing.js';
|
|
27
29
|
import { hashTypedData } from './x402-evm.js';
|
|
@@ -47,7 +49,31 @@ function signAgent(eip712, privateKeyHex) {
|
|
|
47
49
|
// account) or feeds a signing decision (close sizes its order from positions,
|
|
48
50
|
// and asset ids/szDecimals come from meta), so a hit inside the 5-minute TTL
|
|
49
51
|
// would sign against data that has moved.
|
|
52
|
+
// Every read below comes from the Nansen proxy, which serves Hyperliquid
|
|
53
|
+
// MAINNET data — asset ids, szDecimals, positions, open orders, balances.
|
|
54
|
+
// Signing and submission, in contrast, follow NANSEN_HL_API_URL: hlNetwork()
|
|
55
|
+
// flips the L1 phantom-agent source and hyperliquidChain to Testnet and
|
|
56
|
+
// hl-client posts to the testnet host. Pointing the CLI at the testnet
|
|
57
|
+
// therefore signs mainnet asset indices into testnet orders (the two
|
|
58
|
+
// universes are not guaranteed to share an ordering), shows mainnet positions
|
|
59
|
+
// for a testnet account, and validates `close --side` against the wrong
|
|
60
|
+
// network's position. Refuse rather than mix the two, the way bridge.js
|
|
61
|
+
// refuses an action whose hyperliquidChain is not the network it targets.
|
|
62
|
+
//
|
|
63
|
+
// hlNetwork() only reports Testnet for a hyperliquid-testnet host, so a local
|
|
64
|
+
// mock (the other documented use of NANSEN_HL_API_URL) is unaffected.
|
|
65
|
+
function assertPerpNetworkSupported() {
|
|
66
|
+
const network = hlNetwork();
|
|
67
|
+
if (network !== 'Mainnet') {
|
|
68
|
+
throw new CommandError(
|
|
69
|
+
`Perp commands are mainnet-only: NANSEN_HL_API_URL points at ${hlApiUrl()} (${network}), but asset metadata, positions and balances come from the Nansen proxy, which serves mainnet data. Signing ${network} actions against mainnet asset ids could target a different instrument. Unset NANSEN_HL_API_URL to trade on mainnet.`,
|
|
70
|
+
'UNSUPPORTED_NETWORK',
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
50
75
|
async function perpRead(apiInstance, endpoint, params) {
|
|
76
|
+
assertPerpNetworkSupported();
|
|
51
77
|
const qs = new URLSearchParams(params).toString();
|
|
52
78
|
// Only append the query string when there is one; a paramless read like `meta`
|
|
53
79
|
// would otherwise resolve to `/api/v1/perp/meta?` with a bare trailing `?`.
|
|
@@ -60,6 +86,9 @@ async function perpRead(apiInstance, endpoint, params) {
|
|
|
60
86
|
// (missing wallet, wrong password) — callers that need it to build an action
|
|
61
87
|
// re-check for null and abort at that point (see requireAsset).
|
|
62
88
|
async function fetchAssetMeta(apiInstance, coin) {
|
|
89
|
+
// Before the try: a network mismatch is a configuration error the caller
|
|
90
|
+
// must see, not an availability problem to fail open on.
|
|
91
|
+
assertPerpNetworkSupported();
|
|
63
92
|
try {
|
|
64
93
|
const meta = await perpRead(apiInstance, 'meta', {});
|
|
65
94
|
const asset = (meta.assets || []).find(a => String(a.name).toUpperCase() === coin);
|
|
@@ -107,6 +136,7 @@ const MAX_BUILDER_FEE_TENTHS_BP = 80;
|
|
|
107
136
|
// gate. Fail closed — this endpoint shares availability with screening, so if
|
|
108
137
|
// it's down we abort rather than trade without the builder code.
|
|
109
138
|
async function fetchBuilderFee(apiInstance, walletAddress) {
|
|
139
|
+
assertPerpNetworkSupported();
|
|
110
140
|
const qs = new URLSearchParams({ wallet_address: walletAddress }).toString();
|
|
111
141
|
let status;
|
|
112
142
|
try {
|
|
@@ -175,10 +205,8 @@ function resolveWalletAddress(walletName) {
|
|
|
175
205
|
// response that doesn't cover every requested address all abort the trade
|
|
176
206
|
// before signing, never trade through.
|
|
177
207
|
|
|
178
|
-
//
|
|
179
|
-
//
|
|
180
|
-
// screen sits in that path). Worth lifting into its own module if a third caller
|
|
181
|
-
// appears.
|
|
208
|
+
// Shared with bridge.js and trading.js, whose direct signing/broadcast paths do
|
|
209
|
+
// not have a server-side screen after this checkpoint.
|
|
182
210
|
export async function screenOrThrow(apiInstance, addresses) {
|
|
183
211
|
let result;
|
|
184
212
|
try {
|
|
@@ -196,7 +224,9 @@ export async function screenOrThrow(apiInstance, addresses) {
|
|
|
196
224
|
}
|
|
197
225
|
|
|
198
226
|
const results = Array.isArray(result?.results) ? result.results : [];
|
|
199
|
-
const sanctioned = results
|
|
227
|
+
const sanctioned = results
|
|
228
|
+
.filter(r => r && r.sanctioned === true)
|
|
229
|
+
.map(r => r.address);
|
|
200
230
|
if (sanctioned.length > 0) {
|
|
201
231
|
throw new CommandError(
|
|
202
232
|
`Wallet address is on the compliance blocklist and cannot trade: ${sanctioned.join(', ')}`,
|
|
@@ -204,10 +234,21 @@ export async function screenOrThrow(apiInstance, addresses) {
|
|
|
204
234
|
);
|
|
205
235
|
}
|
|
206
236
|
|
|
207
|
-
// A 200 that omitted a requested address
|
|
208
|
-
// than assume the
|
|
209
|
-
|
|
210
|
-
|
|
237
|
+
// A 200 that omitted a requested address or did not return a boolean verdict
|
|
238
|
+
// is unverifiable — fail closed rather than assume the address is clean.
|
|
239
|
+
// EVM addresses are case-insensitive; base58 addresses (including Solana)
|
|
240
|
+
// are case-sensitive and must match exactly. Lowercasing every result here
|
|
241
|
+
// would let a verdict for a different Solana address satisfy the gate.
|
|
242
|
+
const addressKey = (address) => {
|
|
243
|
+
const value = String(address);
|
|
244
|
+
return /^0x[0-9a-f]{40}$/i.test(value) ? value.toLowerCase() : value;
|
|
245
|
+
};
|
|
246
|
+
const screened = new Set(
|
|
247
|
+
results
|
|
248
|
+
.filter(r => r && typeof r.sanctioned === 'boolean' && r.address != null)
|
|
249
|
+
.map(r => addressKey(r.address)),
|
|
250
|
+
);
|
|
251
|
+
const missing = addresses.filter(a => !screened.has(addressKey(a)));
|
|
211
252
|
if (missing.length > 0) {
|
|
212
253
|
throw new CommandError(
|
|
213
254
|
`Compliance screening did not cover all addresses, so the trade was not submitted: ${missing.join(', ')}`,
|
|
@@ -335,6 +376,10 @@ async function buildScreenSignSubmit(apiInstance, prepared, ctx) {
|
|
|
335
376
|
const { action, nonce, eip712, size, price, coin, telemetry } = prepared;
|
|
336
377
|
const { walletAddress, log } = ctx;
|
|
337
378
|
|
|
379
|
+
// Last gate before a signature: every action built above used proxy-sourced
|
|
380
|
+
// mainnet metadata.
|
|
381
|
+
assertPerpNetworkSupported();
|
|
382
|
+
|
|
338
383
|
log(' Screening...');
|
|
339
384
|
await screenOrThrow(apiInstance, [walletAddress]);
|
|
340
385
|
|
|
@@ -653,6 +698,13 @@ OPTIONS:
|
|
|
653
698
|
const sl = options['stop-loss'] !== undefined ? parsePositiveNumber(options['stop-loss'], 'stop-loss') : undefined;
|
|
654
699
|
const isBuy = side === 'buy' || side === 'long';
|
|
655
700
|
|
|
701
|
+
// buildOrderAction re-checks this, but that call happens after the signing
|
|
702
|
+
// context is resolved and after ensureBuilderApproved has already signed
|
|
703
|
+
// and submitted the one-time builder-fee approval. A stop/take on the
|
|
704
|
+
// wrong side of entry would otherwise cost the user an on-chain approval
|
|
705
|
+
// and a password prompt for an order that was never valid.
|
|
706
|
+
validateTpsl({ isBuy, price, takeProfit: tp ?? null, stopLoss: sl ?? null });
|
|
707
|
+
|
|
656
708
|
// One meta read serves both the advisory precision warning and the
|
|
657
709
|
// required build metadata. Fetched fail-open so a meta outage doesn't
|
|
658
710
|
// preempt a clearer error below (missing wallet, wrong password); we
|
package/src/privy.js
CHANGED
|
@@ -10,6 +10,7 @@ import fs from "fs";
|
|
|
10
10
|
import path from "path";
|
|
11
11
|
import { parsePaymentRequirements } from "./x402.js";
|
|
12
12
|
import { isEvmNetwork } from "./x402-evm.js";
|
|
13
|
+
import { mkdirPrivateSync, readWalletJson, writeWalletJsonAtomic } from "./wallet.js";
|
|
13
14
|
import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from "./x402-policy.js";
|
|
14
15
|
import {
|
|
15
16
|
isSvmNetwork,
|
|
@@ -21,6 +22,7 @@ import {
|
|
|
21
22
|
buildEIP712TypedData,
|
|
22
23
|
buildPaymentSignatureHeader,
|
|
23
24
|
} from "./walletconnect-x402.js";
|
|
25
|
+
import { trace } from "./debug.js";
|
|
24
26
|
|
|
25
27
|
// ============= Constants =============
|
|
26
28
|
|
|
@@ -190,22 +192,20 @@ export async function createPrivyWalletPair(name) {
|
|
|
190
192
|
createdAt: new Date().toISOString(),
|
|
191
193
|
};
|
|
192
194
|
|
|
193
|
-
|
|
194
|
-
fs.mkdirSync(walletsDir, { mode: 0o700, recursive: true });
|
|
195
|
-
}
|
|
195
|
+
mkdirPrivateSync(walletsDir);
|
|
196
196
|
|
|
197
197
|
// Write config before wallet file so a crash doesn't leave an orphan without a default entry
|
|
198
198
|
const configPath = path.join(walletsDir, "config.json");
|
|
199
199
|
let config = { defaultWallet: null, passwordHash: null };
|
|
200
200
|
if (fs.existsSync(configPath)) {
|
|
201
|
-
config =
|
|
201
|
+
config = readWalletJson(configPath);
|
|
202
202
|
}
|
|
203
203
|
if (!config.defaultWallet) {
|
|
204
204
|
config.defaultWallet = name;
|
|
205
|
-
|
|
205
|
+
writeWalletJsonAtomic(configPath, config);
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
-
|
|
208
|
+
writeWalletJsonAtomic(walletFile, walletData);
|
|
209
209
|
|
|
210
210
|
return walletData;
|
|
211
211
|
}
|
|
@@ -226,11 +226,11 @@ async function getPrivyEvmWallet(client) {
|
|
|
226
226
|
const walletsDir = path.join(process.env.HOME || process.env.USERPROFILE || "", ".nansen", "wallets");
|
|
227
227
|
const configPath = path.join(walletsDir, "config.json");
|
|
228
228
|
if (fs.existsSync(configPath)) {
|
|
229
|
-
const config =
|
|
229
|
+
const config = readWalletJson(configPath);
|
|
230
230
|
if (config.defaultWallet) {
|
|
231
231
|
const walletFile = path.join(walletsDir, `${config.defaultWallet}.json`);
|
|
232
232
|
if (fs.existsSync(walletFile)) {
|
|
233
|
-
const data =
|
|
233
|
+
const data = readWalletJson(walletFile);
|
|
234
234
|
if (data.provider === "privy" && data.evm?.privyWalletId) {
|
|
235
235
|
return client.getWallet(data.evm.privyWalletId);
|
|
236
236
|
}
|
|
@@ -239,7 +239,7 @@ async function getPrivyEvmWallet(client) {
|
|
|
239
239
|
}
|
|
240
240
|
} catch (err) {
|
|
241
241
|
// Fall through to list-based detection
|
|
242
|
-
|
|
242
|
+
trace("x402.default_wallet_lookup_failed", { error: err.message });
|
|
243
243
|
}
|
|
244
244
|
|
|
245
245
|
const result = await client.listWallets();
|
|
@@ -257,11 +257,11 @@ async function getPrivySolanaWallet(client) {
|
|
|
257
257
|
const walletsDir = path.join(process.env.HOME || process.env.USERPROFILE || "", ".nansen", "wallets");
|
|
258
258
|
const configPath = path.join(walletsDir, "config.json");
|
|
259
259
|
if (fs.existsSync(configPath)) {
|
|
260
|
-
const config =
|
|
260
|
+
const config = readWalletJson(configPath);
|
|
261
261
|
if (config.defaultWallet) {
|
|
262
262
|
const walletFile = path.join(walletsDir, `${config.defaultWallet}.json`);
|
|
263
263
|
if (fs.existsSync(walletFile)) {
|
|
264
|
-
const data =
|
|
264
|
+
const data = readWalletJson(walletFile);
|
|
265
265
|
if (data.provider === "privy" && data.solana?.privyWalletId) {
|
|
266
266
|
return client.getWallet(data.solana.privyWalletId);
|
|
267
267
|
}
|
|
@@ -269,7 +269,7 @@ async function getPrivySolanaWallet(client) {
|
|
|
269
269
|
}
|
|
270
270
|
}
|
|
271
271
|
} catch (err) {
|
|
272
|
-
|
|
272
|
+
trace("x402.solana_wallet_lookup_failed", { error: err.message });
|
|
273
273
|
}
|
|
274
274
|
|
|
275
275
|
const result = await client.listWallets();
|
package/src/query-options.js
CHANGED
|
@@ -25,9 +25,22 @@ export function parseSort(sortOption, orderByOption) {
|
|
|
25
25
|
// If --order-by is provided, use it (full JSON control)
|
|
26
26
|
if (orderByOption) return orderByOption;
|
|
27
27
|
if (!sortOption) return undefined;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
if (typeof sortOption !== 'string') {
|
|
29
|
+
throw new NansenError('--sort must be "field" or "field:direction"', ErrorCode.INVALID_PARAMS);
|
|
30
|
+
}
|
|
31
|
+
const parts = sortOption.split(':');
|
|
32
|
+
const field = parts[0].trim();
|
|
33
|
+
const rawDirection = (parts[1] || '').trim();
|
|
34
|
+
const direction = (rawDirection || 'desc').toUpperCase();
|
|
35
|
+
if (!field) {
|
|
36
|
+
throw new NansenError('--sort needs a field name, e.g. --sort value_usd:desc', ErrorCode.INVALID_PARAMS);
|
|
37
|
+
}
|
|
38
|
+
if (direction !== 'ASC' && direction !== 'DESC') {
|
|
39
|
+
throw new NansenError(
|
|
40
|
+
`--sort direction must be asc or desc, got "${rawDirection}" (e.g. --sort ${field}:desc)`,
|
|
41
|
+
ErrorCode.INVALID_PARAMS,
|
|
42
|
+
);
|
|
43
|
+
}
|
|
31
44
|
return [{ field, direction }];
|
|
32
45
|
}
|
|
33
46
|
|
|
@@ -35,8 +48,8 @@ export function parseSort(sortOption, orderByOption) {
|
|
|
35
48
|
* Normalise a comma-separated-string-or-array CLI option into an array of
|
|
36
49
|
* strings, or undefined if absent. Accepts either a single "a,b,c" string or
|
|
37
50
|
* an array (parseArgs collects repeated flags, e.g. `--tag a --tag b`, into
|
|
38
|
-
* one), and rejects non-string values/elements (e.g. `--flag
|
|
39
|
-
* parsed by parseArgs as
|
|
51
|
+
* one), and rejects non-string values/elements (e.g. `--flag '{}'` is
|
|
52
|
+
* parsed by parseArgs as a JSON object) with an actionable
|
|
40
53
|
* INVALID_PARAMS error instead of crashing on .split()/.trim().
|
|
41
54
|
*/
|
|
42
55
|
export function parseCsvOption(val, name) {
|
|
@@ -45,7 +58,9 @@ export function parseCsvOption(val, name) {
|
|
|
45
58
|
if (!val.every(v => typeof v === 'string')) {
|
|
46
59
|
throw new NansenError(`--${name} values must be strings`, ErrorCode.INVALID_PARAMS);
|
|
47
60
|
}
|
|
48
|
-
|
|
61
|
+
// A repeated flag may itself carry a list (`--tags defi,nft --tags sports`),
|
|
62
|
+
// so split each element the same way a single value is split.
|
|
63
|
+
return val.flatMap(v => v.split(',')).map(v => v.trim()).filter(Boolean);
|
|
49
64
|
}
|
|
50
65
|
if (typeof val !== 'string') {
|
|
51
66
|
throw new NansenError(`--${name} must be a string`, ErrorCode.INVALID_PARAMS);
|
|
@@ -53,6 +68,23 @@ export function parseCsvOption(val, name) {
|
|
|
53
68
|
return val.split(',').map(s => s.trim()).filter(Boolean);
|
|
54
69
|
}
|
|
55
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Normalise a `--filters '<json>'` option into a plain object, or `{}` when
|
|
73
|
+
* absent. parseArgs already JSON-parses the value, so anything that is not a
|
|
74
|
+
* plain object here (`--filters '[]'`, `--filters abc`, a repeated flag) would
|
|
75
|
+
* otherwise go straight into the request body and fail upstream with a 422.
|
|
76
|
+
*/
|
|
77
|
+
export function parseObjectOption(val, name) {
|
|
78
|
+
if (val === undefined || val === '') return {};
|
|
79
|
+
if (val === null || typeof val !== 'object' || Array.isArray(val)) {
|
|
80
|
+
throw new NansenError(
|
|
81
|
+
`--${name} must be a JSON object, e.g. --${name} '{"key": "value"}'`,
|
|
82
|
+
ErrorCode.INVALID_PARAMS,
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
return val;
|
|
86
|
+
}
|
|
87
|
+
|
|
56
88
|
/** Reject explicit blank strings before a handler selects an omitted-option default. */
|
|
57
89
|
export function rejectBlankOption(value, name, example) {
|
|
58
90
|
if (typeof value === 'string' && value.trim() === '') {
|
package/src/response-meta.js
CHANGED
|
@@ -43,7 +43,7 @@ function intHeader(response, name) {
|
|
|
43
43
|
* Read a header as a trimmed non-empty string, or null when absent.
|
|
44
44
|
* Tolerates any header bag with a .get() — a real Headers, or a Map in tests.
|
|
45
45
|
*/
|
|
46
|
-
function stringHeader(response, name) {
|
|
46
|
+
export function stringHeader(response, name) {
|
|
47
47
|
const raw = response?.headers?.get?.(name);
|
|
48
48
|
if (raw == null) return null;
|
|
49
49
|
const value = String(raw).trim();
|
|
@@ -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
|
}
|