nansen-cli 1.44.1 → 1.44.3

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,50 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.44.3
4
+
5
+ ### Patch Changes
6
+
7
+ - [#621](https://github.com/nansen-ai/nansen-cli/pull/621) [`6ece0a1`](https://github.com/nansen-ai/nansen-cli/commit/6ece0a14290444472f0784115e678e73deb3981f) Thanks [@kome12](https://github.com/kome12)! - Validate alerts list pagination flags before fetching alerts.
8
+
9
+ - [#620](https://github.com/nansen-ai/nansen-cli/pull/620) [`bf8f40f`](https://github.com/nansen-ai/nansen-cli/commit/bf8f40f840495d7a92d95d105d131b5406a10e22) Thanks [@Radovenchyk](https://github.com/Radovenchyk)! - Fix `nansen agent` throwing a raw `AbortError` instead of a `NansenError(TIMEOUT)` when the request timeout fires while reading the SSE response body (as opposed to during the initial connection). Both streaming and `--json` output modes now report a consistent timeout error regardless of which phase of the request the abort happened in.
10
+
11
+ - [#618](https://github.com/nansen-ai/nansen-cli/pull/618) [`1e08a15`](https://github.com/nansen-ai/nansen-cli/commit/1e08a150295b44768ce954b9628de10e291924f4) Thanks [@Radovenchyk](https://github.com/Radovenchyk)! - Fix `consumeSSEStream` silently dropping the final SSE event when the stream closes without a trailing blank line (e.g. a `finish` event carrying `conversation_id`, or a trailing `delta` chunk).
12
+
13
+ - [#623](https://github.com/nansen-ai/nansen-cli/pull/623) [`9ae1dc2`](https://github.com/nansen-ai/nansen-cli/commit/9ae1dc2d871b04fae749c7126f970258bf58f41e) Thanks [@kome12](https://github.com/kome12)! - Improve Solana raw-instruction bridge error handling for RPC failures and malformed instruction data.
14
+
15
+ - [#622](https://github.com/nansen-ai/nansen-cli/pull/622) [`d86aae9`](https://github.com/nansen-ai/nansen-cli/commit/d86aae9e8d45d0427fbc0d51363529b5873d8dd0) Thanks [@kome12](https://github.com/kome12)! - Tolerate small refunded native input amounts during bridge outcome verification.
16
+
17
+ - [#617](https://github.com/nansen-ai/nansen-cli/pull/617) [`d048c0f`](https://github.com/nansen-ai/nansen-cli/commit/d048c0f3bb4e5ded6c42324ec7d3e32b58bfd4ee) Thanks [@teyrebaz33](https://github.com/teyrebaz33)! - Fix x402 auto-payment via WalletConnect signing a payment authorization from any connected EVM account instead of verifying the WalletConnect session is actually approved for the payment's chain.
18
+
19
+ `handleX402Payment` resolved its signer with its own `checkWalletConnection()` helper and took `wallet.accounts[0]?.address` with no chain filtering at all -- the same defect class fixed in `getWalletConnectAddress` for `nansen transfer`/`nansen trade execute` (see the WalletConnect chain-scoped signing fix), just left unguarded here because this path never reused that helper. Because EVM addresses are identical across chains, a WalletConnect session approved only for, say, Base could be silently used to authorize an x402 payment on BNB Smart Chain or X Layer -- the other two EVM networks Nansen's x402 payments support.
20
+
21
+ `handleX402Payment` now resolves its signer via `getWalletConnectAddress('evm', chainId)`, scoped to the exact chain of the selected payment requirement, and refuses to pay with a clear error when no WalletConnect session is approved for that chain. The now-unused, duplicate `checkWalletConnection` helper was removed.
22
+
23
+ ## 1.44.2
24
+
25
+ ### Patch Changes
26
+
27
+ - [#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.
28
+
29
+ - [#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
30
+ responses can no longer be shared across different API keys or API origins that
31
+ use the same cache directory. Cache keys now include the base URL, HTTP method,
32
+ and a hashed form of the effective credentials, and use SHA-256.
33
+
34
+ - [#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
35
+
36
+ - [#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
37
+
38
+ - [#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
39
+
40
+ - [#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.
41
+
42
+ - [#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.
43
+
44
+ `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.
45
+
46
+ `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.
47
+
3
48
  ## 1.44.1
4
49
 
5
50
  ### 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.3",
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):
@@ -66,11 +66,49 @@ export async function consumeSSEStream(response, callbacks = {}) {
66
66
  const toolCalls = [];
67
67
  let conversationId = null;
68
68
  let errorPayload = null;
69
+ let done = false;
69
70
 
70
71
  const reader = response.body;
71
72
  const decoder = new TextDecoder();
72
73
  let buffer = '';
73
74
 
75
+ const processFrame = (frame) => {
76
+ for (const line of frame.split('\n')) {
77
+ if (!line.startsWith('data: ')) continue;
78
+ const payload = line.slice(6);
79
+ if (payload === '[DONE]') { done = true; return; }
80
+
81
+ let event;
82
+ try {
83
+ event = JSON.parse(payload);
84
+ } catch {
85
+ continue;
86
+ }
87
+
88
+ switch (event.type) {
89
+ case 'delta':
90
+ if (event.text) {
91
+ chunks.push(event.text);
92
+ if (onDelta) onDelta(event.text);
93
+ }
94
+ break;
95
+ case 'tool_call':
96
+ if (event.name) {
97
+ toolCalls.push(event.name);
98
+ if (onToolCall) onToolCall(event.name);
99
+ }
100
+ break;
101
+ case 'finish':
102
+ conversationId = event.conversation_id ?? null;
103
+ break;
104
+ case 'error':
105
+ errorPayload = event;
106
+ break;
107
+ }
108
+ }
109
+ };
110
+
111
+ outer:
74
112
  for await (const raw of reader) {
75
113
  buffer += decoder.decode(raw, { stream: true });
76
114
 
@@ -79,47 +117,19 @@ export async function consumeSSEStream(response, callbacks = {}) {
79
117
 
80
118
  // SSE: split on double-newline boundaries
81
119
  let boundary;
82
- let done = false;
83
120
  while ((boundary = buffer.indexOf('\n\n')) !== -1) {
84
121
  const frame = buffer.slice(0, boundary);
85
122
  buffer = buffer.slice(boundary + 2);
86
-
87
- for (const line of frame.split('\n')) {
88
- if (!line.startsWith('data: ')) continue;
89
- const payload = line.slice(6);
90
- if (payload === '[DONE]') { done = true; break; }
91
-
92
- let event;
93
- try {
94
- event = JSON.parse(payload);
95
- } catch {
96
- continue;
97
- }
98
-
99
- switch (event.type) {
100
- case 'delta':
101
- if (event.text) {
102
- chunks.push(event.text);
103
- if (onDelta) onDelta(event.text);
104
- }
105
- break;
106
- case 'tool_call':
107
- if (event.name) {
108
- toolCalls.push(event.name);
109
- if (onToolCall) onToolCall(event.name);
110
- }
111
- break;
112
- case 'finish':
113
- conversationId = event.conversation_id ?? null;
114
- break;
115
- case 'error':
116
- errorPayload = event;
117
- break;
118
- }
119
- }
120
- if (done) break;
123
+ processFrame(frame);
124
+ if (done) break outer;
121
125
  }
122
- if (done) break;
126
+ }
127
+
128
+ // Flush a trailing unterminated frame (stream closed without \n\n after
129
+ // the last event, e.g. 'finish' or a final 'delta').
130
+ if (!done && buffer.trim() !== '') {
131
+ buffer += decoder.decode(); // flush any pending multi-byte UTF-8 tail
132
+ processFrame(buffer);
123
133
  }
124
134
 
125
135
  if (errorPayload) {
@@ -300,11 +310,27 @@ EXAMPLES:
300
310
  );
301
311
  }
302
312
 
313
+ // Abort can also fire while reading the SSE body, not just during
314
+ // fetch() — wrap that AbortError the same way for a consistent error.
315
+ const wrapAbortDuringStream = (err) => {
316
+ if (err.name === 'AbortError') {
317
+ throw new NansenError(
318
+ `Request timed out after ${timeoutMs / 1000}s`,
319
+ ErrorCode.TIMEOUT,
320
+ 504,
321
+ { detail: `${modeName} mode timeout (${timeoutMs / 1000}s)` },
322
+ );
323
+ }
324
+ throw err;
325
+ };
326
+
303
327
  // ── JSON mode: buffer everything, return structured data ──
304
328
  if (flags.json) {
305
329
  let result;
306
330
  try {
307
331
  result = await consumeSSEStream(response);
332
+ } catch (err) {
333
+ return wrapAbortDuringStream(err); // always throws; return makes intent explicit
308
334
  } finally {
309
335
  clearTimeout(timer);
310
336
  }
@@ -333,6 +359,8 @@ EXAMPLES:
333
359
  errorLog(`⚙ ${name}`);
334
360
  },
335
361
  });
362
+ } catch (err) {
363
+ return wrapAbortDuringStream(err); // always throws; return makes intent explicit
336
364
  } finally {
337
365
  clearTimeout(timer);
338
366
  }
@@ -124,6 +124,15 @@ function parseFiniteNumber(raw, name) {
124
124
  return n;
125
125
  }
126
126
 
127
+ function parseNonNegativeIntegerOption(raw, name) {
128
+ if (raw === undefined) return undefined;
129
+ const n = Number(raw);
130
+ if (!Number.isInteger(n) || n < 0) {
131
+ throw new NansenError(`--${name} must be a non-negative integer, got "${raw}"`, ErrorCode.INVALID_PARAMS);
132
+ }
133
+ return n;
134
+ }
135
+
127
136
  /**
128
137
  * Build a { min, max } range object from two option values.
129
138
  * Returns undefined if neither is provided.
@@ -601,6 +610,9 @@ USAGE:
601
610
  'list': async () => {
602
611
  if (flags.enabled && flags.disabled) throw new NansenError('Cannot specify both --enabled and --disabled', ErrorCode.INVALID_PARAMS);
603
612
 
613
+ const offset = parseNonNegativeIntegerOption(options.offset, 'offset');
614
+ const limit = parseNonNegativeIntegerOption(options.limit, 'limit');
615
+
604
616
  const results = await apiInstance.alertsList();
605
617
  let alerts = Array.isArray(results) ? results : results?.alerts ?? results?.data ?? [];
606
618
 
@@ -635,18 +647,10 @@ USAGE:
635
647
  // - Negative values (`--offset -1`) were accepted and fed straight
636
648
  // into `slice()`, which treats negative indices as "from the end" —
637
649
  // silently returning the wrong slice instead of rejecting the input.
638
- if (options.offset !== undefined) {
639
- const offset = Number(options.offset);
640
- if (!Number.isInteger(offset) || offset < 0) {
641
- throw new NansenError(`--offset must be a non-negative integer, got "${options.offset}"`, ErrorCode.INVALID_PARAMS);
642
- }
650
+ if (offset !== undefined) {
643
651
  alerts = alerts.slice(offset);
644
652
  }
645
- if (options.limit !== undefined) {
646
- const limit = Number(options.limit);
647
- if (!Number.isInteger(limit) || limit < 0) {
648
- throw new NansenError(`--limit must be a non-negative integer, got "${options.limit}"`, ErrorCode.INVALID_PARAMS);
649
- }
653
+ if (limit !== undefined) {
650
654
  alerts = alerts.slice(0, limit);
651
655
  }
652
656
 
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;
@@ -162,6 +174,14 @@ const NATIVE_TOKEN_ADDRESSES = {
162
174
  // legitimately needs more.
163
175
  export const EVM_BRIDGE_NATIVE_FEE_SLACK = 2_000_000_000_000_000n; // 0.002 ETH
164
176
 
177
+ // Tolerance for a native-ETH refund on an exact-in bridge: some routers receive
178
+ // msg.value = request.amount and return a small unused remainder, so the sim's net
179
+ // outflow can be slightly below the requested input on a correctly funded bridge.
180
+ // Same numeric cap as EVM_BRIDGE_NATIVE_FEE_SLACK (conservative, gas-independent);
181
+ // kept separate so sibling-fee and input-refund tolerances protect distinct
182
+ // assertions and remain distinguishable in reviews.
183
+ export const EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK = 2_000_000_000_000_000n; // 0.002 ETH
184
+
165
185
  // Native SOL has two on-chain spellings that denote the same asset: the
166
186
  // canonical wrapped-SOL mint (what the CLI resolves `SOL` to and persists as
167
187
  // the request intent) and the System Program address that aggregators and
@@ -954,7 +974,9 @@ export function isBridgeRequest(request) {
954
974
  * Four assertions, all derived from the persisted request intent + the quote:
955
975
  * 1. the input token leaves the wallet by no MORE than maxInputAmount. Native
956
976
  * input excludes gas: the sim deltas are log-based, so gas (not a transfer
957
- * log) is never counted.
977
+ * log) is never counted. For exact-in cross-chain bridges with native ETH
978
+ * input, the lower outflow floor is relaxed by EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK
979
+ * to tolerate routers that refund a small unused remainder of msg.value.
958
980
  * 2. the output token arrives by AT LEAST minOut — exactOut: >= the requested
959
981
  * output; exactIn: the quoted output reduced by the slippage in effect.
960
982
  * SKIPPED for a cross-chain bridge: the output settles on the destination
@@ -1021,6 +1043,7 @@ export function assertSwapOutcome(request, quote, sim, { slippage, expectedSpend
1021
1043
 
1022
1044
  // Bridges skip only assertion 2 (output arrival) below — see isBridgeRequest.
1023
1045
  const isBridge = isBridgeRequest(request);
1046
+ const inputIsNative = inputToken === EVM_NATIVE_SENTINEL;
1024
1047
 
1025
1048
  // --- Assertion 1: input outflow within the spend ceiling ---
1026
1049
  // This bounds the outflow by maxInputAmount (the slippage-buffered ceiling),
@@ -1061,8 +1084,9 @@ export function assertSwapOutcome(request, quote, sim, { slippage, expectedSpend
1061
1084
  // fee-only or 1-unit no-op would still verify a bridge that never funded its
1062
1085
  // input. For exactIn the outflow must be ~the requested input (assertion 1
1063
1086
  // already caps it above); for exactOut the input is variable up to the cap, so
1064
- // only a positive-outflow floor is meaningful. EVM native input delta is the
1065
- // transferred value with gas excluded, so the outflow is exact — no fee slack.
1087
+ // only a positive-outflow floor is meaningful. For native ETH input the floor
1088
+ // is relaxed by EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK to tolerate routers that
1089
+ // refund a small unused portion of msg.value; token input floors remain exact.
1066
1090
  if (isBridge) {
1067
1091
  if (swapMode === 'exactIn') {
1068
1092
  if (request.amount == null) throw fail('bridge exactIn request is missing the requested input amount.');
@@ -1073,8 +1097,19 @@ export function assertSwapOutcome(request, quote, sim, { slippage, expectedSpend
1073
1097
  throw fail(`requested input amount (${request.amount}) is not an integer.`);
1074
1098
  }
1075
1099
  if (requested <= 0n) throw fail(`bridge exactIn request has a non-positive input amount (${requested}).`);
1076
- if (outflow < requested) {
1077
- throw fail(`the bridge moved only ${outflow} of the input token (${inputToken}) out of the wallet, below the requested input (${requested}); a bridge must spend its full input on the source chain.`);
1100
+ const floorSlack = inputIsNative ? EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK : 0n;
1101
+ // Cap at requested / 2n: for bridges below 2 × EVM_BRIDGE_NATIVE_INPUT_REFUND_SLACK
1102
+ // (~0.004 ETH), the applied slack shrinks proportionally so the floor stays ≥ 50 %
1103
+ // of the requested amount rather than collapsing toward zero.
1104
+ const appliedSlack = floorSlack < requested / 2n ? floorSlack : requested / 2n;
1105
+ const minOutflow = requested - appliedSlack;
1106
+ if (outflow < minOutflow) {
1107
+ throw fail(
1108
+ `the bridge moved only ${outflow} of the input token (${inputToken}) out of the wallet, ` +
1109
+ `below the minimum required outflow (${minOutflow})` +
1110
+ `${inputIsNative ? ` (requested ${requested} minus native refund slack ${appliedSlack})` : ''}` +
1111
+ `; a bridge must spend its input on the source chain.`
1112
+ );
1078
1113
  }
1079
1114
  } else if (outflow <= 0n) {
1080
1115
  throw fail(`the bridge moved no input token (${inputToken}) out of the wallet; a bridge must spend its input on the source chain.`);
@@ -1152,6 +1187,17 @@ export function assertSwapOutcome(request, quote, sim, { slippage, expectedSpend
1152
1187
  // threshold the caller passes (gas is already excluded from the native delta).
1153
1188
  // ERC-20 siblings and every same-chain swap keep strict-zero. This mirrors the
1154
1189
  // native-only carve-out assertSolanaSwapOutcome already applies for SOL.
1190
+ //
1191
+ // Empirically (survey of the shipping quote path, Sept 2026) no reachable Base
1192
+ // token-input bridge route charges such a native fee: the live aggregator for
1193
+ // Base bridges returns tx.value 0 on token inputs, and the other aggregator
1194
+ // returns no Base route at all. So this carve-out is latent defense-in-depth
1195
+ // today, kept because backend routing can change (a new route, or a fee added).
1196
+ //
1197
+ // Wallet-owned intermediate-token bridge routes are intentionally unsupported
1198
+ // here unless a future quote format identifies the intermediate token and a
1199
+ // safe maximum outflow. Treat every ERC-20 sibling as strict-zero so a route
1200
+ // cannot drain unrelated wallet holdings under the label of "intermediate".
1155
1201
  const nativeDust = isBridge && siblingDustThreshold > 0n ? siblingDustThreshold : 0n;
1156
1202
  for (const [token, delta] of Object.entries(deltas)) {
1157
1203
  if (token === inputToken) continue; // its outflow is bounded by assertion 1
@@ -1484,8 +1530,9 @@ export function assertSolanaSwapOutcome(request, quote, sim, { slippage, sibling
1484
1530
  * within `amount` ± NATIVE_FEE_RENT_SLACK_LAMPORTS for a native-SOL input
1485
1531
  * (two-sided: upper bound caps the drain, lower bound rejects a partial reroute), and
1486
1532
  * 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).
1533
+ * NOTE: this bounds MAGNITUDE, not destination. The create command pairs it with
1534
+ * assertLimitOrderDepositDestination so a wallet-authorized SPL transfer of the
1535
+ * deposited asset must land in the vault's token account.
1489
1536
  * There is no output leg — the deposit funds the vault, nothing returns to the wallet.
1490
1537
  *
1491
1538
  * @param {{deltas: Record<string, bigint|string|number>}} sim - simulateSolanaAssetChanges result
@@ -1848,3 +1895,178 @@ export function assertSolanaInstructionsSafe(txBase64, { walletAddress } = {}) {
1848
1895
 
1849
1896
  return parsed;
1850
1897
  }
1898
+
1899
+ /**
1900
+ * Statically bind a limit-order deposit's wallet-sourced outflow to a token
1901
+ * account provably derived from the trusted vault owner. This closes the
1902
+ * destination gap balance-delta simulation cannot see: a tx can spend exactly
1903
+ * the requested amount from the wallet while sending it to an attacker's
1904
+ * account.
1905
+ *
1906
+ * The real on-chain shape (confirmed by a live create round-trip) is NOT the
1907
+ * vault's canonical ATA. Jupiter Trigger V2 funds each order through a fresh
1908
+ * per-order token account created in the same transaction via
1909
+ * System::CreateAccountWithSeed(base = vaultOwner, seed = <per-order>,
1910
+ * owner = Token program), then:
1911
+ * - SPL input → TransferChecked / Transfer of the input token into it, or
1912
+ * - native SOL → System::Transfer of lamports into it, then SyncNative.
1913
+ * So the destination is per-order and changes every craft; we can't pin a fixed
1914
+ * address. Instead we recompute create_with_seed(base, seed, owner) from the
1915
+ * transaction's own CreateAccountWithSeed instruction, require base == the
1916
+ * trusted vaultOwner, and bind every wallet-sourced transfer to that recomputed
1917
+ * account. This is stronger than an ATA equality check: the destination is
1918
+ * provably seeded off the vault the backend told us to deposit into.
1919
+ *
1920
+ * This check is intentionally limit-order-specific; generic swaps cannot
1921
+ * require a single destination.
1922
+ */
1923
+ export function assertLimitOrderDepositDestination(txBase64, { walletAddress, inputMint, vaultOwner } = {}) {
1924
+ const fail = (detail) => {
1925
+ const e = new Error(`Limit-order deposit destination mismatch (LIMIT_ORDER_DESTINATION_MISMATCH): ${detail} Refusing to sign.`);
1926
+ e.code = 'LIMIT_ORDER_DESTINATION_MISMATCH';
1927
+ return e;
1928
+ };
1929
+
1930
+ if (!walletAddress) throw fail('missing signing wallet address.');
1931
+ if (!inputMint) throw fail('missing deposit input mint.');
1932
+ if (!vaultOwner) throw fail('missing vault owner address.');
1933
+
1934
+ const parsed = parseTransactionMessage(txBase64);
1935
+ const accountAt = (ix, position) => resolveStaticAccount(parsed, ix.accountIndexes[position]);
1936
+ const walletAuthorizes = (ix, authorityPos) => {
1937
+ if (accountAt(ix, authorityPos) === null) return true;
1938
+ for (let i = authorityPos; i < ix.accountIndexes.length; i++) {
1939
+ if (accountAt(ix, i) === walletAddress) return true;
1940
+ }
1941
+ return false;
1942
+ };
1943
+
1944
+ const expectedMint = SOLANA_NATIVE_SOL_ALIASES.has(inputMint) ? WSOL_MINT : inputMint;
1945
+
1946
+ // Pass 1: collect the token accounts this transaction creates via
1947
+ // System::CreateAccountWithSeed seeded off the trusted vault owner, plus the
1948
+ // matching SPL InitializeAccount* owner/mint assignment. A seeded address
1949
+ // alone is not enough: the token-account authority must also be the trusted
1950
+ // vault owner, otherwise the deposit can be withdrawn by whoever controls the
1951
+ // initialized account.
1952
+ const vaultSeededAccounts = new Set();
1953
+ const initializedAccounts = new Map();
1954
+ for (const ix of parsed.instructions) {
1955
+ const programId = resolveStaticAccount(parsed, ix.programIdIndex);
1956
+ if (programId === SYSTEM_PROGRAM) {
1957
+ if (ix.data.length < 4 || ix.data.readUInt32LE(0) !== SYSTEM_INSTR_CREATE_ACCOUNT_WITH_SEED) continue;
1958
+ // Layout: u32 index | 32 base | u64 seedLen | seed | u64 lamports | u64 space | 32 owner
1959
+ let off = 4;
1960
+ const need = (n) => { if (off + n > ix.data.length) throw fail('malformed CreateAccountWithSeed instruction.'); };
1961
+ need(32); const base = ix.data.subarray(off, off + 32); off += 32;
1962
+ need(8); const seedLen = Number(ix.data.readBigUInt64LE(off)); off += 8;
1963
+ need(seedLen); const seed = ix.data.subarray(off, off + seedLen); off += seedLen;
1964
+ need(16); off += 16; // skip lamports (u64) + space (u64)
1965
+ need(32); const owner = ix.data.subarray(off, off + 32);
1966
+ if (base58Encode(base) !== vaultOwner) continue; // not seeded off our vault
1967
+ if (!SPL_TOKEN_PROGRAMS.has(base58Encode(owner))) continue; // not a token account
1968
+ // create_with_seed(base, seed, owner) = base58(sha256(base || seed || owner)).
1969
+ const derived = base58Encode(crypto.createHash('sha256').update(Buffer.concat([base, seed, owner])).digest());
1970
+ // The account the instruction creates (index 1) must equal the recomputed
1971
+ // address; a mismatch means a malformed/crafted instruction — fail closed.
1972
+ const created = accountAt(ix, 1);
1973
+ if (created !== null && created !== derived) {
1974
+ throw fail('CreateAccountWithSeed target does not match its base/seed/owner derivation.');
1975
+ }
1976
+ vaultSeededAccounts.add(derived);
1977
+ continue;
1978
+ }
1979
+
1980
+ if (!SPL_TOKEN_PROGRAMS.has(programId) || ix.data.length === 0) continue;
1981
+ const discriminator = ix.data[0];
1982
+ let account;
1983
+ let mint;
1984
+ let owner;
1985
+
1986
+ if (discriminator === SPL_INITIALIZE_ACCOUNT) {
1987
+ // InitializeAccount: accounts [account, mint, owner, rent].
1988
+ account = accountAt(ix, 0);
1989
+ mint = accountAt(ix, 1);
1990
+ owner = accountAt(ix, 2);
1991
+ } else if (discriminator === SPL_INITIALIZE_ACCOUNT2 || discriminator === SPL_INITIALIZE_ACCOUNT3) {
1992
+ // InitializeAccount2/3: accounts [account, mint, ...], data [disc, owner pubkey].
1993
+ if (ix.data.length < 33) throw fail('malformed InitializeAccount owner field.');
1994
+ account = accountAt(ix, 0);
1995
+ mint = accountAt(ix, 1);
1996
+ owner = base58Encode(ix.data.subarray(1, 33));
1997
+ } else {
1998
+ continue;
1999
+ }
2000
+
2001
+ if (account === null || mint === null || owner === null) {
2002
+ throw fail('token account initializer uses an address only resolvable via an address lookup table.');
2003
+ }
2004
+ initializedAccounts.set(account, { mint, owner });
2005
+ }
2006
+
2007
+ // Pass 2: every wallet-sourced transfer of value must land in a vault-seeded
2008
+ // account that is also initialized in this transaction with the vault as its
2009
+ // token-account authority. Covers both deposit shapes — SPL token transfers
2010
+ // and the native-SOL System::Transfer that funds a wrapped-SOL order account.
2011
+ const requireTrustedDestination = (destination, label) => {
2012
+ if (!vaultSeededAccounts.has(destination)) {
2013
+ 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.`);
2014
+ }
2015
+ const initialized = initializedAccounts.get(destination);
2016
+ if (!initialized) {
2017
+ throw fail(`wallet-authorized ${label} sends funds to ${destination} before verifying it is initialized with the trusted vault authority.`);
2018
+ }
2019
+ if (!tokensEqual(initialized.mint, expectedMint, 'solana')) {
2020
+ throw fail(`vault-seeded token account is initialized for mint ${initialized.mint} instead of deposit mint ${expectedMint}.`);
2021
+ }
2022
+ if (initialized.owner !== vaultOwner) {
2023
+ throw fail(`vault-seeded token account authority is ${initialized.owner} instead of expected vault owner ${vaultOwner}.`);
2024
+ }
2025
+ };
2026
+ let sawValidDepositTransfer = false;
2027
+
2028
+ for (const ix of parsed.instructions) {
2029
+ const programId = resolveStaticAccount(parsed, ix.programIdIndex);
2030
+ if (!programId) {
2031
+ throw fail('transaction invokes a program only resolvable via an address lookup table, so transfer destinations cannot be verified.');
2032
+ }
2033
+
2034
+ if (programId === SYSTEM_PROGRAM) {
2035
+ if (ix.data.length < 4) continue;
2036
+ if (ix.data.readUInt32LE(0) !== SYSTEM_INSTR_TRANSFER) continue;
2037
+ // System::Transfer accounts: [from (signer), to]. `from` must be a signer,
2038
+ // so it can never be ALT-resolved; null means a malformed tx — fail closed.
2039
+ const from = accountAt(ix, 0);
2040
+ if (from === null) throw fail('native transfer source is unresolvable (malformed transaction).');
2041
+ if (from !== walletAddress) continue; // not our funds
2042
+ requireTrustedDestination(accountAt(ix, 1), 'native transfer');
2043
+ sawValidDepositTransfer = true;
2044
+ continue;
2045
+ }
2046
+
2047
+ if (!SPL_TOKEN_PROGRAMS.has(programId) || ix.data.length === 0) continue;
2048
+ const discriminator = ix.data[0];
2049
+ if (discriminator === SPL_TRANSFER) {
2050
+ // Classic Transfer carries no mint in its account list, so we bind only the
2051
+ // destination. Not a weakness: the destination is a vault-seeded account and
2052
+ // the balance-delta gate still bounds which token and how much leave the
2053
+ // wallet. Use TransferChecked (below) for instruction-level mint binding.
2054
+ if (!walletAuthorizes(ix, 2)) continue;
2055
+ requireTrustedDestination(accountAt(ix, 1), 'token transfer');
2056
+ sawValidDepositTransfer = true;
2057
+ } else if (discriminator === SPL_TRANSFER_CHECKED) {
2058
+ if (!walletAuthorizes(ix, 3)) continue;
2059
+ const mint = accountAt(ix, 1);
2060
+ if (!tokensEqual(mint, expectedMint, 'solana')) {
2061
+ throw fail(`wallet-authorized TransferChecked uses mint ${mint || 'an address only resolvable via an address lookup table'} instead of deposit mint ${expectedMint}.`);
2062
+ }
2063
+ requireTrustedDestination(accountAt(ix, 2), 'TransferChecked');
2064
+ sawValidDepositTransfer = true;
2065
+ }
2066
+ }
2067
+
2068
+ if (!sawValidDepositTransfer) {
2069
+ throw fail('no wallet-authorized deposit transfer into a vault-seeded account was detected.');
2070
+ }
2071
+ return { verified: true };
2072
+ }
package/src/trading.js CHANGED
@@ -635,8 +635,22 @@ export function signSolanaTransaction(transactionBase64, privateKeyHex) {
635
635
  // blockhash fetch (no wasted RPC round trip on a request we're going to reject).
636
636
  const SIZE_CHECK_BLOCKHASH = '11111111111111111111111111111111';
637
637
 
638
+ function formatInstructionDataForError(value) {
639
+ try {
640
+ const s = JSON.stringify(value);
641
+ return s.length > 200 ? s.slice(0, 200) + '…' : s;
642
+ } catch {
643
+ return String(value);
644
+ }
645
+ }
646
+
638
647
  function decodeInstructionData(hex) {
639
648
  if (hex == null || hex === '') return Buffer.alloc(0); // some instructions legitimately carry no data
649
+ if (typeof hex !== 'string') {
650
+ throw new Error(
651
+ `Cannot compile Solana transaction: instruction data is not valid hex (${formatInstructionDataForError(hex)})`
652
+ );
653
+ }
640
654
  const body = hex.startsWith('0x') ? hex.slice(2) : hex;
641
655
  // Buffer.from(str, 'hex') silently drops a trailing odd nibble and stops at
642
656
  // the first non-hex character, so it would decode malformed data into a
@@ -2213,9 +2227,19 @@ CROSS-CHAIN NOTES (when using --to-chain):
2213
2227
  let walletProvider = 'local';
2214
2228
  let privyWalletIds = null;
2215
2229
  if (isWalletConnect) {
2216
- walletAddress = await getWalletConnectAddress(chainType);
2230
+ // Scoped to this chain's ID (see getWalletConnectAddress's chainId
2231
+ // param): a session approved only for a different EVM chain must
2232
+ // not be treated as valid here just because it's "some eip155:*"
2233
+ // account -- EVM addresses are identical across chains. chainId is
2234
+ // only ever passed for 'evm': Solana's chainConfig.chainId (501) is
2235
+ // not a CAIP-2 EIP-155 chain ID, and getWalletConnectAddress's own
2236
+ // Solana branch already does its own exact match unconditionally --
2237
+ // passing 501 through here would break it, not narrow it further.
2238
+ walletAddress = chainType === 'evm'
2239
+ ? await getWalletConnectAddress(chainType, chainConfig.chainId)
2240
+ : await getWalletConnectAddress(chainType);
2217
2241
  if (!walletAddress) {
2218
- throw new CommandError('No WalletConnect session active. Run: walletconnect connect', 'NO_WALLET');
2242
+ throw new CommandError(`No WalletConnect session active for chain "${chain}". Run: walletconnect connect`, 'NO_WALLET');
2219
2243
  }
2220
2244
  } else if (walletName) {
2221
2245
  const wallet = showWallet(walletName);
@@ -2564,10 +2588,20 @@ EXAMPLES:
2564
2588
 
2565
2589
  exported = exportWallet(effectiveWalletName, password);
2566
2590
  } else {
2567
- // Verify WalletConnect session is still active and address matches quote
2568
- const wcAddress = await getWalletConnectAddress(chainType);
2591
+ // Verify WalletConnect session is still active, approved for this
2592
+ // chain, and its address matches the quote. Chain-scoped (see
2593
+ // getWalletConnectAddress's chainId param) because an address
2594
+ // match alone can't tell a session on the right chain from one on
2595
+ // the wrong chain -- EVM addresses are identical across chains.
2596
+ // chainId is only ever passed for 'evm': Solana's chainConfig.chainId
2597
+ // (501) is not a CAIP-2 EIP-155 chain ID, and getWalletConnectAddress's
2598
+ // own Solana branch already does its own exact match unconditionally --
2599
+ // passing 501 through here would break it, not narrow it further.
2600
+ const wcAddress = chainType === 'evm'
2601
+ ? await getWalletConnectAddress(chainType, chainConfig.chainId)
2602
+ : await getWalletConnectAddress(chainType);
2569
2603
  if (!wcAddress) {
2570
- throw new CommandError('No WalletConnect session active. Run: walletconnect connect', 'NO_WALLET');
2604
+ throw new CommandError(`No WalletConnect session active for chain "${chain}". Run: walletconnect connect`, 'NO_WALLET');
2571
2605
  }
2572
2606
  // Check address matches the one used during quoting
2573
2607
  const quoteWallet = quoteData.response?.quotes?.[0]?.transaction?.from
@@ -3027,14 +3061,24 @@ EXAMPLES:
3027
3061
  requestId = currentQuote.metadata?.requestId;
3028
3062
 
3029
3063
  } 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
3064
+ // EVM via WalletConnect: wallet signs and may broadcast.
3065
+ // chainType is always 'evm' here (unguarded, unlike the two
3066
+ // other call sites) -- the Solana WalletConnect path is fully
3067
+ // handled above in the `if (chainConfig.type === 'solana')`
3068
+ // branch, so this `else if` is only ever reached for EVM.
3069
+ // Scoped to this chain's ID, not just "any EVM account" -- a
3070
+ // session approved only for a different chain must not sign
3071
+ // here. EVM addresses are identical across chains, so the
3072
+ // address-based checks below (assertQuoteMatchesRequest) can't
3073
+ // catch a session connected to the wrong chain on their own.
3074
+ const wcAddress = await getWalletConnectAddress(chainType, chainConfig.chainId);
3075
+ // A session dropped mid-execute, or one that's connected but not
3076
+ // approved for this chain, returns null here. Without this
3033
3077
  // guard a null address would fall through to assertQuoteMatchesRequest,
3034
3078
  // whose `request.walletAddress && walletAddress` condition would
3035
3079
  // silently skip the signer-binding check. Fail closed instead.
3036
3080
  if (!wcAddress) {
3037
- throw new CommandError('WalletConnect session lost during execute. Reconnect with `walletconnect connect` and retry.', 'NO_WALLET');
3081
+ throw new CommandError('No WalletConnect session for this chain. Reconnect with `walletconnect connect` and retry.', 'NO_WALLET');
3038
3082
  }
3039
3083
  const isNative = isNativeToken(currentQuote.inputMint);
3040
3084
 
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
  }
@@ -8,23 +8,9 @@
8
8
  import crypto from 'crypto';
9
9
  import { NansenError, ErrorCode } from './api.js';
10
10
  import { wcExec } from './walletconnect-exec.js';
11
+ import { getWalletConnectAddress } from './walletconnect-trading.js';
11
12
  import { evaluatePaymentRequirement, resolvePaymentAmount, resolvePayTo } from './x402-policy.js';
12
13
 
13
- /**
14
- * Check if a WalletConnect wallet session is active.
15
- * Returns { wallet, accounts, expires } or null.
16
- */
17
- export async function checkWalletConnection() {
18
- try {
19
- const output = await wcExec('walletconnect', ['whoami', '--json'], 3000);
20
- const data = JSON.parse(output);
21
- if (data.connected === false) return null;
22
- return data;
23
- } catch {
24
- return null;
25
- }
26
- }
27
-
28
14
  /**
29
15
  * Select a compatible payment requirement from the accepts array.
30
16
  * Requires scheme=exact and EIP-3009 TransferWithAuthorization support (extra.name + extra.version).
@@ -160,28 +146,7 @@ function formatPaymentAmount(requirement) {
160
146
  * @throws {NansenError} On failure
161
147
  */
162
148
  export async function handleX402Payment(paymentRequirements) {
163
- // 1. Check wallet connection
164
- const wallet = await checkWalletConnection();
165
- if (!wallet) {
166
- throw new NansenError(
167
- 'x402 payment required but no wallet connected. ' +
168
- 'To pay automatically: create a local wallet with `nansen wallet create` (then set NANSEN_WALLET_PASSWORD), ' +
169
- 'or connect an external wallet via the `walletconnect` CLI (`walletconnect connect`).',
170
- ErrorCode.PAYMENT_REQUIRED,
171
- 402
172
- );
173
- }
174
-
175
- const fromAddress = wallet.accounts[0]?.address;
176
- if (!fromAddress) {
177
- throw new NansenError(
178
- 'x402 payment required but wallet has no accounts.',
179
- ErrorCode.PAYMENT_REQUIRED,
180
- 402
181
- );
182
- }
183
-
184
- // 2. Select compatible payment requirement
149
+ // 1. Select compatible payment requirement
185
150
  const accepts = paymentRequirements.accepts || paymentRequirements;
186
151
  const requirement = selectPaymentRequirement(Array.isArray(accepts) ? accepts : [accepts]);
187
152
  if (!requirement) {
@@ -193,12 +158,37 @@ export async function handleX402Payment(paymentRequirements) {
193
158
  );
194
159
  }
195
160
 
196
- // 3. Evaluate payment policy before touching any signing material
161
+ // 2. Evaluate payment policy before touching any signing material
197
162
  const decision = evaluatePaymentRequirement(requirement);
198
163
  if (!decision.ok) {
199
164
  throw new Error(decision.reason);
200
165
  }
201
166
 
167
+ // 3. Resolve the WalletConnect signer scoped to this exact chain. EVM
168
+ // addresses are identical across chains, so "some account exists in the
169
+ // session" can't prove the session was actually approved for THIS chain --
170
+ // only the CAIP-2 chain tag can (mirrors getWalletConnectAddress's chainId
171
+ // param, used the same way before signing/broadcasting in trading.js and
172
+ // transfer.js). Without this, a session connected only to, say, Base would
173
+ // be silently accepted to authorize a payment on BNB Chain or X Layer --
174
+ // the same defect class fixed in #615, just unguarded here because this
175
+ // path never reused getWalletConnectAddress and instead took accounts[0]
176
+ // with no chain filter at all.
177
+ const chainId = parseChainId(requirement.network);
178
+ if (chainId === null) {
179
+ throw new Error(`Refusing to auto-pay: unsupported or missing EVM network ${requirement.network}.`);
180
+ }
181
+ const fromAddress = await getWalletConnectAddress('evm', chainId);
182
+ if (!fromAddress) {
183
+ throw new NansenError(
184
+ `x402 payment required but no WalletConnect session is active for chain ${requirement.network}. ` +
185
+ 'To pay automatically: create a local wallet with `nansen wallet create` (then set NANSEN_WALLET_PASSWORD), ' +
186
+ 'or connect an external wallet approved for this chain via the `walletconnect` CLI (`walletconnect connect`).',
187
+ ErrorCode.PAYMENT_REQUIRED,
188
+ 402
189
+ );
190
+ }
191
+
202
192
  // 4. Build EIP-712 typed data
203
193
  const typedData = buildEIP712TypedData({ fromAddress, requirement });
204
194
  const typedDataJson = JSON.stringify(typedData);
package/src/x402-svm.js CHANGED
@@ -312,18 +312,59 @@ export function createSvmPaymentPayload(
312
312
  * Fetch recent blockhash from Solana RPC.
313
313
  */
314
314
  export async function fetchRecentBlockhash(rpcUrl = 'https://api.mainnet-beta.solana.com') {
315
- const response = await fetch(rpcUrl, {
316
- method: 'POST',
317
- headers: { 'Content-Type': 'application/json' },
318
- body: JSON.stringify({
319
- jsonrpc: '2.0',
320
- id: 1,
321
- method: 'getLatestBlockhash',
322
- params: [{ commitment: 'finalized' }],
323
- }),
324
- });
325
- const data = await response.json();
326
- return data.result.value.blockhash;
315
+ let response;
316
+ try {
317
+ response = await fetch(rpcUrl, {
318
+ method: 'POST',
319
+ headers: { 'Content-Type': 'application/json' },
320
+ body: JSON.stringify({
321
+ jsonrpc: '2.0',
322
+ id: 1,
323
+ method: 'getLatestBlockhash',
324
+ params: [{ commitment: 'finalized' }],
325
+ }),
326
+ });
327
+ } catch (err) {
328
+ throw new Error(
329
+ `Solana RPC unavailable while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${String(err.message ?? err)}`,
330
+ { cause: err }
331
+ );
332
+ }
333
+
334
+ if (!response.ok) {
335
+ const text = await response.text().catch(() => '');
336
+ throw new Error(
337
+ `Solana RPC returned HTTP ${response.status} while fetching a recent blockhash. Retry or configure a different RPC endpoint. ${text.slice(0, 100)}`
338
+ );
339
+ }
340
+
341
+ let data;
342
+ try {
343
+ data = await response.json();
344
+ } catch {
345
+ throw new Error(
346
+ 'Solana RPC returned an invalid response while fetching a recent blockhash. Retry or configure a different RPC endpoint.'
347
+ );
348
+ }
349
+
350
+ if (data?.error) {
351
+ const detail =
352
+ data.error.message != null ? String(data.error.message)
353
+ : data.error.code != null ? String(data.error.code)
354
+ : 'unknown RPC error';
355
+ throw new Error(
356
+ `Solana RPC failed while fetching a recent blockhash: ${detail}. Retry or configure a different RPC endpoint.`
357
+ );
358
+ }
359
+
360
+ const blockhash = data?.result?.value?.blockhash;
361
+ if (typeof blockhash !== 'string' || blockhash.length === 0) {
362
+ throw new Error(
363
+ 'Solana RPC returned no recent blockhash. Retry or configure a different RPC endpoint.'
364
+ );
365
+ }
366
+
367
+ return blockhash;
327
368
  }
328
369
 
329
370
  /**