nansen-cli 2.6.0 → 2.6.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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.6.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#834](https://github.com/nansen-ai/nansen-cli/pull/834) [`c2e511e`](https://github.com/nansen-ai/nansen-cli/commit/c2e511efbbfc32174083dc9b3f00eda8e0fef519) Thanks [@kome12](https://github.com/kome12)! - `nansen schema` and shell completion now list the type-specific filter options of `alerts create` and `alerts update` (flow thresholds, token, sector, market cap, FDV, event, value and subject filters), with the alert types each one applies to.
8
+
9
+ - [#841](https://github.com/nansen-ai/nansen-cli/pull/841) [`9888c7a`](https://github.com/nansen-ai/nansen-cli/commit/9888c7a3ed3a624fc465965104434d91aa9db221) Thanks [@kome12](https://github.com/kome12)! - `bridge execute` now refuses a Hyperliquid withdrawal quote that has more than one withdrawal leg, or whose withdrawal is not sent to Relay's deposit address, before signing anything.
10
+
11
+ - [#843](https://github.com/nansen-ai/nansen-cli/pull/843) [`16413a9`](https://github.com/nansen-ai/nansen-cli/commit/16413a9f6685d78997b41ec7020d80fd79ef7cf0) Thanks [@kome12](https://github.com/kome12)! - `trade execute` now refuses a native-token EVM swap whose transaction value does not match the quote's input amount (the same field the request check reads) or exceeds the maximum spend saved with the quote, even when swap-outcome verification is off.
12
+
13
+ - [#839](https://github.com/nansen-ai/nansen-cli/pull/839) [`f621b35`](https://github.com/nansen-ai/nansen-cli/commit/f621b35c67ab27194925d3e2bbec8f330d10e764) Thanks [@kome12](https://github.com/kome12)! - `nansen perp transfer` and `nansen perp approve-builder-fee` now honour `--dry-run` and `--yes` like the other perp commands that change state: `--dry-run` prints the plan and signs nothing, an interactive terminal asks before signing, and `NANSEN_REQUIRE_CONFIRM=1` applies off a terminal. Previously both signed and submitted even with `--dry-run`.
14
+
15
+ `perp transfer` also refuses an `--amount` it cannot sign exactly (more than 8 decimal places, or too large to hold exactly) instead of rounding it.
16
+
17
+ - [#842](https://github.com/nansen-ai/nansen-cli/pull/842) [`020c455`](https://github.com/nansen-ai/nansen-cli/commit/020c455a1a151bdefb04891d42d4aa2f703b627e) Thanks [@kome12](https://github.com/kome12)! - Pin the runtime dependencies (`@noble/curves`, `@noble/hashes`, `@scure/base`, `@ethereumjs/rlp`) to exact versions, so a global install no longer picks up a newly published release of a signing library before it has been reviewed.
18
+
19
+ - [#835](https://github.com/nansen-ai/nansen-cli/pull/835) [`197996b`](https://github.com/nansen-ai/nansen-cli/commit/197996b565823ca4e4239dc3dd2376ca510c3eff) Thanks [@kome12](https://github.com/kome12)! - `wallet send --dry-run` from a Privy wallet now rejects a malformed, zero or too-small SPL token amount on Solana, as the real send does, instead of previewing it as a success.
20
+
21
+ - [#837](https://github.com/nansen-ai/nansen-cli/pull/837) [`478eab1`](https://github.com/nansen-ai/nansen-cli/commit/478eab1d4630db3f6b28eccb07b10845864bba42) Thanks [@kome12](https://github.com/kome12)! - `nansen alerts create` and `update` no longer offer the `smart-contract-call` alert type, which the Nansen API retired and now rejects. Passing `--type smart-contract-call`, or one of the flags only that type used (`--signature-hash`, `--caller`, `--contract`, `--exclude-caller`, `--exclude-contract`), now fails with an `INVALID_PARAMS` error that says the type was retired, before any request is sent. An unknown `--type` value is rejected the same way, with the valid types listed. `nansen schema` now lists the valid `--type` values as an enum.
22
+
23
+ - [#838](https://github.com/nansen-ai/nansen-cli/pull/838) [`ead3a57`](https://github.com/nansen-ai/nansen-cli/commit/ead3a570d8c4c22f53471221f8dab90dddc96480) Thanks [@kome12](https://github.com/kome12)! - `wallet send` now refuses sends that would lose funds: a mixed-case EVM `--to` or `--token` address with an invalid EIP-55 checksum (all-lowercase and all-uppercase addresses still work), an ERC-20 sent to its own contract, and on Solana a recipient that is not a wallet (a token account, mint, program or other program-owned account). `--amount <number>` together with `--max` is now rejected with `INVALID_INPUT` instead of sending the whole balance.
24
+
3
25
  ## 2.6.0
4
26
 
5
27
  ### Minor Changes
package/README.md CHANGED
@@ -294,7 +294,7 @@ For limit orders, `--dry-run` is a non-consuming intent preview built from local
294
294
 
295
295
  When stdin is an interactive terminal, each guarded command prints its plan and asks for confirmation first (`Broadcast this transaction?`, `Create this limit order?`, or `Cancel this limit order?`); anything but `y`/`yes` aborts with exit code 1 and nothing signed. `--yes`, `-y`, or `NANSEN_YES=1` skips only 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.
296
296
 
297
- To make an agent stop for your go-ahead, set `NANSEN_REQUIRE_CONFIRM=1` in its environment. Then, when stdin is not a terminal, every guarded command (`trade execute`, `bridge execute`, `trade limit-order create`/`cancel`, `perp order`/`close`/`cancel`/`leverage`) run without `--yes` or `NANSEN_YES=1` fails with exit code 1 and code `CONFIRMATION_REQUIRED` before it makes any request or signs anything. `--dry-run` still previews. Unset (the default), behaviour is unchanged.
297
+ To make an agent stop for your go-ahead, set `NANSEN_REQUIRE_CONFIRM=1` in its environment. Then, when stdin is not a terminal, every guarded command (`trade execute`, `bridge execute`, `trade limit-order create`/`cancel`, `perp order`/`close`/`cancel`/`leverage`/`transfer`/`approve-builder-fee`) run without `--yes` or `NANSEN_YES=1` fails with exit code 1 and code `CONFIRMATION_REQUIRED` before it makes any request or signs anything. `--dry-run` still previews. Unset (the default), behaviour is unchanged.
298
298
 
299
299
  | Exit code | Meaning |
300
300
  |-----------|---------|
@@ -344,7 +344,7 @@ nansen perp positions
344
344
  nansen perp account # value, unrealized PnL, margin, spot USDC
345
345
  ```
346
346
 
347
- `--side` is `buy`/`long` or `sell`/`short` to open (`buy`/`sell` to close); `--tif` is `Gtc`/`Ioc`/`Alo`; `--slippage` is a decimal in `[0,1]`; `--leverage` is a whole integer capped at the asset max. Perp orders are irreversible once signed: add `--dry-run` to `order`, `close`, `cancel` or `leverage` to print the plan without signing anything. In an interactive terminal these four commands ask for confirmation first (`--yes`/`-y` or `NANSEN_YES=1` skips it); off a terminal they submit without asking, as before. USDC sent to a wallet via Hyperliquid's **Send** lands in the **Spot** balance (shown as `Spot USDC`); move it to Perps with `perp transfer` before trading. `perp positions` prints each position's leverage and margin mode next to Hyperliquid's liquidation price (`lev=1x cross liq=1.37`). On cross margin the liquidation price depends on the whole account's equity, so even a 1x position can have one close to the market price; `liq=n/a` means the exchange reports no liquidation price. See the `nansen-trading` skill for details.
347
+ `--side` is `buy`/`long` or `sell`/`short` to open (`buy`/`sell` to close); `--tif` is `Gtc`/`Ioc`/`Alo`; `--slippage` is a decimal in `[0,1]`; `--leverage` is a whole integer capped at the asset max. Perp orders are irreversible once signed: add `--dry-run` to `order`, `close`, `cancel`, `leverage`, `transfer` or `approve-builder-fee` to print the plan without signing anything. In an interactive terminal these commands ask for confirmation first (`--yes`/`-y` or `NANSEN_YES=1` skips it); off a terminal they submit without asking, as before. USDC sent to a wallet via Hyperliquid's **Send** lands in the **Spot** balance (shown as `Spot USDC`); move it to Perps with `perp transfer` before trading. `perp positions` prints each position's leverage and margin mode next to Hyperliquid's liquidation price (`lev=1x cross liq=1.37`). On cross margin the liquidation price depends on the whole account's equity, so even a 1x position can have one close to the market price; `liq=n/a` means the exchange reports no liquidation price. See the `nansen-trading` skill for details.
348
348
 
349
349
  ## Bridge
350
350
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nansen-cli",
3
- "version": "2.6.0",
3
+ "version": "2.6.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",
@@ -83,10 +83,10 @@
83
83
  "vitest": "^4.1.12"
84
84
  },
85
85
  "dependencies": {
86
- "@ethereumjs/rlp": "^10.1.1",
87
- "@noble/curves": "^2.4.0",
88
- "@noble/hashes": "^2.4.0",
89
- "@scure/base": "^2.0.0"
86
+ "@ethereumjs/rlp": "10.1.1",
87
+ "@noble/curves": "2.4.0",
88
+ "@noble/hashes": "2.4.0",
89
+ "@scure/base": "2.0.0"
90
90
  },
91
91
  "optionalDependencies": {
92
92
  "@napi-rs/keyring": "2.1.0",
@@ -316,7 +316,7 @@ Example summary format:
316
316
  3. Create an alert pointing to your webhook (fill in your alert details):
317
317
  nansen alerts create \
318
318
  --name '<your alert name>' \
319
- --type <sm-token-flows|common-token-transfer|smart-contract-call> \
319
+ --type <sm-token-flows|common-token-transfer> \
320
320
  --chains <chains> \
321
321
  --webhook 'https://<your-tunnel-url>/webhook' \
322
322
  --webhook-secret-stdin \
@@ -113,27 +113,6 @@ nansen alerts create \
113
113
  --token 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48:ethereum
114
114
  ```
115
115
 
116
- ### 3. `smart-contract-call` — Smart Contract Interactions
117
-
118
- Track contract calls matching specified criteria.
119
-
120
- **Type-specific flags:**
121
- - `--usd-min/max <usd>`
122
- - `--signature-hash <hash>` (repeatable, e.g. `0x095ea7b3` for `approve`)
123
- - `--caller <type:value>` / `--exclude-caller <type:value>` (repeatable)
124
- - `--contract <type:value>` / `--exclude-contract <type:value>` (repeatable)
125
-
126
- **Example:**
127
- ```bash
128
- nansen alerts create \
129
- --name 'Uniswap V3 Large Swaps' \
130
- --type smart-contract-call \
131
- --chains ethereum \
132
- --telegram 123456789 \
133
- --usd-min 1000000 \
134
- --contract entity:"Uniswap V3"
135
- ```
136
-
137
116
  ## Notes
138
117
 
139
118
  - Chain aliases: Hyperliquid = `hyperevm`, BSC = `bnb`.
@@ -207,7 +207,7 @@ If the user says "$20 worth of X", use `--amount-unit usd` directly — no manua
207
207
  |-----|---------|
208
208
  | `NANSEN_WALLET_PASSWORD` | **Required for `trade execute`.** Wallet encryption password — persisted in `~/.nansen/.env`. Source before executing: `source ~/.nansen/.env && nansen trade execute ...` |
209
209
  | `NANSEN_API_KEY` | API key (also set via explicit `nansen login --human`; browser sessions are not wallet or RPC keys) |
210
- | `NANSEN_YES` | Set to `1` to skip the confirmation prompt of `trade execute`, `bridge execute`, `trade limit-order create`/`cancel` and `perp order`/`close`/`cancel`/`leverage`, like `--yes` |
210
+ | `NANSEN_YES` | Set to `1` to skip the confirmation prompt of `trade execute`, `bridge execute`, `trade limit-order create`/`cancel` and `perp order`/`close`/`cancel`/`leverage`/`transfer`/`approve-builder-fee`, like `--yes` |
211
211
  | `NANSEN_REQUIRE_CONFIRM` | Set to `1` to make those same commands fail with `CONFIRMATION_REQUIRED`, before any request or signature, when stdin is not a terminal and neither `--yes` nor `NANSEN_YES=1` is given. `--dry-run` still works. Opt-in; unset keeps today's behaviour |
212
212
 
213
213
  > **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.
@@ -223,7 +223,7 @@ If the user says "$20 worth of X", use `--amount-unit usd` directly — no manua
223
223
 
224
224
  Use `nansen perp` for Hyperliquid perpetual trading. Uses the same wallet and `NANSEN_WALLET_PASSWORD` as DEX trading; requires an **EVM** wallet. **Perp orders are irreversible once signed.**
225
225
 
226
- Subcommands: `order`, `cancel`, `close`, `leverage`, `positions`, `orders`, `account`, `meta`.
226
+ Subcommands: `order`, `cancel`, `close`, `leverage`, `transfer`, `approve-builder-fee`, `positions`, `orders`, `account`, `meta`.
227
227
 
228
228
  The asset is selected with `--symbol` (e.g. `BTC`, `ETH`); `--coin` is accepted as an alias. List tradable assets and their max leverage with `nansen perp meta` (use `--filter <text>` or `--all` to see beyond the first 20).
229
229
 
@@ -236,13 +236,13 @@ nansen perp order --symbol ETH --side buy --size 0.1 --price 1600 --dry-run #
236
236
  nansen perp order --symbol ETH --side buy --size 0.1 --price 1600 --yes # skip the confirmation prompt
237
237
  ```
238
238
 
239
- **`--dry-run`** runs the normal validation and read-only lookups (asset metadata, builder fee, open position, compliance screen), prints the plan (coin, side, rounded size, price and type, take-profit/stop-loss, estimated notional, leverage, builder fee) and exits 0. Nothing is signed or sent to Hyperliquid, no wallet password is needed, and the one-time builder-fee approval is not submitted. `close` also shows the worst fill price after slippage and the open position, `cancel` shows the open order it would cancel, and `leverage` shows the new setting next to the asset maximum.
239
+ **`--dry-run`** runs the normal validation and read-only lookups (asset metadata, builder fee, open position, compliance screen), prints the plan (coin, side, rounded size, price and type, take-profit/stop-loss, estimated notional, leverage, builder fee) and exits 0. Nothing is signed or sent to Hyperliquid, no wallet password is needed, and the one-time builder-fee approval is not submitted. `close` also shows the worst fill price after slippage and the open position, `cancel` shows the open order it would cancel, `leverage` shows the new setting next to the asset maximum, `transfer` shows the direction and the exact USDC amount, and `approve-builder-fee` shows the builder address and maximum fee rate (or says the fee is already approved, with nothing to preview).
240
240
 
241
241
  **Exception: `close --dry-run` exits 1 with `NO_OPEN_POSITION` when the wallet has no open position in that coin.** That is a definite "nothing to close" answer, not a crash. If the position was opened moments ago, the positions data may not show it yet: retry after a few seconds. A real `close` skips this check and lets Hyperliquid decide; with a prompt, its plan shows a warning instead.
242
242
 
243
- **Confirmation.** When stdin is an interactive terminal, these four commands print the plan and ask, for example, `Submit this order to Hyperliquid? [y/N]` before signing. Answering anything but `y`/`yes` exits 1 with nothing signed (code `CONFIRMATION_DECLINED`). Pass `--yes` (`-y`), or set `NANSEN_YES=1`, to skip the question.
243
+ **Confirmation.** When stdin is an interactive terminal, these commands (`order`, `close`, `cancel`, `leverage`, `transfer`, `approve-builder-fee`) print the plan and ask, for example, `Submit this order to Hyperliquid? [y/N]` before signing. Answering anything but `y`/`yes` exits 1 with nothing signed (code `CONFIRMATION_DECLINED`). Pass `--yes` (`-y`), or set `NANSEN_YES=1`, to skip the question.
244
244
 
245
- **When stdin is *not* a terminal** (agents, CI) the commands submit without prompting, exactly as before, and `--yes` is a no-op. **Exception:** if `NANSEN_REQUIRE_CONFIRM=1` is set, they fail with `CONFIRMATION_REQUIRED` (exit 1) before any request or signature unless `--yes` or `NANSEN_YES=1` is given; follow the operator stop point described above. These are the same rules as `trade execute` and `bridge execute`. `transfer` and `approve-builder-fee` are unchanged.
245
+ **When stdin is *not* a terminal** (agents, CI) the commands submit without prompting, exactly as before, and `--yes` is a no-op. **Exception:** if `NANSEN_REQUIRE_CONFIRM=1` is set, they fail with `CONFIRMATION_REQUIRED` (exit 1) before any request or signature unless `--yes` or `NANSEN_YES=1` is given; follow the operator stop point described above. These are the same rules as `trade execute` and `bridge execute`.
246
246
 
247
247
  ## Open a position
248
248
 
package/src/bridge.js CHANGED
@@ -430,6 +430,19 @@ const HL_SENDASSET_FIELDS = [
430
430
  { name: 'nonce', type: 'uint64' },
431
431
  ];
432
432
 
433
+ // Relay's Hyperliquid deposit address: the only `destination` a bridge
434
+ // withdrawal's sendAsset may name. The signature commits to `destination`
435
+ // (it is in HL_SENDASSET_FIELDS), so leaving it unchecked would let a tampered
436
+ // quote send the withdrawal to any HL address. Captured from real read-only
437
+ // `bridge quote` responses for all three withdrawal routes (HL -> base,
438
+ // ethereum, arbitrum) on 2026-08-28 and again on 2026-11-16: identical every
439
+ // time. Lower-cased for comparison. If Relay rotates this address, every HL
440
+ // withdrawal fails closed until nansen-cli is updated (the same trade-off as
441
+ // BRIDGE_DEPOSIT_TARGETS on the EVM deposit leg).
442
+ export const HL_BRIDGE_RELAYER_DESTINATIONS = new Set([
443
+ '0x66cf0aace1b4e562593bec10ec7868fba9932224',
444
+ ]);
445
+
433
446
  // Parse a non-negative decimal string ("2", "2.000000", "1.97859") to an integer
434
447
  // scaled by `decimals`, via digit slicing (never parseFloat) so it is exact.
435
448
  export function decimalToScaled(raw, decimals = 8) {
@@ -447,10 +460,12 @@ export function decimalToScaled(raw, decimals = 8) {
447
460
  // action; it says nothing about what the action does. Static only, no RPC.
448
461
  //
449
462
  // NOTE ON DESTINATION: in the relayer-mediated flow, action.destination is the
450
- // RELAYER's deposit address, not the user's — so it is deliberately NOT bound to
451
- // the recipient (doing so would reject every legitimate withdrawal). The final
452
- // payout recipient is held off-chain by the relayer and is not in anything we
453
- // sign; the amount cap below is what bounds the loss.
463
+ // RELAYER's deposit address, not the user's — so it is NOT bound to the
464
+ // recipient (doing so would reject every legitimate withdrawal). It IS pinned
465
+ // to the relayer (HL_BRIDGE_RELAYER_DESTINATIONS), so the withdrawal can only
466
+ // go to Relay. The final payout recipient is held off-chain by the relayer and
467
+ // is not in anything we sign; the amount cap below bounds the loss per leg, and
468
+ // preflightHlBridgeSteps bounds the number of legs to one.
454
469
  //
455
470
  // Every check below fails CLOSED (throws) rather than silently skipping when
456
471
  // its anchor is missing. An earlier version skipped the amount cap whenever
@@ -485,6 +500,15 @@ export function assertHlBridgeActionIntent(action, intent, context = 'Bridge act
485
500
  'UNEXPECTED_NETWORK',
486
501
  );
487
502
  }
503
+ // D. destination — must be Relay's deposit address. Fails closed when absent.
504
+ const destination = action.destination ?? action.parameters?.destination;
505
+ if (typeof destination !== 'string' || !HL_BRIDGE_RELAYER_DESTINATIONS.has(destination.toLowerCase())) {
506
+ throw new CommandError(
507
+ `${context} sends to ${destination}, not the Relay deposit address. `
508
+ + `Refusing to sign. Update nansen-cli if Relay changed its deposit address, otherwise request a new quote.`,
509
+ 'UNEXPECTED_ACTION',
510
+ );
511
+ }
488
512
  // B. amount cap — required, not optional. sendAsset's entire purpose is
489
513
  // moving a nonzero amount; an action.type we allowlisted but with no amount
490
514
  // to check is not a smaller withdrawal, it is a signal something is wrong
@@ -666,9 +690,20 @@ function buildHlBridgeAction(signData) {
666
690
  // endpoint pin, and the EIP-712 type-list guard — so this is a strict
667
691
  // superset of the per-step processors' checks, run up front across the whole
668
692
  // plan first.
693
+ //
694
+ // Per-item checks cannot bound a REPEATED plan: [authorize, sendAsset,
695
+ // sendAsset, ...] passes them leg by leg, each sendAsset within the amount cap,
696
+ // and would withdraw N times the reviewed amount. So, mirroring
697
+ // preflightEvmBridgeSteps, count the legs: at most one incomplete authorize,
698
+ // and exactly one sendAsset in total (completed sendAsset legs count toward
699
+ // the total, since a real withdrawal never has two) which is still incomplete.
669
700
  function preflightHlBridgeSteps(steps, intent) {
701
+ let authorizeCount = 0;
702
+ let actionCount = 0;
703
+ let totalActionCount = 0;
670
704
  for (const step of steps) {
671
705
  for (const item of step.items || []) {
706
+ if (item.data?.action) totalActionCount++;
672
707
  // Skip already-signed-and-submitted items, matching the processors
673
708
  // (:769/:838): on resume of a partially-executed bridge, re-validating a
674
709
  // completed step against these now-stricter checks could wedge it.
@@ -684,9 +719,11 @@ function preflightHlBridgeSteps(steps, intent) {
684
719
  assertHlBridgeAuthorizeIntent(signData.sign, intent.signerAddress, `Bridge step "${step.id}"`);
685
720
  resolveRelayTargetUrl(signData.post?.endpoint, `Bridge step "${step.id}"`);
686
721
  assertEip712TypeListNonEmpty(signData.sign.types, signData.sign.primaryType, `Bridge step "${step.id}"`);
722
+ authorizeCount++;
687
723
  } else if (signData.action) {
688
724
  assertHlBridgeActionIntent(buildHlBridgeAction(signData), intent, `Bridge step "${step.id}"`);
689
725
  assertHlSendAssetEip712Shape(signData.eip712Types, signData.eip712PrimaryType, `Bridge step "${step.id}"`);
726
+ actionCount++;
690
727
  } else {
691
728
  // A leg matching neither is never something to sign — the local
692
729
  // processor would silently no-op it (reporting success having signed
@@ -698,6 +735,13 @@ function preflightHlBridgeSteps(steps, intent) {
698
735
  }
699
736
  }
700
737
  }
738
+ if (authorizeCount > 1 || totalActionCount !== 1 || actionCount !== 1) {
739
+ throw new CommandError(
740
+ `Bridge plan has ${authorizeCount} authorize and ${totalActionCount} sendAsset leg(s) (${actionCount} pending); a legitimate withdrawal is at most one authorize and exactly one sendAsset. `
741
+ + `Refusing to sign — repeated legs could withdraw more than the amount you requested. Request a new quote.`,
742
+ 'UNEXPECTED_ACTION',
743
+ );
744
+ }
701
745
  }
702
746
 
703
747
  // ── Step processors ──────────────────────────────────────────────────
package/src/cli.js CHANGED
@@ -2435,7 +2435,7 @@ USAGE:
2435
2435
  nansen perp positions
2436
2436
  nansen perp account
2437
2437
 
2438
- BEFORE SUBMITTING (order, cancel, close, leverage):
2438
+ BEFORE SUBMITTING (order, cancel, close, leverage, transfer, approve-builder-fee):
2439
2439
  --dry-run Validate and print what would be submitted, then stop. Exits 0.
2440
2440
  --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1). The prompt only
2441
2441
  appears when stdin is a terminal; declining exits 1, signing nothing.`);
@@ -544,34 +544,6 @@ export function buildCommonTokenTransferData(options) {
544
544
  return data;
545
545
  }
546
546
 
547
- /**
548
- * Build the data payload for smart-contract-call alerts from named flags.
549
- */
550
- export function buildSmartContractCallData(options) {
551
- const data = {};
552
-
553
- const chains = parseChains(options.chains);
554
- if (chains) data.chains = chains;
555
-
556
- const usdRange = buildRange(options['usd-min'], options['usd-max'], 'usd');
557
- if (usdRange) data.usdValue = usdRange;
558
-
559
- const signatureHash = parseCsvOption(options['signature-hash'], 'signature-hash');
560
- if (signatureHash) data.signatureHash = signatureHash;
561
-
562
- const callers = parseSubjects(options.caller, 'caller');
563
- const contracts = parseSubjects(options.contract, 'contract');
564
- const excludeCallers = parseSubjects(options['exclude-caller'], 'exclude-caller');
565
- const excludeContracts = parseSubjects(options['exclude-contract'], 'exclude-contract');
566
-
567
- if (callers) data.inclusion = { ...data.inclusion, caller: callers };
568
- if (contracts) data.inclusion = { ...data.inclusion, smartContract: contracts };
569
- if (excludeCallers) data.exclusion = { ...data.exclusion, caller: excludeCallers };
570
- if (excludeContracts) data.exclusion = { ...data.exclusion, smartContract: excludeContracts };
571
-
572
- return data;
573
- }
574
-
575
547
  /**
576
548
  * Type-specific defaults for required fields.
577
549
  * Applied in buildAlertData so payloads always satisfy the backend schema.
@@ -602,16 +574,43 @@ const TYPE_DEFAULTS = {
602
574
  inclusion: {},
603
575
  exclusion: {},
604
576
  },
605
- 'smart-contract-call': {
606
- chains: [],
607
- events: ['smart-contract-call'],
608
- usdValue: {},
609
- signatureHash: [],
610
- inclusion: { caller: [], smartContract: [] },
611
- exclusion: { caller: [], smartContract: [] },
612
- },
613
577
  };
614
578
 
579
+ /** Alert types the backend accepts. */
580
+ export const ALERT_TYPES = ['sm-token-flows', 'common-token-transfer'];
581
+
582
+ /** Flags that only the retired smart-contract-call type used. */
583
+ const RETIRED_CONTRACT_CALL_FLAGS = ['signature-hash', 'caller', 'contract', 'exclude-caller', 'exclude-contract'];
584
+
585
+ function retiredTypeError() {
586
+ return new NansenError(
587
+ `The smart-contract-call alert type was retired and can no longer be created or updated. Use one of: ${ALERT_TYPES.join(', ')}.`,
588
+ ErrorCode.INVALID_PARAMS,
589
+ );
590
+ }
591
+
592
+ /**
593
+ * Reject create/update input the backend can no longer act on, before any
594
+ * stdin read or request. The smart-contract-call type was retired, and its
595
+ * flags would otherwise be ignored without a word, since alerts does not
596
+ * reject unknown flags. A bare flag lands in `flags`, a valued one in `options`.
597
+ */
598
+ export function checkAlertInput(options = {}, flags = {}) {
599
+ const valid = ALERT_TYPES.join(', ');
600
+ const type = options.type;
601
+ if (type === 'smart-contract-call') throw retiredTypeError();
602
+ if (type !== undefined && !ALERT_TYPES.includes(type)) {
603
+ throw new NansenError(`Invalid --type "${type}". Use one of: ${valid}.`, ErrorCode.INVALID_PARAMS);
604
+ }
605
+ const retired = RETIRED_CONTRACT_CALL_FLAGS.find(f => options[f] !== undefined || flags[f] !== undefined);
606
+ if (retired) {
607
+ throw new NansenError(
608
+ `--${retired} was only used by smart-contract-call alerts, which were retired. Remove it; supported types: ${valid}.`,
609
+ ErrorCode.INVALID_PARAMS,
610
+ );
611
+ }
612
+ }
613
+
615
614
  /**
616
615
  * Build the alert data payload from named flags, dispatching on type.
617
616
  * --data '<json>' is merged on top as an escape-hatch override.
@@ -626,8 +625,6 @@ export function buildAlertData(options, { applyDefaults = true } = {}) {
626
625
  data = buildSmTokenFlowsData(options);
627
626
  } else if (options.type === 'common-token-transfer') {
628
627
  data = buildCommonTokenTransferData(options);
629
- } else if (options.type === 'smart-contract-call') {
630
- data = buildSmartContractCallData(options);
631
628
  } else {
632
629
  // No type — only --chains and --data are valid; warn if type-specific flags are present
633
630
  const typeSpecificFlags = [
@@ -636,8 +633,7 @@ export function buildAlertData(options, { applyDefaults = true } = {}) {
636
633
  'netflow-1h-min', 'netflow-1h-max', 'netflow-1d-min', 'netflow-1d-max', 'netflow-7d-min', 'netflow-7d-max',
637
634
  'events', 'usd-min', 'usd-max', 'token-amount-min', 'token-amount-max',
638
635
  'token', 'exclude-token',
639
- 'subject', 'counterparty', 'signature-hash', 'caller', 'contract',
640
- 'exclude-caller', 'exclude-contract', 'exclude-from', 'exclude-to',
636
+ 'subject', 'counterparty', 'exclude-from', 'exclude-to',
641
637
  'token-sector', 'exclude-token-sector', 'token-age-min', 'token-age-max',
642
638
  'market-cap-min', 'market-cap-max', 'fdv-min', 'fdv-max',
643
639
  ];
@@ -655,7 +651,7 @@ export function buildAlertData(options, { applyDefaults = true } = {}) {
655
651
 
656
652
  // Apply type defaults underneath so all required fields are present.
657
653
  // Use structuredClone to avoid shared mutable references, and deep-merge
658
- // inclusion/exclusion so partial flags (e.g. --caller without --contract)
654
+ // inclusion/exclusion so partial flags (e.g. --token without --token-sector)
659
655
  // don't drop sibling required sub-fields.
660
656
  if (applyDefaults && TYPE_DEFAULTS[options.type]) {
661
657
  const defaults = structuredClone(TYPE_DEFAULTS[options.type]);
@@ -733,25 +729,12 @@ export function validateAlertData(type, data) {
733
729
  );
734
730
  }
735
731
  }
736
-
737
- if (type === 'smart-contract-call') {
738
- const hasCallers = Array.isArray(data.inclusion?.caller) && data.inclusion.caller.length > 0;
739
- const hasContracts = Array.isArray(data.inclusion?.smartContract) && data.inclusion.smartContract.length > 0;
740
- const hasSignatureHash = Array.isArray(data.signatureHash) && data.signatureHash.length > 0;
741
- if (!hasCallers && !hasContracts && !hasSignatureHash) {
742
- throw new NansenError(
743
- 'smart-contract-call requires at least one --caller, --contract, or --signature-hash',
744
- ErrorCode.INVALID_PARAMS,
745
- );
746
- }
747
- }
748
732
  }
749
733
 
750
734
  // ============= Command Builder =============
751
735
 
752
736
  const TIME_WINDOW_BY_TYPE = {
753
737
  'common-token-transfer': 'realtime',
754
- 'smart-contract-call': 'realtime',
755
738
  'sm-token-flows': '1h',
756
739
  };
757
740
 
@@ -787,7 +770,7 @@ OPTIONS:
787
770
  --table Human-readable table output (columns: ID, NAME, TYPE, ENABLED, CHANNELS)
788
771
  --pretty Indented JSON output
789
772
  --reveal Show full channel webhook URLs and secrets (redacted by default)
790
- --type <type> Filter by alert type (sm-token-flows, common-token-transfer, smart-contract-call)
773
+ --type <type> Filter by alert type (sm-token-flows, common-token-transfer)
791
774
  --enabled / --disabled Filter by enabled state
792
775
  --token <addr> Filter by token address (alias --token-address)
793
776
  --chain <chain> Filter by chain
@@ -806,7 +789,7 @@ USAGE:
806
789
 
807
790
  REQUIRED:
808
791
  --name <name> Alert name
809
- --type <type> sm-token-flows | common-token-transfer | smart-contract-call
792
+ --type <type> sm-token-flows | common-token-transfer
810
793
  At least one channel: --telegram <chatId> | --slack <url> | --discord <url> | --webhook <url>
811
794
 
812
795
  OPTIONS (all types):
@@ -838,11 +821,6 @@ OPTIONS (common-token-transfer):
838
821
  --token-age-min/max <days> --market-cap-min/max <usd>
839
822
  --exclude-from <type:value> --exclude-to <type:value> (repeatable)
840
823
 
841
- OPTIONS (smart-contract-call):
842
- --usd-min/max <usd> --signature-hash <hash> (repeatable)
843
- --caller <type:value> --exclude-caller <type:value> (repeatable)
844
- --contract <type:value> --exclude-contract <type:value> (repeatable)
845
-
846
824
  SUBJECT TYPES: address, entity, label, custom-label
847
825
  CHAIN ALIASES: Hyperliquid = hyperevm, BSC = bnb
848
826
 
@@ -851,7 +829,6 @@ NOTE: Use single quotes for names with $ or special chars: --name 'SM >$1M'
851
829
  EXAMPLES:
852
830
  nansen alerts create --name 'ETH SM Inflow' --type sm-token-flows --chains ethereum --telegram 5238612255 --inflow-1h-min 1000000
853
831
  nansen alerts create --name 'USDC Transfers' --type common-token-transfer --chains ethereum --telegram 5238612255 --events send,receive --usd-min 1000000 --subject label:"Centralized Exchange"
854
- nansen alerts create --name 'Contract Calls' --type smart-contract-call --chains ethereum --telegram 5238612255 --signature-hash 0xa9059cbb --caller address:0xabc
855
832
  nansen alerts create --name 'Hook' --type sm-token-flows --chains ethereum --webhook https://example.com/hook --inflow-1h-min 1000000 --webhook-secret-stdin < secret.txt
856
833
 
857
834
  WEBHOOK SIGNING SECRET (minimum 16 characters, webhook only):
@@ -1044,6 +1021,7 @@ OPTIONS:
1044
1021
  const existing = await apiInstance.alertsGet(id);
1045
1022
  if (!existing) throw new NansenError(`Alert not found: ${id}`, ErrorCode.NOT_FOUND);
1046
1023
  const existingType = existing.type ?? existing.data?.type;
1024
+ if (existingType === 'smart-contract-call') throw retiredTypeError();
1047
1025
  if (options.type && options.type !== existingType) {
1048
1026
  throw new NansenError(
1049
1027
  `Cannot change alert type (${existingType} → ${options.type}). Delete and recreate the alert instead.`,
@@ -1104,6 +1082,7 @@ OPTIONS:
1104
1082
 
1105
1083
  try {
1106
1084
  if (sub === 'create' || sub === 'update') {
1085
+ checkAlertInput(options, flags);
1107
1086
  webhookSecret = await resolveWebhookSecret(options, flags, { env, stdin, stdinTTY });
1108
1087
  }
1109
1088
  const result = await handlers[sub]();
package/src/crypto.js CHANGED
@@ -15,6 +15,23 @@ export function keccak256(input) {
15
15
  return Buffer.from(hash);
16
16
  }
17
17
 
18
+ // ============= EIP-55 =============
19
+
20
+ /**
21
+ * EIP-55 mixed-case checksum form of a 20-byte hex address (with or without
22
+ * 0x, any case). Each hex letter is uppercased when the matching nibble of
23
+ * keccak256(lowercase hex) is 8 or more.
24
+ */
25
+ export function toChecksumAddress(address) {
26
+ const hex = String(address).replace(/^0x/i, '').toLowerCase();
27
+ const hash = keccak256(Buffer.from(hex, 'utf8')).toString('hex');
28
+ let out = '0x';
29
+ for (let i = 0; i < hex.length; i++) {
30
+ out += parseInt(hash[i], 16) >= 8 ? hex[i].toUpperCase() : hex[i];
31
+ }
32
+ return out;
33
+ }
34
+
18
35
  // ============= secp256k1 ECDSA =============
19
36
 
20
37
  /**
package/src/perp.js CHANGED
@@ -548,6 +548,16 @@ function parsePositiveNumber(raw, name) {
548
548
  return n;
549
549
  }
550
550
 
551
+ // Canonical form of a decimal string already validated by parsePositiveNumber,
552
+ // using string operations only: "025" -> "25", "12.50" -> "12.5", ".5" -> "0.5".
553
+ function normalizeDecimalString(raw) {
554
+ const s = String(scalar(raw, 'amount') ?? '').trim();
555
+ const [intPart, fracPart = ''] = s.split('.');
556
+ const int = intPart.replace(/^0+/, '') || '0';
557
+ const frac = fracPart.replace(/0+$/, '');
558
+ return frac ? `${int}.${frac}` : int;
559
+ }
560
+
551
561
  function parsePositiveInt(raw, name) {
552
562
  // Digits-only check before parseInt — parseInt("2.5") floors to 2 and
553
563
  // parseInt("123abc") yields 123, so a fractional or garbage value would
@@ -1248,7 +1258,7 @@ OPTIONS:
1248
1258
 
1249
1259
  if (!direction || options.amount === undefined) {
1250
1260
  throw new CommandError(
1251
- 'Usage: nansen perp transfer --direction <spot-to-perp|perp-to-spot> --amount <usdc> [--wallet <name>]',
1261
+ 'Usage: nansen perp transfer --direction <spot-to-perp|perp-to-spot> --amount <usdc> [--wallet <name>] [--dry-run] [--yes]',
1252
1262
  'MISSING_PARAM',
1253
1263
  );
1254
1264
  }
@@ -1260,13 +1270,41 @@ OPTIONS:
1260
1270
  throw invalid(`Invalid --direction "${direction}". Must be one of: spot-to-perp, perp-to-spot.`);
1261
1271
  }
1262
1272
  const amount = parsePositiveNumber(options.amount, 'amount');
1273
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
1274
+ const directionLabel = toPerp ? 'Spot → Perps' : 'Perps → Spot';
1275
+ // Built (pure, nothing signed) before the gate: validates the amount on a
1276
+ // dry run too, and gives the plan the exact amount string that is signed.
1277
+ const signedAmount = buildUsdClassTransferAction({ amount, toPerp, nonce: 0 }).action.amount;
1278
+ // The amount goes through a float and an 8-decimal string; refuse an
1279
+ // input that string can't carry exactly instead of signing another amount.
1280
+ if (normalizeDecimalString(options.amount) !== signedAmount) {
1281
+ throw invalid(`Invalid --amount "${options.amount}". Hyperliquid takes USDC amounts with at most 8 decimal places, and this amount can't be signed exactly; it would be signed as ${signedAmount}.`);
1282
+ }
1283
+ // transfer makes no proxy read before the gate, so check the network here:
1284
+ // otherwise a dry run previews a transfer the real run refuses.
1285
+ assertPerpNetworkSupported();
1263
1286
 
1264
1287
  const wallet = resolveWalletAddress(walletName);
1265
- const ctx = await resolveSigningCtx(wallet, log);
1288
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
1266
1289
 
1267
- log(`\n Transfer: ${amount} USDC ${toPerp ? 'Spot → Perps' : 'Perps → Spot'}`);
1290
+ const proceed = await guardPerpAction(apiInstance, {
1291
+ guard,
1292
+ walletAddress: wallet.address,
1293
+ question: 'Submit this transfer to Hyperliquid? [y/N] ',
1294
+ buildPlan: async () => formatPlan('Perp transfer plan — USDC', [
1295
+ ['Wallet', wallet.address],
1296
+ ['Direction', directionLabel],
1297
+ ['Amount', `${signedAmount} USDC`],
1298
+ ]),
1299
+ }, guardDeps);
1300
+ if (!proceed) return undefined;
1301
+ ctx ??= await resolveSigningCtx(wallet, log);
1302
+
1303
+ log(`\n Transfer: ${signedAmount} USDC ${directionLabel}`);
1268
1304
 
1269
1305
  // usdClassTransfer is user-signed: the nonce is embedded in the action.
1306
+ // Taken after the gate, since a prompt can wait long enough for a nonce
1307
+ // taken before it to go stale.
1270
1308
  const nonce = hlNonce();
1271
1309
  const { action, primaryType, signTypes } = buildUsdClassTransferAction({ amount, toPerp, nonce });
1272
1310
  const eip712 = userSignedEip712(primaryType, signTypes, action);
@@ -1281,15 +1319,31 @@ OPTIONS:
1281
1319
  // the builder code. order/close auto-fire this on the first trade; this
1282
1320
  // command lets a client approve up front. No-op when already approved.
1283
1321
  const walletName = scalar(options.wallet, 'wallet');
1322
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
1284
1323
  const wallet = resolveWalletAddress(walletName);
1285
- const ctx = await resolveSigningCtx(wallet, log);
1324
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
1286
1325
 
1287
1326
  const builderStatus = await fetchBuilderFee(apiInstance, wallet.address);
1288
1327
  if (builderStatus.approved) {
1328
+ // Nothing would be signed, so there is nothing to preview or confirm.
1289
1329
  log(`\n Builder fee already approved for ${wallet.address}\n`);
1290
1330
  return undefined;
1291
1331
  }
1292
1332
 
1333
+ const proceed = await guardPerpAction(apiInstance, {
1334
+ guard,
1335
+ walletAddress: wallet.address,
1336
+ question: 'Submit this builder-fee approval to Hyperliquid? [y/N] ',
1337
+ buildPlan: async () => formatPlan('Perp builder-fee approval plan', [
1338
+ ['Wallet', wallet.address],
1339
+ ['Builder', String(builderStatus.builder_address).toLowerCase()],
1340
+ ['Max fee rate', `${builderMaxFeeRate(builderStatus.required_fee)} of the order value`],
1341
+ ['Effect', 'One-time approval that lets orders carry the Nansen builder code'],
1342
+ ]),
1343
+ }, guardDeps);
1344
+ if (!proceed) return undefined;
1345
+ ctx ??= await resolveSigningCtx(wallet, log);
1346
+
1293
1347
  log(`\n Approve builder fee: ${wallet.address}`);
1294
1348
  await ensureBuilderApproved(apiInstance, builderStatus, ctx);
1295
1349
  log('');