nansen-cli 2.4.0 → 2.6.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/src/perp.js CHANGED
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { CommandError } from './api.js';
13
13
  import { signSecp256k1 } from './crypto.js';
14
+ import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
14
15
  import {
15
16
  buildApproveBuilderFeeAction,
16
17
  buildCancelAction,
@@ -428,7 +429,7 @@ async function buildScreenSignSubmit(apiInstance, prepared, ctx) {
428
429
  log(` Filled${tag}: ${o.totalSz} @ ${o.avgPx} (${oidText})`);
429
430
  } else {
430
431
  log(` Resting order${tag}: ${oidText}`);
431
- if (coin && o.oidSafe) log(` Cancel: nansen perp cancel --coin ${coin} --oid ${o.oid}`);
432
+ if (coin && o.oidSafe) log(` Cancel: nansen perp cancel --symbol ${coin} --oid ${o.oid}`);
432
433
  }
433
434
  }
434
435
  } else if (result.response) {
@@ -651,21 +652,227 @@ function assertOrderType(raw) {
651
652
  return type;
652
653
  }
653
654
 
654
- // Resolve the asset symbol from --coin (or its --symbol alias), rejecting a
655
+ // Resolve the asset symbol from --symbol (or its --coin alias), rejecting a
655
656
  // duplicated flag. Returns the upper-cased symbol, or '' when neither is set.
656
657
  function resolveCoin(options) {
657
- const raw = scalar(options.coin, 'coin') ?? scalar(options.symbol, 'symbol');
658
- return String(raw ?? '').toUpperCase();
658
+ const symbol = scalar(options.symbol, 'symbol');
659
+ const coin = scalar(options.coin, 'coin');
660
+ // `--symbol ETH --coin BTC` names the market twice; never pick one silently.
661
+ if (symbol !== undefined && coin !== undefined) {
662
+ throw invalid(`--symbol ${symbol} and --coin ${coin} are the same input (--coin is an alias of --symbol); pass one.`);
663
+ }
664
+ return String(symbol ?? coin ?? '').toUpperCase();
665
+ }
666
+
667
+ // ── Preview + confirmation (--dry-run / --yes) ───────────────────────
668
+ //
669
+ // order/close/cancel/leverage share the acknowledgement gate of trade and
670
+ // bridge execute (src/execute-guard.js): --dry-run prints the plan and stops
671
+ // before anything is signed; an interactive terminal is asked to confirm;
672
+ // --yes / -y / NANSEN_YES=1 skips the question. Off a terminal the command
673
+ // proceeds unprompted, exactly as before.
674
+
675
+ const PERP_DRY_RUN_NOTICE = [
676
+ '\n DRY RUN — nothing was sent to Hyperliquid. No action was signed.',
677
+ ' Re-run without --dry-run to sign and submit it.\n',
678
+ ];
679
+
680
+ // A decimal string (a wire value, or a number's shortest form such as "1e-7")
681
+ // as an exact BigInt scaled by 10^scale. null when it isn't one.
682
+ function parseDecimal(value) {
683
+ const match = /^([-+]?)(\d*)(?:\.(\d*))?(?:e([-+]?\d{1,3}))?$/i.exec(String(value ?? '').trim());
684
+ if (!match || !(match[2] || match[3])) return null;
685
+ const fraction = match[3] ?? '';
686
+ let digits = BigInt(`${match[2] || '0'}${fraction}`);
687
+ let scale = fraction.length - Number(match[4] ?? 0);
688
+ if (scale < 0) {
689
+ digits *= 10n ** BigInt(-scale);
690
+ scale = 0;
691
+ }
692
+ return { digits: match[1] === '-' ? -digits : digits, scale };
693
+ }
694
+
695
+ // USD value of size × price, computed in exact decimal arithmetic from the
696
+ // strings that are signed, so the preview cannot drift from the submitted
697
+ // order through float rounding. Only the cent rounding (half up) is approximate.
698
+ function formatUsd(size, price) {
699
+ const a = parseDecimal(size);
700
+ const b = parseDecimal(price);
701
+ if (!a || !b) return null;
702
+ const product = a.digits * b.digits;
703
+ if (product < 0n) return null;
704
+ const scale = a.scale + b.scale;
705
+ let cents;
706
+ if (scale <= 2) {
707
+ cents = product * 10n ** BigInt(2 - scale);
708
+ } else {
709
+ const divisor = 10n ** BigInt(scale - 2);
710
+ cents = (product + divisor / 2n) / divisor;
711
+ }
712
+ if (product > 0n && cents === 0n) return '<$0.01';
713
+ return `~$${cents / 100n}.${String(cents % 100n).padStart(2, '0')}`;
714
+ }
715
+
716
+ // Notional of an IOC order at the reference price and at its worst fill (the
717
+ // limit price encoded after slippage), so a buy's worst-case cost is visible.
718
+ function formatIocNotional(size, referencePrice, worstPrice) {
719
+ const atReference = formatUsd(size, referencePrice);
720
+ const atWorst = formatUsd(size, worstPrice);
721
+ return atReference && atWorst ? `${atReference} at the reference price, ${atWorst} at the worst fill` : null;
722
+ }
723
+
724
+ // The order leg of a built action (not an attached take-profit/stop-loss), whose
725
+ // `s` and `p` are the exact size and limit price strings that get signed.
726
+ function mainOrderLeg(action) {
727
+ return action.orders?.find(o => !o?.t?.trigger);
728
+ }
729
+
730
+ function formatSlippage(slippage) {
731
+ return `${Number((slippage * 100).toFixed(4))}%`;
732
+ }
733
+
734
+ function builderFeeLine(status) {
735
+ const rate = builderMaxFeeRate(status.required_fee);
736
+ if (status.approved) return `${rate} of the order value (approved)`;
737
+ return `${rate} of the order value. Not yet approved: submitting signs and sends a one-time approval (max ${rate} to ${String(status.builder_address).toLowerCase()}) before the order`;
738
+ }
739
+
740
+ // An attached take-profit/stop-loss leg as it will be signed: side, size,
741
+ // reduce-only and trigger read from the built action. undefined when absent.
742
+ function describeTriggerLeg(action, tpsl, coin) {
743
+ const leg = action.orders?.find(o => o?.t?.trigger?.tpsl === tpsl);
744
+ if (!leg) return undefined;
745
+ const { isMarket, triggerPx } = leg.t.trigger;
746
+ return [
747
+ `${leg.b ? 'buy' : 'sell'} ${leg.s} ${coin}`,
748
+ ...(leg.r ? ['reduce-only'] : []),
749
+ `${isMarket ? 'market' : 'limit'} when the price reaches ${triggerPx}`,
750
+ ].join(', ');
751
+ }
752
+
753
+ // Read-only lookup of the wallet's open position in `coin`, for the plan and
754
+ // close's pre-checks. Returns the position, null when there is none, or
755
+ // undefined when the read failed or the answer for `coin` can't be trusted
756
+ // (callers then skip the checks, and the plan says so instead of guessing).
757
+ async function readOpenPosition(apiInstance, walletAddress, coin) {
758
+ try {
759
+ const result = await perpRead(apiInstance, 'positions', { wallet_address: walletAddress });
760
+ return findPosition(result?.positions, coin);
761
+ } catch {
762
+ return undefined;
763
+ }
764
+ }
765
+
766
+ // A position size as the exchange sends it: a plain decimal string, signed
767
+ // for a short. Shared by the parse and the well-formed check so they agree.
768
+ const SZI_RE = /^\s*([-+]?)(\d*\.?\d+)\s*$/;
769
+
770
+ // Side and unsigned size of a position, read from the exchange's own szi
771
+ // string, so no float conversion can round a tiny size to zero or lose its
772
+ // sign. null for a zero, missing or malformed size.
773
+ function positionSide(szi) {
774
+ const match = SZI_RE.exec(String(szi ?? ''));
775
+ if (!match || !/[1-9]/.test(match[2])) return null;
776
+ return { side: match[1] === '-' ? 'short' : 'long', size: match[2] };
777
+ }
778
+
779
+ // The coin's position, null when there is none (no entry, or a zero size), or
780
+ // undefined when the answer can't be trusted: `positions` is not a list, or
781
+ // this coin's entry has a missing or unreadable size. Entries that are not
782
+ // objects or carry no coin name can't be matched and are skipped, and a bad
783
+ // entry for another coin is ignored, so neither switches off this coin's checks.
784
+ // The first entry for the coin wins.
785
+ function findPosition(positions, coin) {
786
+ if (!Array.isArray(positions)) return undefined;
787
+ const pos = positions.find(p => p !== null && typeof p === 'object'
788
+ && p.coin != null && String(p.coin).toUpperCase() === coin);
789
+ if (!pos) return null;
790
+ if (positionSide(pos.szi)) return pos;
791
+ return SZI_RE.test(String(pos.szi ?? '')) ? null : undefined;
792
+ }
793
+
794
+ function describePosition(pos) {
795
+ if (pos === undefined) return 'could not be loaded';
796
+ if (pos === null) return 'none';
797
+ const { side, size } = positionSide(pos.szi);
798
+ const lev = formatPositionLeverage(pos.leverage);
799
+ return `${side} ${size}${pos.entryPx ? ` @ ${pos.entryPx}` : ''}${lev ? `, ${lev}` : ''}`;
800
+ }
801
+
802
+ // Leverage that applies to an order in `coin`: Hyperliquid uses the wallet's
803
+ // per-asset setting, which an open position reports.
804
+ function describeOrderLeverage(pos, coin) {
805
+ const lev = pos ? formatPositionLeverage(pos.leverage) : null;
806
+ if (lev) return `${lev} (current ${coin} setting, unchanged by this order)`;
807
+ return `your current ${coin} setting, unchanged by this order (change it with: nansen perp leverage)`;
808
+ }
809
+
810
+ // When to load the signing key. Unprompted (off a terminal, or --yes): before
811
+ // the gate, exactly where it always was, so a missing or wrong password is
812
+ // still reported before a metadata outage. Prompted: only after the user says
813
+ // yes, so a declined action never decrypts the wallet. Dry run: never for a
814
+ // local key (no password needed); a Privy wallet still has its id/address
815
+ // binding checked, which loads no key, so the preview fails the way the real
816
+ // run would. Returns null when the caller resolves the context after the gate.
817
+ async function signingCtxBeforeGate(wallet, guard, log) {
818
+ if (guard.dryRun) return wallet.provider === 'privy' ? resolveSigningCtx(wallet, log) : null;
819
+ if (guard.isTTY && !guard.assumeYes) return null;
820
+ return resolveSigningCtx(wallet, log);
821
+ }
822
+
823
+ // Print the plan and ask for confirmation when needed. Returns false when a
824
+ // dry run has finished, true to go on and sign. The plan (and the reads it
825
+ // makes) is only built when it will be shown, so the unprompted path makes no
826
+ // extra requests.
827
+ async function guardPerpAction(apiInstance, { guard, walletAddress, buildPlan, question }, deps) {
828
+ const showPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
829
+ // On a dry run, screen as a real run would right before signing, so a
830
+ // preview of a blocked wallet fails the same way instead of looking clean.
831
+ // The plan's reads fail open, so only the screen can throw here.
832
+ const [plan] = await Promise.all([
833
+ showPlan ? buildPlan() : '',
834
+ guard.dryRun ? screenOrThrow(apiInstance, [walletAddress]) : undefined,
835
+ ]);
836
+ return guardExecution({
837
+ plan,
838
+ ...guard,
839
+ promptFn: deps.promptFn,
840
+ log: deps.log,
841
+ confirmationLog: deps.confirmationLog,
842
+ question,
843
+ dryRunNotice: PERP_DRY_RUN_NOTICE,
844
+ });
659
845
  }
660
846
 
661
847
  // ── Command builder ──────────────────────────────────────────────────
662
848
 
849
+ // Hyperliquid reports each position's leverage setting as { type, value }
850
+ // (type is "cross" or "isolated"). The liquidation price is the exchange's own
851
+ // figure and only makes sense next to it: on cross margin it depends on the
852
+ // whole account's equity, so even a 1x position can have a liquidation price
853
+ // near the current price. Returns e.g. "1x cross", or null when absent.
854
+ export function formatPositionLeverage(leverage) {
855
+ if (!leverage || typeof leverage !== 'object') return null;
856
+ const value = Number(leverage.value);
857
+ const hasValue = leverage.value !== null && leverage.value !== '' && Number.isFinite(value);
858
+ const type = typeof leverage.type === 'string' && leverage.type ? leverage.type : null;
859
+ if (!hasValue && !type) return null;
860
+ return [hasValue ? `${value}x` : null, type].filter(Boolean).join(' ');
861
+ }
862
+
663
863
  export function buildPerpCommands(deps = {}) {
664
864
  const {
665
865
  log = console.log,
666
866
  warn = (m) => process.stderr.write(`${m}\n`),
667
867
  track = trackPerpOrderCompleted,
868
+ // Confirmation seams, wired by the CLI exactly as for trade/bridge execute.
869
+ // A library caller that passes none is non-interactive (isTTY false).
870
+ promptFn,
871
+ confirmationLog = log,
872
+ isTTY = false,
873
+ env = process.env,
668
874
  } = deps;
875
+ const guardDeps = { promptFn, log, confirmationLog };
669
876
 
670
877
  return {
671
878
  'order': async (args, apiInstance, flags, options) => {
@@ -674,10 +881,10 @@ export function buildPerpCommands(deps = {}) {
674
881
 
675
882
  if (!coin || !options.side || options.size === undefined || options.price === undefined) {
676
883
  throw new CommandError(
677
- `Usage: nansen perp order --coin <symbol> --side <buy|sell> --size <amount> --price <price> [options]
884
+ `Usage: nansen perp order --symbol <symbol> --side <buy|sell> --size <amount> --price <price> [options]
678
885
 
679
886
  OPTIONS:
680
- --coin Asset symbol (BTC, ETH, etc.)
887
+ --symbol Asset symbol (BTC, ETH, etc.; alias --coin)
681
888
  --side buy (long) or sell (short)
682
889
  --size Position size in base asset units
683
890
  --price Limit price (or mark price for market orders)
@@ -686,7 +893,9 @@ OPTIONS:
686
893
  --slippage Slippage for market orders (default 0.03 = 3%)
687
894
  --take-profit Take-profit trigger price
688
895
  --stop-loss Stop-loss trigger price
689
- --wallet Wallet name`, 'MISSING_PARAM');
896
+ --wallet Wallet name
897
+ --dry-run Validate and print the order plan; sign and send nothing
898
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1)`, 'MISSING_PARAM');
690
899
  }
691
900
 
692
901
  const side = assertSide(options.side, ORDER_SIDES);
@@ -698,6 +907,7 @@ OPTIONS:
698
907
  const tp = options['take-profit'] !== undefined ? parsePositiveNumber(options['take-profit'], 'take-profit') : undefined;
699
908
  const sl = options['stop-loss'] !== undefined ? parsePositiveNumber(options['stop-loss'], 'stop-loss') : undefined;
700
909
  const isBuy = side === 'buy' || side === 'long';
910
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
701
911
 
702
912
  // buildOrderAction re-checks this, but that call happens after the signing
703
913
  // context is resolved and after ensureBuilderApproved has already signed
@@ -714,20 +924,19 @@ OPTIONS:
714
924
  warnImpreciseValue(coin, assetMeta?.szDecimals, { sizeRaw: options.size, priceRaw: options.price }, warn);
715
925
 
716
926
  const wallet = resolveWalletAddress(walletName);
717
- const ctx = await resolveSigningCtx(wallet, log);
927
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
718
928
 
719
929
  const { assetId, szDecimals } = requireAsset(assetMeta, coin);
720
930
 
721
- log(`\n Perp Order: ${coin} ${isBuy ? 'LONG' : 'SHORT'} ${size} @ ${price} (${orderType})`);
722
-
723
931
  // Single source of truth for the builder code + approval gate (D1).
724
932
  // On the first trade this screens the wallet once for the builder-fee
725
933
  // approval and again for the order itself. The two round-trips are
726
934
  // deliberate: each signed action re-screens the signer, so this is not
727
935
  // duplication to collapse.
728
936
  const builderStatus = await fetchBuilderFee(apiInstance, wallet.address);
729
- await ensureBuilderApproved(apiInstance, builderStatus, ctx);
730
937
 
938
+ // Built (pure, nothing signed) before the gate so the plan shows the
939
+ // rounded size and price that will actually be encoded.
731
940
  const { action, size: effSize, price: effPrice } = buildOrderAction(
732
941
  {
733
942
  isBuy,
@@ -743,6 +952,41 @@ OPTIONS:
743
952
  },
744
953
  { assetId, szDecimals },
745
954
  );
955
+
956
+ // Before the builder-fee approval: a dry run or a declined prompt must not
957
+ // put that one-time approval on-chain either.
958
+ const proceed = await guardPerpAction(apiInstance, {
959
+ guard,
960
+ walletAddress: wallet.address,
961
+ question: 'Submit this order to Hyperliquid? [y/N] ',
962
+ buildPlan: async () => {
963
+ const position = await readOpenPosition(apiInstance, wallet.address, coin);
964
+ return formatPlan(`Perp order plan — ${coin}`, [
965
+ ['Wallet', wallet.address],
966
+ ['Side', `${isBuy ? 'buy' : 'sell'} (${isBuy ? 'long' : 'short'})`],
967
+ ['Size', `${effSize} ${coin}`],
968
+ ['Type', orderType === 'market' ? 'market (IOC)' : `limit (${tif})`],
969
+ ['Price', orderType === 'market'
970
+ ? `${price} reference, worst fill ${effPrice} (${formatSlippage(slippage)} slippage)`
971
+ : String(effPrice)],
972
+ ['Take-profit', describeTriggerLeg(action, 'tp', coin)],
973
+ ['Stop-loss', describeTriggerLeg(action, 'sl', coin)],
974
+ ['Est. notional', orderType === 'market'
975
+ ? formatIocNotional(mainOrderLeg(action)?.s, String(price), mainOrderLeg(action)?.p)
976
+ : formatUsd(mainOrderLeg(action)?.s, mainOrderLeg(action)?.p)],
977
+ ['Leverage', describeOrderLeverage(position, coin)],
978
+ ['Open position', describePosition(position)],
979
+ ['Builder fee', builderFeeLine(builderStatus)],
980
+ ]);
981
+ },
982
+ }, guardDeps);
983
+ if (!proceed) return undefined;
984
+ ctx ??= await resolveSigningCtx(wallet, log);
985
+
986
+ log(`\n Perp Order: ${coin} ${isBuy ? 'LONG' : 'SHORT'} ${size} @ ${price} (${orderType})`);
987
+
988
+ await ensureBuilderApproved(apiInstance, builderStatus, ctx);
989
+
746
990
  const nonce = hlNonce();
747
991
  const eip712 = l1Eip712(action, null, nonce);
748
992
 
@@ -772,19 +1016,48 @@ OPTIONS:
772
1016
  const walletName = scalar(options.wallet, 'wallet');
773
1017
 
774
1018
  if (!coin || options.oid === undefined) {
775
- throw new CommandError('Usage: nansen perp cancel --coin <symbol> --oid <orderId> [--wallet <name>]', 'MISSING_PARAM');
1019
+ throw new CommandError('Usage: nansen perp cancel --symbol <symbol> --oid <orderId> [--wallet <name>] [--dry-run] [--yes]', 'MISSING_PARAM');
776
1020
  }
777
1021
 
778
1022
  const oid = parsePositiveInt(options.oid, 'oid');
1023
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
779
1024
 
780
1025
  const assetMeta = await fetchAssetMeta(apiInstance, coin);
781
1026
  const wallet = resolveWalletAddress(walletName);
782
- const ctx = await resolveSigningCtx(wallet, log);
1027
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
783
1028
  const { assetId } = requireAsset(assetMeta, coin);
784
1029
 
1030
+ const { action } = buildCancelAction({ orderId: oid }, { assetId });
1031
+
1032
+ const proceed = await guardPerpAction(apiInstance, {
1033
+ guard,
1034
+ walletAddress: wallet.address,
1035
+ question: 'Submit this cancel to Hyperliquid? [y/N] ',
1036
+ buildPlan: async () => {
1037
+ let order;
1038
+ try {
1039
+ const result = await perpRead(apiInstance, 'orders', { wallet_address: wallet.address });
1040
+ const match = (result.orders || []).find(o => Number(o.oid) === oid && String(o.coin).toUpperCase() === coin);
1041
+ // Hyperliquid reports a resting order's side as B (bid) or A (ask).
1042
+ const orderSide = { B: 'buy', A: 'sell' }[match?.side] ?? match?.side;
1043
+ order = match
1044
+ ? `${orderSide} ${match.sz} @ ${match.limitPx}`
1045
+ : `not among the open ${coin} orders (Hyperliquid rejects the cancel if the order is not open)`;
1046
+ } catch {
1047
+ order = 'could not load open orders';
1048
+ }
1049
+ return formatPlan(`Perp cancel plan — ${coin}`, [
1050
+ ['Wallet', wallet.address],
1051
+ ['Order id', String(oid)],
1052
+ ['Order', order],
1053
+ ]);
1054
+ },
1055
+ }, guardDeps);
1056
+ if (!proceed) return undefined;
1057
+ ctx ??= await resolveSigningCtx(wallet, log);
1058
+
785
1059
  log(`\n Cancel: ${coin} order #${oid}`);
786
1060
 
787
- const { action } = buildCancelAction({ orderId: oid }, { assetId });
788
1061
  const nonce = hlNonce();
789
1062
  const eip712 = l1Eip712(action, null, nonce);
790
1063
 
@@ -799,10 +1072,12 @@ OPTIONS:
799
1072
 
800
1073
  if (!coin || options.size === undefined || options.price === undefined || !options.side) {
801
1074
  throw new CommandError(
802
- `Usage: nansen perp close --coin <symbol> --size <amount> --price <markPrice> --side <buy|sell> [options]
1075
+ `Usage: nansen perp close --symbol <symbol> --size <amount> --price <markPrice> --side <buy|sell> [options]
803
1076
 
804
1077
  --side buy (closing a short) or sell (closing a long)
805
- --slippage Slippage tolerance (default 0.03 = 3%)`, 'MISSING_PARAM');
1078
+ --slippage Slippage tolerance (default 0.03 = 3%)
1079
+ --dry-run Validate and print the close plan; sign and send nothing
1080
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1)`, 'MISSING_PARAM');
806
1081
  }
807
1082
 
808
1083
  const side = assertSide(options.side, CLOSE_SIDES);
@@ -810,6 +1085,7 @@ OPTIONS:
810
1085
  const price = parsePositiveNumber(options.price, 'price');
811
1086
  const slippage = options.slippage !== undefined ? parseSlippage(options.slippage) : 0.03;
812
1087
  const isBuy = side === 'buy';
1088
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
813
1089
 
814
1090
  // Advisory: warn before signing if the close size is finer than the asset
815
1091
  // allows (Hyperliquid rounds rather than rejects). --price here is only a
@@ -823,39 +1099,69 @@ OPTIONS:
823
1099
  // fails fast with a clear message instead of the backend's opaque "reduce
824
1100
  // only order would increase position". sell closes a long, buy closes a
825
1101
  // short. Fall open if positions can't be fetched — HL still checks.
826
- let openPositions = null;
827
- try {
828
- const result = await perpRead(apiInstance, 'positions', { wallet_address: wallet.address });
829
- openPositions = result.positions || [];
830
- } catch {
831
- // positions lookup failed — skip the direction pre-check.
1102
+ // undefined: lookup failed or malformed (skip the checks); null: no position.
1103
+ const openPosition = await readOpenPosition(apiInstance, wallet.address, coin);
1104
+ // The lookup worked and there is nothing to close: a reduce-only order
1105
+ // would be rejected by Hyperliquid, so a dry run must not report success.
1106
+ // Only the dry run fails here. A real close still goes to Hyperliquid,
1107
+ // which holds the live state: the proxy's positions can lag a fill that
1108
+ // just happened, and a stale "none" must never block a risk-reducing close.
1109
+ if (openPosition === null && guard.dryRun) {
1110
+ // An unknown coin or a metadata outage is the more useful answer, and a
1111
+ // dry run screens the wallet as guardPerpAction would (a blocked wallet
1112
+ // must fail the preview the same way whether or not it has a position).
1113
+ requireAsset(assetMeta, coin);
1114
+ await screenOrThrow(apiInstance, [wallet.address]);
1115
+ throw new CommandError(
1116
+ `No open ${coin} position to close for ${wallet.address}. Check with: nansen perp positions. If you opened it moments ago, the positions data may not show it yet; retry in a few seconds.`,
1117
+ 'NO_OPEN_POSITION',
1118
+ );
832
1119
  }
833
- if (openPositions) {
834
- const pos = openPositions.find(p => String(p.coin).toUpperCase() === coin);
835
- const szi = pos ? parseFloat(pos.szi) : NaN;
836
- if (Number.isFinite(szi) && szi !== 0) {
837
- const requiredSide = szi > 0 ? 'sell' : 'buy';
838
- if (side !== requiredSide) {
839
- const posSide = szi > 0 ? 'long' : 'short';
840
- throw invalid(
841
- `Cannot close a ${posSide} ${coin} position with --side ${side}. Use --side ${requiredSide} (sell closes a long, buy closes a short).`,
842
- );
843
- }
1120
+ if (openPosition) {
1121
+ const posSide = positionSide(openPosition.szi).side;
1122
+ const requiredSide = posSide === 'long' ? 'sell' : 'buy';
1123
+ if (side !== requiredSide) {
1124
+ throw invalid(
1125
+ `Cannot close a ${posSide} ${coin} position with --side ${side}. Use --side ${requiredSide} (sell closes a long, buy closes a short).`,
1126
+ );
844
1127
  }
845
1128
  }
846
1129
 
847
- const ctx = await resolveSigningCtx(wallet, log);
1130
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
848
1131
  const { assetId, szDecimals } = requireAsset(assetMeta, coin);
849
1132
 
850
- log(`\n Close: ${coin} ${isBuy ? 'buy-to-close' : 'sell-to-close'} ${size} @ ${price}`);
851
-
852
1133
  const builderStatus = await fetchBuilderFee(apiInstance, wallet.address);
853
- await ensureBuilderApproved(apiInstance, builderStatus, ctx);
854
1134
 
855
1135
  const { action, size: effSize, price: effPrice } = buildCloseAction(
856
1136
  { size, price, isBuy, slippage, builder: builderCode(builderStatus) },
857
1137
  { assetId, szDecimals },
858
1138
  );
1139
+
1140
+ const proceed = await guardPerpAction(apiInstance, {
1141
+ guard,
1142
+ walletAddress: wallet.address,
1143
+ question: 'Submit this close order to Hyperliquid? [y/N] ',
1144
+ buildPlan: async () => formatPlan(`Perp close plan — ${coin}`, [
1145
+ ['Wallet', wallet.address],
1146
+ ['Side', `${side} (${isBuy ? 'closes a short' : 'closes a long'}, reduce-only)`],
1147
+ ['Size', `${effSize} ${coin}`],
1148
+ ['Type', 'market (IOC)'],
1149
+ ['Price', `${price} reference, worst fill ${effPrice} (${formatSlippage(slippage)} slippage)`],
1150
+ ...(openPosition === null
1151
+ ? [['Warning', `no open ${coin} position in the positions data; Hyperliquid rejects a reduce-only close with nothing to close (the data can lag a fill that just happened)`]]
1152
+ : []),
1153
+ ['Est. notional', formatIocNotional(mainOrderLeg(action)?.s, String(price), mainOrderLeg(action)?.p)],
1154
+ ['Open position', describePosition(openPosition)],
1155
+ ['Builder fee', builderFeeLine(builderStatus)],
1156
+ ]),
1157
+ }, guardDeps);
1158
+ if (!proceed) return undefined;
1159
+ ctx ??= await resolveSigningCtx(wallet, log);
1160
+
1161
+ log(`\n Close: ${coin} ${isBuy ? 'buy-to-close' : 'sell-to-close'} ${size} @ ${price}`);
1162
+
1163
+ await ensureBuilderApproved(apiInstance, builderStatus, ctx);
1164
+
859
1165
  const nonce = hlNonce();
860
1166
  const eip712 = l1Eip712(action, null, nonce);
861
1167
 
@@ -885,11 +1191,12 @@ OPTIONS:
885
1191
  const walletName = scalar(options.wallet, 'wallet');
886
1192
 
887
1193
  if (!coin || options.leverage === undefined) {
888
- throw new CommandError('Usage: nansen perp leverage --coin <symbol> --leverage <n> [--margin-type cross|isolated] [--wallet <name>]', 'MISSING_PARAM');
1194
+ throw new CommandError('Usage: nansen perp leverage --symbol <symbol> --leverage <n> [--margin-type cross|isolated] [--wallet <name>] [--dry-run] [--yes]', 'MISSING_PARAM');
889
1195
  }
890
1196
 
891
1197
  const marginType = assertMarginType(options['margin-type']);
892
1198
  const leverage = parsePositiveInt(options.leverage, 'leverage');
1199
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
893
1200
 
894
1201
  // Pre-validate against the asset's max leverage so an over-max value fails
895
1202
  // fast with a clear message instead of an opaque HL rejection. Falls open
@@ -902,12 +1209,31 @@ OPTIONS:
902
1209
 
903
1210
  const isCross = marginType === 'cross';
904
1211
  const wallet = resolveWalletAddress(walletName);
905
- const ctx = await resolveSigningCtx(wallet, log);
1212
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
906
1213
  const { assetId } = requireAsset(assetMeta, coin);
907
1214
 
1215
+ const { action } = buildLeverageAction({ leverage, isCross }, { assetId });
1216
+
1217
+ const proceed = await guardPerpAction(apiInstance, {
1218
+ guard,
1219
+ walletAddress: wallet.address,
1220
+ question: 'Submit this leverage change to Hyperliquid? [y/N] ',
1221
+ buildPlan: async () => {
1222
+ const position = await readOpenPosition(apiInstance, wallet.address, coin);
1223
+ return formatPlan(`Perp leverage plan — ${coin}`, [
1224
+ ['Wallet', wallet.address],
1225
+ ['Leverage', `${leverage}x`],
1226
+ ['Margin type', marginType],
1227
+ ['Asset maximum', Number.isFinite(assetMeta.maxLeverage) ? `${assetMeta.maxLeverage}x` : null],
1228
+ ['Open position', describePosition(position)],
1229
+ ]);
1230
+ },
1231
+ }, guardDeps);
1232
+ if (!proceed) return undefined;
1233
+ ctx ??= await resolveSigningCtx(wallet, log);
1234
+
908
1235
  log(`\n Leverage: ${coin} ${leverage}x ${isCross ? 'cross' : 'isolated'}`);
909
1236
 
910
- const { action } = buildLeverageAction({ leverage, isCross }, { assetId });
911
1237
  const nonce = hlNonce();
912
1238
  const eip712 = l1Eip712(action, null, nonce);
913
1239
 
@@ -985,7 +1311,8 @@ OPTIONS:
985
1311
  log(`\n Open Positions (${positions.length}):`);
986
1312
  for (const p of positions) {
987
1313
  const side = parseFloat(p.szi) >= 0 ? 'LONG' : 'SHORT';
988
- log(` ${p.coin} ${side} size=${p.szi} entry=${p.entryPx} pnl=${p.unrealizedPnl} liq=${p.liquidationPx || 'n/a'}`);
1314
+ const lev = formatPositionLeverage(p.leverage);
1315
+ log(` ${p.coin} ${side} size=${p.szi} entry=${p.entryPx} pnl=${p.unrealizedPnl}${lev ? ` lev=${lev}` : ''} liq=${p.liquidationPx || 'n/a'}`);
989
1316
  }
990
1317
  log('');
991
1318
  return undefined;