nansen-cli 2.4.0 → 2.5.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,
@@ -658,14 +659,215 @@ function resolveCoin(options) {
658
659
  return String(raw ?? '').toUpperCase();
659
660
  }
660
661
 
662
+ // ── Preview + confirmation (--dry-run / --yes) ───────────────────────
663
+ //
664
+ // order/close/cancel/leverage share the acknowledgement gate of trade and
665
+ // bridge execute (src/execute-guard.js): --dry-run prints the plan and stops
666
+ // before anything is signed; an interactive terminal is asked to confirm;
667
+ // --yes / -y / NANSEN_YES=1 skips the question. Off a terminal the command
668
+ // proceeds unprompted, exactly as before.
669
+
670
+ const PERP_DRY_RUN_NOTICE = [
671
+ '\n DRY RUN — nothing was sent to Hyperliquid. No action was signed.',
672
+ ' Re-run without --dry-run to sign and submit it.\n',
673
+ ];
674
+
675
+ // A decimal string (a wire value, or a number's shortest form such as "1e-7")
676
+ // as an exact BigInt scaled by 10^scale. null when it isn't one.
677
+ function parseDecimal(value) {
678
+ const match = /^([-+]?)(\d*)(?:\.(\d*))?(?:e([-+]?\d{1,3}))?$/i.exec(String(value ?? '').trim());
679
+ if (!match || !(match[2] || match[3])) return null;
680
+ const fraction = match[3] ?? '';
681
+ let digits = BigInt(`${match[2] || '0'}${fraction}`);
682
+ let scale = fraction.length - Number(match[4] ?? 0);
683
+ if (scale < 0) {
684
+ digits *= 10n ** BigInt(-scale);
685
+ scale = 0;
686
+ }
687
+ return { digits: match[1] === '-' ? -digits : digits, scale };
688
+ }
689
+
690
+ // USD value of size × price, computed in exact decimal arithmetic from the
691
+ // strings that are signed, so the preview cannot drift from the submitted
692
+ // order through float rounding. Only the cent rounding (half up) is approximate.
693
+ function formatUsd(size, price) {
694
+ const a = parseDecimal(size);
695
+ const b = parseDecimal(price);
696
+ if (!a || !b) return null;
697
+ const product = a.digits * b.digits;
698
+ if (product < 0n) return null;
699
+ const scale = a.scale + b.scale;
700
+ let cents;
701
+ if (scale <= 2) {
702
+ cents = product * 10n ** BigInt(2 - scale);
703
+ } else {
704
+ const divisor = 10n ** BigInt(scale - 2);
705
+ cents = (product + divisor / 2n) / divisor;
706
+ }
707
+ if (product > 0n && cents === 0n) return '<$0.01';
708
+ return `~$${cents / 100n}.${String(cents % 100n).padStart(2, '0')}`;
709
+ }
710
+
711
+ // Notional of an IOC order at the reference price and at its worst fill (the
712
+ // limit price encoded after slippage), so a buy's worst-case cost is visible.
713
+ function formatIocNotional(size, referencePrice, worstPrice) {
714
+ const atReference = formatUsd(size, referencePrice);
715
+ const atWorst = formatUsd(size, worstPrice);
716
+ return atReference && atWorst ? `${atReference} at the reference price, ${atWorst} at the worst fill` : null;
717
+ }
718
+
719
+ // The order leg of a built action (not an attached take-profit/stop-loss), whose
720
+ // `s` and `p` are the exact size and limit price strings that get signed.
721
+ function mainOrderLeg(action) {
722
+ return action.orders?.find(o => !o?.t?.trigger);
723
+ }
724
+
725
+ function formatSlippage(slippage) {
726
+ return `${Number((slippage * 100).toFixed(4))}%`;
727
+ }
728
+
729
+ function builderFeeLine(status) {
730
+ const rate = builderMaxFeeRate(status.required_fee);
731
+ if (status.approved) return `${rate} of the order value (approved)`;
732
+ 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`;
733
+ }
734
+
735
+ // An attached take-profit/stop-loss leg as it will be signed: side, size,
736
+ // reduce-only and trigger read from the built action. undefined when absent.
737
+ function describeTriggerLeg(action, tpsl, coin) {
738
+ const leg = action.orders?.find(o => o?.t?.trigger?.tpsl === tpsl);
739
+ if (!leg) return undefined;
740
+ const { isMarket, triggerPx } = leg.t.trigger;
741
+ return [
742
+ `${leg.b ? 'buy' : 'sell'} ${leg.s} ${coin}`,
743
+ ...(leg.r ? ['reduce-only'] : []),
744
+ `${isMarket ? 'market' : 'limit'} when the price reaches ${triggerPx}`,
745
+ ].join(', ');
746
+ }
747
+
748
+ // Read-only lookup of the wallet's open position in `coin`, for the plan and
749
+ // close's pre-checks. Returns the position, null when there is none, or
750
+ // undefined when the read failed or the answer for `coin` can't be trusted
751
+ // (callers then skip the checks, and the plan says so instead of guessing).
752
+ async function readOpenPosition(apiInstance, walletAddress, coin) {
753
+ try {
754
+ const result = await perpRead(apiInstance, 'positions', { wallet_address: walletAddress });
755
+ return findPosition(result?.positions, coin);
756
+ } catch {
757
+ return undefined;
758
+ }
759
+ }
760
+
761
+ // A position size as the exchange sends it: a plain decimal string, signed
762
+ // for a short. Shared by the parse and the well-formed check so they agree.
763
+ const SZI_RE = /^\s*([-+]?)(\d*\.?\d+)\s*$/;
764
+
765
+ // Side and unsigned size of a position, read from the exchange's own szi
766
+ // string, so no float conversion can round a tiny size to zero or lose its
767
+ // sign. null for a zero, missing or malformed size.
768
+ function positionSide(szi) {
769
+ const match = SZI_RE.exec(String(szi ?? ''));
770
+ if (!match || !/[1-9]/.test(match[2])) return null;
771
+ return { side: match[1] === '-' ? 'short' : 'long', size: match[2] };
772
+ }
773
+
774
+ // The coin's position, null when there is none (no entry, or a zero size), or
775
+ // undefined when the answer can't be trusted: `positions` is not a list, or
776
+ // this coin's entry has a missing or unreadable size. Entries that are not
777
+ // objects or carry no coin name can't be matched and are skipped, and a bad
778
+ // entry for another coin is ignored, so neither switches off this coin's checks.
779
+ // The first entry for the coin wins.
780
+ function findPosition(positions, coin) {
781
+ if (!Array.isArray(positions)) return undefined;
782
+ const pos = positions.find(p => p !== null && typeof p === 'object'
783
+ && p.coin != null && String(p.coin).toUpperCase() === coin);
784
+ if (!pos) return null;
785
+ if (positionSide(pos.szi)) return pos;
786
+ return SZI_RE.test(String(pos.szi ?? '')) ? null : undefined;
787
+ }
788
+
789
+ function describePosition(pos) {
790
+ if (pos === undefined) return 'could not be loaded';
791
+ if (pos === null) return 'none';
792
+ const { side, size } = positionSide(pos.szi);
793
+ const lev = formatPositionLeverage(pos.leverage);
794
+ return `${side} ${size}${pos.entryPx ? ` @ ${pos.entryPx}` : ''}${lev ? `, ${lev}` : ''}`;
795
+ }
796
+
797
+ // Leverage that applies to an order in `coin`: Hyperliquid uses the wallet's
798
+ // per-asset setting, which an open position reports.
799
+ function describeOrderLeverage(pos, coin) {
800
+ const lev = pos ? formatPositionLeverage(pos.leverage) : null;
801
+ if (lev) return `${lev} (current ${coin} setting, unchanged by this order)`;
802
+ return `your current ${coin} setting, unchanged by this order (change it with: nansen perp leverage)`;
803
+ }
804
+
805
+ // When to load the signing key. Unprompted (off a terminal, or --yes): before
806
+ // the gate, exactly where it always was, so a missing or wrong password is
807
+ // still reported before a metadata outage. Prompted: only after the user says
808
+ // yes, so a declined action never decrypts the wallet. Dry run: never for a
809
+ // local key (no password needed); a Privy wallet still has its id/address
810
+ // binding checked, which loads no key, so the preview fails the way the real
811
+ // run would. Returns null when the caller resolves the context after the gate.
812
+ async function signingCtxBeforeGate(wallet, guard, log) {
813
+ if (guard.dryRun) return wallet.provider === 'privy' ? resolveSigningCtx(wallet, log) : null;
814
+ if (guard.isTTY && !guard.assumeYes) return null;
815
+ return resolveSigningCtx(wallet, log);
816
+ }
817
+
818
+ // Print the plan and ask for confirmation when needed. Returns false when a
819
+ // dry run has finished, true to go on and sign. The plan (and the reads it
820
+ // makes) is only built when it will be shown, so the unprompted path makes no
821
+ // extra requests.
822
+ async function guardPerpAction(apiInstance, { guard, walletAddress, buildPlan, question }, deps) {
823
+ const showPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
824
+ // On a dry run, screen as a real run would right before signing, so a
825
+ // preview of a blocked wallet fails the same way instead of looking clean.
826
+ // The plan's reads fail open, so only the screen can throw here.
827
+ const [plan] = await Promise.all([
828
+ showPlan ? buildPlan() : '',
829
+ guard.dryRun ? screenOrThrow(apiInstance, [walletAddress]) : undefined,
830
+ ]);
831
+ return guardExecution({
832
+ plan,
833
+ ...guard,
834
+ promptFn: deps.promptFn,
835
+ log: deps.log,
836
+ confirmationLog: deps.confirmationLog,
837
+ question,
838
+ dryRunNotice: PERP_DRY_RUN_NOTICE,
839
+ });
840
+ }
841
+
661
842
  // ── Command builder ──────────────────────────────────────────────────
662
843
 
844
+ // Hyperliquid reports each position's leverage setting as { type, value }
845
+ // (type is "cross" or "isolated"). The liquidation price is the exchange's own
846
+ // figure and only makes sense next to it: on cross margin it depends on the
847
+ // whole account's equity, so even a 1x position can have a liquidation price
848
+ // near the current price. Returns e.g. "1x cross", or null when absent.
849
+ export function formatPositionLeverage(leverage) {
850
+ if (!leverage || typeof leverage !== 'object') return null;
851
+ const value = Number(leverage.value);
852
+ const hasValue = leverage.value !== null && leverage.value !== '' && Number.isFinite(value);
853
+ const type = typeof leverage.type === 'string' && leverage.type ? leverage.type : null;
854
+ if (!hasValue && !type) return null;
855
+ return [hasValue ? `${value}x` : null, type].filter(Boolean).join(' ');
856
+ }
857
+
663
858
  export function buildPerpCommands(deps = {}) {
664
859
  const {
665
860
  log = console.log,
666
861
  warn = (m) => process.stderr.write(`${m}\n`),
667
862
  track = trackPerpOrderCompleted,
863
+ // Confirmation seams, wired by the CLI exactly as for trade/bridge execute.
864
+ // A library caller that passes none is non-interactive (isTTY false).
865
+ promptFn,
866
+ confirmationLog = log,
867
+ isTTY = false,
868
+ env = process.env,
668
869
  } = deps;
870
+ const guardDeps = { promptFn, log, confirmationLog };
669
871
 
670
872
  return {
671
873
  'order': async (args, apiInstance, flags, options) => {
@@ -686,7 +888,9 @@ OPTIONS:
686
888
  --slippage Slippage for market orders (default 0.03 = 3%)
687
889
  --take-profit Take-profit trigger price
688
890
  --stop-loss Stop-loss trigger price
689
- --wallet Wallet name`, 'MISSING_PARAM');
891
+ --wallet Wallet name
892
+ --dry-run Validate and print the order plan; sign and send nothing
893
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1)`, 'MISSING_PARAM');
690
894
  }
691
895
 
692
896
  const side = assertSide(options.side, ORDER_SIDES);
@@ -698,6 +902,7 @@ OPTIONS:
698
902
  const tp = options['take-profit'] !== undefined ? parsePositiveNumber(options['take-profit'], 'take-profit') : undefined;
699
903
  const sl = options['stop-loss'] !== undefined ? parsePositiveNumber(options['stop-loss'], 'stop-loss') : undefined;
700
904
  const isBuy = side === 'buy' || side === 'long';
905
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
701
906
 
702
907
  // buildOrderAction re-checks this, but that call happens after the signing
703
908
  // context is resolved and after ensureBuilderApproved has already signed
@@ -714,20 +919,19 @@ OPTIONS:
714
919
  warnImpreciseValue(coin, assetMeta?.szDecimals, { sizeRaw: options.size, priceRaw: options.price }, warn);
715
920
 
716
921
  const wallet = resolveWalletAddress(walletName);
717
- const ctx = await resolveSigningCtx(wallet, log);
922
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
718
923
 
719
924
  const { assetId, szDecimals } = requireAsset(assetMeta, coin);
720
925
 
721
- log(`\n Perp Order: ${coin} ${isBuy ? 'LONG' : 'SHORT'} ${size} @ ${price} (${orderType})`);
722
-
723
926
  // Single source of truth for the builder code + approval gate (D1).
724
927
  // On the first trade this screens the wallet once for the builder-fee
725
928
  // approval and again for the order itself. The two round-trips are
726
929
  // deliberate: each signed action re-screens the signer, so this is not
727
930
  // duplication to collapse.
728
931
  const builderStatus = await fetchBuilderFee(apiInstance, wallet.address);
729
- await ensureBuilderApproved(apiInstance, builderStatus, ctx);
730
932
 
933
+ // Built (pure, nothing signed) before the gate so the plan shows the
934
+ // rounded size and price that will actually be encoded.
731
935
  const { action, size: effSize, price: effPrice } = buildOrderAction(
732
936
  {
733
937
  isBuy,
@@ -743,6 +947,41 @@ OPTIONS:
743
947
  },
744
948
  { assetId, szDecimals },
745
949
  );
950
+
951
+ // Before the builder-fee approval: a dry run or a declined prompt must not
952
+ // put that one-time approval on-chain either.
953
+ const proceed = await guardPerpAction(apiInstance, {
954
+ guard,
955
+ walletAddress: wallet.address,
956
+ question: 'Submit this order to Hyperliquid? [y/N] ',
957
+ buildPlan: async () => {
958
+ const position = await readOpenPosition(apiInstance, wallet.address, coin);
959
+ return formatPlan(`Perp order plan — ${coin}`, [
960
+ ['Wallet', wallet.address],
961
+ ['Side', `${isBuy ? 'buy' : 'sell'} (${isBuy ? 'long' : 'short'})`],
962
+ ['Size', `${effSize} ${coin}`],
963
+ ['Type', orderType === 'market' ? 'market (IOC)' : `limit (${tif})`],
964
+ ['Price', orderType === 'market'
965
+ ? `${price} reference, worst fill ${effPrice} (${formatSlippage(slippage)} slippage)`
966
+ : String(effPrice)],
967
+ ['Take-profit', describeTriggerLeg(action, 'tp', coin)],
968
+ ['Stop-loss', describeTriggerLeg(action, 'sl', coin)],
969
+ ['Est. notional', orderType === 'market'
970
+ ? formatIocNotional(mainOrderLeg(action)?.s, String(price), mainOrderLeg(action)?.p)
971
+ : formatUsd(mainOrderLeg(action)?.s, mainOrderLeg(action)?.p)],
972
+ ['Leverage', describeOrderLeverage(position, coin)],
973
+ ['Open position', describePosition(position)],
974
+ ['Builder fee', builderFeeLine(builderStatus)],
975
+ ]);
976
+ },
977
+ }, guardDeps);
978
+ if (!proceed) return undefined;
979
+ ctx ??= await resolveSigningCtx(wallet, log);
980
+
981
+ log(`\n Perp Order: ${coin} ${isBuy ? 'LONG' : 'SHORT'} ${size} @ ${price} (${orderType})`);
982
+
983
+ await ensureBuilderApproved(apiInstance, builderStatus, ctx);
984
+
746
985
  const nonce = hlNonce();
747
986
  const eip712 = l1Eip712(action, null, nonce);
748
987
 
@@ -772,19 +1011,48 @@ OPTIONS:
772
1011
  const walletName = scalar(options.wallet, 'wallet');
773
1012
 
774
1013
  if (!coin || options.oid === undefined) {
775
- throw new CommandError('Usage: nansen perp cancel --coin <symbol> --oid <orderId> [--wallet <name>]', 'MISSING_PARAM');
1014
+ throw new CommandError('Usage: nansen perp cancel --coin <symbol> --oid <orderId> [--wallet <name>] [--dry-run] [--yes]', 'MISSING_PARAM');
776
1015
  }
777
1016
 
778
1017
  const oid = parsePositiveInt(options.oid, 'oid');
1018
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
779
1019
 
780
1020
  const assetMeta = await fetchAssetMeta(apiInstance, coin);
781
1021
  const wallet = resolveWalletAddress(walletName);
782
- const ctx = await resolveSigningCtx(wallet, log);
1022
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
783
1023
  const { assetId } = requireAsset(assetMeta, coin);
784
1024
 
1025
+ const { action } = buildCancelAction({ orderId: oid }, { assetId });
1026
+
1027
+ const proceed = await guardPerpAction(apiInstance, {
1028
+ guard,
1029
+ walletAddress: wallet.address,
1030
+ question: 'Submit this cancel to Hyperliquid? [y/N] ',
1031
+ buildPlan: async () => {
1032
+ let order;
1033
+ try {
1034
+ const result = await perpRead(apiInstance, 'orders', { wallet_address: wallet.address });
1035
+ const match = (result.orders || []).find(o => Number(o.oid) === oid && String(o.coin).toUpperCase() === coin);
1036
+ // Hyperliquid reports a resting order's side as B (bid) or A (ask).
1037
+ const orderSide = { B: 'buy', A: 'sell' }[match?.side] ?? match?.side;
1038
+ order = match
1039
+ ? `${orderSide} ${match.sz} @ ${match.limitPx}`
1040
+ : `not among the open ${coin} orders (Hyperliquid rejects the cancel if the order is not open)`;
1041
+ } catch {
1042
+ order = 'could not load open orders';
1043
+ }
1044
+ return formatPlan(`Perp cancel plan — ${coin}`, [
1045
+ ['Wallet', wallet.address],
1046
+ ['Order id', String(oid)],
1047
+ ['Order', order],
1048
+ ]);
1049
+ },
1050
+ }, guardDeps);
1051
+ if (!proceed) return undefined;
1052
+ ctx ??= await resolveSigningCtx(wallet, log);
1053
+
785
1054
  log(`\n Cancel: ${coin} order #${oid}`);
786
1055
 
787
- const { action } = buildCancelAction({ orderId: oid }, { assetId });
788
1056
  const nonce = hlNonce();
789
1057
  const eip712 = l1Eip712(action, null, nonce);
790
1058
 
@@ -802,7 +1070,9 @@ OPTIONS:
802
1070
  `Usage: nansen perp close --coin <symbol> --size <amount> --price <markPrice> --side <buy|sell> [options]
803
1071
 
804
1072
  --side buy (closing a short) or sell (closing a long)
805
- --slippage Slippage tolerance (default 0.03 = 3%)`, 'MISSING_PARAM');
1073
+ --slippage Slippage tolerance (default 0.03 = 3%)
1074
+ --dry-run Validate and print the close plan; sign and send nothing
1075
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1)`, 'MISSING_PARAM');
806
1076
  }
807
1077
 
808
1078
  const side = assertSide(options.side, CLOSE_SIDES);
@@ -810,6 +1080,7 @@ OPTIONS:
810
1080
  const price = parsePositiveNumber(options.price, 'price');
811
1081
  const slippage = options.slippage !== undefined ? parseSlippage(options.slippage) : 0.03;
812
1082
  const isBuy = side === 'buy';
1083
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
813
1084
 
814
1085
  // Advisory: warn before signing if the close size is finer than the asset
815
1086
  // allows (Hyperliquid rounds rather than rejects). --price here is only a
@@ -823,39 +1094,69 @@ OPTIONS:
823
1094
  // fails fast with a clear message instead of the backend's opaque "reduce
824
1095
  // only order would increase position". sell closes a long, buy closes a
825
1096
  // 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.
1097
+ // undefined: lookup failed or malformed (skip the checks); null: no position.
1098
+ const openPosition = await readOpenPosition(apiInstance, wallet.address, coin);
1099
+ // The lookup worked and there is nothing to close: a reduce-only order
1100
+ // would be rejected by Hyperliquid, so a dry run must not report success.
1101
+ // Only the dry run fails here. A real close still goes to Hyperliquid,
1102
+ // which holds the live state: the proxy's positions can lag a fill that
1103
+ // just happened, and a stale "none" must never block a risk-reducing close.
1104
+ if (openPosition === null && guard.dryRun) {
1105
+ // An unknown coin or a metadata outage is the more useful answer, and a
1106
+ // dry run screens the wallet as guardPerpAction would (a blocked wallet
1107
+ // must fail the preview the same way whether or not it has a position).
1108
+ requireAsset(assetMeta, coin);
1109
+ await screenOrThrow(apiInstance, [wallet.address]);
1110
+ throw new CommandError(
1111
+ `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.`,
1112
+ 'NO_OPEN_POSITION',
1113
+ );
832
1114
  }
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
- }
1115
+ if (openPosition) {
1116
+ const posSide = positionSide(openPosition.szi).side;
1117
+ const requiredSide = posSide === 'long' ? 'sell' : 'buy';
1118
+ if (side !== requiredSide) {
1119
+ throw invalid(
1120
+ `Cannot close a ${posSide} ${coin} position with --side ${side}. Use --side ${requiredSide} (sell closes a long, buy closes a short).`,
1121
+ );
844
1122
  }
845
1123
  }
846
1124
 
847
- const ctx = await resolveSigningCtx(wallet, log);
1125
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
848
1126
  const { assetId, szDecimals } = requireAsset(assetMeta, coin);
849
1127
 
850
- log(`\n Close: ${coin} ${isBuy ? 'buy-to-close' : 'sell-to-close'} ${size} @ ${price}`);
851
-
852
1128
  const builderStatus = await fetchBuilderFee(apiInstance, wallet.address);
853
- await ensureBuilderApproved(apiInstance, builderStatus, ctx);
854
1129
 
855
1130
  const { action, size: effSize, price: effPrice } = buildCloseAction(
856
1131
  { size, price, isBuy, slippage, builder: builderCode(builderStatus) },
857
1132
  { assetId, szDecimals },
858
1133
  );
1134
+
1135
+ const proceed = await guardPerpAction(apiInstance, {
1136
+ guard,
1137
+ walletAddress: wallet.address,
1138
+ question: 'Submit this close order to Hyperliquid? [y/N] ',
1139
+ buildPlan: async () => formatPlan(`Perp close plan — ${coin}`, [
1140
+ ['Wallet', wallet.address],
1141
+ ['Side', `${side} (${isBuy ? 'closes a short' : 'closes a long'}, reduce-only)`],
1142
+ ['Size', `${effSize} ${coin}`],
1143
+ ['Type', 'market (IOC)'],
1144
+ ['Price', `${price} reference, worst fill ${effPrice} (${formatSlippage(slippage)} slippage)`],
1145
+ ...(openPosition === null
1146
+ ? [['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)`]]
1147
+ : []),
1148
+ ['Est. notional', formatIocNotional(mainOrderLeg(action)?.s, String(price), mainOrderLeg(action)?.p)],
1149
+ ['Open position', describePosition(openPosition)],
1150
+ ['Builder fee', builderFeeLine(builderStatus)],
1151
+ ]),
1152
+ }, guardDeps);
1153
+ if (!proceed) return undefined;
1154
+ ctx ??= await resolveSigningCtx(wallet, log);
1155
+
1156
+ log(`\n Close: ${coin} ${isBuy ? 'buy-to-close' : 'sell-to-close'} ${size} @ ${price}`);
1157
+
1158
+ await ensureBuilderApproved(apiInstance, builderStatus, ctx);
1159
+
859
1160
  const nonce = hlNonce();
860
1161
  const eip712 = l1Eip712(action, null, nonce);
861
1162
 
@@ -885,11 +1186,12 @@ OPTIONS:
885
1186
  const walletName = scalar(options.wallet, 'wallet');
886
1187
 
887
1188
  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');
1189
+ throw new CommandError('Usage: nansen perp leverage --coin <symbol> --leverage <n> [--margin-type cross|isolated] [--wallet <name>] [--dry-run] [--yes]', 'MISSING_PARAM');
889
1190
  }
890
1191
 
891
1192
  const marginType = assertMarginType(options['margin-type']);
892
1193
  const leverage = parsePositiveInt(options.leverage, 'leverage');
1194
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
893
1195
 
894
1196
  // Pre-validate against the asset's max leverage so an over-max value fails
895
1197
  // fast with a clear message instead of an opaque HL rejection. Falls open
@@ -902,12 +1204,31 @@ OPTIONS:
902
1204
 
903
1205
  const isCross = marginType === 'cross';
904
1206
  const wallet = resolveWalletAddress(walletName);
905
- const ctx = await resolveSigningCtx(wallet, log);
1207
+ let ctx = await signingCtxBeforeGate(wallet, guard, log);
906
1208
  const { assetId } = requireAsset(assetMeta, coin);
907
1209
 
1210
+ const { action } = buildLeverageAction({ leverage, isCross }, { assetId });
1211
+
1212
+ const proceed = await guardPerpAction(apiInstance, {
1213
+ guard,
1214
+ walletAddress: wallet.address,
1215
+ question: 'Submit this leverage change to Hyperliquid? [y/N] ',
1216
+ buildPlan: async () => {
1217
+ const position = await readOpenPosition(apiInstance, wallet.address, coin);
1218
+ return formatPlan(`Perp leverage plan — ${coin}`, [
1219
+ ['Wallet', wallet.address],
1220
+ ['Leverage', `${leverage}x`],
1221
+ ['Margin type', marginType],
1222
+ ['Asset maximum', Number.isFinite(assetMeta.maxLeverage) ? `${assetMeta.maxLeverage}x` : null],
1223
+ ['Open position', describePosition(position)],
1224
+ ]);
1225
+ },
1226
+ }, guardDeps);
1227
+ if (!proceed) return undefined;
1228
+ ctx ??= await resolveSigningCtx(wallet, log);
1229
+
908
1230
  log(`\n Leverage: ${coin} ${leverage}x ${isCross ? 'cross' : 'isolated'}`);
909
1231
 
910
- const { action } = buildLeverageAction({ leverage, isCross }, { assetId });
911
1232
  const nonce = hlNonce();
912
1233
  const eip712 = l1Eip712(action, null, nonce);
913
1234
 
@@ -985,7 +1306,8 @@ OPTIONS:
985
1306
  log(`\n Open Positions (${positions.length}):`);
986
1307
  for (const p of positions) {
987
1308
  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'}`);
1309
+ const lev = formatPositionLeverage(p.leverage);
1310
+ log(` ${p.coin} ${side} size=${p.szi} entry=${p.entryPx} pnl=${p.unrealizedPnl}${lev ? ` lev=${lev}` : ''} liq=${p.liquidationPx || 'n/a'}`);
989
1311
  }
990
1312
  log('');
991
1313
  return undefined;
package/src/privy.js CHANGED
@@ -11,7 +11,7 @@ import path from "path";
11
11
  import { parsePaymentRequirements } from "./x402.js";
12
12
  import { hasSufficientEvmPaymentBalance, hasSufficientSvmPaymentBalance } from "./x402-payment-balance.js";
13
13
  import { isEvmNetwork } from "./x402-evm.js";
14
- import { mkdirPrivateSync, readWalletJson, withWalletLock, writeWalletJsonAtomic } from "./wallet.js";
14
+ import { mkdirPrivateSync, readWalletJson, validateWalletName, withWalletLock, writeWalletJsonAtomic } from "./wallet.js";
15
15
  import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo, signWithSessionCharge } from "./x402-policy.js";
16
16
  import {
17
17
  isSvmNetwork,
@@ -209,10 +209,7 @@ function getClient() {
209
209
  * Mirrors createWallet() in wallet.js but for Privy server wallets.
210
210
  */
211
211
  export async function createPrivyWalletPair(name) {
212
- const WALLET_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
213
- if (!name || !WALLET_NAME_RE.test(name)) {
214
- throw new Error("Wallet name must be 1-64 characters: letters, numbers, hyphens, underscores only");
215
- }
212
+ validateWalletName(name, { creating: true });
216
213
 
217
214
  const walletsDir = path.join(process.env.HOME || process.env.USERPROFILE || "", ".nansen", "wallets");
218
215
  const walletFile = path.join(walletsDir, `${name}.json`);
@@ -37,12 +37,28 @@ export function buildPagination(options) {
37
37
  // Parse simple sort syntax: "field:direction" or "field" (defaults to DESC)
38
38
  export function parseSort(sortOption, orderByOption) {
39
39
  // If --order-by is provided, use it (full JSON control)
40
- if (orderByOption) return orderByOption;
40
+ if (orderByOption) {
41
+ const isEntry = e => e !== null && typeof e === 'object' && !Array.isArray(e)
42
+ && typeof e.field === 'string' && e.field.trim() !== '';
43
+ if (!Array.isArray(orderByOption) || !orderByOption.every(isEntry)) {
44
+ throw new NansenError(
45
+ `--order-by must be a JSON array of {"field", "direction"} objects, e.g. --order-by '[{"field":"value_usd","direction":"DESC"}]'`,
46
+ ErrorCode.INVALID_PARAMS,
47
+ );
48
+ }
49
+ return orderByOption;
50
+ }
41
51
  if (!sortOption) return undefined;
42
52
  if (typeof sortOption !== 'string') {
43
53
  throw new NansenError('--sort must be "field" or "field:direction"', ErrorCode.INVALID_PARAMS);
44
54
  }
45
55
  const parts = sortOption.split(':');
56
+ if (parts.length > 2) {
57
+ throw new NansenError(
58
+ `--sort must be "field" or "field:direction", got "${sortOption}" (e.g. --sort ${parts[0].trim()}:desc)`,
59
+ ErrorCode.INVALID_PARAMS,
60
+ );
61
+ }
46
62
  const field = parts[0].trim();
47
63
  const rawDirection = (parts[1] || '').trim();
48
64
  const direction = (rawDirection || 'desc').toUpperCase();
@@ -0,0 +1,65 @@
1
+ /**
2
+ * File-level housekeeping for the response cache directory (~/.nansen/cache),
3
+ * shared by api.js (which writes entries) and cache-inspect.js (which clears
4
+ * them). Imports nothing from either so both can use it without a cycle.
5
+ *
6
+ * Names in the directory:
7
+ * <sha256>.json a cache entry
8
+ * <sha256>.json.<pid>.<uuid>.tmp a write in progress; renamed onto the
9
+ * entry when it completes, so a leftover one
10
+ * means the writing process was killed
11
+ */
12
+
13
+ import fs from 'fs';
14
+ import path from 'path';
15
+
16
+ export const RESPONSE_ENTRY = /^[0-9a-f]{64}\.json$/;
17
+ export const RESPONSE_TEMP = /^[0-9a-f]{64}\.json\.\d+\.[0-9a-f-]{36}\.tmp$/;
18
+
19
+ // A write holds its temp file for milliseconds. Anything this old was left by
20
+ // a process that died before the rename.
21
+ export const STALE_TEMP_MS = 10 * 60 * 1000;
22
+
23
+ // Entries are never read back after their TTL (default 300s, set per call with
24
+ // --cache-ttl) and a read does not delete them, so without a sweep, requests
25
+ // that are never repeated leave files behind forever. The sweep after a cache
26
+ // write removes entries older than this, or older than the longest TTL the
27
+ // writing process has read with, whichever is longer.
28
+ export const ENTRY_MAX_AGE_MS = 24 * 60 * 60 * 1000;
29
+
30
+ /** A temp file left behind by a write that never completed. */
31
+ export function isStaleTemp(name, stat, now = Date.now()) {
32
+ return RESPONSE_TEMP.test(name) && now - stat.mtimeMs > STALE_TEMP_MS;
33
+ }
34
+
35
+ /**
36
+ * Remove stale temp files and entries older than `retentionMs` (default
37
+ * ENTRY_MAX_AGE_MS) from `dir`.
38
+ * Only regular files whose names match the two shapes above are touched; a
39
+ * symlinked or missing directory and symlinked entries are left alone.
40
+ * Returns how many files were removed.
41
+ *
42
+ * Another process may rename a fresh entry onto a path between the lstat and
43
+ * the unlink. That costs it one cache miss, never wrong data.
44
+ */
45
+ export function pruneResponseCacheDir(dir, now = Date.now(), retentionMs = ENTRY_MAX_AGE_MS) {
46
+ const dirStat = fs.lstatSync(dir, { throwIfNoEntry: false });
47
+ if (!dirStat || !dirStat.isDirectory()) return 0;
48
+ let removed = 0;
49
+ for (const name of fs.readdirSync(dir)) {
50
+ const isEntry = RESPONSE_ENTRY.test(name);
51
+ if (!isEntry && !RESPONSE_TEMP.test(name)) continue;
52
+ const file = path.join(dir, name);
53
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
54
+ if (!stat || !stat.isFile()) continue;
55
+ const stale = isEntry ? now - stat.mtimeMs > retentionMs : isStaleTemp(name, stat, now);
56
+ if (!stale) continue;
57
+ try {
58
+ fs.unlinkSync(file);
59
+ removed += 1;
60
+ } catch (error) {
61
+ if (error?.code !== 'ENOENT') throw error;
62
+ }
63
+ }
64
+ return removed;
65
+ }