nansen-cli 1.43.1 → 1.44.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 CHANGED
@@ -1,5 +1,99 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.44.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#588](https://github.com/nansen-ai/nansen-cli/pull/588) [`0db1c74`](https://github.com/nansen-ai/nansen-cli/commit/0db1c745b4cdfd05b47bd261159bace7b60f0854) Thanks [@Kewe63](https://github.com/Kewe63)! - Prevent duplicate alert creation after ambiguous network failures and keep Smart Alert mutations out of the response cache.
8
+
9
+ - [#595](https://github.com/nansen-ai/nansen-cli/pull/595) [`1e3fadb`](https://github.com/nansen-ai/nansen-cli/commit/1e3fadb346be2219e8d91ba417806ae7f5b9bcd9) Thanks [@devorun](https://github.com/devorun)! - Fix `--cache` reshaping a cached array response into an object. Endpoints that return a top-level JSON array were object-spread on a cache hit, so `[a, b]` came back as `{ 0: a, 1: b }` and every `Array.isArray()` branch downstream stopped matching — the first call printed rows and the second printed nothing. Cached arrays now stay arrays, and primitive response bodies are returned untouched instead of being exploded into character maps.
10
+
11
+ - [#589](https://github.com/nansen-ai/nansen-cli/pull/589) [`0cc4c18`](https://github.com/nansen-ai/nansen-cli/commit/0cc4c180e5525b6bf8a777d04401ac60b7c926a8) Thanks [@ygd58](https://github.com/ygd58)! - Fix `nansen alerts list --limit`/`--offset` silently misbehaving on invalid or edge-case input. `--limit 0` and `--offset 0` were treated as "not set" (falsy check) and silently ignored instead of honored; a non-numeric value like `--limit abc` silently returned zero results (`Array.prototype.slice` coerces `NaN` to `0`) instead of erroring; and a negative `--offset` was silently accepted by `slice()`, which treats negative indices as "from the end" — returning the wrong records instead of rejecting the input. Both flags are now validated as non-negative integers, matching the strict-validation convention already used elsewhere in the CLI (e.g. `--slippage`), and throw a clear `INVALID_PARAMS` error otherwise.
12
+
13
+ - [#577](https://github.com/nansen-ai/nansen-cli/pull/577) [`3c214a1`](https://github.com/nansen-ai/nansen-cli/commit/3c214a179a3f2c78a8b4b17e2c6b1177828bf2c6) Thanks [@batuhankocyigit](https://github.com/batuhankocyigit)! - Fix `nansen alerts create`/`update` silently dropping numeric range filters (`--usd-min/max`, `--market-cap-min/max`, `--fdv-min/max`, `--token-amount-min/max`, `--token-age-min/max`, and the `--inflow/outflow/netflow-*-min/max` flags) instead of rejecting bad input. These flags were converted with plain `Number(val)`, so a typo or garbage value (e.g. `--usd-min abc`) became `NaN`, which `JSON.stringify` silently turns into `null` in the request body — the alert would get created without the filter the user thought they'd set, with no error at any point. `--*-min`/`--*-max` now reject non-numeric input with a clear `Invalid --<flag> "<value>": must be a number` error; valid negative values (e.g. `--netflow-1h-min -5000` for a net-outflow filter) are unaffected.
14
+
15
+ - [#605](https://github.com/nansen-ai/nansen-cli/pull/605) [`9656d08`](https://github.com/nansen-ai/nansen-cli/commit/9656d08e2df3562ac650d299a5fc6b92bf00d8ad) Thanks [@kome12](https://github.com/kome12)! - Keep non-JSON 4xx responses from trade execute reusable instead of treating them as ambiguous broadcast failures.
16
+
17
+ - [#602](https://github.com/nansen-ai/nansen-cli/pull/602) [`9c72189`](https://github.com/nansen-ai/nansen-cli/commit/9c72189c6760c119784b3534a6777bd1a2e3ce11) Thanks [@kome12](https://github.com/kome12)! - trade limit-order cancel: give distinct, actionable errors when the refund can't be verified — a fully-filled order now says so plainly ("nothing left to refund") instead of sharing the same generic message as unparseable order metadata.
18
+
19
+ - [#598](https://github.com/nansen-ai/nansen-cli/pull/598) [`1450b66`](https://github.com/nansen-ai/nansen-cli/commit/1450b66ffab26d0d9fbe570c90de79916f405ffb) Thanks [@kome12](https://github.com/kome12)! - Close two dust-refund gaps in limit-order cancel verification: a native-SOL refund at or below the fee/rent slack could be "cancelled" by returning a single lamport while the rest of the escrow was rerouted, and a cancel now fails closed when the order is found but its remaining refund amount can't be computed instead of silently downgrading to a bare positive-inflow check.
20
+
21
+ - [#598](https://github.com/nansen-ai/nansen-cli/pull/598) [`b6d5baf`](https://github.com/nansen-ai/nansen-cli/commit/b6d5baf1b14ebd53287744eb23a1f9c4b7ac20a3) Thanks [@kome12](https://github.com/kome12)! - Limit-order create and cancel now verify the API-provided Solana transaction's simulated balance effect against the requested operation before signing, refusing to sign a deposit that would move unexpected funds out of the wallet or a cancel that fails to return the order's own deposited asset to it. The cancel check binds to the full expected remaining refund, not just a positive inflow, so a withdrawal that reroutes most of the escrow and returns only a dust amount of the right asset is refused. Also closes a gap where a cancel could pass on an inflow of any asset (not just the deposited one), and a tiny native-SOL deposit could pass on a fee-only outflow. The pre-cancel order lookup now paginates the active-order list, so an order beyond the first page can still be cancelled.
22
+
23
+ - [#582](https://github.com/nansen-ai/nansen-cli/pull/582) [`8e674c2`](https://github.com/nansen-ai/nansen-cli/commit/8e674c24c6c9340b2c658e511199ac546064fe9b) Thanks [@devorun](https://github.com/devorun)! - Telemetry now creates `~/.nansen` with mode 0700 and writes its id/session files with mode 0600, matching every other module that writes to that directory. Previously these were the only writes there that used default permissions, so when they were the first to create the directory (for example when authenticating with `NANSEN_API_KEY` instead of `nansen login`) it was left group- and world-readable.
24
+
25
+ - [#594](https://github.com/nansen-ai/nansen-cli/pull/594) [`95bdde1`](https://github.com/nansen-ai/nansen-cli/commit/95bdde151057b0bdc6b0bdc5efd67cc3420a9c44) Thanks [@Kewe63](https://github.com/Kewe63)! - Reject invalid cache TTL values before constructing the API client.
26
+
27
+ - [#593](https://github.com/nansen-ai/nansen-cli/pull/593) [`dfc908a`](https://github.com/nansen-ai/nansen-cli/commit/dfc908a74ebc9a6341629c43bea4d98df1219ccc) Thanks [@Kewe63](https://github.com/Kewe63)! - Reject invalid retry counts before constructing the API client.
28
+
29
+ - [#599](https://github.com/nansen-ai/nansen-cli/pull/599) [`bdbdcb2`](https://github.com/nansen-ai/nansen-cli/commit/bdbdcb222ae2f3a4f3b88c8832e7375c46559d79) Thanks [@kome12](https://github.com/kome12)! - x402 auto-pay now signs only for supported schemes and recognized payment networks (exact Solana mainnet CAIP-2 binding), and derives the EIP-712 chain id from the validated network. The EIP-712 domain version is now required across all signing backends (local, WalletConnect, Privy) so a missing version can no longer be silently defaulted to a wrong value, while a null/empty remote chain id is treated as unspecified rather than a conflict.
30
+
31
+ ## 1.44.0
32
+
33
+ ### Minor Changes
34
+
35
+ - [#563](https://github.com/nansen-ai/nansen-cli/pull/563) [`3b3e11b`](https://github.com/nansen-ai/nansen-cli/commit/3b3e11b5d346662bf352cbe2e3f66e54b22213b0) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Emit privacy-preserving per-leg Hyperliquid attribution through the canonical trade-perps outcome events.
36
+
37
+ - [#580](https://github.com/nansen-ai/nansen-cli/pull/580) [`c5085c5`](https://github.com/nansen-ai/nansen-cli/commit/c5085c5d062d848604402949a3e03c87d8b013bd) Thanks [@gulshngill](https://github.com/gulshngill)! - Add `nansen completion <bash|zsh|fish>`, which prints a shell completion script generated from the CLI's own command schema. Completions cover nested subcommands, per-command flags, global flags, and the enum values a flag accepts.
38
+
39
+ - [#597](https://github.com/nansen-ai/nansen-cli/pull/597) [`8453355`](https://github.com/nansen-ai/nansen-cli/commit/845335501837956db2f7a899bf251048bbd706d9) Thanks [@kome12](https://github.com/kome12)! - Security: `nansen mcp verify` no longer sends a saved API key (from `nansen login` / `NANSEN_API_KEY` / config) to a custom `--url` without explicit consent. Forwarding a saved key to a non-default URL now requires `--send-api-key`, and no key is ever sent over plain HTTP to a non-loopback host. An inline `--api-key` is unaffected.
40
+
41
+ Note: verifying a custom `--url` with a saved key now errors unless `--send-api-key` is passed (previously it warned and proceeded).
42
+
43
+ - [#557](https://github.com/nansen-ai/nansen-cli/pull/557) [`5a73b43`](https://github.com/nansen-ai/nansen-cli/commit/5a73b43e4f2fc753c435babcea648b156f7a99a9) Thanks [@gulshngill](https://github.com/gulshngill)! - Add the `nansen research address-premium-labels` command.
44
+
45
+ - [#555](https://github.com/nansen-ai/nansen-cli/pull/555) [`4285d7f`](https://github.com/nansen-ai/nansen-cli/commit/4285d7fc22fde5bacb5b67eb3bcb6e94bb6a680e) Thanks [@gulshngill](https://github.com/gulshngill)! - Add the `nansen research chain-rank` command.
46
+
47
+ - [#561](https://github.com/nansen-ai/nansen-cli/pull/561) [`dd8035c`](https://github.com/nansen-ai/nansen-cli/commit/dd8035c09f5c99c08247686c621c5c14c30607cc) Thanks [@gulshngill](https://github.com/gulshngill)! - Add the `nansen research historical-token-ohlcv` command.
48
+
49
+ - [#560](https://github.com/nansen-ai/nansen-cli/pull/560) [`52f2f09`](https://github.com/nansen-ai/nansen-cli/commit/52f2f095baeaa48c43d5b0f3b1a3b036166266b5) Thanks [@gulshngill](https://github.com/gulshngill)! - Add the `nansen research perp-pnl-summary` command.
50
+
51
+ - [#559](https://github.com/nansen-ai/nansen-cli/pull/559) [`ed2d7a5`](https://github.com/nansen-ai/nansen-cli/commit/ed2d7a5ac00b51240f5a2d0fb7828131dc5074c8) Thanks [@gulshngill](https://github.com/gulshngill)! - Add the `nansen research position-intelligence` command.
52
+
53
+ - [#558](https://github.com/nansen-ai/nansen-cli/pull/558) [`e273152`](https://github.com/nansen-ai/nansen-cli/commit/e273152358792203435191a0f30dd307699721aa) Thanks [@gulshngill](https://github.com/gulshngill)! - Add the `nansen research smart-money-pnl-leaderboard` command.
54
+
55
+ - [#556](https://github.com/nansen-ai/nansen-cli/pull/556) [`3c14359`](https://github.com/nansen-ai/nansen-cli/commit/3c143596b6d7e624338f8d9b1a0972bcbe4d7ad7) Thanks [@gulshngill](https://github.com/gulshngill)! - Add the `nansen research token-sectors` command.
56
+
57
+ - [#562](https://github.com/nansen-ai/nansen-cli/pull/562) [`0d0f5e6`](https://github.com/nansen-ai/nansen-cli/commit/0d0f5e6b83ae91f0215eac3ad2e9216897e6666c) Thanks [@gulshngill](https://github.com/gulshngill)! - Add the `nansen research transaction-with-token-transfer-lookup` command.
58
+
59
+ - [#581](https://github.com/nansen-ai/nansen-cli/pull/581) [`8726a23`](https://github.com/nansen-ai/nansen-cli/commit/8726a23c0e6028c98f941ee9a638dffa50e01ab1) Thanks [@gulshngill](https://github.com/gulshngill)! - Every command option in `nansen schema` now carries a type and a description (140 research and `wallet send` options had neither), and the `research points` group is described. `research token ohlcv --timeframe` documents its real default (`1d`), and `wallet send --chain`, `research search --type`, and the prediction-market `--neg-risk` filters declare the values they accept, so `--help` and shell completion offer them. Fixed `--neg-risk true` on the prediction-market screeners, which was sent to the API as `neg_risk: false` because the parsed boolean was compared against the string `'true'`. `nansen mcp install` and `nansen mcp uninstall` declare their positional client in the schema, and `nansen completion` scripts now complete it (`claude-code`, `claude-desktop`, `cursor`) in bash, zsh, and fish.
60
+
61
+ ### Patch Changes
62
+
63
+ - [#575](https://github.com/nansen-ai/nansen-cli/pull/575) [`927ffea`](https://github.com/nansen-ai/nansen-cli/commit/927ffea1762e7de78160a209aa3cc72298b42c24) Thanks [@kome12](https://github.com/kome12)! - Fail closed on an ambiguous broadcast failure in swap and bridge execute. When
64
+ `/execute` (swap) returns any 5xx (regardless of body shape — a structured 504
65
+ `UPSTREAM_TIMEOUT` is treated the same as a bare 502) or any other
66
+ uninterpretable response — or the POST, or reading its body, throws a network
67
+ error — after the signed tx was sent, or a bridge broadcast fails ambiguously,
68
+ the tx may already be live. The quote is now marked spent and the
69
+ run aborts — rather than trying the next candidate quote or leaving the quote
70
+ reusable — so a re-execute (or agent auto-retry) can't double-broadcast. Gasless
71
+ (Relay solver-paid) swaps additionally do not retry the `/execute` POST: the
72
+ signed authorization is broadcast by Relay's own wrapping tx, so a re-POST can't
73
+ be node-deduped and could trigger a second solve — a single attempt fails closed
74
+ instead. A bridge send is kept reusable only when the node's error proves the tx never
75
+ entered the mempool (a pre-broadcast validation rejection such as insufficient
76
+ funds); in-flight txpool states like "already known" or "nonce too low" fail
77
+ closed.
78
+
79
+ - [#572](https://github.com/nansen-ai/nansen-cli/pull/572) [`2ba5c15`](https://github.com/nansen-ai/nansen-cli/commit/2ba5c15a68f6cc2045dcfb928d65eecdb4083292) Thanks [@teyrebaz33](https://github.com/teyrebaz33)! - Fix `nansen changelog --since <version>` silently returning "No changelog entries found" for a version missing its patch number (e.g. `--since 1.43` instead of `--since 1.43.0`), even when matching entries exist. The comparison compared the missing component against `undefined`, and `>` is always `false` against `undefined` in both directions, so a version that matched on major.minor always came out "less than" the since-value. A missing component is now treated as `0`, and a `--since` value that isn't a valid version (e.g. `--since abc`) now prints a clear error instead of silently matching nothing.
80
+
81
+ The version-comparison logic is now shared (`src/semver.js`) between `nansen changelog --since` and the update-notifier's `isNewer` check, which had the identical bug in its own separate parser. `isNewer` couldn't misfire in practice (both versions it compares are always fully-qualified x.y.z today), but it's the same defect class, so it's fixed the same way rather than left in place.
82
+
83
+ - [#569](https://github.com/nansen-ai/nansen-cli/pull/569) [`04932c7`](https://github.com/nansen-ai/nansen-cli/commit/04932c7fb26fb2c4c4f9b14eddcd43a8e3060aa4) Thanks [@memosr](https://github.com/memosr)! - Refuse to re-execute a swap quote that has already been broadcast, mirroring the single-use guard `nansen bridge execute` already had. `nansen trade execute` now marks the quote as spent (`executedAt`) the instant a transaction is broadcast — before waiting for its receipt — so a `RECEIPT_TIMEOUT` (the tx is on-chain but the command exits non-zero) no longer leaves the quote replayable. Retrying the same `--quote <id>` after such a failure previously re-signed and re-broadcast the swap under a fresh nonce instead of being refused.
84
+
85
+ - [#592](https://github.com/nansen-ai/nansen-cli/pull/592) [`60bd2ef`](https://github.com/nansen-ai/nansen-cli/commit/60bd2ef64f5eebe89112bfa3366c013981f365aa) Thanks [@ygd58](https://github.com/ygd58)! - Fix the x402 auto-payment fallback in `src/api.js` generating multiple payment authorizations for the same request after an ambiguous outcome (issue #583). After a signed `Payment-Signature` was transmitted, `_x402Retry` previously collapsed every non-ok response — a clean rejection, a 5xx, an unreadable body — and every transport failure into a single `null`, and callers treated any `null` as "safe to try the next payment option/provider". That meant a 5xx, a timeout, or an unparseable response (any of which could mean the server already received and settled the payment) triggered signing and transmitting a _second_ independent payment for the same logical request. Separately, a genuine successful response whose JSON body happened to be `null` was indistinguishable from a rejection, risking a second payment for an already-settled call.
86
+
87
+ `_x402Retry` now returns a dedicated `X402_PAYMENT_REJECTED` sentinel only for a provably clean rejection (a non-5xx status with a readable body), and throws `NansenError` with the new `PAYMENT_AMBIGUOUS` code for anything else — a transport failure, a 5xx, or an unreadable body on either a rejection or a success. All three fallback call sites (Privy, local wallet, WalletConnect) now check against the sentinel instead of `null`, and re-throw a `PAYMENT_AMBIGUOUS` error immediately instead of silently moving on to the next provider.
88
+
89
+ - [#524](https://github.com/nansen-ai/nansen-cli/pull/524) [`3e8dcc2`](https://github.com/nansen-ai/nansen-cli/commit/3e8dcc233598383556004da7aaa0a64275beee3f) Thanks [@dolmaciabdullah-byte](https://github.com/dolmaciabdullah-byte)! - Use BigInt for EVM balance in `checkX402Balance` to avoid precision loss on 18-decimal tokens (BSC stablecoins): `parseInt(hex, 16)` loses integer precision once the raw wei value exceeds `Number.MAX_SAFE_INTEGER` (~9.0e15 wei, i.e. ~0.009 tokens at 18 decimals), skewing the low-balance warning.
90
+
91
+ - [#568](https://github.com/nansen-ai/nansen-cli/pull/568) [`9a45fc4`](https://github.com/nansen-ai/nansen-cli/commit/9a45fc494b3bcc0ebeb37f867902aecc075ee92f) Thanks [@Kewe63](https://github.com/Kewe63)! - Reject non-finite limit-order trigger prices and expiry values before wallet or API activity.
92
+
93
+ - [#567](https://github.com/nansen-ai/nansen-cli/pull/567) [`c0fe57b`](https://github.com/nansen-ai/nansen-cli/commit/c0fe57b6f881aa7338a16f6aa2fd33d5e6d42757) Thanks [@Kewe63](https://github.com/Kewe63)! - Keep `research perp` analytics-only instead of routing trading subcommands through the top-level perp dispatcher.
94
+
95
+ - [#558](https://github.com/nansen-ai/nansen-cli/pull/558) [`002921e`](https://github.com/nansen-ai/nansen-cli/commit/002921e5d72e7e54de26f241cb4b409e408b8bf9) Thanks [@gulshngill](https://github.com/gulshngill)! - Reject non-integer or non-positive `--limit` values with an actionable error instead of forwarding them to the API.
96
+
3
97
  ## 1.43.1
4
98
 
5
99
  ### Patch Changes
package/README.md CHANGED
@@ -51,11 +51,23 @@ nansen trade quote --chain solana --from SOL --to USDC --amount 1000000000
51
51
  nansen trade execute --quote <quoteId>
52
52
  nansen wallet <subcommand> [options]
53
53
  nansen mcp install <client> # add the Nansen MCP server to Claude Code/Desktop or Cursor
54
+ nansen completion <bash|zsh|fish> # shell completions (no API key needed)
54
55
  nansen schema [command] [--pretty] # full command reference (no API key needed)
55
56
  ```
56
57
 
57
58
  **Research categories:** `smart-money` (`sm`), `token` (`tgm`), `profiler` (`prof`), `portfolio` (`port`), `prediction-market` (`pm`), `search`, `perp`, `points`
58
59
 
60
+ **Direct research subcommands:**
61
+ - `nansen research chain-rank [--timeframe-days 7|30|365] [--chain-type all|evm]` — rank chains by growth metrics
62
+ - `nansen research token-sectors` — list token sectors available for filtering
63
+ - `nansen research address-premium-labels --address <addr> [--chain <chain>] [--page <n>] [--limit <n>]` — get all labels for an address, including premium labels
64
+ - `nansen research smart-money-pnl-leaderboard [--chains c1,c2] [--timeframe-days 1|7|30|90|180] [--filters '<json>'] [--sort <field[:asc|desc]>] [--page <n>] [--limit <n>]` — rank smart money wallets by PnL
65
+ - `nansen research position-intelligence --symbol <symbol>` — aggregate Hyperliquid positions by trader cohort
66
+ - `nansen research perp-pnl-summary --address <addr> --from-date <date> --to-date <date>` — summarize realized Hyperliquid PnL for an address
67
+ - `nansen research transaction-with-token-transfer-lookup --transaction-hash <hash> [--chain <chain>] [--block-timestamp "YYYY-MM-DD HH:MM:SS"]` — look up a transaction and its token/NFT transfers
68
+
69
+ Plus the `historical-*` point-in-time commands — run `nansen research help` for the full list.
70
+
59
71
  **Trade:** `quote`, `execute`, `bridge-status`, `limit-order` — DEX swaps on Solana and Base, cross-chain bridges, and Solana limit orders.
60
72
 
61
73
  **Wallet:** `create`, `list`, `show`, `export`, `default`, `delete`, `send` — local or Privy server-side wallets (EVM + Solana).
@@ -253,6 +265,28 @@ tempo request POST https://api.nansen.ai/api/v1/smart-money/netflow \
253
265
 
254
266
  > Note: MPP is server-side opt-in (`MPP_ENABLED=true` on the API). It's available on dev today and rolling out to prod — if `tempo request` returns a non-MPP 402, fall back to x402 or an API key.
255
267
 
268
+ ## Shell Completions
269
+
270
+ Tab-completion for commands, subcommands, flags, and the values a flag accepts:
271
+
272
+ ```bash
273
+ # bash
274
+ echo 'eval "$(nansen completion bash)"' >> ~/.bashrc
275
+ # or system-wide: nansen completion bash > /etc/bash_completion.d/nansen
276
+
277
+ # zsh
278
+ nansen completion zsh > "${fpath[1]}/_nansen" && compinit
279
+ # or, in ~/.zshrc after the compinit line: eval "$(nansen completion zsh)"
280
+
281
+ # fish
282
+ nansen completion fish > ~/.config/fish/completions/nansen.fish
283
+ ```
284
+
285
+ The scripts are generated from the same schema as `nansen schema`, so they cover
286
+ every nested subcommand and stay in step with the CLI. Nothing is written to
287
+ disk and no network call is made — the script goes to stdout. Re-run the command
288
+ after upgrading the CLI to pick up new commands.
289
+
256
290
  ## Key Options
257
291
 
258
292
  | Option | Description |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nansen-cli",
3
- "version": "1.43.1",
3
+ "version": "1.44.1",
4
4
  "description": "AI-agent CLI for Nansen API analytics, DEX swaps, and cross-chain trading",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/api.js CHANGED
@@ -19,6 +19,16 @@ import { readResponseMeta } from './response-meta.js';
19
19
  */
20
20
  export const RESPONSE_META = Symbol('nansenResponseMeta');
21
21
 
22
+ /**
23
+ * Sentinel returned by _x402Retry to mean "this payment option was cleanly
24
+ * rejected without settlement, safe to try the next option" — distinct from
25
+ * a genuine successful response whose JSON body happens to be `null`.
26
+ * Using `null` for both (the previous behavior) made a legitimate null-body
27
+ * success indistinguishable from a clean rejection, so the caller would sign
28
+ * and transmit ANOTHER payment for a request that had already succeeded.
29
+ */
30
+ export const X402_PAYMENT_REJECTED = Symbol('x402PaymentRejected');
31
+
22
32
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
23
33
 
24
34
  export function telemetryHeaders() {
@@ -65,6 +75,7 @@ export const ErrorCode = {
65
75
  // Client Errors
66
76
  NETWORK_ERROR: 'NETWORK_ERROR', // Connection failed
67
77
  TIMEOUT: 'TIMEOUT', // Request timed out
78
+ PAYMENT_AMBIGUOUS: 'PAYMENT_AMBIGUOUS', // x402 payment outcome unknown after transmission — do not retry with another payment
68
79
 
69
80
  // Generic
70
81
  UNKNOWN: 'UNKNOWN', // Unclassified error
@@ -264,7 +275,22 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
264
275
  return null;
265
276
  }
266
277
 
267
- return { ...cached.data, _meta: { ...cached.data._meta, fromCache: true, cacheAge: Math.round(age) } };
278
+ // Re-attach the cache marker without reshaping the payload. Object-spreading
279
+ // a top-level array turns it into { 0: …, 1: … }, so a cached array came back
280
+ // as an object and every Array.isArray() branch downstream (the table/CSV/
281
+ // markdown formatters in cli.js, alertsGet) stopped recognising it — the first
282
+ // call rendered rows and the second rendered nothing. Arrays therefore get
283
+ // _meta hung off the array itself, exactly as the live request path does when
284
+ // it records retriedAttempts, and primitives are handed back untouched
285
+ // because a non-object cannot carry the marker at all.
286
+ const meta = { ...cached.data?._meta, fromCache: true, cacheAge: Math.round(age) };
287
+ if (Array.isArray(cached.data)) {
288
+ const rows = cached.data.slice();
289
+ rows._meta = meta;
290
+ return rows;
291
+ }
292
+ if (cached.data === null || typeof cached.data !== 'object') return cached.data;
293
+ return { ...cached.data, _meta: meta };
268
294
  } catch (_e) {
269
295
  // Invalid cache file, delete it
270
296
  try { fs.unlinkSync(cacheFile); } catch { /* ignore */ }
@@ -530,7 +556,14 @@ export class NansenAPI {
530
556
 
531
557
  /**
532
558
  * Retry a POST request with a payment signature.
533
- * Returns parsed JSON if the paid request succeeds, or null if still rejected.
559
+ * Returns parsed JSON if the paid request succeeds, or the X402_PAYMENT_REJECTED
560
+ * sentinel if the server cleanly, legibly rejected it without settling.
561
+ * Throws a NansenError(PAYMENT_AMBIGUOUS) — instead of returning the sentinel —
562
+ * for any outcome that doesn't prove the payment was rejected: a transport
563
+ * failure after transmission, an HTTP 5xx, or a response body that can't be
564
+ * parsed. In all of those cases the server may already have received and
565
+ * settled the payment, so the caller must not treat it as safe to retry with
566
+ * a different option — that would risk paying twice for the same request.
534
567
  * Logs the payment and warns about low balance when walletLabel and network are given.
535
568
  *
536
569
  * @param {string} signature - Payment-Signature header value
@@ -539,7 +572,7 @@ export class NansenAPI {
539
572
  * @param {string} url - Request URL
540
573
  * @param {object} body - Request body (will be cleaned)
541
574
  * @param {object} [options={}] - Request options (may include .method, .headers)
542
- * @returns {Promise<object|null>} Parsed JSON on success, null if rejected
575
+ * @returns {Promise<object|typeof X402_PAYMENT_REJECTED>}
543
576
  *
544
577
  * TODO: full fix — extract the entire x402 provider dispatch from request() into
545
578
  * an attemptX402Payment() method so adding a new payment provider only requires
@@ -550,21 +583,52 @@ export class NansenAPI {
550
583
  // POST burned a payment signature then hit the wrong route for GET/DELETE/PATCH.
551
584
  const method = options.method || 'POST';
552
585
  const isGet = method === 'GET';
553
- const paidResponse = await fetch(url, {
554
- method,
555
- redirect: 'error',
556
- headers: {
557
- ...(!isGet && { 'Content-Type': 'application/json' }),
558
- 'X-Client-Type': 'nansen-cli',
559
- 'X-Client-Version': packageVersion,
560
- ...telemetryHeaders(),
561
- 'Payment-Signature': signature,
562
- ...this.defaultHeaders,
563
- ...options.headers,
564
- },
565
- ...(!isGet && method !== 'DELETE' && { body: JSON.stringify(NansenAPI.cleanBody(body)) }),
566
- });
567
- if (!paidResponse.ok) return null;
586
+ let paidResponse;
587
+ try {
588
+ paidResponse = await fetch(url, {
589
+ method,
590
+ redirect: 'error',
591
+ headers: {
592
+ ...(!isGet && { 'Content-Type': 'application/json' }),
593
+ 'X-Client-Type': 'nansen-cli',
594
+ 'X-Client-Version': packageVersion,
595
+ ...telemetryHeaders(),
596
+ 'Payment-Signature': signature,
597
+ ...this.defaultHeaders,
598
+ ...options.headers,
599
+ },
600
+ ...(!isGet && method !== 'DELETE' && { body: JSON.stringify(NansenAPI.cleanBody(body)) }),
601
+ });
602
+ } catch (err) {
603
+ // The signature was already on the wire when the connection failed —
604
+ // the server may have received and settled it before we lost the
605
+ // response. Fail closed rather than let the caller sign and send a
606
+ // second payment for the same logical request.
607
+ throw new NansenError(
608
+ `x402 payment outcome unknown: request failed after the signed payment was transmitted (${err.message}). Not attempting another payment for the same request.`,
609
+ ErrorCode.PAYMENT_AMBIGUOUS,
610
+ );
611
+ }
612
+ if (!paidResponse.ok) {
613
+ // A 5xx doesn't prove the payment was rejected — the server could have
614
+ // processed it before failing to respond. Only a readable non-5xx
615
+ // rejection body is safe to treat as "try the next option".
616
+ if (paidResponse.status >= 500) {
617
+ throw new NansenError(
618
+ `x402 payment outcome unknown: server returned ${paidResponse.status} after the signed payment was transmitted. Not attempting another payment for the same request.`,
619
+ ErrorCode.PAYMENT_AMBIGUOUS,
620
+ );
621
+ }
622
+ try {
623
+ await paidResponse.json();
624
+ } catch (err) {
625
+ throw new NansenError(
626
+ `x402 payment outcome unknown: rejection response body was unreadable (${err.message}). Not attempting another payment for the same request.`,
627
+ ErrorCode.PAYMENT_AMBIGUOUS,
628
+ );
629
+ }
630
+ return X402_PAYMENT_REJECTED;
631
+ }
568
632
  if (walletLabel) {
569
633
  console.error(`[x402] Paid via ${walletLabel}${network ? ` (${network})` : ''}`);
570
634
  }
@@ -577,7 +641,18 @@ export class NansenAPI {
577
641
  }
578
642
  } catch { /* balance check is best-effort */ }
579
643
  }
580
- const data = await paidResponse.json();
644
+ let data;
645
+ try {
646
+ data = await paidResponse.json();
647
+ } catch (err) {
648
+ // The payment was accepted (2xx) — it settled. We just can't read the
649
+ // response body, so surface that plainly rather than silently treating
650
+ // it as a rejection and paying again.
651
+ throw new NansenError(
652
+ `x402 payment succeeded but its response body was unreadable (${err.message}). The payment was not repeated.`,
653
+ ErrorCode.PAYMENT_AMBIGUOUS,
654
+ );
655
+ }
581
656
  const meta = readResponseMeta(paidResponse);
582
657
  this.lastResponseMeta = meta;
583
658
  if (meta && data !== null && typeof data === 'object') data[RESPONSE_META] = meta;
@@ -712,9 +787,14 @@ export class NansenAPI {
712
787
  const { createPrivyPaymentSignatures } = await import('./privy.js');
713
788
  for await (const { signature, network } of createPrivyPaymentSignatures(response, url)) {
714
789
  const result = await this._x402Retry(signature, `Privy wallet ${defaultWalletName}`, network, url, body, options);
715
- if (result !== null) return result;
790
+ if (result !== X402_PAYMENT_REJECTED) return result;
716
791
  }
717
792
  } catch (privyErr) {
793
+ // An ambiguous outcome (transport failure, 5xx, unreadable body)
794
+ // after a signed payment was already transmitted must not be
795
+ // treated as an ordinary payment failure — there is no other
796
+ // provider to fall back to here, and retrying could double-pay.
797
+ if (privyErr instanceof NansenError && privyErr.code === ErrorCode.PAYMENT_AMBIGUOUS) throw privyErr;
718
798
  message = `x402 Privy payment failed: ${privyErr.message}`;
719
799
  }
720
800
  } else {
@@ -724,10 +804,17 @@ export class NansenAPI {
724
804
  const { createPaymentSignatures } = await import('./x402.js');
725
805
  for await (const { signature, network, asset } of createPaymentSignatures(response, url)) {
726
806
  const result = await this._x402Retry(signature, `local wallet ${defaultWalletName}`, network, url, body, options, asset);
727
- if (result !== null) return result;
728
- // This payment option was rejected, try next
807
+ if (result !== X402_PAYMENT_REJECTED) return result;
808
+ // This payment option was cleanly rejected without settling, try next
729
809
  }
730
- } catch { /* local wallet unavailable, try WalletConnect */ }
810
+ } catch (localErr) {
811
+ // An ambiguous outcome here means a signed payment may already
812
+ // be in flight or settled server-side. Do NOT fall through to
813
+ // WalletConnect below — that would sign and transmit a second,
814
+ // independent payment authorization for the same request.
815
+ if (localErr instanceof NansenError && localErr.code === ErrorCode.PAYMENT_AMBIGUOUS) throw localErr;
816
+ /* local wallet unavailable for any other reason, try WalletConnect */
817
+ }
731
818
 
732
819
  // 2. Fall back to WalletConnect (walletconnect-x402.js)
733
820
  {
@@ -749,8 +836,13 @@ export class NansenAPI {
749
836
  const { handleX402Payment } = await import('./walletconnect-x402.js');
750
837
  const paymentSignature = await handleX402Payment(paymentRequirements);
751
838
  const result = await this._x402Retry(paymentSignature, 'WalletConnect', null, url, body, options);
752
- if (result !== null) return result;
839
+ if (result !== X402_PAYMENT_REJECTED) return result;
753
840
  } catch (x402Err) {
841
+ // WalletConnect is the last resort in this chain — an
842
+ // ambiguous outcome here still must not be reported as an
843
+ // ordinary "payment failed" that invites the caller to
844
+ // retry the whole request (and sign yet another payment).
845
+ if (x402Err instanceof NansenError && x402Err.code === ErrorCode.PAYMENT_AMBIGUOUS) throw x402Err;
754
846
  if (!this.apiKey) {
755
847
  message = 'No API key configured. Three ways to authenticate:\n' +
756
848
  ' 1. API key: run `nansen login --human` or set NANSEN_API_KEY (get key at https://app.nansen.ai/auth/agent-setup)\n' +
@@ -834,6 +926,16 @@ export class NansenAPI {
834
926
  return this.request('/api/v1/account', {}, { method: 'GET', cache: false });
835
927
  }
836
928
 
929
+ // ============= Chain Endpoints =============
930
+
931
+ async chainRank(params = {}) {
932
+ const { timeFrame = 7, chainType = 'all' } = params;
933
+ return this.request('/api/v1/chains/chain-rank', {
934
+ time_frame: timeFrame,
935
+ chain_type: chainType
936
+ });
937
+ }
938
+
837
939
  // ============= Smart Money Endpoints =============
838
940
 
839
941
  async smartMoneyNetflow(params = {}) {
@@ -896,6 +998,17 @@ export class NansenAPI {
896
998
  });
897
999
  }
898
1000
 
1001
+ async smartMoneyPnlLeaderboard(params = {}) {
1002
+ const { chains = ['solana'], timeframe = 7, filters = {}, orderBy, pagination } = params;
1003
+ return this.request('/api/v1/smart-money/pnl-leaderboard', {
1004
+ chains,
1005
+ timeframe,
1006
+ filters,
1007
+ order_by: orderBy,
1008
+ pagination
1009
+ });
1010
+ }
1011
+
899
1012
  // ============= Profiler Endpoints =============
900
1013
 
901
1014
  async addressBalance(params = {}) {
@@ -921,6 +1034,16 @@ export class NansenAPI {
921
1034
  });
922
1035
  }
923
1036
 
1037
+ async addressPremiumLabels(params = {}) {
1038
+ const { address, chain = 'all', pagination = { page: 1, per_page: 100 } } = params;
1039
+ if (address) requireValidAddress(address, chain);
1040
+ return this.request('/api/v1/profiler/address/premium-labels', {
1041
+ address,
1042
+ chain,
1043
+ pagination
1044
+ });
1045
+ }
1046
+
924
1047
  async addressTransactions(params = {}) {
925
1048
  const { address, chain = 'ethereum', filters = {}, orderBy, pagination, days = 30, date } = params;
926
1049
  if (address) requireValidAddress(address, chain);
@@ -970,6 +1093,10 @@ export class NansenAPI {
970
1093
  return this.request('/api/v1/search/general', body);
971
1094
  }
972
1095
 
1096
+ async tokenSectors() {
1097
+ return this.request('/api/v1/search/token-sectors', {}, { method: 'GET' });
1098
+ }
1099
+
973
1100
  async webSearch(params = {}) {
974
1101
  const { queries, numResults = 10 } = params;
975
1102
  if (!queries || queries.length === 0) {
@@ -1092,6 +1219,25 @@ export class NansenAPI {
1092
1219
  });
1093
1220
  }
1094
1221
 
1222
+ async addressPerpPnlSummary(params = {}) {
1223
+ const { address, fromDate, toDate } = params;
1224
+ // HL addresses are EVM-format, so ethereum validation accepts every valid HL address
1225
+ if (address) requireValidAddress(address, 'ethereum');
1226
+ return this.request('/api/v1/profiler/perp-pnl-summary', {
1227
+ address,
1228
+ date: { from: fromDate, to: toDate }
1229
+ });
1230
+ }
1231
+
1232
+ async transactionWithTokenTransferLookup(params = {}) {
1233
+ const { chain = 'ethereum', transactionHash, blockTimestamp } = params;
1234
+ return this.request('/api/v1/transaction-with-token-transfer-lookup', {
1235
+ chain,
1236
+ transaction_hash: transactionHash,
1237
+ block_timestamp: blockTimestamp
1238
+ });
1239
+ }
1240
+
1095
1241
  // ============= Token God Mode Endpoints =============
1096
1242
 
1097
1243
  async tokenScreener(params = {}) {
@@ -1240,6 +1386,13 @@ export class NansenAPI {
1240
1386
  });
1241
1387
  }
1242
1388
 
1389
+ async tokenPositionIntelligence(params = {}) {
1390
+ const { tokenAddress } = params;
1391
+ return this.request('/api/v1/tgm/position-intelligence', {
1392
+ token_address: tokenAddress
1393
+ });
1394
+ }
1395
+
1243
1396
  async tokenPerpPnlLeaderboard(params = {}) {
1244
1397
  const { tokenSymbol, filters = {}, orderBy, pagination, days = 30, withLabels } = params;
1245
1398
  const body = {
@@ -1632,6 +1785,29 @@ export class NansenAPI {
1632
1785
  });
1633
1786
  }
1634
1787
 
1788
+ async researchHistoricalTokenOhlcv(params = {}) {
1789
+ const { chain = 'solana', tokenAddress, fromDate, asOfDate, asOfTs, timeframe, applyBlacklistFilter } = params;
1790
+ if (tokenAddress) requireValidToken(tokenAddress, chain);
1791
+ if (!fromDate) {
1792
+ throw new NansenError('fromDate is required', ErrorCode.MISSING_PARAM);
1793
+ }
1794
+ if (asOfDate && asOfTs) {
1795
+ throw new NansenError('asOfDate and asOfTs are mutually exclusive', ErrorCode.INVALID_PARAMS);
1796
+ }
1797
+ if (!asOfDate && !asOfTs) {
1798
+ throw new NansenError('One of asOfDate or asOfTs is required', ErrorCode.MISSING_PARAM);
1799
+ }
1800
+ return this.request('/api/v1beta1/tgm/historical-token-ohlcv', {
1801
+ chain,
1802
+ token_address: tokenAddress,
1803
+ date_from: fromDate,
1804
+ as_of_date: asOfDate,
1805
+ as_of_ts: asOfTs,
1806
+ timeframe,
1807
+ apply_blacklist_filter: applyBlacklistFilter
1808
+ });
1809
+ }
1810
+
1635
1811
  // ============= Smart Alert Endpoints =============
1636
1812
 
1637
1813
  async alertsList(params = {}) {
@@ -1641,15 +1817,17 @@ export class NansenAPI {
1641
1817
  }
1642
1818
 
1643
1819
  async alertsCreate(params = {}) {
1644
- return this.request('/api/v1/smart-alert', params);
1820
+ // Creating an alert is non-idempotent: a lost response after a committed
1821
+ // create must not trigger another request through the generic retry loop.
1822
+ return this.request('/api/v1/smart-alert', params, { cache: false, retry: false });
1645
1823
  }
1646
1824
 
1647
1825
  async alertsUpdate(params = {}) {
1648
- return this.request('/api/v1/smart-alert', params, { method: 'PATCH' });
1826
+ return this.request('/api/v1/smart-alert', params, { method: 'PATCH', cache: false });
1649
1827
  }
1650
1828
 
1651
1829
  async alertsToggle(params = {}) {
1652
- return this.request('/api/v1/smart-alert/toggle', params, { method: 'PATCH' });
1830
+ return this.request('/api/v1/smart-alert/toggle', params, { method: 'PATCH', cache: false });
1653
1831
  }
1654
1832
 
1655
1833
  async alertsGet(id) {
@@ -1661,7 +1839,7 @@ export class NansenAPI {
1661
1839
  }
1662
1840
 
1663
1841
  async alertsDelete(alertId) {
1664
- return this.request(`/api/v1/smart-alert/${encodeURIComponent(alertId)}`, {}, { method: 'DELETE' });
1842
+ return this.request(`/api/v1/smart-alert/${encodeURIComponent(alertId)}`, {}, { method: 'DELETE', cache: false });
1665
1843
  }
1666
1844
  }
1667
1845