nansen-cli 2.0.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,58 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#735](https://github.com/nansen-ai/nansen-cli/pull/735) [`223acdd`](https://github.com/nansen-ai/nansen-cli/commit/223acddb391778f6fde4acd258dd90283147ecfe) Thanks [@kome12](https://github.com/kome12)! - `trade execute`: non-gasless swaps now broadcast through the execution route that tracks the on-chain outcome server-side, instead of the deprecated `/execute` route. Set `NANSEN_TRADING_EXECUTION_ROUTE=legacy` to go back to the old route; any value other than `standard` or `legacy` is rejected rather than silently falling back.
8
+
9
+ Three behaviours change for swaps that previously succeeded, so they are worth knowing before you upgrade:
10
+
11
+ - **A failed swap no longer falls through to the next candidate quote.** The command stops and reports the failure. Once a transaction hash exists the backend keeps the quote claimed, so the next candidate could only have been rejected anyway — but a command that used to retry silently now surfaces an error and expects you to request a fresh quote.
12
+ - **A duplicate submission of a quote that is already in flight is refused**, rather than broadcast a second time.
13
+ - **A quote carrying no backend quote id is refused outright** (`MISSING_QUOTE_ID`), because that id is the key the route's duplicate-submission lock is held on, and broadcasting without it would claim a protection that is not there. Every live `/quote` response carries one, so this means a stale or hand-edited quote file: request a fresh quote. This includes a quote that carries only an aggregator's own quote id: the deprecated route accepted that and sent it, but it does not key the lock, so the standard route refuses it rather than submit unprotected.
14
+
15
+ On this route the command opts into the server-side pre-broadcast simulation, which the endpoint leaves off by default, so a transaction that would revert still does not reach the network. It also surfaces the aggregator's own revert reason alongside the backend's failure code, fails closed if the endpoint reports success without a transaction hash or returns a body that is not this route's shape, and reports a node-rejected broadcast on Solana as an unverified outcome rather than a successful swap (the EVM path resolves that case by polling for a receipt; Solana has no such poll). The `Broadcaster:` line is no longer printed, because this route does not report one.
16
+
17
+ Two paths deliberately do not move:
18
+
19
+ - **Gasless swaps stay on the deprecated route.** The standard route has no gasless envelope, so a signed Relay authorization sent there would lose its framing and submit as a plain swap.
20
+ - **A WalletConnect wallet broadcasts the swap itself** and never reaches this endpoint. The command now says so, and applies the same stop-at-a-failed-swap rule there — both when the transaction reverts and when the wallet returns no hash at all — rather than prompting for the next candidate.
21
+
22
+ Approval and allowance-revoke broadcasts also continue to use the deprecated route; it is swaps that moved.
23
+
24
+ ### Patch Changes
25
+
26
+ - [#736](https://github.com/nansen-ai/nansen-cli/pull/736) [`3f59ed8`](https://github.com/nansen-ai/nansen-cli/commit/3f59ed8b744b1a435868149277281b4612d479dd) Thanks [@kome12](https://github.com/kome12)! - `trade execute`: treat every `/execute` response this client cannot interpret as an ambiguous broadcast instead of a pre-broadcast rejection. HTTP status alone — including 400, 408, 409 and 429 — no longer claims the backend rejected the transaction before broadcast, a 2xx body that is unreadable or carries no documented `Success`/`Failed` status now fails closed, and a success response must carry a usable transaction identifier on Solana and on gasless EVM. Previously these shapes let the candidate loop sign and broadcast the next quote on top of a transaction that may already be live.
27
+
28
+ A success or failure response carrying a malformed identifier — an object, a non-string, a non-base58 Solana signature, or a hash that is not 32 bytes of hex — is also refused, instead of reaching the explorer URL, the stored broadcast marker and receipt polling as a value that identifies nothing. EVM paths no longer read Solana's `signature` field at all.
29
+
30
+ - [#740](https://github.com/nansen-ai/nansen-cli/pull/740) [`5e23501`](https://github.com/nansen-ai/nansen-cli/commit/5e2350149a6d6a6232f50e857d24b1a424dc0ac4) Thanks [@kome12](https://github.com/kome12)! - `trade execute`: keep a quote claimed whenever a transaction may have left this process, and stop rather than falling through to the next candidate. An application-level failure that still carries a transaction identifier is now terminal and records that hash, approval and allowance-revoke broadcasts retain the claim so a quote cannot be reused while the wallet's allowance state is unknown, and a post-broadcast allowance verification failure ends the command instead of swapping against an allowance of unknown value. A candidate that throws after the swap was handed off is treated as ambiguous and marks the quote spent. Conversely, a backend failure response carrying no transaction identifier now releases the local claim, so a quote that was never broadcast is not left unusable.
31
+
32
+ - [#737](https://github.com/nansen-ai/nansen-cli/pull/737) [`4361d95`](https://github.com/nansen-ai/nansen-cli/commit/4361d95ad47c9a9473f158a2096185b16c43bf3b) Thanks [@kome12](https://github.com/kome12)! - `trade execute`: a confirmed on-chain revert now ends the command instead of signing and broadcasting the next candidate quote. The revert is reported with its hash and explorer link as before, and the user is told to review that transaction and request a fresh quote. `waitForReceipt` tags the failure `TX_REVERTED` rather than relying on the error message text.
33
+
34
+ - [#739](https://github.com/nansen-ai/nansen-cli/pull/739) [`fe3e63f`](https://github.com/nansen-ai/nansen-cli/commit/fe3e63fd17c69c846b6e8e1227948ff048900c49) Thanks [@kome12](https://github.com/kome12)! - `trade execute`: a WalletConnect send that fails after the wallet was asked to broadcast now ends the command instead of trying the next candidate quote. The WalletConnect helpers collapse a user rejection, a 120-second approval timeout and a spawn failure into the same error, so none of them proves the wallet did not broadcast; every send is now tagged ambiguous at that boundary and treated as terminal. This covers the swap, approval, allowance-revoke and Solana paths, and a wallet reply carrying neither a transaction hash nor signed bytes.
35
+
36
+ ## 2.1.0
37
+
38
+ ### Minor Changes
39
+
40
+ - [#728](https://github.com/nansen-ai/nansen-cli/pull/728) [`c5ef96f`](https://github.com/nansen-ai/nansen-cli/commit/c5ef96f63181711304f832f26c5156c8c2d5841c) Thanks [@gulshngill](https://github.com/gulshngill)! - Drop support for Node.js 20 (EOL since April 2026). The minimum supported version is now Node.js 22: `engines.node` is `>=22.0.0`, CI tests on Node 22 and 24, and `nansen doctor` reports Node 20 as below the required version.
41
+
42
+ - [#584](https://github.com/nansen-ai/nansen-cli/pull/584) [`435ae1a`](https://github.com/nansen-ai/nansen-cli/commit/435ae1a717f7f3771ccce4dd3026851bbccd8166) Thanks [@ygd58](https://github.com/ygd58)! - `nansen wallet list` now prints the standard JSON envelope on stdout, `{"success":true,"data":{"wallets":[...],"defaultWallet":...}}`, so `nansen wallet list | jq .` works and `--pretty`, `--table`, `--format csv` and `--fields` apply to it like any other command. It previously printed a readable summary with no data envelope, which agents could not parse. The output is the same in a terminal and in a pipe; use `--pretty` for readable JSON or `--table` for a table. With no wallets it returns an empty `wallets` list instead of a hint.
43
+
44
+ - [#727](https://github.com/nansen-ai/nansen-cli/pull/727) [`9404c13`](https://github.com/nansen-ai/nansen-cli/commit/9404c13ec32a063cbc54aba697e6297374993591) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - `nansen wallet show <name>` now prints the standard JSON envelope on stdout, `{"success":true,"data":{"name":...,"provider":...,"evm":...,"solana":...,"createdAt":...,"isDefault":...}}`, so `nansen wallet show main | jq .` works and `--pretty`, `--table`, `--format csv` and `--fields` apply to it. Privy wallets also include `privyWalletIds`. The redacted default of `nansen wallet export <name>` does the same, returning `{"name":...,"redacted":true,"evm":{"address":...},"solana":{"address":...}}` with no key fields. Both previously printed a readable summary that agents could not parse. `wallet export --reveal` and `--file` are unchanged.
45
+
46
+ ### Patch Changes
47
+
48
+ - [#724](https://github.com/nansen-ai/nansen-cli/pull/724) [`1f2fc6e`](https://github.com/nansen-ai/nansen-cli/commit/1f2fc6e3b76ae9faa66202ba295c1d668ae33a73) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Use the resolved gas limit when signing local EVM swaps, including quotes with both gas and gasLimit fields.
49
+
50
+ - [#731](https://github.com/nansen-ai/nansen-cli/pull/731) [`f4cf188`](https://github.com/nansen-ai/nansen-cli/commit/f4cf188191b0973d7058381febccf36149cfaba5) Thanks [@hulk-linus](https://github.com/apps/hulk-linus)! - Reject symlinks, hard links, and replaced files when reading saved authentication and trading quotes. Validate authentication lock descriptors before use. Claim bridge quotes before signing and block reuse if a post-broadcast execution marker cannot be saved. Authentication reads now require user-owned paths without group or other write permissions on POSIX; repair permissions before retrying an unsafe saved-key read.
51
+
52
+ - [#729](https://github.com/nansen-ai/nansen-cli/pull/729) [`7b54c0e`](https://github.com/nansen-ai/nansen-cli/commit/7b54c0e5448f672dadb071a467f7812ad6775581) Thanks [@gulshngill](https://github.com/gulshngill)! - Solana-source bridge routes that are too large to fit in a transaction without address lookup tables (for example a token swap ahead of the bridge deposit) now compile and sign. The CLI fetches the route's lookup tables, checks that each one is active and on-chain, and uses them to compress accounts. Routes that already fit are compiled as before.
53
+
54
+ - [#733](https://github.com/nansen-ai/nansen-cli/pull/733) [`353629a`](https://github.com/nansen-ai/nansen-cli/commit/353629a5ddf8dcace3fe66cba653e33e41330067) Thanks [@kome12](https://github.com/kome12)! - `trade execute`: accept a capitalised chain name. `trade quote --chain Base` stores the chain exactly as you typed it, but the RPC registry is keyed lowercase, so the quote could be created and then never executed ("No RPC URL configured for chain: Base"). The chain is now normalised once when the quote is loaded, which also fixes quotes already on disk.
55
+
3
56
  ## 2.0.1
4
57
 
5
58
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nansen-cli",
3
- "version": "2.0.1",
3
+ "version": "2.2.0",
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",
@@ -64,7 +64,7 @@
64
64
  },
65
65
  "homepage": "https://github.com/nansen-ai/nansen-cli#readme",
66
66
  "engines": {
67
- "node": ">=20.0.0"
67
+ "node": ">=22.0.0"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@changesets/changelog-github": "^0.5.1",
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { readLocalFile } from './local-file.js';
5
6
 
6
7
  export const DEFAULT_API_ORIGIN = 'https://api.nansen.ai';
7
8
  const DEV_CONFIG = fileURLToPath(new URL('../config.json', import.meta.url));
@@ -32,17 +33,28 @@ export function validAuthPointer(auth) {
32
33
  }
33
34
  export function readAuthConfig(env = process.env, devConfigPath = DEV_CONFIG) {
34
35
  const userPath = path.join(authDirectory(env), 'config.json');
35
- const configPath = fs.existsSync(userPath) ? userPath : fs.existsSync(devConfigPath) ? devConfigPath : null;
36
+ let configFileExists;
37
+ try { configFileExists = Boolean(fs.lstatSync(userPath, { throwIfNoEntry: false })); }
38
+ catch { return { config: {}, configPath: userPath, configError: 'unreadable', configFileExists: true, devConfigPath }; }
39
+ const configPath = configFileExists ? userPath : fs.existsSync(devConfigPath) ? devConfigPath : null;
36
40
  let config = {};
37
41
  let configError = null;
38
42
  if (configPath) {
39
43
  try {
40
- config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
44
+ const options = { root: path.dirname(configPath), privateFile: configPath === userPath };
45
+ let contents;
46
+ try { contents = readLocalFile(configPath, options); }
47
+ catch (error) {
48
+ // Login and renewal replace config atomically. Revalidate once from scratch.
49
+ if (!error.localFileRace) throw error;
50
+ contents = readLocalFile(configPath, options);
51
+ }
52
+ config = JSON.parse(contents);
41
53
  if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error();
42
54
  } catch (err) { config = {}; configError = err instanceof SyntaxError ? 'parse' : 'unreadable'; }
43
55
  }
44
56
  if (config.auth && !validAuthPointer(config.auth)) configError = 'format';
45
- return { config, configPath, configError, configFileExists: fs.existsSync(userPath), devConfigPath };
57
+ return { config, configPath, configError, configFileExists, devConfigPath };
46
58
  }
47
59
  export function resolveCredential({ env = process.env, explicitKey, snapshot = readAuthConfig(env) } = {}) {
48
60
  if (explicitKey !== undefined) return explicitKey === null ? { kind: 'anonymous', source: null } : { kind: 'api-key', source: 'explicit', apiKey: explicitKey };
package/src/auth-state.js CHANGED
@@ -5,6 +5,7 @@ import { setTimeout as delay } from 'node:timers/promises';
5
5
  import { AuthError, authDirectory, validAuthPointer } from './auth-credentials.js';
6
6
  import { createAuthStore } from './auth-store.js';
7
7
  import { refreshSession, retireSession, validateSession } from './auth-device.js';
8
+ import { openLocalFile, readLocalFile } from './local-file.js';
8
9
 
9
10
  const queues = new Map();
10
11
  const MAX_RETRYABLE_RENEWALS = 5;
@@ -16,8 +17,8 @@ const journalExists = file => {
16
17
  };
17
18
  const stateError = () => new AuthError('AUTH_STATE_INVALID', 'Saved authentication cannot be read safely. Repair config.json permissions or restore the file; no other credential was selected.');
18
19
  function safePath(file, directory = false) {
19
- if (!fs.existsSync(file)) return;
20
- const stat = fs.lstatSync(file);
20
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
21
+ if (!stat) return;
21
22
  if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
22
23
  (process.platform !== 'win32' && ((stat.mode & 0o022) || stat.uid !== process.getuid()))) throw stateError();
23
24
  }
@@ -25,8 +26,7 @@ const uuid = value => typeof value === 'string' && /^[a-f0-9-]{36}$/.test(value)
25
26
  function readJournal(file, id) {
26
27
  try {
27
28
  safePath(file);
28
- if (fs.statSync(file).size > 4096) throw journalError();
29
- const value = JSON.parse(fs.readFileSync(file, 'utf8'));
29
+ const value = JSON.parse(readLocalFile(file, { root: path.dirname(path.dirname(file)), privateFile: true, maxBytes: 4096 }));
30
30
  if (value?.id !== id) throw journalError();
31
31
  if (value.kind === 'rotation') {
32
32
  if (value.version !== 2 || value.id !== value.selectionEpoch || !uuid(value.selectionEpoch) ||
@@ -96,7 +96,7 @@ export function createAuthState({ directory = authDirectory(), store = createAut
96
96
  safePath(configFile);
97
97
  if (!fs.existsSync(configFile)) return {};
98
98
  try {
99
- const value = JSON.parse(fs.readFileSync(configFile, 'utf8'));
99
+ const value = JSON.parse(readLocalFile(configFile, { root: directory, privateFile: true }));
100
100
  if (!value || typeof value !== 'object' || Array.isArray(value) || (value.auth && !validAuthPointer(value.auth))) throw new Error();
101
101
  return value;
102
102
  } catch { throw stateError(); }
@@ -129,7 +129,9 @@ export function createAuthState({ directory = authDirectory(), store = createAut
129
129
  const native = await locks();
130
130
  signal?.throwIfAborted();
131
131
  safePath(file);
132
- const fd = fs.openSync(file, 'a+', 0o600);
132
+ let fd;
133
+ try { fd = openLocalFile(file, { root: directory, flags: fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_APPEND, privateFile: true }); }
134
+ catch { throw stateError(); }
133
135
 
134
136
  try {
135
137
  while (!native.tryLock(fd)) {
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { Worker } from 'node:worker_threads';
6
6
  import locks from 'fs-native-extensions';
7
+ import { openLocalFile } from './local-file.js';
7
8
 
8
9
  const stop = () => process.kill(process.pid, 'SIGKILL');
9
10
  const timer = setTimeout(stop, 10000);
@@ -13,8 +14,8 @@ process.stdout.on('error', stop);
13
14
  let input = '', phase = 'guard';
14
15
  let fd;
15
16
  function safe(file, directory = false) {
16
- if (!fs.existsSync(file)) return;
17
- const stat = fs.lstatSync(file);
17
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
18
+ if (!stat) return;
18
19
  if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) ||
19
20
  (process.platform !== 'win32' && ((stat.mode & 0o022) || stat.uid !== process.getuid()))) throw new Error();
20
21
  }
@@ -27,7 +28,7 @@ function receive(line) {
27
28
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
28
29
  const file = path.join(directory, 'auth-store.lock');
29
30
  safe(file);
30
- fd = fs.openSync(file, 'a+', 0o600);
31
+ fd = openLocalFile(file, { root: directory, flags: fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_APPEND, privateFile: true });
31
32
  // Independent acquisition: no cross-platform inherited-lock assumptions.
32
33
  // This stable inode is never unlinked, including by recovery.
33
34
  if (!locks.tryLock(fd)) throw new Error();
package/src/bridge.js CHANGED
@@ -9,11 +9,13 @@
9
9
  import * as crypto from 'node:crypto';
10
10
  import * as fs from 'node:fs';
11
11
  import * as path from 'node:path';
12
+ import { readLocalFile, writeLocalFile } from './local-file.js';
12
13
 
13
14
  import { CommandError, validateAddress } from './api.js';
14
15
  import { signSecp256k1 } from './crypto.js';
15
16
  import {
16
17
  assertEvmFeeWithinCap,
18
+ claimQuoteForExecution,
17
19
  convertToBaseUnits,
18
20
  evmRpcCall,
19
21
  getEvmNonce,
@@ -242,11 +244,19 @@ function saveBridgeQuote(response, originChain, destinationChain, walletProvider
242
244
  }
243
245
 
244
246
  export function loadBridgeQuote(quoteId) {
247
+ const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
248
+ if (claimedPath && fs.lstatSync(claimedPath, { throwIfNoEntry: false })) {
249
+ throw new Error(`Bridge quote "${quoteId}" is claimed by another execution. Funds may be in flight. Check "nansen bridge status" before requesting a new quote.`);
250
+ }
245
251
  const filePath = safeQuotesPath(`${quoteId}.json`);
246
252
  if (!filePath || !fs.existsSync(filePath)) {
247
253
  throw new Error(`Bridge quote "${quoteId}" not found. Quotes expire after 1 hour.`);
248
254
  }
249
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
255
+ return readBridgeQuoteFile(filePath, quoteId);
256
+ }
257
+
258
+ function readBridgeQuoteFile(filePath, quoteId) {
259
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
250
260
  if (Date.now() - data.timestamp > QUOTE_TTL_MS) {
251
261
  fs.unlinkSync(filePath);
252
262
  throw new Error('Bridge quote has expired. Please request a new quote.');
@@ -289,10 +299,15 @@ export function loadBridgeQuote(quoteId) {
289
299
  // later step throwing must not leave the quote reusable. The step counters make
290
300
  // a partial failure legible to the operator (see loadBridgeQuote).
291
301
  export function markBridgeQuoteExecuted(quoteId, progress = {}) {
292
- const filePath = safeQuotesPath(`${quoteId}.json`);
293
- if (!filePath || !fs.existsSync(filePath)) return;
302
+ const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
303
+ const filePath = claimedPath && fs.lstatSync(claimedPath, { throwIfNoEntry: false })
304
+ ? claimedPath : safeQuotesPath(`${quoteId}.json`);
294
305
  try {
295
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
306
+ if (!filePath || !fs.existsSync(filePath)) {
307
+ if (progress.required) throw new Error('Missing execution state');
308
+ return;
309
+ }
310
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
296
311
  data.executedAt = data.executedAt || Date.now();
297
312
  if (progress.broadcast) {
298
313
  data.broadcasts = [...(data.broadcasts || []), { ...progress.broadcast, at: Date.now() }];
@@ -301,11 +316,9 @@ export function markBridgeQuoteExecuted(quoteId, progress = {}) {
301
316
  data.broadcastSteps = Math.max(data.broadcastSteps || 0, progress.broadcastSteps);
302
317
  }
303
318
  if (progress.totalSteps !== undefined) data.totalSteps = progress.totalSteps;
304
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { mode: 0o600 });
319
+ writeLocalFile(filePath, JSON.stringify(data, null, 2), { root: path.dirname(getQuotesDir()) });
305
320
  } catch {
306
- // Best-effort: if the marker can't be written, the next execute attempt
307
- // will still proceed, but that's preferable to crashing after a successful
308
- // broadcast.
321
+ throw new CommandError('Could not safely record bridge execution. Funds may already be in flight. The quote remains claimed; check "nansen bridge status" before requesting a new quote.', 'QUOTE_STATE_UNSAFE');
309
322
  }
310
323
  }
311
324
 
@@ -2043,90 +2056,105 @@ from a quote are the same ones that got stuck. Check the stuck nonce with
2043
2056
  preflightResult ??= await preflightPlan();
2044
2057
  const { evmIntent, hlIntent } = preflightResult;
2045
2058
 
2046
- // Consume the quote at each INDIVIDUAL broadcast, before any receipt wait.
2047
- // A tx can be accepted by the network and then have waitForReceipt time
2048
- // out; if the quote were still unspent, a retry would re-sign and re-send
2049
- // it with a fresh nonce. markBridgeQuoteExecuted pins executedAt on the
2050
- // first call, so the quote is spent the instant anything is in flight.
2051
- const onBroadcast = (stepId, txHash) =>
2052
- markBridgeQuoteExecuted(quoteId, {
2053
- broadcast: { step: stepId, txHash: txHash || null },
2054
- totalSteps: steps.length,
2055
- });
2056
-
2057
- // Step-level counter, recorded only once a step fully completes.
2058
- const markBroadcast = (index) =>
2059
- markBridgeQuoteExecuted(quoteId, {
2060
- broadcastSteps: index + 1,
2061
- totalSteps: steps.length,
2062
- });
2063
-
2064
- if (execution_type === 'evm_transaction') {
2065
- // Overrides move real money differently from what was quoted, so say so
2066
- // rather than letting them apply silently.
2067
- if (overridesSummary) {
2068
- log(` Overrides: ${overridesSummary}`);
2059
+ const claim = claimQuoteForExecution(quoteId, readBridgeQuoteFile);
2060
+ let handedOff = false;
2061
+ let keepClaimed = false;
2062
+ try {
2063
+ if (JSON.stringify(claim.quote) !== JSON.stringify(quoteData)) {
2064
+ throw new CommandError('Bridge quote changed while awaiting execution. Request a fresh quote.', 'QUOTE_STATE_UNSAFE');
2069
2065
  }
2070
- for (const [index, step] of steps.entries()) {
2071
- await processEvmStep(step, {
2072
- chain: quoteData.originChain,
2073
- privateKeyHex: creds.privateKey,
2074
- signerAddress: signer.address,
2075
- log,
2076
- onBroadcast,
2077
- feeOverrides,
2078
- nonceSequence,
2079
- intent: evmIntent,
2066
+ // Consume the quote at each INDIVIDUAL broadcast, before any receipt wait.
2067
+ // A tx can be accepted by the network and then have waitForReceipt time
2068
+ // out; if the quote were still unspent, a retry would re-sign and re-send
2069
+ // it with a fresh nonce. markBridgeQuoteExecuted pins executedAt on the
2070
+ // first call, so the quote is spent the instant anything is in flight.
2071
+ const onBroadcast = (stepId, txHash) => {
2072
+ handedOff = true;
2073
+ markBridgeQuoteExecuted(quoteId, {
2074
+ required: true,
2075
+ broadcast: { step: stepId, txHash: txHash || null },
2076
+ totalSteps: steps.length,
2080
2077
  });
2081
- markBroadcast(index);
2082
- }
2083
- } else if (execution_type === 'hyperliquid_signature') {
2084
- if (creds.provider === 'privy') {
2085
- const { PrivyClient } = await import('./privy.js');
2086
- const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
2087
- for (const [index, step] of steps.entries()) {
2088
- await processSignatureStepPrivy(step, {
2089
- privyClient,
2090
- // `signer` above — the same resolution that was screened and
2091
- // matched against the quote, rather than resolving a second time.
2092
- walletId: signer.privyWalletIds?.evm,
2093
- log,
2094
- apiInstance,
2095
- onBroadcast,
2096
- intent: hlIntent,
2097
- });
2098
- markBroadcast(index);
2078
+ };
2079
+
2080
+ // Step-level counter, recorded only once a step fully completes.
2081
+ const markBroadcast = (index) =>
2082
+ markBridgeQuoteExecuted(quoteId, {
2083
+ required: true,
2084
+ broadcastSteps: index + 1,
2085
+ totalSteps: steps.length,
2086
+ });
2087
+
2088
+ if (execution_type === 'evm_transaction') {
2089
+ // Overrides move real money differently from what was quoted, so say so
2090
+ // rather than letting them apply silently.
2091
+ if (overridesSummary) {
2092
+ log(` Overrides: ${overridesSummary}`);
2099
2093
  }
2100
- } else {
2101
2094
  for (const [index, step] of steps.entries()) {
2102
- await processSignatureStepLocal(step, {
2095
+ await processEvmStep(step, {
2096
+ chain: quoteData.originChain,
2103
2097
  privateKeyHex: creds.privateKey,
2098
+ signerAddress: signer.address,
2104
2099
  log,
2105
- apiInstance,
2106
2100
  onBroadcast,
2107
- intent: hlIntent,
2101
+ feeOverrides,
2102
+ nonceSequence,
2103
+ intent: evmIntent,
2108
2104
  });
2109
2105
  markBroadcast(index);
2110
2106
  }
2107
+ } else if (execution_type === 'hyperliquid_signature') {
2108
+ if (creds.provider === 'privy') {
2109
+ const { PrivyClient } = await import('./privy.js');
2110
+ const privyClient = new PrivyClient(process.env.PRIVY_APP_ID, process.env.PRIVY_APP_SECRET);
2111
+ for (const [index, step] of steps.entries()) {
2112
+ await processSignatureStepPrivy(step, {
2113
+ privyClient,
2114
+ // `signer` above — the same resolution that was screened and
2115
+ // matched against the quote, rather than resolving a second time.
2116
+ walletId: signer.privyWalletIds?.evm,
2117
+ log,
2118
+ apiInstance,
2119
+ onBroadcast,
2120
+ intent: hlIntent,
2121
+ });
2122
+ markBroadcast(index);
2123
+ }
2124
+ } else {
2125
+ for (const [index, step] of steps.entries()) {
2126
+ await processSignatureStepLocal(step, {
2127
+ privateKeyHex: creds.privateKey,
2128
+ log,
2129
+ apiInstance,
2130
+ onBroadcast,
2131
+ intent: hlIntent,
2132
+ });
2133
+ markBroadcast(index);
2134
+ }
2135
+ }
2136
+ } else {
2137
+ throw new Error(`Unknown execution type: ${execution_type}`);
2111
2138
  }
2112
- } else {
2113
- throw new Error(`Unknown execution type: ${execution_type}`);
2114
- }
2115
2139
 
2116
- // Every step is out; the marker above already consumed the quote.
2117
- markBridgeQuoteExecuted(quoteId, { broadcastSteps: steps.length, totalSteps: steps.length });
2140
+ // Every step is out; the marker above already consumed the quote.
2141
+ markBridgeQuoteExecuted(quoteId, { required: true, broadcastSteps: steps.length, totalSteps: steps.length });
2118
2142
 
2119
- log(`\n Bridge submitted. Polling for completion...`);
2120
- const status = await pollBridgeCompletion(apiInstance, { requestId: request_id, log });
2143
+ log(`\n Bridge submitted. Polling for completion...`);
2144
+ const status = await pollBridgeCompletion(apiInstance, { requestId: request_id, log });
2121
2145
 
2122
- if (status.status === 'success') {
2123
- log(`\n Bridge completed!`);
2124
- if (status.destination_tx_hashes?.length) {
2125
- log(` Destination tx: ${status.destination_tx_hashes[0]}`);
2146
+ if (status.status === 'success') {
2147
+ log(`\n Bridge completed!`);
2148
+ if (status.destination_tx_hashes?.length) {
2149
+ log(` Destination tx: ${status.destination_tx_hashes[0]}`);
2150
+ }
2126
2151
  }
2127
- }
2128
- log('');
2129
- return undefined;
2152
+ log('');
2153
+ return undefined;
2154
+ } catch (error) {
2155
+ keepClaimed = handedOff && error.code === 'QUOTE_STATE_UNSAFE';
2156
+ throw error;
2157
+ } finally { claim.release({ handedOff, keepClaimed }); }
2130
2158
  },
2131
2159
 
2132
2160
  'status': async (args, apiInstance, flags, options) => {
@@ -21,6 +21,7 @@
21
21
 
22
22
  import fs from 'fs';
23
23
  import path from 'path';
24
+ import { openLocalFile } from './local-file.js';
24
25
 
25
26
  import { getCacheDir, getConfigDir, DEFAULT_CACHE_TTL, NansenError, ErrorCode } from './api.js';
26
27
  import { getCostMapFile, COST_MAP_TTL_MS } from './cost-cache.js';
@@ -86,15 +87,10 @@ function readTimestamp(file, field) {
86
87
  let fd;
87
88
  let raw;
88
89
  try {
89
- // O_NOFOLLOW prevents a final-component symlink replacement after lstat.
90
- // Windows does not define it. There, only the earlier lstat check applies;
91
- // opening with O_RDONLY does not prevent this race.
92
- const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0);
93
- fd = fs.openSync(file, flags);
94
- if (!fs.fstatSync(fd).isFile()) return { raced: true };
90
+ fd = openLocalFile(file, { root: getConfigDir() });
95
91
  raw = fs.readFileSync(fd, 'utf8');
96
92
  } catch (error) {
97
- if (error?.code === 'ENOENT' || error?.code === 'ELOOP') return { raced: true };
93
+ if (error?.code === 'ENOENT' || error?.code === 'ELOOP' || error?.code === 'LOCAL_FILE_UNSAFE') return { raced: true };
98
94
  throw fsError('read', file, error);
99
95
  } finally {
100
96
  if (fd !== undefined) fs.closeSync(fd);
package/src/doctor.js CHANGED
@@ -251,7 +251,7 @@ export function runDoctorChecks(deps = {}) {
251
251
  const auth = resolveAuthConfig(env, devConfigPath);
252
252
 
253
253
  // --- environment ---
254
- const requiredMajor = parseEngineMajor(engines?.node) ?? 20;
254
+ const requiredMajor = parseEngineMajor(engines?.node) ?? 22;
255
255
  const currentMajor = parseInt(nodeVersion.replace(/^v/, ''), 10);
256
256
  checks.push(currentMajor >= requiredMajor
257
257
  ? check('node-version', 'ok', `Node ${nodeVersion} (>= ${requiredMajor} required)`)
@@ -0,0 +1,75 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const unsafe = (file, reason) => Object.assign(new Error(`Refusing an unsafe local file at ${file}: ${reason}. Repair that path before retrying.`), { code: 'LOCAL_FILE_UNSAFE' });
5
+ const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
6
+ function checkStat(stat, directory, privateFile, file) {
7
+ if (!stat || (directory ? !stat.isDirectory() : !stat.isFile())) throw unsafe(file, directory ? 'expected a directory without symlinks' : 'expected a regular file without symlinks');
8
+ if (!directory && stat.nlink !== 1) throw unsafe(file, 'file has unexpected hard links');
9
+ if (privateFile && process.platform !== 'win32') {
10
+ if (stat.mode & 0o022) throw unsafe(file, 'authentication path is writable by group or other users');
11
+ if (stat.uid !== process.getuid()) throw unsafe(file, 'authentication path belongs to another user');
12
+ }
13
+ }
14
+
15
+ // Non-private stores may use an intentionally symlinked storage root.
16
+ // Authentication and all components below either root must be link-free.
17
+ // Descriptor checks reject replacements before any bytes are read or written.
18
+ export function openLocalFile(file, { root, flags = fs.constants.O_RDONLY, mode = 0o600, privateFile = false, maxBytes = Infinity } = {}) {
19
+ const base = path.resolve(root);
20
+ const target = path.resolve(file);
21
+ const relative = path.relative(base, target);
22
+ if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw unsafe(target, 'path is outside its storage root');
23
+ const directories = [base];
24
+ for (const part of relative.split(path.sep).slice(0, -1)) directories.push(path.join(directories.at(-1), part));
25
+ const directoryStat = (dir, i) => i === 0 && !privateFile ? fs.statSync(dir) : fs.lstatSync(dir);
26
+ const parents = directories.map((dir, i) => {
27
+ const stat = directoryStat(dir, i);
28
+ checkStat(stat, true, privateFile, dir);
29
+ return stat;
30
+ });
31
+ const before = fs.lstatSync(target, { throwIfNoEntry: false });
32
+ if (before) checkStat(before, false, privateFile, target);
33
+ let fd;
34
+ try {
35
+ fd = fs.openSync(target, flags | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), mode);
36
+ const opened = fs.fstatSync(fd);
37
+ checkStat(opened, false, privateFile, target);
38
+ if (opened.size > maxBytes) throw unsafe(target, `file exceeds its ${maxBytes}-byte limit`);
39
+ if (before && !sameFile(before, opened)) throw Object.assign(unsafe(target, 'file was replaced while opening'), { localFileRace: true });
40
+ const after = fs.lstatSync(target);
41
+ checkStat(after, false, privateFile, target);
42
+ if (!sameFile(opened, after)) throw Object.assign(unsafe(target, 'file was replaced while opening'), { localFileRace: true });
43
+ directories.forEach((dir, i) => {
44
+ const stat = directoryStat(dir, i);
45
+ checkStat(stat, true, privateFile, dir);
46
+ if (!sameFile(parents[i], stat)) throw unsafe(dir, 'directory was replaced while opening');
47
+ });
48
+ return fd;
49
+ } catch (error) {
50
+ if (fd !== undefined) fs.closeSync(fd);
51
+ if (error.code === 'ELOOP') throw unsafe(target, 'file became a symbolic link while opening');
52
+ throw error;
53
+ }
54
+ }
55
+
56
+ export function readLocalFile(file, options) {
57
+ const fd = openLocalFile(file, options);
58
+ try { return fs.readFileSync(fd, 'utf8'); }
59
+ finally { fs.closeSync(fd); }
60
+ }
61
+
62
+ export function writeLocalFile(file, contents, options) {
63
+ const fd = openLocalFile(file, { ...options, flags: fs.constants.O_WRONLY });
64
+ try {
65
+ const bytes = Buffer.from(contents, 'utf8');
66
+ fs.ftruncateSync(fd, 0);
67
+ let offset = 0;
68
+ while (offset < bytes.length) {
69
+ const written = fs.writeSync(fd, bytes, offset, bytes.length - offset, offset);
70
+ if (!written) throw new Error('Could not write the local file.');
71
+ offset += written;
72
+ }
73
+ fs.fsyncSync(fd);
74
+ } finally { fs.closeSync(fd); }
75
+ }
package/src/schema.json CHANGED
@@ -2119,7 +2119,7 @@
2119
2119
  ]
2120
2120
  },
2121
2121
  "execute": {
2122
- "description": "Sign and broadcast a quoted trade. Explicitly blank --wallet values are rejected.",
2122
+ "description": "Sign and broadcast a quoted trade. Explicitly blank --wallet values are rejected. Non-gasless swaps broadcast through the execution route that tracks the on-chain outcome server-side; NANSEN_TRADING_EXECUTION_ROUTE=legacy is an escape hatch back to the deprecated broadcast route, and any value other than standard or legacy is rejected rather than silently falling back. Gasless swaps and WalletConnect wallets never use the standard route.",
2123
2123
  "apiEndpoints": [
2124
2124
  "/api/v1/sanctions/screen"
2125
2125
  ],
@@ -2364,6 +2364,15 @@
2364
2364
  },
2365
2365
  "list": {
2366
2366
  "description": "List all wallets",
2367
+ "returns": [
2368
+ "wallets[].name",
2369
+ "wallets[].provider",
2370
+ "wallets[].evm",
2371
+ "wallets[].solana",
2372
+ "wallets[].createdAt",
2373
+ "wallets[].isDefault",
2374
+ "defaultWallet"
2375
+ ],
2367
2376
  "examples": [
2368
2377
  "nansen wallet list",
2369
2378
  "nansen wallet list --pretty"
@@ -2376,6 +2385,16 @@
2376
2385
  "description": "Wallet name"
2377
2386
  }
2378
2387
  },
2388
+ "returns": [
2389
+ "name",
2390
+ "provider",
2391
+ "evm",
2392
+ "solana",
2393
+ "createdAt",
2394
+ "isDefault",
2395
+ "privyWalletIds.evm",
2396
+ "privyWalletIds.solana"
2397
+ ],
2379
2398
  "examples": [
2380
2399
  "nansen wallet show <name>"
2381
2400
  ]
@@ -2409,7 +2428,7 @@
2409
2428
  ]
2410
2429
  },
2411
2430
  "export": {
2412
- "description": "Export private keys (redacted by default; pass --reveal or --file <path> for the actual keys)",
2431
+ "description": "Export private keys (redacted by default: returns the addresses as JSON with no keys; pass --reveal or --file <path> for the actual keys)",
2413
2432
  "options": {
2414
2433
  "reveal": {
2415
2434
  "type": "boolean",
@@ -2420,6 +2439,12 @@
2420
2439
  "description": "Write private keys to this path instead of stdout (created with 0600 permissions, refuses to overwrite)"
2421
2440
  }
2422
2441
  },
2442
+ "returns": [
2443
+ "name",
2444
+ "redacted",
2445
+ "evm.address",
2446
+ "solana.address"
2447
+ ],
2423
2448
  "examples": [
2424
2449
  "nansen wallet export <name>",
2425
2450
  "nansen wallet export <name> --file backup.json"