nansen-cli 1.44.1 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.44.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#604](https://github.com/nansen-ai/nansen-cli/pull/604) [`9d541d7`](https://github.com/nansen-ai/nansen-cli/commit/9d541d7d6aef232b0761846f6e716222f67798c4) Thanks [@kome12](https://github.com/kome12)! - Bind limit-order deposits to the trusted vault destination: reject any deposit whose wallet-sourced transfer (SPL token or native SOL) does not land in a token account this same transaction creates via CreateAccountWithSeed seeded off the user's vault. Covers both the SPL-token and native-SOL deposit paths.
8
+
9
+ - [#600](https://github.com/nansen-ai/nansen-cli/pull/600) [`c86af55`](https://github.com/nansen-ai/nansen-cli/commit/c86af55dff3fa71c61726650ec66060b61d1918e) Thanks [@kome12](https://github.com/kome12)! - Isolate the response cache by credential and request context so cached
10
+ responses can no longer be shared across different API keys or API origins that
11
+ use the same cache directory. Cache keys now include the base URL, HTTP method,
12
+ and a hashed form of the effective credentials, and use SHA-256.
13
+
14
+ - [#612](https://github.com/nansen-ai/nansen-cli/pull/612) [`492b441`](https://github.com/nansen-ai/nansen-cli/commit/492b441d49df6e256b3e63645e16644bdec3a56c) Thanks [@gulshngill](https://github.com/gulshngill)! - Reject hard-linked `.credentials` files in the wallet-password fallback write, so the credential write cannot chmod, truncate, or overwrite an unrelated file
15
+
16
+ - [#611](https://github.com/nansen-ai/nansen-cli/pull/611) [`959225c`](https://github.com/nansen-ai/nansen-cli/commit/959225c1527540359763bb55a90f12fc4ffb14ea) Thanks [@gulshngill](https://github.com/gulshngill)! - Report `from_cache` telemetry from the API instance so it survives command handlers that rebuild their result, and pass it on the `alerts list --table` path, which previously never reported the field at all
17
+
18
+ - [#609](https://github.com/nansen-ai/nansen-cli/pull/609) [`288f566`](https://github.com/nansen-ai/nansen-cli/commit/288f566b674f8b550b19b26b4721e3fe68cc54f6) Thanks [@gulshngill](https://github.com/gulshngill)! - Fix `from_cache` telemetry always reporting `false` on cache hits
19
+
20
+ - [#586](https://github.com/nansen-ai/nansen-cli/pull/586) [`b254240`](https://github.com/nansen-ai/nansen-cli/commit/b25424008fe0202972ac706913721a3433f30d59) Thanks [@Kewe63](https://github.com/Kewe63)! - Tighten POSIX permissions when rewriting the fallback wallet credentials file and refuse non-regular credential paths.
21
+
22
+ - [#615](https://github.com/nansen-ai/nansen-cli/pull/615) [`9166884`](https://github.com/nansen-ai/nansen-cli/commit/916688496c2c83dee17e81a9b6c753a94b8ff0be) Thanks [@teyrebaz33](https://github.com/teyrebaz33)! - Fix `nansen transfer`/`nansen trade execute` with `--wallet walletconnect` using any connected EVM account instead of verifying the WalletConnect session is actually approved for the chain being signed/broadcast on.
23
+
24
+ `getWalletConnectAddress('evm')` matched any account whose CAIP-2 chain tag started with `eip155:`, regardless of which specific chain it was approved for. Because EVM addresses are identical across chains, a session connected only to Ethereum mainnet would be silently used to sign a transaction destined for Base (or vice versa) -- nothing downstream (including the quote/request-intent binding checks) could catch this, since they only compare addresses, not chains.
25
+
26
+ `getWalletConnectAddress` now accepts an optional `chainId`, and when given, only returns an account the session has approved for that exact chain (mirroring the mainnet-only exact match already used for Solana in the same function). Every place that resolves a WalletConnect EVM address before signing or broadcasting a real transaction now passes the target chain ID and fails closed with a clear error instead of proceeding with a wrong-chain session: `nansen transfer`'s `sendTokensViaWalletConnect`, and `nansen trade execute`'s quote-building, pre-execute wallet-match check, and immediate pre-signing check for its EVM WalletConnect swap path.
27
+
3
28
  ## 1.44.1
4
29
 
5
30
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nansen-cli",
3
- "version": "1.44.1",
3
+ "version": "1.44.2",
4
4
  "description": "AI-agent CLI for Nansen API analytics, DEX swaps, and cross-chain trading",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/api.js CHANGED
@@ -246,19 +246,53 @@ const DEFAULT_CACHE_TTL = 300; // 5 minutes
246
246
 
247
247
  import crypto from 'crypto';
248
248
 
249
- /**
250
- * Generate cache key from endpoint and request body
251
- */
252
- function getCacheKey(endpoint, body) {
253
- const data = JSON.stringify({ endpoint, body });
254
- return crypto.createHash('md5').update(data).digest('hex');
249
+ const AUTH_HEADER_NAMES = ['apikey', 'authorization', 'payment-signature'];
250
+
251
+ // payment-signature is intentionally included: it is an auth credential and
252
+ // including it isolates caches between users with different static signatures.
253
+ // This is safe because:
254
+ // (a) User-supplied signatures (--x402-payment-signature) live in defaultHeaders
255
+ // and are stable across calls, keeping the identity hash stable.
256
+ // (b) Auto-generated signatures from the x402 retry path are added inside
257
+ // _x402Retry(), which calls fetch() directly and never goes through the
258
+ // cache check — so they never appear in options.headers here.
259
+ // INVARIANT: do not place a freshly-generated per-request Payment-Signature in
260
+ // options.headers before calling request() — it would produce a unique identity
261
+ // hash on every call and silently disable caching for those requests.
262
+ export function computeIdentityDigest(apiKey, ...headerSets) {
263
+ const authHeaders = {};
264
+ for (const headers of headerSets) {
265
+ if (!headers) continue;
266
+ for (const [name, value] of Object.entries(headers)) {
267
+ const lower = name.toLowerCase();
268
+ if (AUTH_HEADER_NAMES.includes(lower)) authHeaders[lower] = value;
269
+ }
270
+ }
271
+ const material = JSON.stringify({
272
+ apiKey: apiKey ?? null,
273
+ authHeaders: Object.fromEntries(
274
+ Object.entries(authHeaders).sort(([a], [b]) => a.localeCompare(b))
275
+ ),
276
+ });
277
+ return crypto.createHash('sha256').update(material).digest('hex');
278
+ }
279
+
280
+ function getCacheKey(endpoint, body, context = {}) {
281
+ const data = JSON.stringify({
282
+ endpoint,
283
+ body,
284
+ baseUrl: context.baseUrl ?? null,
285
+ method: context.method ?? null,
286
+ identity: context.identity ?? null,
287
+ });
288
+ return crypto.createHash('sha256').update(data).digest('hex');
255
289
  }
256
290
 
257
291
  /**
258
292
  * Get cached response if valid
259
293
  */
260
- export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL) {
261
- const cacheKey = getCacheKey(endpoint, body);
294
+ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL, context = {}) {
295
+ const cacheKey = getCacheKey(endpoint, body, context);
262
296
  const cacheFile = path.join(CACHE_DIR, `${cacheKey}.json`);
263
297
 
264
298
  if (!fs.existsSync(cacheFile)) {
@@ -301,12 +335,12 @@ export function getCachedResponse(endpoint, body, ttlSeconds = DEFAULT_CACHE_TTL
301
335
  /**
302
336
  * Save response to cache
303
337
  */
304
- export function setCachedResponse(endpoint, body, data) {
338
+ export function setCachedResponse(endpoint, body, data, context = {}) {
305
339
  if (!fs.existsSync(CACHE_DIR)) {
306
340
  fs.mkdirSync(CACHE_DIR, { mode: 0o700, recursive: true });
307
341
  }
308
-
309
- const cacheKey = getCacheKey(endpoint, body);
342
+
343
+ const cacheKey = getCacheKey(endpoint, body, context);
310
344
  const cacheFile = path.join(CACHE_DIR, `${cacheKey}.json`);
311
345
 
312
346
  const cached = {
@@ -543,6 +577,17 @@ export class NansenAPI {
543
577
  this.lastResponseMeta = null;
544
578
  /** API path of the most recent request(), for pairing lastResponseMeta with a cost estimate. */
545
579
  this.lastEndpoint = null;
580
+ /**
581
+ * Whether the most recent request() was answered from the local response
582
+ * cache instead of the network.
583
+ *
584
+ * Lives on the instance for the same reason lastResponseMeta does: a cache
585
+ * hit returns early, and a handler that rebuilds its result (alerts list,
586
+ * for one) drops the `_meta.fromCache` marker carried on the body, so the
587
+ * payload alone can't be trusted to still say so by the time telemetry
588
+ * reads it. Last write wins when a handler makes several calls.
589
+ */
590
+ this.servedFromCache = false;
546
591
  }
547
592
 
548
593
  static cleanBody(body) {
@@ -668,20 +713,33 @@ export class NansenAPI {
668
713
  // Check cache first (if enabled and not bypassed)
669
714
  const useCache = options.cache !== false && this.cacheOptions.enabled;
670
715
  const cacheTtl = options.cacheTtl ?? this.cacheOptions.ttl;
671
-
672
- if (useCache) {
673
- const cached = getCachedResponse(endpoint, body, cacheTtl);
716
+ const method = options.method || 'POST';
717
+ // Defer identity hashing to keep the uncached (default) path free of crypto work.
718
+ // cacheContext is therefore null unless caching is on; the `&& cacheContext`
719
+ // guards below ensure that null never reaches getCacheKey, where a missing
720
+ // identity would silently produce a credential-agnostic (shared) cache key.
721
+ const cacheContext = useCache
722
+ ? {
723
+ baseUrl: this.baseUrl,
724
+ method,
725
+ identity: computeIdentityDigest(this.apiKey, this.defaultHeaders, options.headers),
726
+ }
727
+ : null;
728
+
729
+ if (useCache && cacheContext) {
730
+ const cached = getCachedResponse(endpoint, body, cacheTtl, cacheContext);
674
731
  if (cached) {
732
+ this.servedFromCache = true;
675
733
  return cached;
676
734
  }
677
735
  }
736
+ this.servedFromCache = false;
678
737
 
679
738
  let lastError;
680
-
739
+
681
740
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
682
741
  let response;
683
742
  try {
684
- const method = options.method || 'POST';
685
743
  const isGet = method === 'GET';
686
744
  response = await fetch(url, {
687
745
  method,
@@ -900,8 +958,8 @@ export class NansenAPI {
900
958
  }
901
959
 
902
960
  // Cache successful response
903
- if (useCache) {
904
- setCachedResponse(endpoint, body, data);
961
+ if (useCache && cacheContext) {
962
+ setCachedResponse(endpoint, body, data, cacheContext);
905
963
  }
906
964
 
907
965
  // Attach after caching so the cache stores the payload alone — quota
package/src/chain-ids.js CHANGED
@@ -4,6 +4,12 @@
4
4
  * Single source of truth — import from here instead of defining inline.
5
5
  */
6
6
 
7
+ // If you add a chain to EVM_CHAINS below, add its numeric chain ID here too.
8
+ // transfer.js's EVM transfer paths (both local-wallet and WalletConnect) look
9
+ // up the chain ID here and fail closed with "Unsupported chain" when it's
10
+ // missing -- so a chain listed in EVM_CHAINS but absent here can't actually
11
+ // be used to send a transfer yet, even though address-format validation and
12
+ // ENS resolution already accept it.
7
13
  export const EVM_CHAIN_IDS = {
8
14
  ethereum: 1,
9
15
  base: 8453,
package/src/cli.js CHANGED
@@ -2101,6 +2101,19 @@ export async function runCLI(rawArgs, deps = {}) {
2101
2101
 
2102
2102
  let result = await commands[command](subArgs, api, flags, options);
2103
2103
 
2104
+ // The cache marker is hung off the payload's `_meta` by getCachedResponse(),
2105
+ // never as a top-level `fromCache`. Capture it here, before `--fields`
2106
+ // filtering below drops `_meta` along with every other unrequested key —
2107
+ // read any later and a cache hit with `--fields` reports as a live call.
2108
+ //
2109
+ // `_meta` alone isn't enough either: handlers are free to rebuild their
2110
+ // result and some do (`alerts list` filters the array into a fresh one),
2111
+ // which drops the marker before we get here. `api.servedFromCache` is set
2112
+ // on the instance next to the cache-hit early return in request(), so it
2113
+ // survives that reshaping. Compared against `true` so a stubbed API whose
2114
+ // every property is a mock function doesn't read as a hit.
2115
+ const fromCache = !!result?._meta?.fromCache || api.servedFromCache === true;
2116
+
2104
2117
  // Credit balance warning, from the headers on the call just made. Goes to
2105
2118
  // stderr so it never contaminates the JSON on stdout that agents parse.
2106
2119
  // Placed before every return path below so it fires for operational
@@ -2141,7 +2154,7 @@ export async function runCLI(rawArgs, deps = {}) {
2141
2154
  // Alerts list with --table uses custom table format
2142
2155
  if (command === 'alerts' && subcommand === 'list' && table) {
2143
2156
  output(formatAlertsTable(result));
2144
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, flags: usedFlags, chain });
2157
+ await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2145
2158
  return { type: 'success', data: result };
2146
2159
  }
2147
2160
 
@@ -2152,14 +2165,14 @@ export async function runCLI(rawArgs, deps = {}) {
2152
2165
  if (streamOutput) {
2153
2166
  output(streamOutput);
2154
2167
  }
2155
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: !!result?.fromCache, flags: usedFlags, chain });
2168
+ await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2156
2169
  return { type: 'stream', data: result };
2157
2170
  }
2158
2171
 
2159
2172
  const successData = { success: true, data: result };
2160
2173
  const formatted = formatOutput(successData, { pretty, table, csv });
2161
2174
  output(formatted.text);
2162
- await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: !!result?.fromCache, flags: usedFlags, chain });
2175
+ await trackSucceeded({ command: fullCommand, duration_ms: Date.now() - startTime, from_cache: fromCache, flags: usedFlags, chain });
2163
2176
  return { type: csv ? 'csv' : 'success', data: result };
2164
2177
  } catch (error) {
2165
2178
  // Unified error envelope across all command families (perp/bridge/trade):
package/src/keychain.js CHANGED
@@ -151,8 +151,38 @@ function credentialsFileWrite(password) {
151
151
  fs.mkdirSync(dir, { mode: 0o700, recursive: true });
152
152
  }
153
153
  const encoded = Buffer.from(password, 'utf8').toString('base64');
154
- fs.writeFileSync(filePath, `NANSEN_WALLET_PASSWORD_B64=${encoded}\n`, { mode: 0o600 });
155
- return true;
154
+ const content = `NANSEN_WALLET_PASSWORD_B64=${encoded}\n`;
155
+
156
+ // Windows does not implement POSIX modes or O_NOFOLLOW consistently.
157
+ if (process.platform === 'win32') {
158
+ fs.writeFileSync(filePath, content, { mode: 0o600 });
159
+ return true;
160
+ }
161
+
162
+ let fd;
163
+ try {
164
+ const flags = fs.constants.O_WRONLY
165
+ | fs.constants.O_CREAT
166
+ | fs.constants.O_NOFOLLOW
167
+ | fs.constants.O_NONBLOCK;
168
+ fd = fs.openSync(filePath, flags, 0o600);
169
+ const stats = fs.fstatSync(fd);
170
+ if (!stats.isFile()) throw new Error('Credentials path is not a regular file');
171
+ // O_NOFOLLOW only rejects symlinks. A hard link at .credentials points at
172
+ // a victim file that is indistinguishable by path or type, so refuse any
173
+ // regular file with extra links before fchmod/ftruncate touch it.
174
+ if (stats.nlink !== 1) throw new Error('Credentials file has unexpected hard links');
175
+
176
+ // Opening an existing file does not apply the requested mode. Tighten it
177
+ // before replacing the secret, then enforce the final mode after writing.
178
+ fs.fchmodSync(fd, 0o600);
179
+ fs.ftruncateSync(fd, 0);
180
+ fs.writeFileSync(fd, content, 'utf8');
181
+ fs.fchmodSync(fd, 0o600);
182
+ return true;
183
+ } finally {
184
+ if (fd !== undefined) fs.closeSync(fd);
185
+ }
156
186
  } catch {
157
187
  return false;
158
188
  }
@@ -13,6 +13,7 @@ import { signEd25519, base58Decode, parseAmount, getTokenInfo } from './transfer
13
13
  import { signSolanaTransaction, resolveTokenAddress } from './trading.js';
14
14
  import {
15
15
  assertSolanaInstructionsSafe,
16
+ assertLimitOrderDepositDestination,
16
17
  assertLimitOrderDepositOutcome,
17
18
  assertLimitOrderCancelOutcome,
18
19
  NATIVE_FEE_RENT_SLACK_LAMPORTS,
@@ -782,20 +783,38 @@ EXAMPLES:
782
783
  // 3. Check vault, auto-register if needed
783
784
  // Backend returns { vaultPubkey: "..." } when vault exists, or throws/returns empty when not
784
785
  let hasVault = false;
786
+ let vaultPubkey;
785
787
  try {
786
788
  const vaultInfo = await getVault(token, pubkey);
787
- hasVault = !!(vaultInfo?.vaultPubkey || vaultInfo?.vaultAddress);
789
+ vaultPubkey = vaultInfo?.vaultPubkey || vaultInfo?.vaultAddress;
790
+ hasVault = !!vaultPubkey;
788
791
  } catch {
789
792
  // No vault found
790
793
  }
791
794
  if (!hasVault) {
792
795
  log(' Registering vault for first-time use...');
793
796
  try {
794
- await registerVault(token);
797
+ const vaultInfo = await registerVault(token);
798
+ vaultPubkey = vaultInfo?.vaultPubkey || vaultInfo?.vaultAddress;
795
799
  } catch (regErr) {
796
800
  // Vault may already exist — ignore "already registered" errors
797
801
  if (!/already registered/i.test(regErr.message)) throw regErr;
798
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.');
799
818
  }
800
819
 
801
820
  // 4. Craft deposit transaction
@@ -808,21 +827,22 @@ EXAMPLES:
808
827
  });
809
828
 
810
829
  // 5. Sign deposit transaction
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).
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.
825
840
  assertSolanaInstructionsSafe(deposit.transaction, { walletAddress: pubkey });
841
+ assertLimitOrderDepositDestination(deposit.transaction, {
842
+ walletAddress: pubkey,
843
+ inputMint: from,
844
+ vaultOwner: vaultPubkey,
845
+ });
826
846
  const depositOutcome = await verifyLimitOrderOutcome({
827
847
  kind: 'deposit', walletAddress: pubkey, txBase64: deposit.transaction,
828
848
  inputMint: from, amount: amountBaseUnits, log,
@@ -4,8 +4,10 @@
4
4
  * bad amounts) before any network call.
5
5
  */
6
6
 
7
+ import crypto from 'crypto';
7
8
  import { validateAddress } from './api.js';
8
9
  import { CHAIN_RPCS } from './rpc-urls.js';
10
+ import { base58Encode } from './wallet.js';
9
11
  import { parseTransactionMessage, resolveStaticAccount } from './solana-tx.js';
10
12
  import { SOL_SENTINEL } from './solana-simulation.js';
11
13
  import { EVM_NATIVE_SENTINEL } from './swap-simulation.js';
@@ -20,10 +22,20 @@ const SPL_TOKEN_PROGRAMS = new Set([
20
22
  'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
21
23
  'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',
22
24
  ]);
25
+ const SPL_TRANSFER = 3;
23
26
  const SPL_APPROVE = 4;
24
27
  const SPL_SET_AUTHORITY = 6;
25
28
  const SPL_CLOSE_ACCOUNT = 9;
29
+ const SPL_TRANSFER_CHECKED = 12;
26
30
  const SPL_APPROVE_CHECKED = 13;
31
+ const SPL_INITIALIZE_ACCOUNT = 1;
32
+ const SPL_INITIALIZE_ACCOUNT2 = 16;
33
+ const SPL_INITIALIZE_ACCOUNT3 = 18;
34
+
35
+ const SYSTEM_PROGRAM = '11111111111111111111111111111111';
36
+ const SYSTEM_INSTR_TRANSFER = 2;
37
+ const SYSTEM_INSTR_CREATE_ACCOUNT_WITH_SEED = 3;
38
+ const WSOL_MINT = 'So11111111111111111111111111111111111111112';
27
39
 
28
40
  const COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';
29
41
  const COMPUTE_BUDGET_SET_UNIT_LIMIT = 2;
@@ -1484,8 +1496,9 @@ export function assertSolanaSwapOutcome(request, quote, sim, { slippage, sibling
1484
1496
  * within `amount` ± NATIVE_FEE_RENT_SLACK_LAMPORTS for a native-SOL input
1485
1497
  * (two-sided: upper bound caps the drain, lower bound rejects a partial reroute), and
1486
1498
  * 2. no token OTHER than the input leaves the wallet (native-SOL dust tolerated).
1487
- * NOTE: this bounds MAGNITUDE, not destination — a full-`amount` transfer to a non-vault
1488
- * address still passes; that is closed by the vault-destination binding (fast-follow).
1499
+ * NOTE: this bounds MAGNITUDE, not destination. The create command pairs it with
1500
+ * assertLimitOrderDepositDestination so a wallet-authorized SPL transfer of the
1501
+ * deposited asset must land in the vault's token account.
1489
1502
  * There is no output leg — the deposit funds the vault, nothing returns to the wallet.
1490
1503
  *
1491
1504
  * @param {{deltas: Record<string, bigint|string|number>}} sim - simulateSolanaAssetChanges result
@@ -1848,3 +1861,178 @@ export function assertSolanaInstructionsSafe(txBase64, { walletAddress } = {}) {
1848
1861
 
1849
1862
  return parsed;
1850
1863
  }
1864
+
1865
+ /**
1866
+ * Statically bind a limit-order deposit's wallet-sourced outflow to a token
1867
+ * account provably derived from the trusted vault owner. This closes the
1868
+ * destination gap balance-delta simulation cannot see: a tx can spend exactly
1869
+ * the requested amount from the wallet while sending it to an attacker's
1870
+ * account.
1871
+ *
1872
+ * The real on-chain shape (confirmed by a live create round-trip) is NOT the
1873
+ * vault's canonical ATA. Jupiter Trigger V2 funds each order through a fresh
1874
+ * per-order token account created in the same transaction via
1875
+ * System::CreateAccountWithSeed(base = vaultOwner, seed = <per-order>,
1876
+ * owner = Token program), then:
1877
+ * - SPL input → TransferChecked / Transfer of the input token into it, or
1878
+ * - native SOL → System::Transfer of lamports into it, then SyncNative.
1879
+ * So the destination is per-order and changes every craft; we can't pin a fixed
1880
+ * address. Instead we recompute create_with_seed(base, seed, owner) from the
1881
+ * transaction's own CreateAccountWithSeed instruction, require base == the
1882
+ * trusted vaultOwner, and bind every wallet-sourced transfer to that recomputed
1883
+ * account. This is stronger than an ATA equality check: the destination is
1884
+ * provably seeded off the vault the backend told us to deposit into.
1885
+ *
1886
+ * This check is intentionally limit-order-specific; generic swaps cannot
1887
+ * require a single destination.
1888
+ */
1889
+ export function assertLimitOrderDepositDestination(txBase64, { walletAddress, inputMint, vaultOwner } = {}) {
1890
+ const fail = (detail) => {
1891
+ const e = new Error(`Limit-order deposit destination mismatch (LIMIT_ORDER_DESTINATION_MISMATCH): ${detail} Refusing to sign.`);
1892
+ e.code = 'LIMIT_ORDER_DESTINATION_MISMATCH';
1893
+ return e;
1894
+ };
1895
+
1896
+ if (!walletAddress) throw fail('missing signing wallet address.');
1897
+ if (!inputMint) throw fail('missing deposit input mint.');
1898
+ if (!vaultOwner) throw fail('missing vault owner address.');
1899
+
1900
+ const parsed = parseTransactionMessage(txBase64);
1901
+ const accountAt = (ix, position) => resolveStaticAccount(parsed, ix.accountIndexes[position]);
1902
+ const walletAuthorizes = (ix, authorityPos) => {
1903
+ if (accountAt(ix, authorityPos) === null) return true;
1904
+ for (let i = authorityPos; i < ix.accountIndexes.length; i++) {
1905
+ if (accountAt(ix, i) === walletAddress) return true;
1906
+ }
1907
+ return false;
1908
+ };
1909
+
1910
+ const expectedMint = SOLANA_NATIVE_SOL_ALIASES.has(inputMint) ? WSOL_MINT : inputMint;
1911
+
1912
+ // Pass 1: collect the token accounts this transaction creates via
1913
+ // System::CreateAccountWithSeed seeded off the trusted vault owner, plus the
1914
+ // matching SPL InitializeAccount* owner/mint assignment. A seeded address
1915
+ // alone is not enough: the token-account authority must also be the trusted
1916
+ // vault owner, otherwise the deposit can be withdrawn by whoever controls the
1917
+ // initialized account.
1918
+ const vaultSeededAccounts = new Set();
1919
+ const initializedAccounts = new Map();
1920
+ for (const ix of parsed.instructions) {
1921
+ const programId = resolveStaticAccount(parsed, ix.programIdIndex);
1922
+ if (programId === SYSTEM_PROGRAM) {
1923
+ if (ix.data.length < 4 || ix.data.readUInt32LE(0) !== SYSTEM_INSTR_CREATE_ACCOUNT_WITH_SEED) continue;
1924
+ // Layout: u32 index | 32 base | u64 seedLen | seed | u64 lamports | u64 space | 32 owner
1925
+ let off = 4;
1926
+ const need = (n) => { if (off + n > ix.data.length) throw fail('malformed CreateAccountWithSeed instruction.'); };
1927
+ need(32); const base = ix.data.subarray(off, off + 32); off += 32;
1928
+ need(8); const seedLen = Number(ix.data.readBigUInt64LE(off)); off += 8;
1929
+ need(seedLen); const seed = ix.data.subarray(off, off + seedLen); off += seedLen;
1930
+ need(16); off += 16; // skip lamports (u64) + space (u64)
1931
+ need(32); const owner = ix.data.subarray(off, off + 32);
1932
+ if (base58Encode(base) !== vaultOwner) continue; // not seeded off our vault
1933
+ if (!SPL_TOKEN_PROGRAMS.has(base58Encode(owner))) continue; // not a token account
1934
+ // create_with_seed(base, seed, owner) = base58(sha256(base || seed || owner)).
1935
+ const derived = base58Encode(crypto.createHash('sha256').update(Buffer.concat([base, seed, owner])).digest());
1936
+ // The account the instruction creates (index 1) must equal the recomputed
1937
+ // address; a mismatch means a malformed/crafted instruction — fail closed.
1938
+ const created = accountAt(ix, 1);
1939
+ if (created !== null && created !== derived) {
1940
+ throw fail('CreateAccountWithSeed target does not match its base/seed/owner derivation.');
1941
+ }
1942
+ vaultSeededAccounts.add(derived);
1943
+ continue;
1944
+ }
1945
+
1946
+ if (!SPL_TOKEN_PROGRAMS.has(programId) || ix.data.length === 0) continue;
1947
+ const discriminator = ix.data[0];
1948
+ let account;
1949
+ let mint;
1950
+ let owner;
1951
+
1952
+ if (discriminator === SPL_INITIALIZE_ACCOUNT) {
1953
+ // InitializeAccount: accounts [account, mint, owner, rent].
1954
+ account = accountAt(ix, 0);
1955
+ mint = accountAt(ix, 1);
1956
+ owner = accountAt(ix, 2);
1957
+ } else if (discriminator === SPL_INITIALIZE_ACCOUNT2 || discriminator === SPL_INITIALIZE_ACCOUNT3) {
1958
+ // InitializeAccount2/3: accounts [account, mint, ...], data [disc, owner pubkey].
1959
+ if (ix.data.length < 33) throw fail('malformed InitializeAccount owner field.');
1960
+ account = accountAt(ix, 0);
1961
+ mint = accountAt(ix, 1);
1962
+ owner = base58Encode(ix.data.subarray(1, 33));
1963
+ } else {
1964
+ continue;
1965
+ }
1966
+
1967
+ if (account === null || mint === null || owner === null) {
1968
+ throw fail('token account initializer uses an address only resolvable via an address lookup table.');
1969
+ }
1970
+ initializedAccounts.set(account, { mint, owner });
1971
+ }
1972
+
1973
+ // Pass 2: every wallet-sourced transfer of value must land in a vault-seeded
1974
+ // account that is also initialized in this transaction with the vault as its
1975
+ // token-account authority. Covers both deposit shapes — SPL token transfers
1976
+ // and the native-SOL System::Transfer that funds a wrapped-SOL order account.
1977
+ const requireTrustedDestination = (destination, label) => {
1978
+ if (!vaultSeededAccounts.has(destination)) {
1979
+ throw fail(`wallet-authorized ${label} sends funds to ${destination || 'an address only resolvable via an address lookup table'} instead of a vault-seeded deposit account.`);
1980
+ }
1981
+ const initialized = initializedAccounts.get(destination);
1982
+ if (!initialized) {
1983
+ throw fail(`wallet-authorized ${label} sends funds to ${destination} before verifying it is initialized with the trusted vault authority.`);
1984
+ }
1985
+ if (!tokensEqual(initialized.mint, expectedMint, 'solana')) {
1986
+ throw fail(`vault-seeded token account is initialized for mint ${initialized.mint} instead of deposit mint ${expectedMint}.`);
1987
+ }
1988
+ if (initialized.owner !== vaultOwner) {
1989
+ throw fail(`vault-seeded token account authority is ${initialized.owner} instead of expected vault owner ${vaultOwner}.`);
1990
+ }
1991
+ };
1992
+ let sawValidDepositTransfer = false;
1993
+
1994
+ for (const ix of parsed.instructions) {
1995
+ const programId = resolveStaticAccount(parsed, ix.programIdIndex);
1996
+ if (!programId) {
1997
+ throw fail('transaction invokes a program only resolvable via an address lookup table, so transfer destinations cannot be verified.');
1998
+ }
1999
+
2000
+ if (programId === SYSTEM_PROGRAM) {
2001
+ if (ix.data.length < 4) continue;
2002
+ if (ix.data.readUInt32LE(0) !== SYSTEM_INSTR_TRANSFER) continue;
2003
+ // System::Transfer accounts: [from (signer), to]. `from` must be a signer,
2004
+ // so it can never be ALT-resolved; null means a malformed tx — fail closed.
2005
+ const from = accountAt(ix, 0);
2006
+ if (from === null) throw fail('native transfer source is unresolvable (malformed transaction).');
2007
+ if (from !== walletAddress) continue; // not our funds
2008
+ requireTrustedDestination(accountAt(ix, 1), 'native transfer');
2009
+ sawValidDepositTransfer = true;
2010
+ continue;
2011
+ }
2012
+
2013
+ if (!SPL_TOKEN_PROGRAMS.has(programId) || ix.data.length === 0) continue;
2014
+ const discriminator = ix.data[0];
2015
+ if (discriminator === SPL_TRANSFER) {
2016
+ // Classic Transfer carries no mint in its account list, so we bind only the
2017
+ // destination. Not a weakness: the destination is a vault-seeded account and
2018
+ // the balance-delta gate still bounds which token and how much leave the
2019
+ // wallet. Use TransferChecked (below) for instruction-level mint binding.
2020
+ if (!walletAuthorizes(ix, 2)) continue;
2021
+ requireTrustedDestination(accountAt(ix, 1), 'token transfer');
2022
+ sawValidDepositTransfer = true;
2023
+ } else if (discriminator === SPL_TRANSFER_CHECKED) {
2024
+ if (!walletAuthorizes(ix, 3)) continue;
2025
+ const mint = accountAt(ix, 1);
2026
+ if (!tokensEqual(mint, expectedMint, 'solana')) {
2027
+ throw fail(`wallet-authorized TransferChecked uses mint ${mint || 'an address only resolvable via an address lookup table'} instead of deposit mint ${expectedMint}.`);
2028
+ }
2029
+ requireTrustedDestination(accountAt(ix, 2), 'TransferChecked');
2030
+ sawValidDepositTransfer = true;
2031
+ }
2032
+ }
2033
+
2034
+ if (!sawValidDepositTransfer) {
2035
+ throw fail('no wallet-authorized deposit transfer into a vault-seeded account was detected.');
2036
+ }
2037
+ return { verified: true };
2038
+ }
package/src/trading.js CHANGED
@@ -2213,9 +2213,19 @@ CROSS-CHAIN NOTES (when using --to-chain):
2213
2213
  let walletProvider = 'local';
2214
2214
  let privyWalletIds = null;
2215
2215
  if (isWalletConnect) {
2216
- walletAddress = await getWalletConnectAddress(chainType);
2216
+ // Scoped to this chain's ID (see getWalletConnectAddress's chainId
2217
+ // param): a session approved only for a different EVM chain must
2218
+ // not be treated as valid here just because it's "some eip155:*"
2219
+ // account -- EVM addresses are identical across chains. chainId is
2220
+ // only ever passed for 'evm': Solana's chainConfig.chainId (501) is
2221
+ // not a CAIP-2 EIP-155 chain ID, and getWalletConnectAddress's own
2222
+ // Solana branch already does its own exact match unconditionally --
2223
+ // passing 501 through here would break it, not narrow it further.
2224
+ walletAddress = chainType === 'evm'
2225
+ ? await getWalletConnectAddress(chainType, chainConfig.chainId)
2226
+ : await getWalletConnectAddress(chainType);
2217
2227
  if (!walletAddress) {
2218
- throw new CommandError('No WalletConnect session active. Run: walletconnect connect', 'NO_WALLET');
2228
+ throw new CommandError(`No WalletConnect session active for chain "${chain}". Run: walletconnect connect`, 'NO_WALLET');
2219
2229
  }
2220
2230
  } else if (walletName) {
2221
2231
  const wallet = showWallet(walletName);
@@ -2564,10 +2574,20 @@ EXAMPLES:
2564
2574
 
2565
2575
  exported = exportWallet(effectiveWalletName, password);
2566
2576
  } else {
2567
- // Verify WalletConnect session is still active and address matches quote
2568
- const wcAddress = await getWalletConnectAddress(chainType);
2577
+ // Verify WalletConnect session is still active, approved for this
2578
+ // chain, and its address matches the quote. Chain-scoped (see
2579
+ // getWalletConnectAddress's chainId param) because an address
2580
+ // match alone can't tell a session on the right chain from one on
2581
+ // the wrong chain -- EVM addresses are identical across chains.
2582
+ // chainId is only ever passed for 'evm': Solana's chainConfig.chainId
2583
+ // (501) is not a CAIP-2 EIP-155 chain ID, and getWalletConnectAddress's
2584
+ // own Solana branch already does its own exact match unconditionally --
2585
+ // passing 501 through here would break it, not narrow it further.
2586
+ const wcAddress = chainType === 'evm'
2587
+ ? await getWalletConnectAddress(chainType, chainConfig.chainId)
2588
+ : await getWalletConnectAddress(chainType);
2569
2589
  if (!wcAddress) {
2570
- throw new CommandError('No WalletConnect session active. Run: walletconnect connect', 'NO_WALLET');
2590
+ throw new CommandError(`No WalletConnect session active for chain "${chain}". Run: walletconnect connect`, 'NO_WALLET');
2571
2591
  }
2572
2592
  // Check address matches the one used during quoting
2573
2593
  const quoteWallet = quoteData.response?.quotes?.[0]?.transaction?.from
@@ -3027,14 +3047,24 @@ EXAMPLES:
3027
3047
  requestId = currentQuote.metadata?.requestId;
3028
3048
 
3029
3049
  } else if (isWalletConnect) {
3030
- // EVM via WalletConnect: wallet signs and may broadcast
3031
- const wcAddress = await getWalletConnectAddress(chainType);
3032
- // A session dropped mid-execute returns null here. Without this
3050
+ // EVM via WalletConnect: wallet signs and may broadcast.
3051
+ // chainType is always 'evm' here (unguarded, unlike the two
3052
+ // other call sites) -- the Solana WalletConnect path is fully
3053
+ // handled above in the `if (chainConfig.type === 'solana')`
3054
+ // branch, so this `else if` is only ever reached for EVM.
3055
+ // Scoped to this chain's ID, not just "any EVM account" -- a
3056
+ // session approved only for a different chain must not sign
3057
+ // here. EVM addresses are identical across chains, so the
3058
+ // address-based checks below (assertQuoteMatchesRequest) can't
3059
+ // catch a session connected to the wrong chain on their own.
3060
+ const wcAddress = await getWalletConnectAddress(chainType, chainConfig.chainId);
3061
+ // A session dropped mid-execute, or one that's connected but not
3062
+ // approved for this chain, returns null here. Without this
3033
3063
  // guard a null address would fall through to assertQuoteMatchesRequest,
3034
3064
  // whose `request.walletAddress && walletAddress` condition would
3035
3065
  // silently skip the signer-binding check. Fail closed instead.
3036
3066
  if (!wcAddress) {
3037
- throw new CommandError('WalletConnect session lost during execute. Reconnect with `walletconnect connect` and retry.', 'NO_WALLET');
3067
+ throw new CommandError('No WalletConnect session for this chain. Reconnect with `walletconnect connect` and retry.', 'NO_WALLET');
3038
3068
  }
3039
3069
  const isNative = isNativeToken(currentQuote.inputMint);
3040
3070
 
package/src/transfer.js CHANGED
@@ -116,8 +116,9 @@ function bigIntToHex(n) {
116
116
  // ============= EVM Transaction =============
117
117
 
118
118
  async function buildEvmTransaction({ to, amount, token, privateKey, chain, max = false }) {
119
+ const chainId = CHAIN_IDS[chain];
120
+ if (!chainId) throw new Error(`Unsupported chain: ${chain} (no chain ID configured for EVM transfers)`);
119
121
  const rpcUrl = CHAIN_RPCS[chain] || CHAIN_RPCS.evm;
120
- const chainId = CHAIN_IDS[chain] || 1;
121
122
 
122
123
  // Derive address and buffer for signing
123
124
  const privBuf = Buffer.from(privateKey, 'hex');
@@ -829,11 +830,16 @@ export async function sendTokens({ to, amount, chain, token = null, wallet = nul
829
830
  * Send tokens via WalletConnect (EVM only).
830
831
  */
831
832
  async function sendTokensViaWalletConnect({ to, amount, chain, token, max, dryRun }) {
833
+ const chainId = CHAIN_IDS[chain];
834
+ if (!chainId) throw new Error(`Unsupported chain: ${chain} (no chain ID configured for EVM transfers)`);
832
835
  const rpcUrl = CHAIN_RPCS[chain] || CHAIN_RPCS.evm;
833
- const chainId = CHAIN_IDS[chain] || 1;
834
836
 
835
- const wcAddress = await getWalletConnectAddress();
836
- if (!wcAddress) throw new Error('No WalletConnect session active. Run: walletconnect connect');
837
+ // Scoped to this specific chain, not just "any EVM account" — a session
838
+ // approved only for a different chain must not be used to sign a transfer
839
+ // on this one (addresses are identical across EVM chains, so an address
840
+ // match alone can't catch this; the CAIP-2 chain tag can).
841
+ const wcAddress = await getWalletConnectAddress('evm', chainId);
842
+ if (!wcAddress) throw new Error(`No WalletConnect session active for chain "${chain}" (eip155:${chainId}). Run: walletconnect connect`);
837
843
 
838
844
  let txTo, txValue, txData;
839
845
 
@@ -43,8 +43,19 @@ function parseWcJson(output) {
43
43
  *
44
44
  * @param {string} [chainType] - Optional: 'evm' or 'solana'. Filters accounts by chain prefix.
45
45
  * No arg = first account (backward compat).
46
+ * @param {number} [chainId] - Optional, 'evm' only: the specific EIP-155 chain ID the
47
+ * caller is about to sign/broadcast on. When given, only an account the session has
48
+ * actually approved for THAT chain (`eip155:<chainId>`) is returned — a session
49
+ * connected only to, say, Ethereum mainnet must not be handed back as if it were
50
+ * approved for Base just because both are "eip155:*". Mirrors the mainnet-only
51
+ * exact-match already done for Solana above. Only meaningful for
52
+ * chainType === 'evm' -- the Solana branch already does its own exact
53
+ * match unconditionally, so omit chainId there (a chain-config chain ID
54
+ * like Solana's 501 is not a CAIP-2 EIP-155 chain ID and would not match
55
+ * anything); also omit it when no specific chain needs verifying at all
56
+ * (chainType itself omitted, for first-account backward compat).
46
57
  */
47
- export async function getWalletConnectAddress(chainType) {
58
+ export async function getWalletConnectAddress(chainType, chainId) {
48
59
  try {
49
60
  const output = await wcExec('walletconnect', ['whoami', '--json'], 3000);
50
61
  const data = JSON.parse(output);
@@ -58,6 +69,10 @@ export async function getWalletConnectAddress(chainType) {
58
69
  return solAccount?.address || null;
59
70
  }
60
71
  if (chainType === 'evm') {
72
+ if (chainId != null) {
73
+ const evmAccount = accounts.find(a => a.chain === `eip155:${chainId}`);
74
+ return evmAccount?.address || null;
75
+ }
61
76
  const evmAccount = accounts.find(a => a.chain?.startsWith('eip155:'));
62
77
  return evmAccount?.address || null;
63
78
  }