nansen-cli 1.45.0 → 1.46.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 CHANGED
@@ -1,5 +1,69 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.46.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#667](https://github.com/nansen-ai/nansen-cli/pull/667) [`8dad3b9`](https://github.com/nansen-ai/nansen-cli/commit/8dad3b9a2938bbf83d4d7cbce5986e728df7b975) Thanks [@gulshngill](https://github.com/gulshngill)! - `trade execute` and `bridge execute` now take `--dry-run` and `--yes`. `--dry-run` runs the sign-free preflight available from the cached quote, its public signer address, and read-only RPC calls; prints the trade or transfer that would be sent (chain, tokens, amounts, recipient, approvals, fees — plus the current allowance and revert simulation on EVM); and stops before wallet credentials or signing: no wallet password needed, the quote is not consumed, exit code 0. Real execution still resolves and revalidates the live signer. When stdin is an interactive terminal, both commands now print that plan and ask `Broadcast this transaction? [y/N]` before broadcasting; declining exits 1 with nothing signed. `--yes` (`-y`) or `NANSEN_YES=1` skips the prompt. Non-interactive callers — agents, CI, pipes — are unchanged: they proceed without prompting, and `--yes` is accepted there as a no-op.
8
+
9
+ - [#501](https://github.com/nansen-ai/nansen-cli/pull/501) [`5a79f9d`](https://github.com/nansen-ai/nansen-cli/commit/5a79f9db91aa3dab3d0e8b043172e5a3af418924) Thanks [@gulshngill](https://github.com/gulshngill)! - Guard `wallet export` against accidental plaintext key disclosure. The default output is now redacted (addresses only — no decryption, no password needed). Printing private keys to stdout requires explicit acknowledgement via `--reveal` (which also warns on stderr when stdout is an interactive terminal), and the new `--file <path>` writes keys to a file created with 0600 permissions (refusing to overwrite) while keeping stdout clean. Scripts that parsed `wallet export` output must add `--reveal` or switch to `--file`. `--file` failures carry machine-readable codes: `FILE_EXISTS` when the path already exists, `FILE_WRITE_FAILED` for any other create/write error.
10
+
11
+ This safety hardening is intentionally classified as a minor change rather than a major release: it changes an unsafe default to prevent accidental private-key disclosure while preserving explicit export through `--reveal` and `--file`.
12
+
13
+ - [#669](https://github.com/nansen-ai/nansen-cli/pull/669) [`b821104`](https://github.com/nansen-ai/nansen-cli/commit/b821104abb2860b9c0bf13b79a0bb3043b65cb5f) Thanks [@gulshngill](https://github.com/gulshngill)! - Show the real subcommand help for `nansen research perp screener --help` and `nansen research perp leaderboard --help`. Because `perp` is also a top-level trading command, the help lookup stopped at the trading command's subcommand list and fell back to printing the category listing — "Use: nansen research perp <subcommand> --help", the command that had just been run — so the parameters, credit cost and example were unreachable. `nansen perp screener --help` now resolves to the same help, with an example pointing at the `research` path. Boolean options now accept `--flag=false` and reject invalid or repeated values instead of silently falling back to the server default; value-taking options also accept the conventional `--key=value` spelling, while valueless switches reject inline values instead of creating unusable stale flags. Invalid `changelog --since` values now return a structured error and a non-zero exit status.
14
+
15
+ The stricter validation intentionally rejects invalid, previously undocumented inputs that only appeared to succeed while being ignored; relying on that quiet fallback was relying on a bug, so this is classified as a minor change rather than a major breaking release.
16
+
17
+ ### Patch Changes
18
+
19
+ - [#682](https://github.com/nansen-ai/nansen-cli/pull/682) [`3e172f2`](https://github.com/nansen-ai/nansen-cli/commit/3e172f26cca04e52187b95dfbed0b43d35dc9f93) Thanks [@Bruce039](https://github.com/Bruce039)! - `alerts update` no longer resends a PATCH through the retry loop after a transient failure, matching `alerts create`
20
+
21
+ - [#649](https://github.com/nansen-ai/nansen-cli/pull/649) [`66152af`](https://github.com/nansen-ai/nansen-cli/commit/66152af23024cad484393d37849e05d749409b7e) Thanks [@kriss39](https://github.com/kriss39)! - `research profiler compare` no longer turns failed API requests into an empty comparison. When every request fails the command errors with the underlying code (for example `UNAUTHORIZED` or `RATE_LIMITED`); when some fail the result carries `incomplete: true`, an `errors` list, and `null` for the fields that could not be computed. Shared tokens are now matched on the token address when both wallets report one, falling back to the symbol when either side omits it, so two different contracts with the same symbol are no longer reported as shared.
22
+
23
+ - [#674](https://github.com/nansen-ai/nansen-cli/pull/674) [`ad178db`](https://github.com/nansen-ai/nansen-cli/commit/ad178db7cbcd21628df3c68c90a8defaef85db57) Thanks [@0xShadowX](https://github.com/0xShadowX)! - A repeated list option whose values are themselves comma-separated (`--tags defi,nft --tags sports`) is now flattened to `defi, nft, sports`. Previously the first value was kept as the literal `defi,nft`, so the same list was read differently depending on whether it was passed once or as repeated flags.
24
+
25
+ - [#652](https://github.com/nansen-ai/nansen-cli/pull/652) [`d0433d4`](https://github.com/nansen-ai/nansen-cli/commit/d0433d4e0da5092c47f63c9a74d71f167c9a347e) Thanks [@Bruce039](https://github.com/Bruce039)! - Resolve ENS names when the profiler chain is `all`. The profiler commands default `--chain` to `all`, but the resolver only accepted explicit EVM chains, so `research profiler labels --address vitalik.eth` (and every other profiler subcommand except `first-funder`) failed with `ENS names can only be resolved on EVM chains, not all` unless `--chain ethereum` was passed.
26
+
27
+ - [#654](https://github.com/nansen-ai/nansen-cli/pull/654) [`0aad196`](https://github.com/nansen-ai/nansen-cli/commit/0aad1963027ad90761e860501db4db9d438c1143) Thanks [@Bruce039](https://github.com/Bruce039)! - `--fields` now supports dotted paths. `--fields data.results.address` selects that field at that position only (array elements do not add a segment), while a bare name such as `--fields address` keeps matching at any depth. Dotted paths were mentioned in the code but matched nothing, so `--fields data.results` returned an empty object.
28
+
29
+ - [#672](https://github.com/nansen-ai/nansen-cli/pull/672) [`b10dc31`](https://github.com/nansen-ai/nansen-cli/commit/b10dc31fc0509a7941f6fac02dda76088ece71eb) Thanks [@0xShadowX](https://github.com/0xShadowX)! - `--filters` is validated as a JSON object before the request is sent. A value such as `--filters '[]'`, `--filters abc` or a repeated `--filters` flag used to be forwarded to the API as-is and only failed there with a 422; it now fails with an `INVALID_PARAMS` error that shows the expected form.
30
+
31
+ - [#660](https://github.com/nansen-ai/nansen-cli/pull/660) [`42db750`](https://github.com/nansen-ai/nansen-cli/commit/42db750fbc261572f53f02dab1716125ec3b2079) Thanks [@Ahmett101](https://github.com/Ahmett101)! - Parse SSE `data:` fields with or without the optional space after the colon so standards-compliant agent streams do not produce an empty response.
32
+
33
+ - [#651](https://github.com/nansen-ai/nansen-cli/pull/651) [`ab784a3`](https://github.com/nansen-ai/nansen-cli/commit/ab784a331aba66c7899845d22961a52c4f50b93a) Thanks [@kriss39](https://github.com/kriss39)! - Respect the server's `Retry-After` header when retrying rate-limited (429) requests. The wait was capped at the local backoff ceiling (30s), so a `Retry-After: 60` led to a retry after 30s that could only hit the limiter again. The client now waits at least as long as the header asks, and if the server asks for more than `maxRetryAfterMs` (default 120s) it fails immediately with the `retryAfterMs` in the error details instead of retrying too early. A `Retry-After` on a 5xx response is still treated as advisory and capped at the backoff ceiling as before.
34
+
35
+ - [#663](https://github.com/nansen-ai/nansen-cli/pull/663) [`bc4ecc8`](https://github.com/nansen-ai/nansen-cli/commit/bc4ecc82c4bfedfc66dbe621f96a581437bb415d) Thanks [@gulshngill](https://github.com/gulshngill)! - Option values that spell a JSON keyword (`--sort true`, `--search false`, `--label null`) are now kept as the literal strings `true`/`false`/`null` instead of being converted to a boolean or null, so string options no longer crash or silently drop the value; `--filters '{}'` and `--order-by '[...]'` still parse as JSON, and `--sort` now rejects a repeated or non-text value with `--sort must be "field" or "field:direction"`.
36
+
37
+ - [#671](https://github.com/nansen-ai/nansen-cli/pull/671) [`8a4e98f`](https://github.com/nansen-ai/nansen-cli/commit/8a4e98f8275701f328ab8d4cef850afbd5183177) Thanks [@0xShadowX](https://github.com/0xShadowX)! - Keep the body of a non-JSON error response (gateway HTML, plain text) in the error details instead of reporting `body: null`, and apply the same retry policy to it as to a JSON error: a plain-text `429` is now retried, with its `Retry-After` respected, instead of failing on the first attempt.
38
+
39
+ - [#676](https://github.com/nansen-ai/nansen-cli/pull/676) [`0112fa1`](https://github.com/nansen-ai/nansen-cli/commit/0112fa1aba981e961a2795ae4c92534eb3a8694f) Thanks [@0xShadowX](https://github.com/0xShadowX)! - Refuse to sign EVM approval, revoke, and Privy swap transactions when the quote carries no gas price, instead of defaulting to an unmineable 0.001 gwei fee that left the wallet's nonce stuck
40
+
41
+ - [#681](https://github.com/nansen-ai/nansen-cli/pull/681) [`c82492d`](https://github.com/nansen-ai/nansen-cli/commit/c82492df4d7f260f5d234aa8cbe362e4d27b08aa) Thanks [@kriss39](https://github.com/kriss39)! - `wallet send` and `trade limit-order create` reject an amount of zero, or one that truncates to zero base units at the token's precision, instead of broadcasting a transfer of nothing or creating a limit order with `inputAmount: "0"`
42
+
43
+ - [#650](https://github.com/nansen-ai/nansen-cli/pull/650) [`d4b4925`](https://github.com/nansen-ai/nansen-cli/commit/d4b4925d0de9035df6cd01a5a9165691646e9a9f) Thanks [@kriss39](https://github.com/kriss39)! - `research token screener --search` now honours `--page`. The search filter runs client-side, and previously every page returned the same first slice of matches; the candidate fetch is now widened to cover the requested page and the filtered list is sliced at the page offset.
44
+
45
+ - [#661](https://github.com/nansen-ai/nansen-cli/pull/661) [`fe5b294`](https://github.com/nansen-ai/nansen-cli/commit/fe5b294d30a8dc3e93270aead4a27a4b6513ce60) Thanks [@gulshngill](https://github.com/gulshngill)! - Recognise the API's full set of structured error codes. A 401 `unauthenticated` response once again shows `Not logged in. Run: nansen login`, `insufficient_credits` gets its do-not-retry hint, and codes that previously leaked through as raw server strings now surface as CLI codes, including the new `PLAN_UPGRADE_REQUIRED`, `GEO_BLOCKED`, `QUERY_TOO_LARGE`, `PAYLOAD_TOO_LARGE`, `METHOD_NOT_ALLOWED`, and `CONFLICT`. Retry behaviour is unchanged: it stays keyed on the HTTP status.
46
+
47
+ - [#679](https://github.com/nansen-ai/nansen-cli/pull/679) [`5c8d22b`](https://github.com/nansen-ai/nansen-cli/commit/5c8d22bc52a23574de6138a396ea878ccfb5efca) Thanks [@0xShadowX](https://github.com/0xShadowX)! - Fail with an actionable error when a Solana RPC cannot return an SPL mint's decimals, instead of silently assuming 9 and building a transfer or limit order with a mis-scaled amount
48
+
49
+ - [#675](https://github.com/nansen-ai/nansen-cli/pull/675) [`938a011`](https://github.com/nansen-ai/nansen-cli/commit/938a0112cba40f9f80ced1569fd9d2e2f32db608) Thanks [@kome12](https://github.com/kome12)! - Reject malformed or negative profiler `--delay` and token `top-tokens --limit` values instead of partially parsing them.
50
+
51
+ - [#646](https://github.com/nansen-ai/nansen-cli/pull/646) [`3290e3c`](https://github.com/nansen-ai/nansen-cli/commit/3290e3cefa2c7c5e1405d09e4d5d860ca05d404f) Thanks [@gulshngill](https://github.com/gulshngill)! - `--table` and `--format csv` error output now includes the error `code`, HTTP `status`, and `details` instead of only the message. CSV errors are emitted as a header row plus one record; table errors keep the leading `Error:` line and add one `key: value` line per field.
52
+
53
+ - [#662](https://github.com/nansen-ai/nansen-cli/pull/662) [`7fd923f`](https://github.com/nansen-ai/nansen-cli/commit/7fd923ff4d58128c19e6995e015af6093dee7586) Thanks [@gulshngill](https://github.com/gulshngill)! - Sync the `chains` list reported by `nansen schema` (and mirrored in `--help` and the README) with the chains the Nansen API actually accepts. Drops `scroll` and `ronin`, which no endpoint serves any more, and adds the chains that were missing: `algorand`, `aptos`, `arc`, `bitcoin`, `bitlayer`, `chiliz`, `citrea`, `gravity`, `hyperliquid`, `injective`, `mantra`, `near`, `robinhood`, `stacks`, `starknet`, `stellar`, `sui`, `ton`, `tron`, `viction`. Not every chain is served by every endpoint; the API still validates `--chain` per endpoint.
54
+
55
+ - [#664](https://github.com/nansen-ai/nansen-cli/pull/664) [`d034ae1`](https://github.com/nansen-ai/nansen-cli/commit/d034ae1d01582f721e8572dcd40234d21b31708a) Thanks [@gulshngill](https://github.com/gulshngill)! - `trade quote` and `trade execute` now screen the signing wallet (and any distinct `--to-wallet` destination) against the compliance blocklist before requesting a quote or signing — the same fail-closed check `bridge` and `perp` already run — so a flagged address, or a screening call that fails, aborts the command before anything is signed or broadcast. Both commands now require API access for this check; authenticate with `nansen login` or `NANSEN_API_KEY` before trading.
56
+
57
+ - [#653](https://github.com/nansen-ai/nansen-cli/pull/653) [`337271d`](https://github.com/nansen-ai/nansen-cli/commit/337271d10d226cf61b24c18d656e955cd588d91d) Thanks [@Bruce039](https://github.com/Bruce039)! - `--sort` now rejects a direction other than `asc`/`desc` and an empty field name with an `INVALID_PARAMS` error. Previously `--sort pnl_usd:sideways` was uppercased and sent to the API as `direction: SIDEWAYS`, which only failed later with an upstream 422.
58
+
59
+ - [#648](https://github.com/nansen-ai/nansen-cli/pull/648) [`0514c76`](https://github.com/nansen-ai/nansen-cli/commit/0514c76029a6c0609743d8c4af87cbdf80d9bbff) Thanks [@kriss39](https://github.com/kriss39)! - Validate `token screener --search` and `token who-bought-sold --buy-or-sell` before the request is sent, so a JSON array/object or a repeated flag (`--search '[]'`, `--buy-or-sell '{}'`) and values outside the `BUY`/`SELL` enum produce an actionable `INVALID_PARAMS` error instead of a raw `.toLowerCase()`/`.toUpperCase()` TypeError.
60
+
61
+ - [#666](https://github.com/nansen-ai/nansen-cli/pull/666) [`6539558`](https://github.com/nansen-ai/nansen-cli/commit/65395584ab9844ec3f0117ef951b2eb26ff6342c) Thanks [@gulshngill](https://github.com/gulshngill)! - Make every wallet subcommand discoverable from the places agents look first. `nansen --help` now lists `send`, `forget-password` and `secure` on the wallet line (previously only seven of the nine were shown) and the full perp subcommand set (`transfer`, `approve-builder-fee`, `orders`, `account`, `meta`, `screener` and `leaderboard` were missing). It also stops describing the combined top-level `perp` command as a deprecated analytics alias. README lists the same wallet set, and `nansen schema wallet` now documents `forget-password` and `secure` with descriptions plus an example for every wallet subcommand. Help text, README, runtime command help and schema are pinned together by a new drift-guard test.
62
+
63
+ - [#677](https://github.com/nansen-ai/nansen-cli/pull/677) [`b91e108`](https://github.com/nansen-ai/nansen-cli/commit/b91e10878d8606aa419b71a12493fbd8d273e731) Thanks [@0xShadowX](https://github.com/0xShadowX)! - Read a pretty-printed WalletConnect `sign-typed-data` result on the x402 payment path instead of failing after the user has already approved the payment in their wallet
64
+
65
+ - [#673](https://github.com/nansen-ai/nansen-cli/pull/673) [`05a2056`](https://github.com/nansen-ai/nansen-cli/commit/05a20562edb6875541998db57ec47375e2dbb2ab) Thanks [@0xShadowX](https://github.com/0xShadowX)! - `web search --num-results` now rejects a malformed value (`5abc`, `2.5`, `abc`, a repeated or valueless flag) with `INVALID_PARAMS`. Previously `5abc` was silently truncated to 5, `2.5` to 2, and a non-numeric value fell back to the API default instead of reporting the mistake.
66
+
3
67
  ## 1.45.0
4
68
 
5
69
  ### Minor Changes
package/README.md CHANGED
@@ -72,7 +72,7 @@ Plus the `historical-*` point-in-time commands — run `nansen research help` fo
72
72
 
73
73
  **Trade:** `quote`, `execute`, `bridge-status`, `limit-order` — DEX swaps on Solana and Base, cross-chain bridges, and Solana limit orders.
74
74
 
75
- **Wallet:** `create`, `list`, `show`, `export`, `default`, `delete`, `send` — local or Privy server-side wallets (EVM + Solana).
75
+ **Wallet:** `create`, `list`, `show`, `export`, `default`, `delete`, `send`, `forget-password`, `secure` — local or Privy server-side wallets (EVM + Solana).
76
76
 
77
77
  Run `nansen schema --pretty` for the full subcommand and field reference.
78
78
 
@@ -163,6 +163,24 @@ nansen trade execute --quote <quoteId> --gasless # Relay-only: solver pays
163
163
  nansen trade bridge-status --tx-hash <hash> --from-chain base --to-chain solana
164
164
  ```
165
165
 
166
+ ### Before broadcasting
167
+
168
+ `trade execute` and `bridge execute` move funds irreversibly, so both accept:
169
+
170
+ ```bash
171
+ nansen trade execute --quote <quoteId> --dry-run # validate + print the plan, broadcast nothing
172
+ nansen trade execute --quote <quoteId> --yes # skip the confirmation prompt (also: -y)
173
+ ```
174
+
175
+ `--dry-run` runs every sign-free preflight available from the cached quote, its public signer address, and read-only RPC calls; prints what *would* be sent (chain, tokens, amounts, recipient, approvals, fees); and stops before wallet credentials, signing, or broadcast — no wallet password needed, the quote stays usable, exit code 0. Real execution still resolves and revalidates the live signer before signing.
176
+
177
+ When stdin is an interactive terminal, execute prints that plan and asks `Broadcast this transaction? [y/N]` first; anything but `y`/`yes` aborts with exit code 1 and nothing signed. `--yes`, or `NANSEN_YES=1`, skips the question. **When stdin is not a terminal — agents, CI, pipes — nothing changes: the command proceeds without prompting**, and `--yes` is accepted as a no-op so it is always safe to pass.
178
+
179
+ | Exit code | Meaning |
180
+ |-----------|---------|
181
+ | `0` | Broadcast succeeded, or the dry run completed |
182
+ | `1` | Declined at the confirmation prompt, or the execution failed |
183
+
166
184
  Amounts are in base units (lamports, wei) by default — use `--amount-unit token|usd|percent` for friendlier inputs. Common symbols (`SOL`, `ETH`, `USDC`, `USDT`) resolve automatically. A wallet is required — set one with `nansen wallet default <name>`.
167
185
 
168
186
  ## Limit Orders
@@ -213,11 +231,12 @@ Move USDC between EVM chains and Hyperliquid via `nansen bridge`. Uses the same
213
231
  ```bash
214
232
  nansen bridge quote --from-chain base --to-chain hyperliquid --from-token USDC --amount 1000000
215
233
  nansen bridge execute --quote <quoteId>
234
+ nansen bridge execute --quote <quoteId> --dry-run # preview, nothing is broadcast
216
235
  nansen bridge execute --quote <quoteId> --nonce 20 --priority-fee 5 # replace a stuck EVM deposit
217
236
  nansen bridge status --request-id <id>
218
237
  ```
219
238
 
220
- Supported routes: `base → hyperliquid` (deposit), and `hyperliquid → base`/`ethereum`/`arbitrum` (withdraw). Deposits broadcast an EVM transaction locally, so only Base is offered on the deposit side; run `nansen bridge help` for the current list. `--amount` is a base-unit integer by default; pass `--amount-unit token` for a human amount. `--recipient` defaults to the wallet's own EVM address. `--priority-fee`/`--max-fee` (gwei) and `--nonce` apply only to EVM deposit legs and let a stuck transaction be replaced. Bridge transfers are irreversible once signed.
239
+ Supported routes: `base → hyperliquid` (deposit), and `hyperliquid → base`/`ethereum`/`arbitrum` (withdraw). Deposits broadcast an EVM transaction locally, so only Base is offered on the deposit side; run `nansen bridge help` for the current list. `--amount` is a base-unit integer by default; pass `--amount-unit token` for a human amount. `--recipient` defaults to the wallet's own EVM address. `--priority-fee`/`--max-fee` (gwei) and `--nonce` apply only to EVM deposit legs and let a stuck transaction be replaced. Bridge transfers are irreversible once signed, so `bridge execute` takes the same `--dry-run` and `--yes`/`NANSEN_YES` gate as `trade execute` (see [Before broadcasting](#before-broadcasting)); on a multi-step transfer, a dry run stops before the first step.
221
240
 
222
241
  ## Wallet
223
242
 
@@ -227,6 +246,8 @@ nansen wallet create --name my-wallet --provider privy # server-side via Privy
227
246
  nansen wallet list
228
247
  nansen wallet default <name>
229
248
  nansen wallet send --wallet <name> --to <addr> --amount <n> --chain <chain>
249
+ nansen wallet secure # move a saved password into the OS keychain
250
+ nansen wallet forget-password # drop the saved password from every store
230
251
  ```
231
252
 
232
253
  **Local wallets** are password-encrypted. Set `NANSEN_WALLET_PASSWORD` to skip the prompt.
@@ -296,7 +317,7 @@ after upgrading the CLI to pick up new commands.
296
317
  | `--chain <chain>` | Blockchain to query |
297
318
  | `--limit <n>` | Result count |
298
319
  | `--timeframe <tf>` | Time window: `5m` `1h` `6h` `24h` `7d` `30d` |
299
- | `--fields <list>` | Comma-separated fields (reduces response size) |
320
+ | `--fields <list>` | Comma-separated fields (reduces response size); a bare name matches at any depth, a dotted path such as `data.results.address` only at that position |
300
321
  | `--sort <field:dir>` | Sort results, e.g. `--sort value_usd:desc` |
301
322
  | `--pretty` | Human-readable JSON |
302
323
  | `--table` | Table format |
@@ -306,7 +327,7 @@ after upgrading the CLI to pick up new commands.
306
327
 
307
328
  ## Supported Chains
308
329
 
309
- `ethereum` `solana` `base` `bnb` `arbitrum` `polygon` `optimism` `avalanche` `linea` `scroll` `mantle` `ronin` `sei` `plasma` `sonic` `monad` `hyperevm` `iotaevm`
330
+ `algorand` `aptos` `arbitrum` `arc` `avalanche` `base` `bitcoin` `bitlayer` `bnb` `chiliz` `citrea` `ethereum` `gravity` `hyperevm` `hyperliquid` `injective` `iotaevm` `linea` `mantle` `mantra` `monad` `near` `optimism` `plasma` `polygon` `robinhood` `sei` `solana` `sonic` `stacks` `starknet` `stellar` `sui` `ton` `tron` `viction`
310
331
 
311
332
  > Run `nansen schema` to get the current chain list (source of truth).
312
333
 
@@ -336,9 +357,13 @@ nansen research smart-money netflow --chain solana --fields token_symbol,net_flo
336
357
  | `UNAUTHORIZED` | Wrong or missing key. Re-auth. |
337
358
  | `RATE_LIMITED` | Auto-retried by CLI. `details.rateLimit.resetSeconds` is how long the window needs to drain. |
338
359
  | `UNSUPPORTED_FILTER` | Remove the filter and retry. |
360
+ | `PLAN_UPGRADE_REQUIRED` | The endpoint or option needs a higher subscription plan. Do not retry. |
361
+ | `GEO_BLOCKED` | Not available in your region. Do not retry. |
339
362
  | `SERVER_ERROR` | Not your fault. Quote `details.requestId` when reporting it. |
340
363
  | `COMMAND_UNAVAILABLE` | The command is no longer available. For points leaderboard, run `nansen research` to explore other analytics commands. |
341
364
 
365
+ Every code documented on the API's [error-handling page](https://docs.nansen.ai/getting-started/error-handling) maps onto a stable CLI error code; a code the CLI does not recognise is passed through unchanged.
366
+
342
367
  **Error metadata.** When the API reports them, `details` carries:
343
368
 
344
369
  | Field | Meaning |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nansen-cli",
3
- "version": "1.45.0",
3
+ "version": "1.46.0",
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",
@@ -54,8 +54,23 @@ For cross-chain swaps, each token is checked against its own chain (from vs `--c
54
54
 
55
55
  ```bash
56
56
  nansen trade execute --quote <quote-id>
57
+ nansen trade execute --quote <quote-id> --dry-run # preview only, nothing is broadcast
58
+ nansen trade execute --quote <quote-id> --yes # skip the confirmation prompt
57
59
  ```
58
60
 
61
+ **`--dry-run`** runs every sign-free preflight available from the cached quote, its public signer address, and read-only RPC calls; prints the trade that *would* be sent (chain, tokens, amounts, recipient, approval, fees); and stops before wallet credentials or signing. No wallet password is needed, the quote is not consumed, and the command exits 0. Real execution still resolves and revalidates the live signer. On Base, preview also reads the current token allowance and runs the pre-broadcast revert simulation when no approval is outstanding.
62
+
63
+ **Confirmation.** When stdin is an interactive terminal, `execute` prints the plan and asks `Broadcast this transaction? [y/N]` before broadcasting. Answering anything but `y`/`yes` aborts with exit code 1 and nothing signed. Pass `--yes` (`-y`), or set `NANSEN_YES=1`, to skip the question.
64
+
65
+ **Agents and CI are unaffected:** when stdin is *not* a terminal (a pipe, a CI job, an agent shell) the command proceeds without prompting, exactly as before. `--yes` is accepted there and is simply a no-op, so it is safe to always pass it. The same flags and rules apply to `nansen bridge execute`.
66
+
67
+ ### Exit codes (`trade execute`, `bridge execute`)
68
+
69
+ | Code | Meaning |
70
+ |------|---------|
71
+ | `0` | Broadcast succeeded, or the dry run completed |
72
+ | `1` | Declined at the confirmation prompt, or the execution failed |
73
+
59
74
  ## Cross-Chain Swap
60
75
 
61
76
  Bridge tokens between Solana and Base using `--to-chain`:
@@ -167,6 +182,8 @@ If the user says "$20 worth of X", use `--amount-unit usd` directly — no manua
167
182
  | `--wallet` | Wallet name (default: default wallet) |
168
183
  | `--quote-index` | Pin a specific quote by index (0-based) when multiple quotes were returned |
169
184
  | `--no-simulate` | Skip pre-broadcast simulation |
185
+ | `--dry-run` | Validate and print what would be sent, then stop. Nothing is signed or broadcast |
186
+ | `--yes`, `-y` | Skip the confirmation prompt (same as `NANSEN_YES=1`); no-op when stdin is not a terminal |
170
187
 
171
188
  ### `trade bridge-status` flags
172
189
 
@@ -181,7 +198,8 @@ If the user says "$20 worth of X", use `--amount-unit usd` directly — no manua
181
198
  | Var | Purpose |
182
199
  |-----|---------|
183
200
  | `NANSEN_WALLET_PASSWORD` | **Required for `trade execute`.** Wallet encryption password — persisted in `~/.nansen/.env`. Source before executing: `source ~/.nansen/.env && nansen trade execute ...` |
184
- | `NANSEN_API_KEY` | API key (also set via `nansen login`) |
201
+ | `NANSEN_API_KEY` | API key (also set via `nansen login`). `trade quote` and `trade execute` need it for the pre-trade compliance screen below. |
202
+ | `NANSEN_YES` | Set to `1` to skip the `execute` confirmation prompt, like `--yes` |
185
203
 
186
204
  > **Agents:** Never hold a wallet password only in session memory. If `NANSEN_WALLET_PASSWORD` is not in `~/.nansen/.env`, follow the setup flow in the nansen-wallet-manager skill Password Policy to generate and persist one before proceeding.
187
205
 
@@ -189,6 +207,7 @@ If the user says "$20 worth of X", use `--amount-unit usd` directly — no manua
189
207
 
190
208
  - Quotes expire after ~1 hour. If execute fails, get a fresh quote.
191
209
  - A wallet is required even for quotes (the API builds sender-specific transactions).
210
+ - Compliance screen: `trade quote` and `trade execute` check the signing wallet (and any distinct `--to-wallet` destination) against the compliance blocklist through the Nansen API before requesting a quote or signing — the same fail-closed check `bridge` and `perp` run. A flagged address aborts with code `SANCTIONED`; if the screening call itself fails the command aborts with `SCREENING_UNAVAILABLE`. Nothing is signed or broadcast in either case.
192
211
  - ERC-20 swaps may require an approval step — execute handles this automatically.
193
212
 
194
213
  # Perp Trading
@@ -50,7 +50,7 @@ Interpret `x402.password.source`:
50
50
  - `null` → password not persisted anywhere (Path C or D)
51
51
  - `"env"` → `NANSEN_WALLET_PASSWORD` is set; check where it is being exported from (a `.env` file → Path A)
52
52
 
53
- Do NOT use `nansen wallet export` to probe the password state — it prints private keys.
53
+ Do NOT use `nansen wallet export` to probe the password state — the default is redacted and never loads the password, so it proves nothing (and `--reveal` prints private keys).
54
54
 
55
55
  ## Migration paths
56
56
 
@@ -76,13 +76,15 @@ source ~/.nansen/.env 2>/dev/null && nansen wallet secure
76
76
  **Step 3 — Verify the password actually decrypts the wallet:**
77
77
 
78
78
  ```bash
79
- # Unset env var to prove keychain works, then export to verify decryption
79
+ # Unset env var to prove keychain works, then run a decrypting export with
80
+ # all output discarded — the exit code alone is the signal, so no key
81
+ # material can land in a transcript or log
80
82
  unset NANSEN_WALLET_PASSWORD
81
- nansen wallet export default 2>&1
83
+ if nansen wallet export default --reveal > /dev/null 2>&1; then echo "decryption OK"; else echo "decryption FAILED"; fi
82
84
  ```
83
85
 
84
- If export succeeds (shows private keys), the migration worked. If it shows
85
- `Incorrect password`, the wrong password was migrated — run `nansen wallet
86
+ If the export exits 0 (`decryption OK`), the migration worked. If it fails,
87
+ the wrong password was migrated — run `nansen wallet
86
88
  forget-password` and retry with the correct password.
87
89
 
88
90
  **Step 4 — Clean up the insecure file:**
@@ -102,10 +104,11 @@ nansen wallet secure
102
104
  If the keychain is still unavailable (e.g. containerized Linux without D-Bus),
103
105
  `nansen wallet secure` will explain the situation and suggest alternatives.
104
106
 
105
- After migrating, verify decryption works:
107
+ After migrating, verify decryption works (output discarded on purpose —
108
+ branch on the exit code):
106
109
 
107
110
  ```bash
108
- nansen wallet export default 2>&1
111
+ if nansen wallet export default --reveal > /dev/null 2>&1; then echo "decryption OK"; else echo "decryption FAILED"; fi
109
112
  ```
110
113
 
111
114
  ### Path C: Password only in `NANSEN_WALLET_PASSWORD` env var
@@ -115,11 +118,12 @@ nansen wallet export default 2>&1
115
118
  nansen wallet secure
116
119
  ```
117
120
 
118
- Then verify without the env var:
121
+ Then verify without the env var (exit code is the signal; output is
122
+ discarded so no keys are disclosed):
119
123
 
120
124
  ```bash
121
125
  unset NANSEN_WALLET_PASSWORD
122
- nansen wallet export default 2>&1
126
+ if nansen wallet export default --reveal > /dev/null 2>&1; then echo "decryption OK"; else echo "decryption FAILED"; fi
123
127
  ```
124
128
 
125
129
  ### Path D: Password lost entirely
@@ -147,11 +151,12 @@ the keychain password can actually decrypt the wallet:
147
151
  # Unset env var to prove keychain works
148
152
  unset NANSEN_WALLET_PASSWORD
149
153
 
150
- # This MUST succeed — it proves the keychain password decrypts the wallet
151
- nansen wallet export default 2>&1
154
+ # This MUST exit 0 — it proves the keychain password decrypts the wallet.
155
+ # Output is discarded on purpose: the exit code alone is the signal.
156
+ if nansen wallet export default --reveal > /dev/null 2>&1; then echo "decryption OK"; else echo "decryption FAILED"; fi
152
157
  ```
153
158
 
154
- If export shows `Incorrect password`, the wrong password was saved to the
159
+ If the export fails, the wrong password was saved to the
155
160
  keychain. Fix with:
156
161
 
157
162
  ```bash
@@ -182,4 +187,4 @@ wallet operations will require `NANSEN_WALLET_PASSWORD` env var or re-running
182
187
  - **NEVER use `--human` flag** — interactive prompts break agents
183
188
  - If the human authorizes reading `~/.nansen/.env`, read it in the same command
184
189
  (`source ~/.nansen/.env && nansen wallet secure`) — do not echo or log the value
185
- - **ALWAYS verify after migration** with `nansen wallet export default` — `wallet show` does NOT prove the password works (it never loads the password)
190
+ - **ALWAYS verify after migration** with `nansen wallet export default --reveal > /dev/null 2>&1` (branch on the exit code; never let the output print) — `wallet show` does NOT prove the password works (it never loads the password)
@@ -152,11 +152,23 @@ nansen wallet send --to <addr> --amount 1.0 --chain evm --dry-run
152
152
  ## Export & Delete
153
153
 
154
154
  ```bash
155
- # Password auto-resolved from keychain
155
+ # Default is REDACTED — shows addresses only, never private keys
156
156
  nansen wallet export <name>
157
+
158
+ # Write private keys to a file only the owner can read (0600, refuses to overwrite)
159
+ nansen wallet export <name> --file <path>
160
+
161
+ # Print private keys in plaintext to stdout (explicit acknowledgement required;
162
+ # warns on stderr when stdout is an interactive terminal)
163
+ nansen wallet export <name> --reveal
164
+
165
+ # Password auto-resolved from keychain (needed for --reveal / --file)
157
166
  nansen wallet delete <name>
158
167
  ```
159
168
 
169
+ Prefer `--file` over `--reveal`: plaintext on stdout ends up in terminal
170
+ scrollback, shell logs, and agent transcripts.
171
+
160
172
  ## Forget Password
161
173
 
162
174
  ```bash
@@ -182,6 +194,8 @@ For detailed migration steps (from `~/.nansen/.env`, `.credentials`, or env-var-
182
194
  | `--max` | Send entire balance |
183
195
  | `--dry-run` | Preview without broadcasting |
184
196
  | `--provider` | Wallet provider: `local` (default, encrypted on disk) or `privy` (server-side via Privy API) |
197
+ | `--reveal` | Export only: print private keys in plaintext to stdout (required acknowledgement) |
198
+ | `--file` | Export only: write private keys to this path (created 0600, refuses to overwrite) |
185
199
  | `--human` | Enable interactive prompts (human terminal use only — agents must NOT use this) |
186
200
  | `--unsafe-no-password` | Skip encryption (keys stored in plaintext — NOT recommended) |
187
201
 
package/src/api.js CHANGED
@@ -8,7 +8,7 @@ import path from 'path';
8
8
  import { fileURLToPath } from 'url';
9
9
  import { EVM_CHAINS } from './chain-ids.js';
10
10
  import { getAnonymousId, TELEMETRY_DISABLED } from './telemetry.js';
11
- import { readResponseMeta } from './response-meta.js';
11
+ import { readResponseMeta, stringHeader } from './response-meta.js';
12
12
 
13
13
  /**
14
14
  * Key for the credit/rate-limit metadata attached to a successful response.
@@ -50,6 +50,8 @@ export const ErrorCode = {
50
50
  UNAUTHORIZED: 'UNAUTHORIZED', // 401 - Invalid or missing API key
51
51
  FORBIDDEN: 'FORBIDDEN', // 403 - Valid key but insufficient permissions
52
52
  CREDITS_EXHAUSTED: 'CREDITS_EXHAUSTED', // 403 - Insufficient API credits
53
+ PLAN_UPGRADE_REQUIRED: 'PLAN_UPGRADE_REQUIRED', // 403 - Feature needs a higher subscription plan
54
+ GEO_BLOCKED: 'GEO_BLOCKED', // 451 - Not available in the caller's region
53
55
  PAYMENT_REQUIRED: 'PAYMENT_REQUIRED', // 402 - x402 payment required
54
56
 
55
57
  // Rate Limiting
@@ -62,11 +64,15 @@ export const ErrorCode = {
62
64
  INVALID_PARAMS: 'INVALID_PARAMS', // Generic parameter validation error
63
65
  MISSING_PARAM: 'MISSING_PARAM', // Required parameter not provided
64
66
  UNSUPPORTED_FILTER: 'UNSUPPORTED_FILTER', // Filter not supported for this token/chain
67
+ QUERY_TOO_LARGE: 'QUERY_TOO_LARGE', // Query would return too much data - narrow it; retrying will not help
68
+ PAYLOAD_TOO_LARGE: 'PAYLOAD_TOO_LARGE', // 413 - Request body exceeds the size limit
65
69
 
66
70
  // Resource Errors
67
71
  NOT_FOUND: 'NOT_FOUND', // 404 - Resource not found
68
72
  TOKEN_NOT_FOUND: 'TOKEN_NOT_FOUND', // Token doesn't exist
69
73
  ADDRESS_NOT_FOUND: 'ADDRESS_NOT_FOUND', // Address has no data
74
+ METHOD_NOT_ALLOWED: 'METHOD_NOT_ALLOWED', // 405 - HTTP method not allowed for this endpoint
75
+ CONFLICT: 'CONFLICT', // 409 - Request conflicts with the current state
70
76
 
71
77
  // Server Errors
72
78
  SERVER_ERROR: 'SERVER_ERROR', // 500+ - Nansen API internal error
@@ -96,8 +102,8 @@ export const ErrorCode = {
96
102
  * parse (e.g. PASSWORD_REQUIRED, API_KEY_REQUIRED).
97
103
  */
98
104
  export class CommandError extends Error {
99
- constructor(message, code = 'COMMAND_ERROR', data = null) {
100
- super(message);
105
+ constructor(message, code = 'COMMAND_ERROR', data = null, options = undefined) {
106
+ super(message, options); // options.cause keeps the originating error attached
101
107
  this.name = 'CommandError';
102
108
  this.code = code;
103
109
  this.data = data;
@@ -127,16 +133,46 @@ export class NansenError extends Error {
127
133
  }
128
134
 
129
135
  /**
130
- * Stable snake_case codes the server sends in error bodies, mapped to the
136
+ * Stable snake_case codes the API sends in error bodies, mapped to the
131
137
  * ErrorCode values downstream consumers already key on.
138
+ *
139
+ * Every code documented at
140
+ * https://docs.nansen.ai/getting-started/error-handling has an entry here, so
141
+ * friendly messages and agent-facing hints engage for each of them. A code
142
+ * missing from this map passes through statusToErrorCode verbatim; keep the
143
+ * table in step with that page when the API adds a code.
132
144
  */
133
- const SERVER_CODE_MAP = {
134
- rate_limit_exceeded: ErrorCode.RATE_LIMITED,
135
- insufficient_credits: ErrorCode.CREDITS_EXHAUSTED,
136
- payment_required: ErrorCode.PAYMENT_REQUIRED,
137
- unauthorized: ErrorCode.UNAUTHORIZED,
145
+ export const SERVER_CODE_MAP = {
146
+ // Request validation (400 / 422)
147
+ missing_field: ErrorCode.MISSING_PARAM,
148
+ unknown_field: ErrorCode.INVALID_PARAMS,
149
+ invalid_field_value: ErrorCode.INVALID_PARAMS,
150
+ invalid_address_format: ErrorCode.INVALID_ADDRESS,
151
+ invalid_date_format: ErrorCode.INVALID_PARAMS,
152
+ invalid_date_range: ErrorCode.INVALID_PARAMS,
153
+ mutually_exclusive_fields: ErrorCode.INVALID_PARAMS,
154
+ value_out_of_range: ErrorCode.INVALID_PARAMS,
155
+ too_many_items: ErrorCode.INVALID_PARAMS,
156
+ // Authentication, authorization, quota
157
+ unauthenticated: ErrorCode.UNAUTHORIZED,
138
158
  forbidden: ErrorCode.FORBIDDEN,
159
+ geo_blocked: ErrorCode.GEO_BLOCKED,
160
+ plan_upgrade_required: ErrorCode.PLAN_UPGRADE_REQUIRED,
161
+ insufficient_credits: ErrorCode.CREDITS_EXHAUSTED,
162
+ rate_limit_exceeded: ErrorCode.RATE_LIMITED,
163
+ // Resource and request shape
139
164
  not_found: ErrorCode.NOT_FOUND,
165
+ method_not_allowed: ErrorCode.METHOD_NOT_ALLOWED,
166
+ conflict: ErrorCode.CONFLICT,
167
+ payload_too_large: ErrorCode.PAYLOAD_TOO_LARGE,
168
+ // Server side
169
+ query_timeout: ErrorCode.TIMEOUT,
170
+ query_too_large: ErrorCode.QUERY_TOO_LARGE,
171
+ upstream_unavailable: ErrorCode.SERVICE_UNAVAILABLE,
172
+ internal_error: ErrorCode.SERVER_ERROR,
173
+ // Aliases from earlier error-body shapes, kept so older responses still map.
174
+ unauthorized: ErrorCode.UNAUTHORIZED,
175
+ payment_required: ErrorCode.PAYMENT_REQUIRED,
140
176
  unsupported_filter: ErrorCode.UNSUPPORTED_FILTER,
141
177
  validation_error: ErrorCode.INVALID_PARAMS,
142
178
  invalid_params: ErrorCode.INVALID_PARAMS,
@@ -183,8 +219,18 @@ export function statusToErrorCode(status, data = {}) {
183
219
  if (messageLower.includes('token')) return ErrorCode.TOKEN_NOT_FOUND;
184
220
  if (messageLower.includes('address') || messageLower.includes('wallet')) return ErrorCode.ADDRESS_NOT_FOUND;
185
221
  return ErrorCode.NOT_FOUND;
222
+ case 405:
223
+ return ErrorCode.METHOD_NOT_ALLOWED;
224
+ case 408:
225
+ return ErrorCode.TIMEOUT;
226
+ case 409:
227
+ return ErrorCode.CONFLICT;
228
+ case 413:
229
+ return ErrorCode.PAYLOAD_TOO_LARGE;
186
230
  case 429:
187
231
  return ErrorCode.RATE_LIMITED;
232
+ case 451:
233
+ return ErrorCode.GEO_BLOCKED;
188
234
  case 500:
189
235
  case 502:
190
236
  return ErrorCode.SERVER_ERROR;
@@ -397,9 +443,8 @@ export const COUNTERPARTIES_BATCH_MAX_DAYS = 90;
397
443
  * validates `chain` against. Anything outside it is a 422.
398
444
  *
399
445
  * Deliberately NOT derived from EVM_CHAINS. That list is this CLI's own
400
- * address-format/ENS set and disagrees with the endpoint in both directions: it
401
- * carries `scroll` and `ronin`, which the endpoint rejects, and omits every
402
- * non-EVM chain the endpoint does serve (bitcoin, tron, sui, ton, near, ...).
446
+ * address-format/ENS set and omits every non-EVM chain the endpoint does serve
447
+ * (bitcoin, tron, sui, ton, near, ...).
403
448
  * Mirrors ADDRESS_COUNTERPARTIES_BATCH_CHAINS on the MCP side (nansen-ra#3550),
404
449
  * which additionally drops `arc` and `starknet`; the spec enum is the contract
405
450
  * here, so they stay in.
@@ -586,9 +631,35 @@ const DEFAULT_RETRY_OPTIONS = {
586
631
  maxRetries: 3,
587
632
  baseDelayMs: 1000,
588
633
  maxDelayMs: 30000,
634
+ // Longest server Retry-After we are willing to wait out. A longer one is not
635
+ // retried at all: retrying earlier than the server asked only burns the
636
+ // remaining attempts on more 429s.
637
+ maxRetryAfterMs: 120000,
589
638
  retryOnStatus: [429, 500, 502, 503, 504],
590
639
  };
591
640
 
641
+ /**
642
+ * Read a response body once. A fetch body can only be consumed once, and
643
+ * response.json() consumes it even when parsing fails, so a body the server
644
+ * declares as non-JSON (gateway HTML, plain text) is read as text first. It
645
+ * is still parsed as JSON when it turns out to be JSON; otherwise the thrown
646
+ * error carries the text so the caller can report it.
647
+ */
648
+ async function readBody(response) {
649
+ const contentType = stringHeader(response, 'content-type');
650
+ if (contentType && !/json/i.test(contentType)) {
651
+ const rawBody = await response.text();
652
+ try {
653
+ return JSON.parse(rawBody);
654
+ } catch (_err) {
655
+ const error = new Error('Response body is not JSON');
656
+ error.rawBody = rawBody;
657
+ throw error;
658
+ }
659
+ }
660
+ return response.json();
661
+ }
662
+
592
663
  /**
593
664
  * Sleep for a given number of milliseconds
594
665
  */
@@ -600,10 +671,12 @@ export function sleep(ms) {
600
671
  * Calculate delay with exponential backoff and jitter
601
672
  */
602
673
  function calculateBackoff(attempt, baseDelayMs, maxDelayMs, retryAfterMs = null) {
603
- // If server specifies retry-after, use it (with some jitter)
604
- if (retryAfterMs) {
674
+ // If server specifies retry-after, wait at least that long (plus some jitter).
675
+ // maxDelayMs only bounds the local exponential backoff; the caller decides
676
+ // whether a Retry-After is too long to wait for at all.
677
+ if (retryAfterMs !== null && retryAfterMs !== undefined) {
605
678
  const jitter = Math.random() * 1000;
606
- return Math.min(retryAfterMs + jitter, maxDelayMs);
679
+ return retryAfterMs + jitter;
607
680
  }
608
681
 
609
682
  // Exponential backoff: base * 2^attempt + random jitter
@@ -795,7 +868,7 @@ export class NansenAPI {
795
868
  async request(endpoint, body = {}, options = {}) {
796
869
  this.lastEndpoint = endpoint;
797
870
  const url = `${this.baseUrl}${endpoint}`;
798
- const { maxRetries, baseDelayMs, maxDelayMs, retryOnStatus } = this.retryOptions;
871
+ const { maxRetries, baseDelayMs, maxDelayMs, maxRetryAfterMs, retryOnStatus } = this.retryOptions;
799
872
  const shouldRetry = options.retry !== false; // Allow disabling retry per-request
800
873
 
801
874
  // Check cache first (if enabled and not bypassed)
@@ -862,24 +935,31 @@ export class NansenAPI {
862
935
 
863
936
  let data;
864
937
  try {
865
- data = await response.json();
866
- } catch (_err) {
938
+ data = await readBody(response);
939
+ } catch (err) {
867
940
  // Non-JSON response (rare, usually server errors)
868
941
  const meta = readResponseMeta(response);
869
942
  this.lastResponseMeta = meta;
943
+ // readBody already holds the text when the server declared a non-JSON
944
+ // body; otherwise try to read it now (null once json() consumed it).
945
+ const rawBody = err?.rawBody ?? await response.text().catch(() => null);
946
+ const retryAfterMs = parseRetryAfter(stringHeader(response, 'retry-after'));
870
947
  const error = new NansenError(
871
948
  `Invalid response from API (status ${response.status})`,
872
- response.status >= 500 ? ErrorCode.SERVER_ERROR : ErrorCode.UNKNOWN,
949
+ statusToErrorCode(response.status, {}),
873
950
  response.status,
874
951
  {
875
- body: await response.text().catch(() => null),
952
+ body: rawBody,
876
953
  attempt: attempt + 1,
954
+ retryAfterMs,
877
955
  ...(meta?.requestId && { requestId: meta.requestId })
878
956
  }
879
957
  );
880
958
 
881
- if (shouldRetry && attempt < maxRetries && response.status >= 500) {
882
- const delayMs = calculateBackoff(attempt, baseDelayMs, maxDelayMs);
959
+ // Same retry policy as a JSON error body: a rate limiter or gateway
960
+ // that answers in plain text or HTML is still a 429/5xx.
961
+ if (shouldRetry && attempt < maxRetries && retryOnStatus.includes(response.status)) {
962
+ const delayMs = calculateBackoff(attempt, baseDelayMs, maxDelayMs, retryAfterMs);
883
963
  await sleep(delayMs);
884
964
  lastError = error;
885
965
  continue;
@@ -1030,9 +1110,18 @@ export class NansenAPI {
1030
1110
  ...(meta?.rateLimit && { rateLimit: meta.rateLimit })
1031
1111
  });
1032
1112
 
1033
- // Retry on specific status codes
1034
- if (shouldRetry && attempt < maxRetries && retryOnStatus.includes(response.status)) {
1035
- const delayMs = calculateBackoff(attempt, baseDelayMs, maxDelayMs, retryAfterMs);
1113
+ // Retry on specific status codes. A 429 Retry-After is binding: retrying
1114
+ // earlier only burns attempts on more 429s, so wait it out in full or,
1115
+ // if it is longer than we are willing to block, give up right away (the
1116
+ // error already carries retryAfterMs so the caller can come back later).
1117
+ // A Retry-After on a 5xx is only advisory and keeps the old maxDelayMs cap.
1118
+ const isRateLimit = response.status === 429;
1119
+ if (shouldRetry && attempt < maxRetries && retryOnStatus.includes(response.status)
1120
+ && !(isRateLimit && retryAfterMs !== null && retryAfterMs > maxRetryAfterMs)) {
1121
+ const serverDelayMs = retryAfterMs === null || isRateLimit
1122
+ ? retryAfterMs
1123
+ : Math.min(retryAfterMs, maxDelayMs);
1124
+ const delayMs = calculateBackoff(attempt, baseDelayMs, maxDelayMs, serverDelayMs);
1036
1125
  await sleep(delayMs);
1037
1126
  continue;
1038
1127
  }
@@ -2038,7 +2127,10 @@ export class NansenAPI {
2038
2127
  }
2039
2128
 
2040
2129
  async alertsUpdate(params = {}) {
2041
- return this.request('/api/v1/smart-alert', params, { method: 'PATCH', cache: false });
2130
+ // Same hazard as alertsCreate: an update that sets channels makes the
2131
+ // server re-send the channel welcome message, so a lost response after a
2132
+ // committed update must not resend the PATCH through the retry loop.
2133
+ return this.request('/api/v1/smart-alert', params, { method: 'PATCH', cache: false, retry: false });
2042
2134
  }
2043
2135
 
2044
2136
  async alertsToggle(params = {}) {