nansen-cli 1.43.1 → 1.44.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.
@@ -11,7 +11,17 @@ 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
+ assertLimitOrderDepositOutcome,
17
+ assertLimitOrderCancelOutcome,
18
+ NATIVE_FEE_RENT_SLACK_LAMPORTS,
19
+ } from './trade-validation.js';
20
+ import {
21
+ simulateSolanaAssetChanges,
22
+ SolanaSimulationError,
23
+ hasSolanaSimulationRpc,
24
+ } from './solana-simulation.js';
15
25
  import { validateTokenAddress, telemetryHeaders, packageVersion } from './api.js';
16
26
  import { getWalletConnectAddress, sendSolanaTransactionViaWalletConnect, signSolanaMessageViaWalletConnect } from './walletconnect-trading.js';
17
27
  import { retrievePassword } from './keychain.js';
@@ -22,6 +32,7 @@ import { CHAIN_RPCS } from './rpc-urls.js';
22
32
  const TRADING_API_URL = process.env.NANSEN_TRADING_API_URL || 'https://trading-api.nansen.ai';
23
33
  const LO_PREFIX = '/limit-order/v2';
24
34
  const SOLSCAN_TX_URL = 'https://solscan.io/tx/';
35
+ const WSOL_MINT = 'So11111111111111111111111111111111111111112';
25
36
 
26
37
  // ============= JWT Auth & Caching (Local File) =============
27
38
 
@@ -383,6 +394,88 @@ export async function signTransaction(txBase64, walletType, walletInfo) {
383
394
  throw new Error(`Unsupported wallet type: ${walletType}`);
384
395
  }
385
396
 
397
+ /**
398
+ * The limit-order sibling of verifySolanaSwapOutcome: simulates the deposit/
399
+ * cancel transaction and checks the resulting balance deltas against the
400
+ * requested operation, degrading (warn + proceed) on any RPC/sim outage so an
401
+ * outage never blocks an order — only a real outcome mismatch or an
402
+ * in-simulation revert refuses to sign.
403
+ */
404
+ async function verifyLimitOrderOutcome({ kind, walletAddress, txBase64, inputMint, amount, log = () => {} }) {
405
+ if (!hasSolanaSimulationRpc('solana')) {
406
+ log(' ⚠ Outcome verification unavailable (no Solana simulation endpoint); proceeding without it.');
407
+ return { proceed: true };
408
+ }
409
+ try {
410
+ const sim = await simulateSolanaAssetChanges('solana', txBase64, { walletAddress });
411
+ if (kind === 'deposit') {
412
+ assertLimitOrderDepositOutcome(sim, { inputMint, amount });
413
+ } else {
414
+ assertLimitOrderCancelOutcome(sim, { inputMint, amount });
415
+ }
416
+ log(` ✓ ${kind === 'deposit' ? 'Deposit' : 'Cancellation'} outcome verified (via ${sim.method}).`);
417
+ return { proceed: true };
418
+ } catch (e) {
419
+ if (e instanceof SolanaSimulationError && ['NO_SIM_RPC', 'SIM_RPC_ERROR'].includes(e.code)) {
420
+ log(` ⚠ Outcome verification could not run (${e.message}); proceeding without it.`);
421
+ return { proceed: true };
422
+ }
423
+ return { proceed: false, reason: e.message };
424
+ }
425
+ }
426
+
427
+ // Page size and scan ceiling for the pre-cancel order lookup. The ceiling is a
428
+ // defensive bound: it stops an unbounded loop if the API never surfaces the order
429
+ // and never reports a total or a short page, at the cost of not finding a target
430
+ // buried beyond it (which then fails closed, same as any not-found order).
431
+ const ACTIVE_ORDER_PAGE = 100;
432
+ const MAX_ACTIVE_ORDERS_SCANNED = 5000;
433
+
434
+ /**
435
+ * Find one active order by id, paginating state:'active' until the order is found or
436
+ * the active set is exhausted, so a user with more than one page of active orders can
437
+ * still cancel one that doesn't land on page 1. Returns the order object or undefined.
438
+ */
439
+ async function findActiveOrder(token, userPubkey, orderId) {
440
+ let offset = 0;
441
+ while (offset < MAX_ACTIVE_ORDERS_SCANNED) {
442
+ const page = await listOrders(token, userPubkey, { limit: ACTIVE_ORDER_PAGE, offset, state: 'active' });
443
+ const orders = page.orders || [];
444
+ const found = orders.find((o) => o.id === orderId);
445
+ if (found) return found;
446
+ offset += orders.length;
447
+ if (orders.length < ACTIVE_ORDER_PAGE) break; // short/empty page — no more to fetch
448
+ const total = page.pagination?.total;
449
+ if (total != null && offset >= total) break; // consumed everything the API reports
450
+ }
451
+ return undefined;
452
+ }
453
+
454
+ /**
455
+ * Classify how much a cancel should refund: the order's input less whatever has
456
+ * already been filled (partial fills consume escrow). Returns one of:
457
+ * { amount: <bigint> } the unfilled remainder still owed (always > 0)
458
+ * { error: 'unparseable' } the order's amounts couldn't be parsed as integers
459
+ * { error: 'fully-filled' } parsing succeeded but nothing is left to refund
460
+ *
461
+ * The two error cases are kept distinct (not collapsed to a single undefined) so the
462
+ * cancel command can surface an actionable message: 'unparseable' is an unexpected
463
+ * API-shape problem, 'fully-filled' is a normal user-facing state (the order already
464
+ * executed). Both are fatal for the caller — a cancel whose refund magnitude can't be
465
+ * bound must not be signed — but the user needs to know which one they hit.
466
+ */
467
+ function classifyCancelRefund(order) {
468
+ let remaining;
469
+ try {
470
+ const total = BigInt(order.inputAmount);
471
+ const filled = (order.fills || []).reduce((sum, f) => sum + BigInt(f.inputAmount ?? 0), 0n);
472
+ remaining = total - filled;
473
+ } catch {
474
+ return { error: 'unparseable' };
475
+ }
476
+ return remaining > 0n ? { amount: remaining } : { error: 'fully-filled' };
477
+ }
478
+
386
479
  // ============= Expiry Parsing =============
387
480
 
388
481
  /**
@@ -396,23 +489,34 @@ export function parseExpiry(expiryStr) {
396
489
  const match = expiryStr.match(/^(\d+)(h|d)$/i);
397
490
  if (match) {
398
491
  const value = parseInt(match[1], 10);
492
+ if (!Number.isFinite(value)) {
493
+ throw new Error(`Invalid expiry "${expiryStr}". Duration must be finite.`);
494
+ }
399
495
  if (value <= 0) {
400
496
  throw new Error(`Invalid expiry "${expiryStr}". Duration must be greater than 0.`);
401
497
  }
402
498
  const unit = match[2].toLowerCase();
403
499
  const ms = unit === 'h' ? value * 3600 * 1000 : value * 24 * 3600 * 1000;
404
- return Date.now() + ms;
500
+ const expiresAt = Date.now() + ms;
501
+ if (!Number.isFinite(expiresAt)) {
502
+ throw new Error(`Invalid expiry "${expiryStr}". Duration is too large.`);
503
+ }
504
+ return expiresAt;
405
505
  }
406
506
 
407
507
  // Try as raw epoch ms — must be in the future, or the order expires on arrival.
408
508
  const num = Number(expiryStr);
409
- if (!isNaN(num)) {
509
+ if (Number.isFinite(num)) {
410
510
  if (num <= Date.now()) {
411
511
  throw new Error(`Expiry "${expiryStr}" is in the past. Provide a future time (e.g. "24h", "7d", or a future epoch in ms).`);
412
512
  }
413
513
  return num;
414
514
  }
415
515
 
516
+ if (!Number.isNaN(num)) {
517
+ throw new Error(`Invalid expiry "${expiryStr}". Provide a finite future epoch in milliseconds or a duration such as "24h" or "7d".`);
518
+ }
519
+
416
520
  throw new Error(`Invalid expiry format: "${expiryStr}". Use "24h", "7d", "30d", or epoch ms.`);
417
521
  }
418
522
 
@@ -569,6 +673,22 @@ EXAMPLES:
569
673
  return;
570
674
  }
571
675
 
676
+ const price = Number(triggerPrice);
677
+ if (!Number.isFinite(price) || price <= 0) {
678
+ log('Error: --trigger-price must be a finite positive number.');
679
+ exit(1);
680
+ return;
681
+ }
682
+
683
+ let expiresAt;
684
+ try {
685
+ expiresAt = parseExpiry(expiresStr);
686
+ } catch (err) {
687
+ log(`Error: ${err.message}`);
688
+ exit(1);
689
+ return;
690
+ }
691
+
572
692
  // Amount is always in human-readable token units (e.g. 1.5 = 1.5 SOL)
573
693
  // Converted to base units (lamports) internally
574
694
  let amountBaseUnits;
@@ -594,9 +714,18 @@ EXAMPLES:
594
714
  return;
595
715
  }
596
716
 
597
- const price = Number(triggerPrice);
598
- if (isNaN(price) || price <= 0) {
599
- log('Error: --trigger-price must be a positive number (USD price).');
717
+ // Fail fast on a native-SOL amount too small for outcome verification to bound by
718
+ // magnitude (see assertLimitOrderDepositOutcome's NATIVE_FEE_RENT_SLACK_LAMPORTS
719
+ // floor) — otherwise this would only surface as a LIMIT_ORDER_OUTCOME_MISMATCH
720
+ // after crafting and simulating the deposit transaction, well into the flow.
721
+ // Gated on hasSolanaSimulationRpc deliberately: the floor is a pre-empt of the
722
+ // magnitude check, so it only applies when that check would actually run. In a
723
+ // degraded (no-sim-RPC) environment there is no magnitude bound to pre-empt — the
724
+ // deposit falls back to the static gate alone (verifyLimitOrderOutcome already warns
725
+ // that outcome verification is unavailable), so blocking a small amount here would
726
+ // add a floor that the rest of that path doesn't enforce.
727
+ if (from === WSOL_MINT && hasSolanaSimulationRpc('solana') && BigInt(amountBaseUnits) <= NATIVE_FEE_RENT_SLACK_LAMPORTS) {
728
+ 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.`);
600
729
  exit(1);
601
730
  return;
602
731
  }
@@ -619,15 +748,6 @@ EXAMPLES:
619
748
  }
620
749
  }
621
750
 
622
- let expiresAt;
623
- try {
624
- expiresAt = parseExpiry(expiresStr);
625
- } catch (err) {
626
- log(`Error: ${err.message}`);
627
- exit(1);
628
- return;
629
- }
630
-
631
751
  const triggerMint = resolveTokenAddress(triggerMintRaw, 'solana');
632
752
 
633
753
  const tmValidation = validateTokenAddress(triggerMint, 'solana');
@@ -688,17 +808,26 @@ EXAMPLES:
688
808
  });
689
809
 
690
810
  // 5. Sign deposit transaction
691
- // Same pre-signing drain gate the swap path uses. The legitimate deposit
692
- // moves the input token into the already-registered vault (step 3) with an
693
- // SPL Transfer/TransferChecked — which this gate does not classify — plus,
694
- // when selling native SOL, a temp-WSOL CloseAccount whose rent returns to
695
- // the wallet (permitted). Neither trips the delegate/authority/
696
- // close-to-stranger checks, so this does not reject a well-formed deposit;
697
- // it only fires if the crafted tx additionally grants a delegate, reassigns
698
- // authority, or closes to a stranger. Verified live: a real SOL→USDC create
699
- // round-trip clears this gate (the API-crafted deposit is a SOL-wrap
700
- // transfer into the vault plus a temp-WSOL close-to-self).
811
+ // Two layers of pre-signing defense, same as the swap path. First, the
812
+ // static gate: the legitimate deposit moves the input token into the
813
+ // already-registered vault (step 3) with an SPL Transfer/TransferChecked —
814
+ // which this gate does not classify — plus, when selling native SOL, a
815
+ // temp-WSOL CloseAccount whose rent returns to the wallet (permitted).
816
+ // Neither trips the delegate/authority/close-to-stranger checks, so this
817
+ // does not reject a well-formed deposit; it only fires if the crafted tx
818
+ // additionally grants a delegate, reassigns authority, or closes to a
819
+ // stranger. Second, balance-delta outcome verification below binds the
820
+ // deposit's magnitude: the input token must leave the wallet by exactly
821
+ // `amount` (± fee/rent slack for native SOL) and no other token may leave.
822
+ // Verified live: a real SOL→USDC create round-trip clears both gates (the
823
+ // API-crafted deposit is a SOL-wrap transfer into the vault plus a
824
+ // temp-WSOL close-to-self).
701
825
  assertSolanaInstructionsSafe(deposit.transaction, { walletAddress: pubkey });
826
+ const depositOutcome = await verifyLimitOrderOutcome({
827
+ kind: 'deposit', walletAddress: pubkey, txBase64: deposit.transaction,
828
+ inputMint: from, amount: amountBaseUnits, log,
829
+ });
830
+ if (!depositOutcome.proceed) throw new Error(`Refusing to sign deposit — ${depositOutcome.reason}`);
702
831
  log(' Signing deposit transaction...');
703
832
  const signedDepositTx = await signTransaction(deposit.transaction, walletType, walletInfo);
704
833
 
@@ -828,23 +957,83 @@ EXAMPLES:
828
957
  // 1. Authenticate
829
958
  const token = await authenticate(pubkey, walletType, walletInfo, log);
830
959
 
831
- // 2. Request cancellation — get unsigned withdrawal tx
960
+ // 2. Look up the order, but only when outcome verification will actually run —
961
+ // cancel only receives an orderId, not order details, from the caller, and the
962
+ // refund check below (see assertLimitOrderCancelOutcome) needs to know both which
963
+ // asset the refund must land in AND how much of it is still owed (the unfilled
964
+ // remainder). Skip the extra lookup entirely when there's no simulation RPC to
965
+ // verify against, so a degraded environment doesn't gain a new API dependency for
966
+ // a check it isn't going to run anyway. Done before requesting cancellation so a
967
+ // lookup failure fails closed without first consuming a one-time withdrawal request
968
+ // server-side. Filtered to state: 'active' (the only state a cancellable order can
969
+ // be in) so filled/cancelled/expired history never crowds out the target — the API
970
+ // only accepts 'active' or 'past' for this filter. Paginated until the order is
971
+ // found or the active set is exhausted, so a user with more than one page of active
972
+ // orders can still cancel one that doesn't land on page 1.
973
+ let cancelInputMint;
974
+ let cancelRefundAmount;
975
+ if (hasSolanaSimulationRpc('solana')) {
976
+ const order = await findActiveOrder(token, pubkey, orderId);
977
+ if (!order) {
978
+ 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".`);
979
+ }
980
+ cancelInputMint = order.inputMint;
981
+ // The whole point of the outcome check is to bind the refund's MAGNITUDE. If the
982
+ // remaining refund can't be pinned to an exact amount, passing amount: undefined
983
+ // would silently downgrade the verifier to a bare positive-inflow check —
984
+ // reopening the dust-refund gap for exactly the metadata we can least trust. Fail
985
+ // closed instead, with a message that distinguishes the two reasons: unparseable
986
+ // amounts are an unexpected API-shape problem, a fully-filled order is a normal
987
+ // state the user should just be told about plainly.
988
+ const refund = classifyCancelRefund(order);
989
+ if (refund.error === 'unparseable') {
990
+ 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".`);
991
+ }
992
+ if (refund.error === 'fully-filled') {
993
+ 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".`);
994
+ }
995
+ cancelRefundAmount = refund.amount;
996
+ }
997
+
998
+ // 3. Request cancellation — get unsigned withdrawal tx
999
+ //
1000
+ // NOTE (deliberate, do not "fix" by loosening the check): there is a narrow TOCTOU
1001
+ // window between the lookup in step 2 (which pins cancelRefundAmount to the unfilled
1002
+ // remainder seen then) and this cancellation request. If a partial fill lands in
1003
+ // between, the real withdrawal returns LESS than cancelRefundAmount and the outcome
1004
+ // check in step 4 fails closed on a legitimate cancel. That's acceptable: the user
1005
+ // simply retries and the next lookup sees the new remainder. The safe response to a
1006
+ // spurious failure here is a retry, NOT relaxing the exact-magnitude bind — that bind
1007
+ // is what closes the dust-refund redirect (a crafted withdrawal that reroutes most of
1008
+ // the escrow and returns only a token of the right mint), so widening it reopens the
1009
+ // exact gap this verification exists to close.
832
1010
  log(' Requesting cancellation...');
833
1011
  const cancelResult = await cancelOrderRequest(token, orderId);
834
1012
 
835
- // 3. Sign the withdrawal transaction
1013
+ // 4. Sign the withdrawal transaction
836
1014
  // Withdrawal moves the deposited token back out of the vault; that transfer
837
1015
  // is authorized by the vault program's PDA, not our wallet, so it isn't a
838
1016
  // wallet-authorized drain even if it were classified. Any temp-WSOL close
839
- // returns rent to the wallet. This gate is defense-in-depth against a
840
- // crafted withdrawal that instead grants a delegate, reassigns authority, or
841
- // closes to a stranger. Verified live alongside the deposit path via a real
842
- // cancel round-trip.
1017
+ // returns rent to the wallet. The static gate below is defense-in-depth
1018
+ // against a crafted withdrawal that instead grants a delegate, reassigns
1019
+ // authority, or closes to a stranger. Balance-delta outcome verification
1020
+ // then binds the withdrawal's effect: since a cancel should only return
1021
+ // funds to the wallet, no token may leave it at all (native-SOL fee/rent
1022
+ // dust tolerated), and the order's own input asset must return by the full
1023
+ // expected remaining amount (looked up in step 2) — not merely a positive
1024
+ // delta, so a redirect of most of the escrow paired with a dust or unrelated
1025
+ // inflow no longer counts. Verified live alongside the deposit path via a
1026
+ // real cancel round-trip.
843
1027
  assertSolanaInstructionsSafe(cancelResult.transaction, { walletAddress: pubkey });
1028
+ const cancelOutcome = await verifyLimitOrderOutcome({
1029
+ kind: 'cancel', walletAddress: pubkey, txBase64: cancelResult.transaction,
1030
+ inputMint: cancelInputMint, amount: cancelRefundAmount, log,
1031
+ });
1032
+ if (!cancelOutcome.proceed) throw new Error(`Refusing to sign withdrawal — ${cancelOutcome.reason}`);
844
1033
  log(' Signing withdrawal transaction...');
845
1034
  const signedTx = await signTransaction(cancelResult.transaction, walletType, walletInfo);
846
1035
 
847
- // 4. Confirm cancellation
1036
+ // 5. Confirm cancellation
848
1037
  log(' Confirming cancellation...');
849
1038
  const confirmed = await confirmCancelOrder(token, orderId, {
850
1039
  signedTransaction: signedTx,
@@ -899,8 +1088,8 @@ EXAMPLES:
899
1088
  const updateBody = { orderType: 'single' };
900
1089
  if (triggerPrice != null) {
901
1090
  const price = Number(triggerPrice);
902
- if (isNaN(price) || price <= 0) {
903
- log('Error: --trigger-price must be a positive number.');
1091
+ if (!Number.isFinite(price) || price <= 0) {
1092
+ log('Error: --trigger-price must be a finite positive number.');
904
1093
  exit(1);
905
1094
  return;
906
1095
  }
package/src/mcp-verify.js CHANGED
@@ -12,6 +12,37 @@ class McpRequestError extends Error {
12
12
  }
13
13
  }
14
14
 
15
+ const IPV4_OCTET = '(?:25[0-5]|2[0-4]\\d|1?\\d{1,2})';
16
+ const LOOPBACK_IPV4 = new RegExp(`^127\\.${IPV4_OCTET}\\.${IPV4_OCTET}\\.${IPV4_OCTET}$`);
17
+
18
+ // IPv4-mapped IPv6 loopback (127.0.0.0/8). Node's URL canonicalizes
19
+ // ::ffff:127.x.x.x to ::ffff:7fNN:NNNN (the 127 becomes the 7f high byte), so
20
+ // match that form; non-loopback mapped addresses fall outside the 7f prefix.
21
+ const LOOPBACK_IPV4_MAPPED = /^::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/i;
22
+
23
+ function isLoopbackHostname(hostname) {
24
+ if (!hostname) return false;
25
+ const host = hostname.toLowerCase().replace(/^\[/, '').replace(/\]$/, '');
26
+ if (host === 'localhost' || host === '::1') return true;
27
+ if (LOOPBACK_IPV4_MAPPED.test(host)) return true;
28
+ return LOOPBACK_IPV4.test(host);
29
+ }
30
+
31
+ /**
32
+ * Classify a destination URL for the credential-disclosure guard: its origin
33
+ * (for messaging), protocol, and whether the host is loopback.
34
+ */
35
+ function classifyDestination(url) {
36
+ try {
37
+ const parsed = new URL(url);
38
+ return { origin: parsed.origin, protocol: parsed.protocol, loopback: isLoopbackHostname(parsed.hostname) };
39
+ } catch {
40
+ // An unparseable URL never reaches an authenticated fetch (tools/list fails
41
+ // first), so this is only for messaging; treat it as an unsafe destination.
42
+ return { origin: url, protocol: null, loopback: false };
43
+ }
44
+ }
45
+
15
46
  function responseContentType(response) {
16
47
  return (
17
48
  response.headers?.get?.('content-type')
@@ -185,6 +216,7 @@ export async function runMcpVerifyChecks({
185
216
  fetchFn = fetch,
186
217
  timeoutMs = 30_000,
187
218
  devConfigPath,
219
+ sendApiKey = false,
188
220
  } = {}) {
189
221
  const checks = [];
190
222
  const auth = resolveAuthConfig(env, devConfigPath);
@@ -205,8 +237,39 @@ export async function runMcpVerifyChecks({
205
237
  ));
206
238
  }
207
239
 
240
+ // A saved key is trusted for the default Nansen endpoint only. Forwarding it
241
+ // to a caller-supplied URL requires explicit per-invocation consent, and no
242
+ // key may travel in cleartext to a public host.
243
+ let keyWithheld = null;
208
244
  if (key && url !== DEFAULT_MCP_URL) {
209
- checks.push(check('mcp-url', 'warn', `Non-default MCP URL: ${url} — the API key will be sent to this host`));
245
+ const dest = classifyDestination(url);
246
+ if (dest.protocol === 'http:' && !dest.loopback) {
247
+ keyWithheld = check(
248
+ 'mcp-url',
249
+ 'error',
250
+ `Refusing to send the API key over plain HTTP to a non-loopback host (${dest.origin})`,
251
+ 'Use an https:// URL. Plain HTTP is only permitted for localhost/loopback development.',
252
+ );
253
+ } else if (dest.protocol !== 'https:' && !(dest.protocol === 'http:' && dest.loopback)) {
254
+ // Anything not provably secure — an unparseable URL or a non-http(s)
255
+ // scheme — is refused rather than relied on to fail later in fetch.
256
+ keyWithheld = check(
257
+ 'mcp-url',
258
+ 'error',
259
+ `Refusing to send the API key to an unsupported MCP URL (${dest.origin})`,
260
+ 'Use an https:// URL, or a loopback http:// URL for local development.',
261
+ );
262
+ } else if (!explicitKey && !sendApiKey) {
263
+ keyWithheld = check(
264
+ 'mcp-url',
265
+ 'error',
266
+ `Saved API key withheld from custom MCP URL (${dest.origin})`,
267
+ `Re-run with --send-api-key to authorize sending your saved key to ${dest.origin}, or pass --api-key <key> to supply one explicitly.`,
268
+ );
269
+ } else {
270
+ checks.push(check('mcp-url', 'warn', `Sending the API key to custom MCP host: ${dest.origin}`));
271
+ }
272
+ if (keyWithheld) checks.push(keyWithheld);
210
273
  }
211
274
 
212
275
  let serverReady = false;
@@ -239,6 +302,8 @@ export async function runMcpVerifyChecks({
239
302
 
240
303
  if (!key) {
241
304
  checks.push(skippedAuth('no API key was provided'));
305
+ } else if (keyWithheld) {
306
+ checks.push(skippedAuth('the API key was withheld from this custom URL (see above)'));
242
307
  } else if (!serverReady) {
243
308
  checks.push(skippedAuth('tools/list did not establish server reachability'));
244
309
  } else {
package/src/perp.js CHANGED
@@ -245,17 +245,28 @@ async function signHlAction(eip712, { privateKeyHex, privyClient, privyWalletId,
245
245
  // Parse the per-order statuses HL returns for an `order` action so the oid and
246
246
  // fill are surfaced — the perp analogue of spot printing its quote id. HL replies:
247
247
  // response.data.statuses[] = { resting:{oid} } | { filled:{oid,totalSz,avgPx} } | { error }
248
- // A rejected leg ({error}) has already thrown in submitExchange, so only
249
- // resting/filled legs reach here. A TP/SL bracket returns multiple legs; label
250
- // them the same way extractActionErrors does (parent / take-profit / stop-loss).
248
+ // Successful responses and structured rejection responses both pass through
249
+ // here. A TP/SL bracket returns multiple legs; label them the same way
250
+ // extractActionErrors does (parent / take-profit / stop-loss).
251
251
  // Gated on the SUBMITTED action being an order: leverage/transfer/builder-fee
252
252
  // actions (type "default") and cancels return no oids, so [] falls back to the
253
253
  // concise raw response line in buildScreenSignSubmit.
254
254
  export function summarizeOrderResult(result, action) {
255
255
  if (action?.type !== 'order') return [];
256
- const statuses = result?.response?.data?.statuses;
257
- if (!Array.isArray(statuses)) return [];
258
- const multiLeg = (action.orders?.length ?? 0) > 1;
256
+ const responseStatuses = result?.response?.data?.statuses;
257
+ if (!Array.isArray(responseStatuses)) return [];
258
+ const orderCount = action.orders?.length ?? 0;
259
+ const multiLeg = orderCount > 1;
260
+ // Hyperliquid may return one pre-validation error for an entire batch rather
261
+ // than one status per order. Treat that single error as the outcome of every
262
+ // submitted leg so bracket attribution remains one-to-one with action.orders.
263
+ const statuses = multiLeg
264
+ && responseStatuses.length === 1
265
+ && responseStatuses[0]
266
+ && typeof responseStatuses[0] === 'object'
267
+ && 'error' in responseStatuses[0]
268
+ ? Array.from({ length: orderCount }, () => responseStatuses[0])
269
+ : responseStatuses;
259
270
  const out = [];
260
271
  for (const [index, entry] of statuses.entries()) {
261
272
  if (!entry || typeof entry !== 'object') continue;
@@ -273,31 +284,51 @@ export function summarizeOrderResult(result, action) {
273
284
  // above 2^53 arrived rounded. Flag precision (oidSafe) so the caller can
274
285
  // withhold a copy-paste cancel — and BI can drop the id — rather than act on
275
286
  // a wrong oid presented as authoritative.
287
+ const orderSide = action.orders?.[index]?.b;
288
+ const side = orderSide === true ? 'buy' : orderSide === false ? 'sell' : undefined;
289
+ const reduceOnly = action.orders?.[index]?.r === true;
290
+ const positionSide = side === undefined
291
+ ? undefined
292
+ : reduceOnly
293
+ ? (side === 'buy' ? 'short' : 'long')
294
+ : (side === 'buy' ? 'long' : 'short');
276
295
  if (entry.filled && entry.filled.oid !== undefined) {
277
296
  const { oid, totalSz, avgPx } = entry.filled;
278
- out.push({ leg, kind: 'filled', oid, oidSafe: Number.isSafeInteger(oid), totalSz, avgPx });
297
+ out.push({ index, leg, side, positionSide, kind: 'filled', oid, oidSafe: Number.isSafeInteger(oid), totalSz, avgPx });
279
298
  } else if (entry.resting && entry.resting.oid !== undefined) {
280
299
  const { oid } = entry.resting;
281
- out.push({ leg, kind: 'resting', oid, oidSafe: Number.isSafeInteger(oid) });
300
+ out.push({ index, leg, side, positionSide, kind: 'resting', oid, oidSafe: Number.isSafeInteger(oid) });
301
+ } else if ('error' in entry) {
302
+ out.push({ index, leg, side, positionSide, kind: 'rejected' });
282
303
  }
283
304
  }
284
305
  return out;
285
306
  }
286
307
 
287
- // Fire the perp_order_completed event via the injected tracker. Deliberately
288
- // minimal (privacy): only the trade side and the parent Hyperliquid order id —
289
- // no asset, price, size, or fill detail. The order-placement response carries no
290
- // trade/fill id (that exists only once the order fills, via the fills feed), so
291
- // side + oid is the reliable maximum here. The oid is omitted when it arrived
292
- // rounded past 2^53 (oidSafe false) so BI never records a wrong id. `summary` is
293
- // summarizeOrderResult's output; its parent leg carries the order id.
294
- function emitPerpOrderCompleted(telemetry, summary) {
295
- const parent = summary.find((o) => o.leg === 'parent') ?? summary[0];
296
- return telemetry.track({
308
+ // Fire one privacy-minimal event per response leg. Each oid is joined to fills
309
+ // in BI; the shared nonce reconstructs the submitted batch. Raw wallet, prices,
310
+ // sizes and error text never leave the CLI. Unsafe uint64 ids are omitted.
311
+ function emitPerpOrderCompleted(telemetry, summary, walletAddress, submissionId, errorCode) {
312
+ return Promise.all(summary.map((order) => telemetry.track({
297
313
  command: telemetry.command,
298
- side: telemetry.side,
299
- oid: parent && parent.oidSafe ? parent.oid : undefined,
300
- });
314
+ // Pass the leg's own side (not the command-level side) so telemetry can
315
+ // distinguish a leg whose side is unknown and omit position_side rather
316
+ // than fabricate one. order.side is always set for real HL legs.
317
+ side: order.side,
318
+ position_side: order.positionSide,
319
+ outcome: order.kind,
320
+ // Guard submission_id so a future refactor that drops the nonce can never
321
+ // stringify undefined into the BI dedup key (perpOutcomeEventId derives
322
+ // the event id from it).
323
+ ...(submissionId !== undefined && { submission_id: String(submissionId) }),
324
+ leg_index: order.index,
325
+ leg: order.leg,
326
+ wallet_address: walletAddress,
327
+ oid: order.oidSafe ? order.oid : undefined,
328
+ // A mixed response is a command-level PARTIAL_FILL, but successful legs
329
+ // remain successful. Attach the stable code only to rejected legs.
330
+ ...(order.kind === 'rejected' && errorCode ? { error_code: errorCode } : {}),
331
+ })));
301
332
  }
302
333
 
303
334
  async function buildScreenSignSubmit(apiInstance, prepared, ctx) {
@@ -317,7 +348,24 @@ async function buildScreenSignSubmit(apiInstance, prepared, ctx) {
317
348
  const signature = await signHlAction(eip712, ctx);
318
349
 
319
350
  log(' Submitting to Hyperliquid...');
320
- const result = await submitExchange({ action, nonce, signature, vaultAddress: null });
351
+ let result;
352
+ try {
353
+ result = await submitExchange({ action, nonce, signature, vaultAddress: null });
354
+ } catch (error) {
355
+ if (telemetry && error.exchangeResult) {
356
+ // Emit only authoritative per-leg outcomes. An opaque or malformed HTTP
357
+ // body has an indeterminate result and remains covered by cli_command_failed.
358
+ const outcomes = summarizeOrderResult(error.exchangeResult, action);
359
+ if (outcomes.length) {
360
+ try {
361
+ await emitPerpOrderCompleted(telemetry, outcomes, walletAddress, nonce, error.code);
362
+ } catch {
363
+ // Best-effort; preserve the original exchange error.
364
+ }
365
+ }
366
+ }
367
+ throw error;
368
+ }
321
369
 
322
370
  const status = result.status ?? 'ok';
323
371
  log(` Status: ${status}`);
@@ -345,7 +393,7 @@ async function buildScreenSignSubmit(apiInstance, prepared, ctx) {
345
393
  log(` Response: ${resp}`);
346
394
  }
347
395
 
348
- // Emit the order OUTCOME to BI (oid, fill status/price/size, TP/SL legs) — the
396
+ // Emit the order outcome to BI (one privacy-minimal event per response leg) — the
349
397
  // perp analogue of the command-level telemetry, which fires too early (before
350
398
  // this HL response) to observe any of it. Order/close only: cancel / leverage
351
399
  // / transfer / builder-fee actions carry no `telemetry` and also summarize to
@@ -353,7 +401,7 @@ async function buildScreenSignSubmit(apiInstance, prepared, ctx) {
353
401
  // completed order into a cli_command_failed.
354
402
  if (telemetry && orders.length) {
355
403
  try {
356
- await emitPerpOrderCompleted(telemetry, orders);
404
+ await emitPerpOrderCompleted(telemetry, orders, walletAddress, nonce);
357
405
  } catch {
358
406
  // Best-effort; never surface a tracking error after a real fill.
359
407
  }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Nansen CLI - Shared list-query helpers
3
+ *
4
+ * Builds pagination and order_by request fragments from CLI options.
5
+ * Lives in a leaf module so src/cli.js and src/commands/*.js share one
6
+ * implementation without circular imports.
7
+ */
8
+
9
+ import { NansenError, ErrorCode } from './api.js';
10
+
11
+ export function buildPagination(options) {
12
+ if (options.limit === undefined && options.page === undefined) return undefined;
13
+ const perPage = options.limit === undefined ? undefined : Number(options.limit);
14
+ if (perPage !== undefined && (!Number.isInteger(perPage) || perPage < 1)) {
15
+ throw new NansenError('--limit must be a positive integer', ErrorCode.INVALID_PARAMS);
16
+ }
17
+ return {
18
+ page: Math.max(1, parseInt(options.page, 10) || 1),
19
+ per_page: perPage,
20
+ };
21
+ }
22
+
23
+ // Parse simple sort syntax: "field:direction" or "field" (defaults to DESC)
24
+ export function parseSort(sortOption, orderByOption) {
25
+ // If --order-by is provided, use it (full JSON control)
26
+ if (orderByOption) return orderByOption;
27
+ if (!sortOption) return undefined;
28
+ const parts = String(sortOption).split(':');
29
+ const field = parts[0];
30
+ const direction = (parts[1] || 'desc').toUpperCase();
31
+ return [{ field, direction }];
32
+ }