nansen-cli 1.44.0 → 1.44.2

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.
@@ -11,7 +11,18 @@ import path from 'path';
11
11
  import { base58Encode, exportWallet, getWalletConfig, showWallet } from './wallet.js';
12
12
  import { signEd25519, base58Decode, parseAmount, getTokenInfo } from './transfer.js';
13
13
  import { signSolanaTransaction, resolveTokenAddress } from './trading.js';
14
- import { assertSolanaInstructionsSafe } from './trade-validation.js';
14
+ import {
15
+ assertSolanaInstructionsSafe,
16
+ assertLimitOrderDepositDestination,
17
+ assertLimitOrderDepositOutcome,
18
+ assertLimitOrderCancelOutcome,
19
+ NATIVE_FEE_RENT_SLACK_LAMPORTS,
20
+ } from './trade-validation.js';
21
+ import {
22
+ simulateSolanaAssetChanges,
23
+ SolanaSimulationError,
24
+ hasSolanaSimulationRpc,
25
+ } from './solana-simulation.js';
15
26
  import { validateTokenAddress, telemetryHeaders, packageVersion } from './api.js';
16
27
  import { getWalletConnectAddress, sendSolanaTransactionViaWalletConnect, signSolanaMessageViaWalletConnect } from './walletconnect-trading.js';
17
28
  import { retrievePassword } from './keychain.js';
@@ -22,6 +33,7 @@ import { CHAIN_RPCS } from './rpc-urls.js';
22
33
  const TRADING_API_URL = process.env.NANSEN_TRADING_API_URL || 'https://trading-api.nansen.ai';
23
34
  const LO_PREFIX = '/limit-order/v2';
24
35
  const SOLSCAN_TX_URL = 'https://solscan.io/tx/';
36
+ const WSOL_MINT = 'So11111111111111111111111111111111111111112';
25
37
 
26
38
  // ============= JWT Auth & Caching (Local File) =============
27
39
 
@@ -383,6 +395,88 @@ export async function signTransaction(txBase64, walletType, walletInfo) {
383
395
  throw new Error(`Unsupported wallet type: ${walletType}`);
384
396
  }
385
397
 
398
+ /**
399
+ * The limit-order sibling of verifySolanaSwapOutcome: simulates the deposit/
400
+ * cancel transaction and checks the resulting balance deltas against the
401
+ * requested operation, degrading (warn + proceed) on any RPC/sim outage so an
402
+ * outage never blocks an order — only a real outcome mismatch or an
403
+ * in-simulation revert refuses to sign.
404
+ */
405
+ async function verifyLimitOrderOutcome({ kind, walletAddress, txBase64, inputMint, amount, log = () => {} }) {
406
+ if (!hasSolanaSimulationRpc('solana')) {
407
+ log(' ⚠ Outcome verification unavailable (no Solana simulation endpoint); proceeding without it.');
408
+ return { proceed: true };
409
+ }
410
+ try {
411
+ const sim = await simulateSolanaAssetChanges('solana', txBase64, { walletAddress });
412
+ if (kind === 'deposit') {
413
+ assertLimitOrderDepositOutcome(sim, { inputMint, amount });
414
+ } else {
415
+ assertLimitOrderCancelOutcome(sim, { inputMint, amount });
416
+ }
417
+ log(` ✓ ${kind === 'deposit' ? 'Deposit' : 'Cancellation'} outcome verified (via ${sim.method}).`);
418
+ return { proceed: true };
419
+ } catch (e) {
420
+ if (e instanceof SolanaSimulationError && ['NO_SIM_RPC', 'SIM_RPC_ERROR'].includes(e.code)) {
421
+ log(` ⚠ Outcome verification could not run (${e.message}); proceeding without it.`);
422
+ return { proceed: true };
423
+ }
424
+ return { proceed: false, reason: e.message };
425
+ }
426
+ }
427
+
428
+ // Page size and scan ceiling for the pre-cancel order lookup. The ceiling is a
429
+ // defensive bound: it stops an unbounded loop if the API never surfaces the order
430
+ // and never reports a total or a short page, at the cost of not finding a target
431
+ // buried beyond it (which then fails closed, same as any not-found order).
432
+ const ACTIVE_ORDER_PAGE = 100;
433
+ const MAX_ACTIVE_ORDERS_SCANNED = 5000;
434
+
435
+ /**
436
+ * Find one active order by id, paginating state:'active' until the order is found or
437
+ * the active set is exhausted, so a user with more than one page of active orders can
438
+ * still cancel one that doesn't land on page 1. Returns the order object or undefined.
439
+ */
440
+ async function findActiveOrder(token, userPubkey, orderId) {
441
+ let offset = 0;
442
+ while (offset < MAX_ACTIVE_ORDERS_SCANNED) {
443
+ const page = await listOrders(token, userPubkey, { limit: ACTIVE_ORDER_PAGE, offset, state: 'active' });
444
+ const orders = page.orders || [];
445
+ const found = orders.find((o) => o.id === orderId);
446
+ if (found) return found;
447
+ offset += orders.length;
448
+ if (orders.length < ACTIVE_ORDER_PAGE) break; // short/empty page — no more to fetch
449
+ const total = page.pagination?.total;
450
+ if (total != null && offset >= total) break; // consumed everything the API reports
451
+ }
452
+ return undefined;
453
+ }
454
+
455
+ /**
456
+ * Classify how much a cancel should refund: the order's input less whatever has
457
+ * already been filled (partial fills consume escrow). Returns one of:
458
+ * { amount: <bigint> } the unfilled remainder still owed (always > 0)
459
+ * { error: 'unparseable' } the order's amounts couldn't be parsed as integers
460
+ * { error: 'fully-filled' } parsing succeeded but nothing is left to refund
461
+ *
462
+ * The two error cases are kept distinct (not collapsed to a single undefined) so the
463
+ * cancel command can surface an actionable message: 'unparseable' is an unexpected
464
+ * API-shape problem, 'fully-filled' is a normal user-facing state (the order already
465
+ * executed). Both are fatal for the caller — a cancel whose refund magnitude can't be
466
+ * bound must not be signed — but the user needs to know which one they hit.
467
+ */
468
+ function classifyCancelRefund(order) {
469
+ let remaining;
470
+ try {
471
+ const total = BigInt(order.inputAmount);
472
+ const filled = (order.fills || []).reduce((sum, f) => sum + BigInt(f.inputAmount ?? 0), 0n);
473
+ remaining = total - filled;
474
+ } catch {
475
+ return { error: 'unparseable' };
476
+ }
477
+ return remaining > 0n ? { amount: remaining } : { error: 'fully-filled' };
478
+ }
479
+
386
480
  // ============= Expiry Parsing =============
387
481
 
388
482
  /**
@@ -621,6 +715,22 @@ EXAMPLES:
621
715
  return;
622
716
  }
623
717
 
718
+ // Fail fast on a native-SOL amount too small for outcome verification to bound by
719
+ // magnitude (see assertLimitOrderDepositOutcome's NATIVE_FEE_RENT_SLACK_LAMPORTS
720
+ // floor) — otherwise this would only surface as a LIMIT_ORDER_OUTCOME_MISMATCH
721
+ // after crafting and simulating the deposit transaction, well into the flow.
722
+ // Gated on hasSolanaSimulationRpc deliberately: the floor is a pre-empt of the
723
+ // magnitude check, so it only applies when that check would actually run. In a
724
+ // degraded (no-sim-RPC) environment there is no magnitude bound to pre-empt — the
725
+ // deposit falls back to the static gate alone (verifyLimitOrderOutcome already warns
726
+ // that outcome verification is unavailable), so blocking a small amount here would
727
+ // add a floor that the rest of that path doesn't enforce.
728
+ if (from === WSOL_MINT && hasSolanaSimulationRpc('solana') && BigInt(amountBaseUnits) <= NATIVE_FEE_RENT_SLACK_LAMPORTS) {
729
+ log(`Error: SOL deposit amount (${amountBaseUnits} lamports) is too small to verify against network fee/rent noise (${NATIVE_FEE_RENT_SLACK_LAMPORTS} lamports). Use a larger amount.`);
730
+ exit(1);
731
+ return;
732
+ }
733
+
624
734
  if (triggerCondition !== 'above' && triggerCondition !== 'below') {
625
735
  log('Error: --trigger-condition must be "above" or "below".');
626
736
  exit(1);
@@ -673,20 +783,38 @@ EXAMPLES:
673
783
  // 3. Check vault, auto-register if needed
674
784
  // Backend returns { vaultPubkey: "..." } when vault exists, or throws/returns empty when not
675
785
  let hasVault = false;
786
+ let vaultPubkey;
676
787
  try {
677
788
  const vaultInfo = await getVault(token, pubkey);
678
- hasVault = !!(vaultInfo?.vaultPubkey || vaultInfo?.vaultAddress);
789
+ vaultPubkey = vaultInfo?.vaultPubkey || vaultInfo?.vaultAddress;
790
+ hasVault = !!vaultPubkey;
679
791
  } catch {
680
792
  // No vault found
681
793
  }
682
794
  if (!hasVault) {
683
795
  log(' Registering vault for first-time use...');
684
796
  try {
685
- await registerVault(token);
797
+ const vaultInfo = await registerVault(token);
798
+ vaultPubkey = vaultInfo?.vaultPubkey || vaultInfo?.vaultAddress;
686
799
  } catch (regErr) {
687
800
  // Vault may already exist — ignore "already registered" errors
688
801
  if (!/already registered/i.test(regErr.message)) throw regErr;
689
802
  }
803
+ // Registration either reported "already registered" or returned no
804
+ // address. The vault exists in both cases, so fetch it to recover the
805
+ // address rather than failing the deposit below with a misleading
806
+ // "cannot determine vault address".
807
+ if (!vaultPubkey) {
808
+ try {
809
+ const vaultInfo = await getVault(token, pubkey);
810
+ vaultPubkey = vaultInfo?.vaultPubkey || vaultInfo?.vaultAddress;
811
+ } catch {
812
+ // Still unknown — fall through to the guard below.
813
+ }
814
+ }
815
+ }
816
+ if (!vaultPubkey) {
817
+ throw new Error('Could not determine your limit-order vault address; refusing to sign a deposit whose destination cannot be verified.');
690
818
  }
691
819
 
692
820
  // 4. Craft deposit transaction
@@ -699,17 +827,27 @@ EXAMPLES:
699
827
  });
700
828
 
701
829
  // 5. Sign deposit transaction
702
- // Same pre-signing drain gate the swap path uses. The legitimate deposit
703
- // moves the input token into the already-registered vault (step 3) with an
704
- // SPL Transfer/TransferChecked — which this gate does not classify — plus,
705
- // when selling native SOL, a temp-WSOL CloseAccount whose rent returns to
706
- // the wallet (permitted). Neither trips the delegate/authority/
707
- // close-to-stranger checks, so this does not reject a well-formed deposit;
708
- // it only fires if the crafted tx additionally grants a delegate, reassigns
709
- // authority, or closes to a stranger. Verified live: a real SOL→USDC create
710
- // round-trip clears this gate (the API-crafted deposit is a SOL-wrap
711
- // transfer into the vault plus a temp-WSOL close-to-self).
830
+ // Three pre-signing defenses run here. The generic static gate rejects
831
+ // delegate grants, authority changes, close-to-stranger, and excessive
832
+ // priority fees. The limit-order destination gate then binds every
833
+ // wallet-sourced transfer (SPL for token deposits, native System::Transfer
834
+ // for SOL) to a token account this same tx creates via
835
+ // CreateAccountWithSeed seeded off the trusted vault owner — the real
836
+ // Jupiter Trigger V2 deposit shape, confirmed by a live create round-trip.
837
+ // Finally, balance-delta outcome verification binds magnitude: the input
838
+ // token must leave the wallet by exactly `amount` (± fee/rent slack for
839
+ // native SOL) and no other token may leave.
712
840
  assertSolanaInstructionsSafe(deposit.transaction, { walletAddress: pubkey });
841
+ assertLimitOrderDepositDestination(deposit.transaction, {
842
+ walletAddress: pubkey,
843
+ inputMint: from,
844
+ vaultOwner: vaultPubkey,
845
+ });
846
+ const depositOutcome = await verifyLimitOrderOutcome({
847
+ kind: 'deposit', walletAddress: pubkey, txBase64: deposit.transaction,
848
+ inputMint: from, amount: amountBaseUnits, log,
849
+ });
850
+ if (!depositOutcome.proceed) throw new Error(`Refusing to sign deposit — ${depositOutcome.reason}`);
713
851
  log(' Signing deposit transaction...');
714
852
  const signedDepositTx = await signTransaction(deposit.transaction, walletType, walletInfo);
715
853
 
@@ -839,23 +977,83 @@ EXAMPLES:
839
977
  // 1. Authenticate
840
978
  const token = await authenticate(pubkey, walletType, walletInfo, log);
841
979
 
842
- // 2. Request cancellation — get unsigned withdrawal tx
980
+ // 2. Look up the order, but only when outcome verification will actually run —
981
+ // cancel only receives an orderId, not order details, from the caller, and the
982
+ // refund check below (see assertLimitOrderCancelOutcome) needs to know both which
983
+ // asset the refund must land in AND how much of it is still owed (the unfilled
984
+ // remainder). Skip the extra lookup entirely when there's no simulation RPC to
985
+ // verify against, so a degraded environment doesn't gain a new API dependency for
986
+ // a check it isn't going to run anyway. Done before requesting cancellation so a
987
+ // lookup failure fails closed without first consuming a one-time withdrawal request
988
+ // server-side. Filtered to state: 'active' (the only state a cancellable order can
989
+ // be in) so filled/cancelled/expired history never crowds out the target — the API
990
+ // only accepts 'active' or 'past' for this filter. Paginated until the order is
991
+ // found or the active set is exhausted, so a user with more than one page of active
992
+ // orders can still cancel one that doesn't land on page 1.
993
+ let cancelInputMint;
994
+ let cancelRefundAmount;
995
+ if (hasSolanaSimulationRpc('solana')) {
996
+ const order = await findActiveOrder(token, pubkey, orderId);
997
+ if (!order) {
998
+ throw new Error(`Could not find order ${orderId} among your active orders; refusing to verify the cancel's refund asset. It may already be filled/cancelled/expired — check with "nansen trade limit-order list --state active".`);
999
+ }
1000
+ cancelInputMint = order.inputMint;
1001
+ // The whole point of the outcome check is to bind the refund's MAGNITUDE. If the
1002
+ // remaining refund can't be pinned to an exact amount, passing amount: undefined
1003
+ // would silently downgrade the verifier to a bare positive-inflow check —
1004
+ // reopening the dust-refund gap for exactly the metadata we can least trust. Fail
1005
+ // closed instead, with a message that distinguishes the two reasons: unparseable
1006
+ // amounts are an unexpected API-shape problem, a fully-filled order is a normal
1007
+ // state the user should just be told about plainly.
1008
+ const refund = classifyCancelRefund(order);
1009
+ if (refund.error === 'unparseable') {
1010
+ throw new Error(`Found order ${orderId} but its input/fill amounts couldn't be parsed from the order metadata; refusing to sign a cancel whose refund magnitude can't be verified. Check the order with "nansen trade limit-order list --state active".`);
1011
+ }
1012
+ if (refund.error === 'fully-filled') {
1013
+ throw new Error(`Order ${orderId} appears fully filled — there is nothing left to refund, so it can't be cancelled. Check its status with "nansen trade limit-order list --state active".`);
1014
+ }
1015
+ cancelRefundAmount = refund.amount;
1016
+ }
1017
+
1018
+ // 3. Request cancellation — get unsigned withdrawal tx
1019
+ //
1020
+ // NOTE (deliberate, do not "fix" by loosening the check): there is a narrow TOCTOU
1021
+ // window between the lookup in step 2 (which pins cancelRefundAmount to the unfilled
1022
+ // remainder seen then) and this cancellation request. If a partial fill lands in
1023
+ // between, the real withdrawal returns LESS than cancelRefundAmount and the outcome
1024
+ // check in step 4 fails closed on a legitimate cancel. That's acceptable: the user
1025
+ // simply retries and the next lookup sees the new remainder. The safe response to a
1026
+ // spurious failure here is a retry, NOT relaxing the exact-magnitude bind — that bind
1027
+ // is what closes the dust-refund redirect (a crafted withdrawal that reroutes most of
1028
+ // the escrow and returns only a token of the right mint), so widening it reopens the
1029
+ // exact gap this verification exists to close.
843
1030
  log(' Requesting cancellation...');
844
1031
  const cancelResult = await cancelOrderRequest(token, orderId);
845
1032
 
846
- // 3. Sign the withdrawal transaction
1033
+ // 4. Sign the withdrawal transaction
847
1034
  // Withdrawal moves the deposited token back out of the vault; that transfer
848
1035
  // is authorized by the vault program's PDA, not our wallet, so it isn't a
849
1036
  // wallet-authorized drain even if it were classified. Any temp-WSOL close
850
- // returns rent to the wallet. This gate is defense-in-depth against a
851
- // crafted withdrawal that instead grants a delegate, reassigns authority, or
852
- // closes to a stranger. Verified live alongside the deposit path via a real
853
- // cancel round-trip.
1037
+ // returns rent to the wallet. The static gate below is defense-in-depth
1038
+ // against a crafted withdrawal that instead grants a delegate, reassigns
1039
+ // authority, or closes to a stranger. Balance-delta outcome verification
1040
+ // then binds the withdrawal's effect: since a cancel should only return
1041
+ // funds to the wallet, no token may leave it at all (native-SOL fee/rent
1042
+ // dust tolerated), and the order's own input asset must return by the full
1043
+ // expected remaining amount (looked up in step 2) — not merely a positive
1044
+ // delta, so a redirect of most of the escrow paired with a dust or unrelated
1045
+ // inflow no longer counts. Verified live alongside the deposit path via a
1046
+ // real cancel round-trip.
854
1047
  assertSolanaInstructionsSafe(cancelResult.transaction, { walletAddress: pubkey });
1048
+ const cancelOutcome = await verifyLimitOrderOutcome({
1049
+ kind: 'cancel', walletAddress: pubkey, txBase64: cancelResult.transaction,
1050
+ inputMint: cancelInputMint, amount: cancelRefundAmount, log,
1051
+ });
1052
+ if (!cancelOutcome.proceed) throw new Error(`Refusing to sign withdrawal — ${cancelOutcome.reason}`);
855
1053
  log(' Signing withdrawal transaction...');
856
1054
  const signedTx = await signTransaction(cancelResult.transaction, walletType, walletInfo);
857
1055
 
858
- // 4. Confirm cancellation
1056
+ // 5. Confirm cancellation
859
1057
  log(' Confirming cancellation...');
860
1058
  const confirmed = await confirmCancelOrder(token, orderId, {
861
1059
  signedTransaction: signedTx,
package/src/schema.json CHANGED
@@ -2545,9 +2545,18 @@
2545
2545
  "description": "Disable automatic retry on rate limits/errors"
2546
2546
  },
2547
2547
  "retries": {
2548
- "type": "number",
2548
+ "type": "integer",
2549
+ "minimum": 0,
2550
+ "maximum": 9007199254740991,
2549
2551
  "default": 3,
2550
- "description": "Max retry attempts"
2552
+ "description": "Max retry attempts (non-negative safe integer)"
2553
+ },
2554
+ "cache-ttl": {
2555
+ "type": "integer",
2556
+ "minimum": 0,
2557
+ "maximum": 9007199254740991,
2558
+ "default": 300,
2559
+ "description": "Cache TTL in seconds (non-negative safe integer; 0 disables cache reads)"
2551
2560
  },
2552
2561
  "format": {
2553
2562
  "type": "string",
package/src/telemetry.js CHANGED
@@ -31,6 +31,16 @@ const TELEMETRY_URL =
31
31
 
32
32
  const TIMEOUT_MS = 1000;
33
33
 
34
+ // Every other module that writes under ~/.nansen (api.js, wallet.js, keychain.js,
35
+ // trading.js, update-check.js, …) creates directories 0700 and files 0600, because
36
+ // the same directory also holds the API key and the encrypted wallet keystores.
37
+ // Telemetry writes there too, so it uses the same modes: mkdir with recursive:true
38
+ // leaves an existing directory's mode alone, so whichever module creates ~/.nansen
39
+ // first fixes its permissions for good — and on the documented NANSEN_API_KEY path
40
+ // no config is ever saved, so that first writer is this file.
41
+ const DIR_MODE = 0o700;
42
+ const FILE_MODE = 0o600;
43
+
34
44
  // ─── opt-out ──────────────────────────────────────────────
35
45
 
36
46
  /**
@@ -83,8 +93,8 @@ export function getAnonymousId() {
83
93
  if (!_anonymousId) {
84
94
  _anonymousId = crypto.randomUUID();
85
95
  try {
86
- fs.mkdirSync(path.dirname(TELEMETRY_ID_FILE), { recursive: true });
87
- fs.writeFileSync(TELEMETRY_ID_FILE, _anonymousId, 'utf8');
96
+ fs.mkdirSync(path.dirname(TELEMETRY_ID_FILE), { mode: DIR_MODE, recursive: true });
97
+ fs.writeFileSync(TELEMETRY_ID_FILE, _anonymousId, { encoding: 'utf8', mode: FILE_MODE });
88
98
  } catch { /* best-effort persist */ }
89
99
  }
90
100
  }
@@ -121,7 +131,7 @@ export function getSessionId() {
121
131
  _sessionId = raw.id;
122
132
  // touch timestamp, but only if >1 min elapsed to reduce writes
123
133
  if (now - raw.ts > 60_000) {
124
- try { fs.writeFileSync(SESSION_FILE, JSON.stringify({ id: _sessionId, ts: now }), 'utf8'); } catch { /* best-effort touch */ }
134
+ try { fs.writeFileSync(SESSION_FILE, JSON.stringify({ id: _sessionId, ts: now }), { encoding: 'utf8', mode: FILE_MODE }); } catch { /* best-effort touch */ }
125
135
  }
126
136
  return _sessionId;
127
137
  }
@@ -129,8 +139,8 @@ export function getSessionId() {
129
139
 
130
140
  _sessionId = crypto.randomUUID();
131
141
  try {
132
- fs.mkdirSync(path.dirname(SESSION_FILE), { recursive: true });
133
- fs.writeFileSync(SESSION_FILE, JSON.stringify({ id: _sessionId, ts: now }), 'utf8');
142
+ fs.mkdirSync(path.dirname(SESSION_FILE), { mode: DIR_MODE, recursive: true });
143
+ fs.writeFileSync(SESSION_FILE, JSON.stringify({ id: _sessionId, ts: now }), { encoding: 'utf8', mode: FILE_MODE });
134
144
  } catch { /* best-effort */ }
135
145
  return _sessionId;
136
146
  }