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/src/trading.js CHANGED
@@ -9,9 +9,10 @@ import { rejectBlankOption } from './query-options.js';
9
9
  import crypto from 'crypto';
10
10
  import fs from 'fs';
11
11
  import path from 'path';
12
+ import { readLocalFile, writeLocalFile } from './local-file.js';
12
13
  import { base58Encode, exportWallet, getWalletConfig, showWallet, listWallets } from './wallet.js';
13
14
  import { base58Decode, encodeCompactU16 } from './transfer.js';
14
- import { buildMessageV0, fetchRecentBlockhash } from './x402-svm.js';
15
+ import { buildMessageV0, fetchAddressLookupTables, fetchRecentBlockhash } from './x402-svm.js';
15
16
  import { keccak256, signSecp256k1, rlpEncode } from './crypto.js';
16
17
  import { getWalletConnectAddress, sendTransactionViaWalletConnect, sendSolanaTransactionViaWalletConnect, sendApprovalViaWalletConnect } from './walletconnect-trading.js';
17
18
  import { retrievePassword } from './keychain.js';
@@ -29,6 +30,28 @@ import { screenOrThrow } from './perp.js';
29
30
 
30
31
  const TRADING_API_URL = process.env.NANSEN_TRADING_API_URL || 'https://trading-api.nansen.ai';
31
32
  const CLIENT_USER_AGENT = `nansen-cli/${packageVersion}`;
33
+ // Swap broadcast route. 'standard' posts the signed swap to the receipt-watching
34
+ // execution endpoint (server-side outcome tracking); 'legacy' keeps the original
35
+ // broadcast-only endpoint, kept as an escape hatch. Defaults to 'standard' now
36
+ // that the route is verified end to end on live funds (both routes, all three
37
+ // swap groups, including both bridge directions).
38
+ // Read at call time (not frozen at import) so the route can be selected per run.
39
+ // Validated rather than defaulted: a typo ('Legacy', a stray space) silently
40
+ // running the standard route is the worst failure mode now that standard is the
41
+ // default — someone reaching for the escape hatch would believe they had left it
42
+ // and would not have.
43
+ function executionRoute() {
44
+ const route = process.env.NANSEN_TRADING_EXECUTION_ROUTE;
45
+ if (!route) return 'standard';
46
+ if (route !== 'legacy' && route !== 'standard') {
47
+ throw new CommandError(
48
+ `Unknown NANSEN_TRADING_EXECUTION_ROUTE "${route}". Use "standard" or "legacy" (unset means standard).`,
49
+ 'INVALID_EXECUTION_ROUTE',
50
+ );
51
+ }
52
+ return route;
53
+ }
54
+
32
55
  // Solana's max transaction wire size (IPv6 MTU minus headers).
33
56
  const SOLANA_MAX_TX_SIZE = 1232;
34
57
 
@@ -37,6 +60,13 @@ const CHAIN_MAP = {
37
60
  base: { index: '8453', type: 'evm', chainId: 8453, name: 'Base', explorer: 'https://basescan.org/tx/', lifiChainId: '8453' },
38
61
  };
39
62
 
63
+ // CHAIN_MAP is keyed lowercase, but a quote stores the chain exactly as the
64
+ // user typed it (`--chain Base`) — only resolveChain() lowercases on the way
65
+ // through, and direct lookups bypass it.
66
+ function chainConfigFor(name) {
67
+ return name ? CHAIN_MAP[String(name).toLowerCase()] : undefined;
68
+ }
69
+
40
70
  // Extend when adding new EVM chains (e.g. arbitrum WETH, polygon WMATIC)
41
71
  const WRAPPED_NATIVE_TOKENS = {
42
72
  base: { address: '0x4200000000000000000000000000000000000006', symbol: 'WETH', nativeSymbol: 'ETH' },
@@ -135,11 +165,8 @@ export function getQuotesDir() {
135
165
 
136
166
  // Resolve a filename inside the quotes dir, rejecting path traversal.
137
167
  export function safeQuotesPath(filename) {
138
- const base = path.resolve(getQuotesDir());
139
- const target = path.resolve(base, filename);
140
- const relative = path.relative(base, target);
141
- if (relative.startsWith('..') || path.isAbsolute(relative)) return null;
142
- return target;
168
+ if (typeof filename !== 'string' || !filename || filename === '.' || filename === '..' || /[/\\:]/.test(filename) || filename.includes('\0')) return null;
169
+ return path.join(path.resolve(getQuotesDir()), filename);
143
170
  }
144
171
 
145
172
  // ============= Trading API Client =============
@@ -194,12 +221,200 @@ export async function getQuote(params) {
194
221
  * @param {boolean} [params.simulate] - Run pre-broadcast simulation
195
222
  * @returns {Promise<object>} Execution result
196
223
  */
197
- export async function executeTransaction(params, { retries = 2, retryDelayMs = 1500 } = {}) {
224
+
225
+ /**
226
+ * Translate the CLI's legacy broadcast params into the standard-route request body.
227
+ *
228
+ * The standard route keys the chain on VM type ('evm' | 'solana') plus an explicit
229
+ * chain id, and reads the client source and wallet from the body rather than
230
+ * inferring them. Only the whitelisted fields are forwarded.
231
+ *
232
+ * @param {object} params - legacy executeTransaction params
233
+ * @returns {object} standard-route request body
234
+ */
235
+ function toStandardBody(params) {
236
+ const cfg = chainConfigFor(params.chain);
237
+ const body = {
238
+ chain: cfg.type, // VM type, not the chain name
239
+ signedTransaction: params.signedTransaction,
240
+ source: 'cli', // no longer inferred from the client header
241
+ // Opt into the server-side pre-broadcast simulation. This route's `simulate`
242
+ // defaults to FALSE, which means Solana broadcasts with `skipPreflight: true`
243
+ // and the EVM path only re-simulates AFTER an approval is submitted — whereas
244
+ // the deprecated /execute route simulated unconditionally. Sending `true` is
245
+ // what keeps "a transaction that would revert does not reach the network"
246
+ // true across the move; omitting it would drop that guarantee silently, which
247
+ // is the one failure mode a route switch must not have.
248
+ //
249
+ // Hardcoded rather than forwarded from `params.simulate`: on the legacy route
250
+ // that field was inert (the trading service simulated every broadcast whatever
251
+ // it said), so --no-simulate has only ever governed the CLI's own eth_call
252
+ // revert check. Forwarding it here would quietly widen that flag into "also
253
+ // disable the backend preflight" — a new, sharper meaning for a flag users
254
+ // already pass for a different reason.
255
+ //
256
+ // Honoured as sent: the backend ignores `simulate` on the EVM path when
257
+ // `signedApprovalTransaction` is set, and the CLI never sets it (approvals
258
+ // broadcast as their own executeTransaction call). Upstream EVM preflight
259
+ // coverage is Base-only, which costs us nothing — Base is the only EVM chain
260
+ // CHAIN_MAP trades.
261
+ simulate: true,
262
+ };
263
+ if (cfg.type === 'evm') body.chainId = String(cfg.chainId);
264
+ if (params.quoteId) body.quoteId = params.quoteId;
265
+ if (params.requestId) body.requestId = params.requestId;
266
+ if (params.aggregator) body.aggregator = params.aggregator;
267
+ if (params.walletAddress) body.walletAddress = params.walletAddress;
268
+ if (params.isCrossChain) {
269
+ body.isCrossChain = true;
270
+ const toCfg = chainConfigFor(params.toChain);
271
+ if (toCfg) body.toChainId = toCfg.index;
272
+ }
273
+ return body;
274
+ }
275
+
276
+ /**
277
+ * Pick the most specific failure reason a standard-route response carries.
278
+ *
279
+ * For a landed revert the route returns a typed `code` plus a STATIC `message`,
280
+ * and puts the aggregator's actual on-chain failure reason in `revertReason` —
281
+ * so taking `message` alone drops the only informative field. Keep the typed
282
+ * code alongside the detail so the reason stays attributable.
283
+ *
284
+ * @param {object} body - standard-route response body
285
+ * @returns {string|undefined} the reason, or undefined on a success body
286
+ */
287
+ function standardFailureReason(body) {
288
+ const detail = body.revertReason || body.error || body.message;
289
+ if (body.code && detail) return `${body.code}: ${detail}`;
290
+ return detail || body.code;
291
+ }
292
+
293
+ /**
294
+ * Normalise a standard-route response into the legacy result shape the call sites
295
+ * and output block already understand. Keeps `signature` populated for Solana so
296
+ * the existing success output and its matchers keep working, and synthesises
297
+ * `chainType` since the standard route does not echo it. Fields the legacy route
298
+ * added but this route does not (`broadcaster`, `swapEvents`) are left undefined
299
+ * and handled by the output block rather than invented here.
300
+ *
301
+ * @param {object} body - standard-route response body
302
+ * @param {string} chainType - 'evm' | 'solana'
303
+ * @returns {object} legacy-shaped result
304
+ */
305
+ function fromStandardResponse(body, chainType) {
306
+ return {
307
+ ...body,
308
+ status: body.success ? 'Success' : 'Failed',
309
+ txHash: body.txHash,
310
+ signature: chainType === 'solana' ? body.txHash : undefined,
311
+ chainType,
312
+ // Collapsed into `error` so the shared output block keeps reading one field
313
+ // on both routes; undefined on a success body.
314
+ error: standardFailureReason(body),
315
+ };
316
+ }
317
+
318
+ /**
319
+ * `ambiguousBroadcast` is the default for every failure after the signed payload
320
+ * is handed to fetch. An HTTP status describes the response, not whether the
321
+ * backend forwarded the transaction before producing it: 408/429 and even an
322
+ * intermediary-generated 400/409 can arrive after processing began. Until the
323
+ * execute API has a documented, authenticated field that explicitly guarantees
324
+ * pre-broadcast rejection, no response from this endpoint may authorize signing
325
+ * the next candidate.
326
+ */
327
+ function ambiguousBroadcast(message, { status, details } = {}) {
328
+ // Deliberately never carries broadcastRuledOut. BROADCAST_FAILED is classified
329
+ // fatal by isFatalBroadcastError, so the caller aborts the whole execute.
330
+ return Object.assign(new Error(message), { code: 'BROADCAST_FAILED', status, details });
331
+ }
332
+
333
+ /**
334
+ * A JSON body the branches below can read fields off. JSON.parse also succeeds
335
+ * on `null`, an array and a bare string or number, none of which carry the
336
+ * diagnostic fields used below.
337
+ */
338
+ function isReadableBody(value) {
339
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
340
+ }
341
+
342
+ /**
343
+ * A transaction identifier is not decoration: it reaches the explorer URL, the
344
+ * quote's persisted broadcast marker and receipt polling. A value of the wrong
345
+ * shape is worse than none at all — it produces a link to nothing and a marker
346
+ * that cannot be checked — so a malformed one is an unverifiable outcome, not a
347
+ * cosmetic defect.
348
+ *
349
+ * Only presence was checked before, and presence is a weak test: `signature:
350
+ * {}`, `signature: "not-a-signature"` and a non-string `txHash` are all truthy.
351
+ * Validating at this one boundary covers every execution path, because this is
352
+ * where they all read the response — a per-call-site check would have to be
353
+ * repeated for each new broadcaster. Presence remains the caller's business,
354
+ * since only it knows whether a local hash exists to fall back on.
355
+ */
356
+ function assertUsableTxId(body, chainType) {
357
+ const check = (field, label, isValid) => {
358
+ const value = body[field];
359
+ // Absent is not malformed. Whether an identifier is REQUIRED depends on the
360
+ // execution mode (gasless EVM and Solana have no locally derived hash), so
361
+ // that call stays at the call site.
362
+ if (value === undefined || value === null || value === '') return;
363
+ if (typeof value !== 'string' || !isValid(value)) {
364
+ throw ambiguousBroadcast(
365
+ `The execute endpoint reported ${body.status} with an unusable ${label} (${JSON.stringify(value)}), so the transaction cannot be identified or verified. It may still be live — check the wallet on the explorer before retrying.`,
366
+ { details: body },
367
+ );
368
+ }
369
+ };
370
+
371
+ if (chainType === 'solana') {
372
+ // A Solana signature is 64 bytes, base58-encoded. `txHash` is read as an
373
+ // alias for it on this chain, so it has to satisfy the same rule.
374
+ const isSignature = (v) => {
375
+ try { return base58Decode(v).length === 64; } catch { return false; }
376
+ };
377
+ check('signature', 'transaction signature', isSignature);
378
+ check('txHash', 'transaction signature', isSignature);
379
+ } else if (chainType === 'evm') {
380
+ // 32 bytes of hex. The 0x is optional because a broadcaster may report the
381
+ // hash bare — assertTxHashMatch normalizes both sides before comparing.
382
+ check('txHash', 'transaction hash', (v) => /^(0x)?[0-9a-fA-F]{64}$/.test(v));
383
+ }
384
+ }
385
+
386
+ // A readable application-level failure can still describe a transaction that
387
+ // was broadcast. The identifier is evidence of handoff, so callers must retain
388
+ // the quote claim and stop rather than treating the response as "nothing sent".
389
+ function hashBearingFailure(result, label, chainType) {
390
+ const txId = chainType === 'evm'
391
+ ? result?.txHash
392
+ : (result?.signature || result?.txHash);
393
+ if (!txId) return null;
394
+ const error = ambiguousBroadcast(
395
+ `${label} reported ${result.status || 'failure'} with transaction identifier ${txId}. The transaction may have been broadcast, so no further quote will be tried. Check it on-chain before requesting a fresh quote.`,
396
+ { details: result },
397
+ );
398
+ error.txHash = txId;
399
+ return error;
400
+ }
401
+
402
+ // `route` defaults to 'legacy' independently of executionRoute(), which now
403
+ // resolves to 'standard' when unset. That is deliberate and must stay: the six
404
+ // approval and allowance-revoke call sites omit `route` on purpose, and the
405
+ // standard route is swap-only — toStandardBody() builds a swap-shaped body
406
+ // (quoteId, aggregator, isCrossChain), so routing an approval there would submit
407
+ // it stripped of its own framing. Only the swap call site passes `route`.
408
+ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1500, attemptId, route = 'legacy' } = {}) {
409
+ const isStandard = route === 'standard';
410
+ const requestPath = isStandard ? '/execution/standard' : '/execute';
411
+ const requestBody = isStandard ? toStandardBody(params) : params;
198
412
  const headers = {
199
413
  'Content-Type': 'application/json',
200
414
  'Accept': 'application/json',
201
415
  'User-Agent': CLIENT_USER_AGENT,
202
416
  'X-Client-Type': 'nansen-cli',
417
+ ...(attemptId ? { 'x-trade-attempt-id': attemptId } : {}),
203
418
  ...telemetryHeaders(),
204
419
  };
205
420
  let lastError;
@@ -210,10 +425,10 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
210
425
 
211
426
  let res;
212
427
  try {
213
- res = await fetch(`${TRADING_API_URL}/execute`, {
428
+ res = await fetch(`${TRADING_API_URL}${requestPath}`, {
214
429
  method: 'POST',
215
430
  headers,
216
- body: JSON.stringify(params),
431
+ body: JSON.stringify(requestBody),
217
432
  });
218
433
  } catch (netErr) {
219
434
  // The POST left this process but no response came back (a reset/timeout).
@@ -223,10 +438,7 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
223
438
  // the SAME signed bytes (a byte-identical replay a node dedupes), so a
224
439
  // retry here can't itself double-broadcast; only exhausting them fails
225
440
  // closed at the caller (isFatalBroadcastError → mark the quote spent).
226
- lastError = Object.assign(
227
- new Error(`Execute POST to /execute failed: ${netErr.message}`),
228
- { code: 'BROADCAST_FAILED' }
229
- );
441
+ lastError = ambiguousBroadcast(`Execute POST to ${requestPath} failed: ${netErr.message}`);
230
442
  if (attempt < retries) continue;
231
443
  throw lastError;
232
444
  }
@@ -240,10 +452,7 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
240
452
  // fail closed as BROADCAST_FAILED rather than surface a codeless error the
241
453
  // candidate loop would treat as nonfatal. A retry re-sends byte-identical
242
454
  // bytes a node dedupes.
243
- lastError = Object.assign(
244
- new Error(`Execute response body read failed (status ${res.status}): ${bodyErr.message}`),
245
- { code: 'BROADCAST_FAILED', status: res.status }
246
- );
455
+ lastError = ambiguousBroadcast(`Execute response body read failed (status ${res.status}): ${bodyErr.message}`, { status: res.status });
247
456
  if (res.status >= 500 && attempt < retries) continue;
248
457
  throw lastError;
249
458
  }
@@ -272,7 +481,7 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
272
481
  // JSON error (e.g. { code: "UPSTREAM_TIMEOUT" }) already explains itself
273
482
  // via `details`; tacking "you may be out of SOL" onto a gateway timeout
274
483
  // would misdirect the user.
275
- const chainType = params.chain && CHAIN_MAP[params.chain]?.type;
484
+ const chainType = chainConfigFor(params.chain)?.type;
276
485
  const feeHint = !parsed
277
486
  ? chainType === 'solana'
278
487
  ? ' This often means the transaction failed simulation — check that you have enough SOL for fees (~0.005 SOL minimum).'
@@ -280,32 +489,110 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
280
489
  ? ' This often means the transaction failed simulation — check that you have enough ETH for gas fees.'
281
490
  : ''
282
491
  : '';
283
- lastError = Object.assign(
284
- new Error(`Execute API returned ${res.status} — treating as an ambiguous broadcast failure; the transaction may already be live.${feeHint}`),
285
- { code: 'BROADCAST_FAILED', status: res.status, details: parsed ? body : text.slice(0, 200) }
492
+ lastError = ambiguousBroadcast(
493
+ `Execute API returned ${res.status} — treating as an ambiguous broadcast failure; the transaction may already be live.${feeHint}`,
494
+ { status: res.status, details: parsed ? body : text.slice(0, 200) }
286
495
  );
287
496
  // Retry (re-POSTs byte-identical bytes) then fail closed at the caller.
288
497
  if (attempt < retries) continue;
289
498
  throw lastError;
290
499
  }
291
500
 
292
- if (!parsed) {
293
- // Non-JSON on a sub-500 status (a Cloudflare challenge or HTML error
294
- // page). A clean sub-500 HTTP response is a definitive edge/backend
295
- // rejection, so it stays nonfatal and leaves the quote reusable.
296
- lastError = Object.assign(
297
- new Error(`Execute API returned non-JSON response (status ${res.status}). This may be a Cloudflare challenge or server error.`),
298
- { code: 'EXECUTE_ERROR', status: res.status, details: text.slice(0, 200) }
501
+ // The standard route holds a single-flight lock on the quote id, so ANY 409
502
+ // is ambiguous: the first attempt is in flight or already produced a hash,
503
+ // never "safe to try again". Carved out ahead of the status-based rejection
504
+ // below, which would otherwise read the refusal as proof nothing was sent and
505
+ // let the candidate loop sign the next quote on top of an execution the
506
+ // backend is still holding.
507
+ //
508
+ // Matched on the STATUS ALONE. DUPLICATE_EXECUTION is the one documented
509
+ // conflict code and JSON is the documented shape, but a conflict this client
510
+ // does not recognise is more reason to fail closed, not less. This also makes
511
+ // an internal retry safe: if the first POST landed and the retry races back a
512
+ // 409, it aborts.
513
+ if (isStandard && res.status === 409) {
514
+ const readable = parsed && isReadableBody(body);
515
+ const conflict = readable && body.code === 'DUPLICATE_EXECUTION'
516
+ ? 'This quote was already submitted for execution'
517
+ : `The execution endpoint reported a conflict for this quote (${(readable && body.code) || 'no code'})`;
518
+ throw ambiguousBroadcast(
519
+ `${conflict}; the first transaction may be live. Request a new quote with "nansen trade quote".`,
520
+ { status: 409, details: readable ? body.details : text.slice(0, 200) }
299
521
  );
300
- throw lastError;
301
522
  }
302
523
 
524
+ // A non-2xx status does not prove the signed transaction stayed put. The
525
+ // backend or an intermediary may have produced the response after forwarding
526
+ // it, so preserve any structured error only as diagnostic detail and fail
527
+ // closed. Do not allow the candidate loop to sign another transaction.
303
528
  if (!res.ok) {
304
- const code = body.code || 'EXECUTE_ERROR';
305
- const msg = body.message || `Execute request failed with status ${res.status}`;
306
- throw Object.assign(new Error(msg), { code, status: res.status, details: body.details });
529
+ const readableBody = parsed && isReadableBody(body);
530
+ throw ambiguousBroadcast(
531
+ readableBody
532
+ ? `${body.message || `Execute request failed with status ${res.status}`} — the response does not prove the transaction was rejected before broadcast.`
533
+ : `Execute API returned an uninterpretable error response (status ${res.status}) — the response does not prove the transaction was rejected before broadcast.`,
534
+ {
535
+ status: res.status,
536
+ details: readableBody ? body : text.slice(0, 200),
537
+ }
538
+ );
539
+ }
540
+
541
+ // 2xx: the endpoint ACCEPTED the request. Everything from here on is about
542
+ // reading its answer — and if we cannot read it, we do not know what it did
543
+ // with the signed transaction. That is not the backend saying "I never
544
+ // broadcast"; it is this client failing to understand the reply, so it is
545
+ // ambiguous and fails closed.
546
+ if (!parsed || !isReadableBody(body)) {
547
+ throw ambiguousBroadcast(
548
+ `The execute endpoint returned a ${res.status} this client cannot interpret, so the outcome cannot be verified. The transaction may still be live — check the wallet on the explorer before retrying.`,
549
+ { status: res.status, details: text.slice(0, 200) }
550
+ );
551
+ }
552
+
553
+ if (isStandard) {
554
+ // The route's contract is a boolean `success`. The check above already
555
+ // rejected a body we cannot read fields off at all; this is the narrower
556
+ // question of whether the body is THIS route's shape. A 2xx that is not is
557
+ // still the endpoint having accepted the request, so it stays ambiguous
558
+ // rather than becoming a rejection.
559
+ if (typeof body.success !== 'boolean') {
560
+ throw ambiguousBroadcast(
561
+ 'The execution endpoint returned a response this client does not recognise, so the outcome cannot be verified. The swap may still be live — check the wallet on the explorer before retrying.',
562
+ { status: res.status, details: text.slice(0, 200) }
563
+ );
564
+ }
565
+ // A success with no hash is not a success we can report: nothing to print,
566
+ // nothing to poll, nothing the user can check on an explorer, and on Solana
567
+ // nothing downstream fills it in (the EVM path derives its own hash from the
568
+ // signed bytes; Solana has no equivalent step here). The request WAS
569
+ // accepted, so it is ambiguous rather than failed.
570
+ if (body.success && !body.txHash) {
571
+ throw ambiguousBroadcast(
572
+ 'The execution endpoint reported success but returned no transaction hash, so the outcome cannot be verified. The swap may still be live — check the wallet on the explorer before retrying.',
573
+ { status: res.status }
574
+ );
575
+ }
576
+ // Same boundary rule as the legacy path below: an identifier of the wrong
577
+ // shape reaches the explorer URL, the persisted broadcast marker and receipt
578
+ // polling, so it is an unverifiable outcome rather than a cosmetic defect.
579
+ assertUsableTxId(body, chainConfigFor(params.chain)?.type);
580
+ return fromStandardResponse(body, chainConfigFor(params.chain)?.type);
307
581
  }
308
582
 
583
+ // A readable object is not necessarily a valid acknowledgement. Only the
584
+ // documented terminal statuses are safe for callers to interpret; treating
585
+ // a missing or unknown status as an ordinary failure could make the quote
586
+ // loop broadcast another candidate after an incomplete success response.
587
+ if (body.status !== 'Success' && body.status !== 'Failed') {
588
+ throw ambiguousBroadcast(
589
+ `The execute endpoint returned an invalid application status (${JSON.stringify(body.status)}), so the outcome cannot be verified. The transaction may still be live — check the wallet on the explorer before retrying.`,
590
+ { status: res.status, details: body },
591
+ );
592
+ }
593
+
594
+ assertUsableTxId(body, chainConfigFor(params.chain)?.type);
595
+
309
596
  return body;
310
597
  }
311
598
  throw lastError;
@@ -457,7 +744,7 @@ export function loadTxRecord(txHash) {
457
744
  if (!filePath) return null;
458
745
  if (!fs.existsSync(filePath)) return null;
459
746
  try {
460
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
747
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
461
748
  if (Date.now() - data.timestamp > TX_RECORD_TTL_MS) {
462
749
  fs.unlinkSync(filePath);
463
750
  return null;
@@ -516,7 +803,7 @@ export function loadQuote(quoteId) {
516
803
  }
517
804
 
518
805
  function readQuoteFile(filePath, quoteId) {
519
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
806
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
520
807
  if (Date.now() - data.timestamp > 3600000) {
521
808
  fs.unlinkSync(filePath);
522
809
  throw new Error('Quote has expired. Please request a new quote.');
@@ -543,7 +830,7 @@ function readQuoteFile(filePath, quoteId) {
543
830
 
544
831
  function quoteClaimedError(quoteId, claimedPath) {
545
832
  return new Error(
546
- `Quote "${quoteId}" is claimed by another execution (${claimedPath}). If that run is still going, wait for it to finish. If it was interrupted, a swap may or may not have been broadcast: check the wallet on the explorer, then request a new quote with "nansen trade quote". The claimed quote is removed when it expires.`,
833
+ `Quote "${quoteId}" is claimed by another execution (${claimedPath}). If that run is still going, wait for it to finish. If it was interrupted, a transaction may or may not have been broadcast: check the wallet on the explorer, then request a new quote with the matching quote command. The claimed quote is removed when it expires.`,
547
834
  );
548
835
  }
549
836
 
@@ -566,20 +853,22 @@ function quoteClaimedError(quoteId, claimedPath) {
566
853
  * loaded it before another run executed it (for instance while waiting at the
567
854
  * confirmation prompt) sees that run's `executedAt` here, before signing.
568
855
  *
569
- * `release({ handedOff })` puts the quote back under its own name when no swap
856
+ * `release({ handedOff })` puts the quote back under its own name when no
570
857
  * transaction left this process, or when one did and `executedAt` was recorded
571
- * (loadQuote then refuses it with the broadcast hashes). A swap that was handed
572
- * off with no recorded marker leaves the quote claimed: a retry is refused
573
- * rather than risk a second broadcast, and the claim goes away with the quote
574
- * after its 1-hour lifetime.
858
+ * (loadQuote then refuses it with the broadcast hashes). A swap, approval, or
859
+ * revoke that was handed off with no recorded marker leaves the quote claimed:
860
+ * a retry is refused rather than risk another broadcast, and the claim goes
861
+ * away with the quote after its 1-hour lifetime.
575
862
  *
576
863
  * @param {string} quoteId
577
- * @returns {{ quote: object, release: (opts?: { handedOff?: boolean }) => void }}
864
+ * @param {function} [readQuote] Validates the claimed quote, including its type.
865
+ * @returns {{ quote: object, release: (opts?: { handedOff?: boolean, keepClaimed?: boolean }) => void }}
578
866
  */
579
- export function claimQuoteForExecution(quoteId) {
867
+ export function claimQuoteForExecution(quoteId, readQuote = readQuoteFile) {
580
868
  const quotePath = safeQuotesPath(`${quoteId}.json`);
581
869
  const claimedPath = safeQuotesPath(`${quoteId}.executing.json`);
582
870
  if (!quotePath || !claimedPath) throw new Error(`Invalid quote id "${quoteId}".`);
871
+ if (fs.lstatSync(claimedPath, { throwIfNoEntry: false })) throw quoteClaimedError(quoteId, claimedPath);
583
872
 
584
873
  try {
585
874
  fs.renameSync(quotePath, claimedPath);
@@ -592,19 +881,24 @@ export function claimQuoteForExecution(quoteId) {
592
881
  }
593
882
 
594
883
  let released = false;
595
- const release = ({ handedOff = false } = {}) => {
884
+ const release = ({ handedOff = false, keepClaimed = false } = {}) => {
596
885
  if (released) return;
597
886
  released = true;
887
+ if (keepClaimed) return;
598
888
  try {
599
- if (handedOff && !JSON.parse(fs.readFileSync(claimedPath, 'utf8')).executedAt) return;
889
+ if (handedOff && !JSON.parse(readLocalFile(claimedPath, { root: path.dirname(getQuotesDir()) })).executedAt) return;
600
890
  fs.renameSync(claimedPath, quotePath);
601
891
  } catch { /* gone (expired and cleaned up): nothing to release */ }
602
892
  };
603
893
 
604
894
  try {
605
- return { quote: readQuoteFile(claimedPath, quoteId), release };
895
+ if (process.platform !== 'win32') {
896
+ const fd = fs.openSync(path.dirname(claimedPath), 'r');
897
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
898
+ }
899
+ return { quote: readQuote(claimedPath, quoteId), release };
606
900
  } catch (err) {
607
- // Already executed, expired or not a swap quote: nothing is signed, so
901
+ // Invalid, already executed, or expired: nothing is signed, so
608
902
  // put back whatever is still there.
609
903
  release();
610
904
  throw err;
@@ -624,16 +918,15 @@ export function markQuoteExecuted(quoteId, progress = {}) {
624
918
  : safeQuotesPath(`${quoteId}.json`);
625
919
  if (!filePath || !fs.existsSync(filePath)) return;
626
920
  try {
627
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
921
+ const data = JSON.parse(readLocalFile(filePath, { root: path.dirname(getQuotesDir()) }));
628
922
  data.executedAt = data.executedAt || Date.now();
629
923
  if (progress.broadcast) {
630
924
  data.broadcasts = [...(data.broadcasts || []), { ...progress.broadcast, at: Date.now() }];
631
925
  }
632
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { mode: 0o600 });
926
+ writeLocalFile(filePath, JSON.stringify(data, null, 2), { root: path.dirname(getQuotesDir()) });
633
927
  } catch {
634
- // Best-effort: if the marker can't be written, the next execute attempt
635
- // will still proceed, but that's preferable to crashing after a successful
636
- // broadcast.
928
+ // The execution claim stays in place without a readable marker, so a
929
+ // later execution cannot sign again after an uncertain broadcast.
637
930
  }
638
931
  }
639
932
 
@@ -650,7 +943,7 @@ export function cleanupQuotes() {
650
943
  if (!file.endsWith('.json')) continue;
651
944
  const ttl = file.startsWith('tx-') ? TX_RECORD_TTL_MS : 3600000;
652
945
  try {
653
- const data = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));
946
+ const data = JSON.parse(readLocalFile(path.join(dir, file), { root: path.dirname(dir) }));
654
947
  if (now - data.timestamp > ttl) fs.unlinkSync(path.join(dir, file));
655
948
  } catch { /* ignore */ }
656
949
  }
@@ -749,10 +1042,13 @@ function decodeInstructionData(hex) {
749
1042
  * — into a signable base64 VersionedTransaction. Some aggregators (Relay's Solana-source
750
1043
  * bridge quotes) return this shape instead of a ready-to-sign serialized transaction.
751
1044
  *
752
- * Every account is kept static; the address-lookup-table hint is a size optimization,
753
- * not a correctness requirement, so skipping it is valid as long as the compiled
754
- * transaction still fits Solana's packet limit. Full lookup-table compilation is
755
- * unimplemented — throws instead of silently building an oversized/invalid transaction.
1045
+ * Accounts stay static whenever the transaction fits Solana's packet limit that way, so
1046
+ * the common case needs no extra RPC call and the safety checks see every account. Only
1047
+ * a route too large to fit (e.g. a source-chain swap ahead of the bridge deposit) has its
1048
+ * addressLookupTableAddresses fetched and used to compress accounts. A table only ever
1049
+ * replaces an account with a reference to that same address, and lookup-table entries
1050
+ * are immutable once written, so compression doesn't change what the instructions touch.
1051
+ * Throws instead of building an oversized/invalid transaction.
756
1052
  *
757
1053
  * getExpectedSigner is an async thunk resolving to the address of the wallet that is
758
1054
  * about to sign. The transaction only ever gets a single signature written into slot 0
@@ -785,6 +1081,7 @@ export async function compileRawSolanaTransaction(transaction, rpcUrl, getExpect
785
1081
  );
786
1082
  }
787
1083
 
1084
+ const unsignedSize = (message) => 1 + 64 + message.messageBytes.length; // compact-u16(1) + 1 signature slot
788
1085
  const preflight = buildMessageV0({ feePayer, instructions, recentBlockhash: SIZE_CHECK_BLOCKHASH });
789
1086
  if (preflight.numRequiredSignatures !== 1) {
790
1087
  throw new Error(
@@ -792,17 +1089,32 @@ export async function compileRawSolanaTransaction(transaction, rpcUrl, getExpect
792
1089
  `but only the wallet's own signature can be provided.`
793
1090
  );
794
1091
  }
795
- const unsignedSize = 1 + 64 + preflight.messageBytes.length; // compact-u16(1) + 1 signature slot
796
- if (unsignedSize > SOLANA_MAX_TX_SIZE) {
797
- throw new Error(
798
- `Solana transaction too large to compile without address-lookup-table support ` +
799
- `(${unsignedSize} bytes > ${SOLANA_MAX_TX_SIZE} limit). This route needs its ` +
800
- `address lookup tables resolved, which isn't supported yet.`
801
- );
1092
+
1093
+ let addressLookupTables = [];
1094
+ let size = unsignedSize(preflight);
1095
+ if (size > SOLANA_MAX_TX_SIZE) {
1096
+ const hint = transaction.addressLookupTableAddresses;
1097
+ const tableAddresses = [...new Set(Array.isArray(hint) ? hint : [])];
1098
+ if (tableAddresses.length === 0) {
1099
+ throw new Error(
1100
+ `Solana transaction too large to compile (${size} bytes > ${SOLANA_MAX_TX_SIZE} limit) and ` +
1101
+ `the quote supplied no address lookup tables to compress it. Get a new quote.`
1102
+ );
1103
+ }
1104
+ addressLookupTables = await fetchAddressLookupTables(rpcUrl, tableAddresses);
1105
+ size = unsignedSize(buildMessageV0({
1106
+ feePayer, instructions, recentBlockhash: SIZE_CHECK_BLOCKHASH, addressLookupTables,
1107
+ }));
1108
+ if (size > SOLANA_MAX_TX_SIZE) {
1109
+ throw new Error(
1110
+ `Solana transaction too large to compile (${size} bytes > ${SOLANA_MAX_TX_SIZE} limit) even ` +
1111
+ `with its ${tableAddresses.length} address lookup table(s). Get a new quote.`
1112
+ );
1113
+ }
802
1114
  }
803
1115
 
804
1116
  const recentBlockhash = await fetchRecentBlockhash(rpcUrl);
805
- const { messageBytes } = buildMessageV0({ feePayer, instructions, recentBlockhash });
1117
+ const { messageBytes } = buildMessageV0({ feePayer, instructions, recentBlockhash, addressLookupTables });
806
1118
  const unsignedTx = Buffer.concat([encodeCompactU16(1), Buffer.alloc(64), messageBytes]);
807
1119
  return unsignedTx.toString('base64');
808
1120
  }
@@ -847,13 +1159,14 @@ export async function normalizeSolanaTransaction(transaction, rpcUrl, getExpecte
847
1159
  * @param {string} chain - Chain name
848
1160
  * @param {number} nonce - Account nonce
849
1161
  * @param {object} [opts]
1162
+ * @param {string|number|bigint} [opts.gasLimit] - Resolved gas limit, overriding quote transaction fields
850
1163
  * @param {string} [opts.label='swap'] - What is being signed, for the fee-cap error
851
1164
  * @param {bigint} [opts.maxTxFeeWei] - Fee cap in wei (--max-tx-fee); 0n disables it
852
1165
  * @returns {string} 0x-prefixed signed transaction hex
853
1166
  */
854
1167
  // Pure EVM encode/sign primitive. Quote authorization and request-intent binding
855
1168
  // happen upstream before this function receives transaction calldata.
856
- export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { label = 'swap', maxTxFeeWei = MAX_EVM_TX_FEE_WEI } = {}) {
1169
+ export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { gasLimit, label = 'swap', maxTxFeeWei = MAX_EVM_TX_FEE_WEI } = {}) {
857
1170
  const chainConfig = CHAIN_MAP[chain];
858
1171
  if (!chainConfig || chainConfig.type !== 'evm') {
859
1172
  throw new Error(`Unsupported EVM chain: ${chain}`);
@@ -861,7 +1174,7 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce, { label
861
1174
 
862
1175
  const common = {
863
1176
  nonce,
864
- gasLimit: toHex(txData.gas || txData.gasLimit || '210000'),
1177
+ gasLimit: toHex(gasLimit ?? (txData.gas || txData.gasLimit || '210000')),
865
1178
  to: txData.to,
866
1179
  value: toHex(txData.value || '0'),
867
1180
  data: txData.data || '0x',
@@ -1141,39 +1454,41 @@ export async function waitForReceipt(chain, txHash, timeoutMs = 180000, pollMs =
1141
1454
  if (receipt) {
1142
1455
  const status = parseInt(receipt.status, 16);
1143
1456
  if (status !== 1) {
1144
- throw new Error(`Transaction reverted on-chain (status: ${receipt.status}). Tx: ${txHash}`);
1457
+ const revertErr = new Error(`Transaction reverted on-chain (status: ${receipt.status}). Tx: ${txHash}`);
1458
+ revertErr.code = 'TX_REVERTED';
1459
+ throw revertErr;
1145
1460
  }
1146
1461
  return receipt;
1147
1462
  }
1148
1463
  } catch (e) {
1149
1464
  // Re-throw confirmed on-chain reverts immediately; swallow transient RPC/network errors
1150
- if (e.message?.startsWith('Transaction reverted')) throw e;
1465
+ if (e.code === 'TX_REVERTED') throw e;
1151
1466
  // else: continue polling (pending tx, transient network error, etc.)
1152
1467
  }
1153
1468
  // Receipt not yet available — wait and retry
1154
1469
  await new Promise(r => setTimeout(r, pollMs));
1155
1470
  }
1156
1471
  // A timeout is NOT a confirmed revert: the tx may still be pending under our
1157
- // nonce. Tag it so callers can distinguish "reverted" (safe to try the next
1158
- // quote) from "unconfirmed" (retrying may broadcast a second tx that races
1159
- // the first for the same nonce). See the swap-path receipt catch.
1472
+ // nonce. Tag it so callers can distinguish "reverted" (confirmed failure,
1473
+ // but still terminal for this invocation) from "unconfirmed" (the tx may
1474
+ // still be live). See the swap-path receipt catch.
1160
1475
  const timeoutErr = new Error(`Transaction receipt not found after ${timeoutMs}ms. Tx: ${txHash}`);
1161
1476
  timeoutErr.code = 'RECEIPT_TIMEOUT';
1162
1477
  throw timeoutErr;
1163
1478
  }
1164
1479
 
1165
1480
  /**
1166
- * Post-broadcast failures that must abort the whole `execute` rather than fall
1167
- * through to the next quote. Once a transaction is broadcast we hold no evidence
1168
- * about what landed on-chain, so "try the next quote" would sign and broadcast a
1169
- * second transaction — the one thing we must not do. Covers every path (swap,
1481
+ * Post-broadcast outcomes that must abort the whole `execute` rather than fall
1482
+ * through to the next quote. Ambiguous failures may conceal a live transaction;
1483
+ * confirmed reverts are known failures, but still require the user to review the
1484
+ * transaction and request a fresh quote explicitly. Covers every path (swap,
1170
1485
  * approval, revoke; Privy/WalletConnect/local-key). Each code is thrown with a
1171
1486
  * rationale at its throw site:
1172
1487
  * - TXHASH_MISMATCH — broadcaster reported a tx we did not sign
1173
1488
  * - INVALID_SIGNED_TX — we cannot even derive a hash for what we broadcast
1174
1489
  * - RECEIPT_TIMEOUT — receipt never landed; the tx may still be pending, so
1175
1490
  * retrying would race a second tx against the same nonce
1176
- * (a confirmed on-chain revert is NOT this — it may retry)
1491
+ * - TX_REVERTED — receipt confirmed failure; stop and require a new quote
1177
1492
  * - BROADCAST_FAILED — /execute returned an uninterpretable response (non-JSON,
1178
1493
  * typically a 502/503 after all retries) AFTER we POSTed
1179
1494
  * the signed tx. A dropped ack is indistinguishable from
@@ -1185,10 +1500,20 @@ export async function waitForReceipt(chain, txHash, timeoutMs = 180000, pollMs =
1185
1500
  * @returns {boolean}
1186
1501
  */
1187
1502
  function isFatalBroadcastError(err) {
1188
- return err?.code === 'TXHASH_MISMATCH'
1503
+ // Set at the WalletConnect boundary (see markBroadcastAmbiguous): the wallet
1504
+ // was asked to send and we never learned the outcome. This covers the approval
1505
+ // and allowance-revoke sends too, which run BEFORE swapHandedOff is set and so
1506
+ // are invisible to the handed-off check in the candidate loop's outer catch.
1507
+ return err?.broadcastAmbiguous === true
1508
+ || err?.code === 'TXHASH_MISMATCH'
1189
1509
  || err?.code === 'INVALID_SIGNED_TX'
1190
1510
  || err?.code === 'RECEIPT_TIMEOUT'
1191
- || err?.code === 'BROADCAST_FAILED';
1511
+ || err?.code === 'BROADCAST_FAILED'
1512
+ // A confirmed revert is terminal too. Although its outcome is definitive
1513
+ // and its nonce is consumed, one `trade execute` invocation must never
1514
+ // broadcast a second transaction automatically. The user must inspect the
1515
+ // reverted transaction and request a fresh quote explicitly.
1516
+ || err?.code === 'TX_REVERTED';
1192
1517
  }
1193
1518
 
1194
1519
  /**
@@ -3117,15 +3442,63 @@ EXAMPLES:
3117
3442
 
3118
3443
  let quoteClaim = null;
3119
3444
  // Set just before the swap transaction leaves this process (the Trading
3120
- // API broadcast, or a WalletConnect wallet that may broadcast it), so the
3121
- // claim is only handed back when no swap can be in flight.
3445
+ // API broadcast, or a WalletConnect wallet that may broadcast it).
3122
3446
  let swapHandedOff = false;
3447
+ // Approval and allowance-revoke transactions can leave before the swap.
3448
+ // Keep this sticky once any such broadcast is acknowledged: if receipt,
3449
+ // hash, or allowance verification later fails, the cached quote must not
3450
+ // become reusable while the wallet's allowance state is unknown.
3451
+ let ancillaryHandedOff = false;
3452
+ // Sticky across candidates: set once any attempt ends without the backend
3453
+ // telling us whether it broadcast. An explicit "failed, no hash" response
3454
+ // clears swapHandedOff for its own attempt, but it says nothing about an
3455
+ // earlier attempt that threw mid-POST — so that one has to keep the claim.
3456
+ let handoffAmbiguous = false;
3123
3457
  try {
3124
3458
  const quoteData = loadQuote(quoteId);
3125
- const chain = quoteData.chain;
3459
+ // The quote command stores the chain exactly as the user typed it
3460
+ // (`--chain Base`), but the lookups downstream — CHAIN_RPCS here above
3461
+ // all — are keyed lowercase, and only resolveChain() normalises on its
3462
+ // own. Without this a capitalised spelling quotes fine and then fails at
3463
+ // execute with "No RPC URL configured for chain: Base", so the quote can
3464
+ // never be used. Normalised once here, which also fixes quotes already
3465
+ // on disk.
3466
+ const chain = quoteData.chain?.toLowerCase();
3126
3467
  const chainConfig = resolveChain(chain);
3127
3468
  const chainType = chainConfig.type;
3128
3469
 
3470
+
3471
+ // One correlation id per execute invocation, reused across the swap POST
3472
+ // and its internal retries so the backend can tie an execution to a single
3473
+ // user attempt rather than counting each retry as a new one.
3474
+ const attemptId = crypto.randomUUID();
3475
+ // Resolved once here, before any signing, so an unrecognised route value
3476
+ // aborts the command instead of surfacing mid-loop as a per-quote failure.
3477
+ const configuredRoute = executionRoute();
3478
+ // Gasless stays on the legacy route: the standard route has no gasless
3479
+ // envelope, so sending a signed Relay authorization there would drop the
3480
+ // gasless framing and submit it as a plain swap. Only a non-gasless swap
3481
+ // can opt into the standard route. Resolved here rather than at the
3482
+ // broadcast call because the WalletConnect branch — which may never reach
3483
+ // that call — also has to know which route is in force.
3484
+ const swapRoute = gasless ? 'legacy' : configuredRoute;
3485
+
3486
+ // The standard route keys its per-quote single-flight lock on the backend
3487
+ // quote id, so a submission without one claims duplicate protection and
3488
+ // has none. Every live /quote response carries
3489
+ // response.metadata.quoteId, so reaching this is shape drift or a
3490
+ // hand-edited quote file, never a routine swap — the cost of stopping is
3491
+ // a re-quote, the cost of proceeding is an unprotected broadcast, and the
3492
+ // local claim is per-machine and does not replace it. Checked here, with
3493
+ // the route itself, so it refuses before anything is signed instead of
3494
+ // surfacing mid-loop as a per-candidate failure.
3495
+ const backendQuoteId = quoteData.response?.metadata?.quoteId;
3496
+ if (swapRoute === 'standard' && !backendQuoteId) {
3497
+ throw new CommandError(
3498
+ `Quote "${quoteId}" carries no backend quote id, which the standard execution route requires for its duplicate-submission lock. Request a fresh quote with "nansen trade quote", or set NANSEN_TRADING_EXECUTION_ROUTE=legacy to broadcast on the deprecated route.`,
3499
+ 'MISSING_QUOTE_ID',
3500
+ );
3501
+ }
3129
3502
  const allQuotes = quoteData.response.quotes || [];
3130
3503
  if (!allQuotes.length) {
3131
3504
  throw new CommandError('❌ No quote data found', 'NO_QUOTES');
@@ -3422,6 +3795,10 @@ EXAMPLES:
3422
3795
  try {
3423
3796
  let signedTransaction;
3424
3797
  let requestId;
3798
+ // The signer address, hoisted out of the per-signer branches below so
3799
+ // the shared broadcast can send it as the standard-route attribution
3800
+ // field (the branch-local address vars are out of scope there).
3801
+ let swapWalletAddress;
3425
3802
 
3426
3803
  if (chainType === 'solana' && isPrivy) {
3427
3804
  // Solana via Privy: sign the serialized transaction
@@ -3429,6 +3806,7 @@ EXAMPLES:
3429
3806
  if (!solWalletId) throw new Error('No Solana Privy wallet ID in quote');
3430
3807
  const walletResult = await privyClient.getWallet(solWalletId);
3431
3808
  const walletAddress = walletResult.address;
3809
+ swapWalletAddress = walletAddress;
3432
3810
  // Fail closed if the signer address doesn't resolve: without it the
3433
3811
  // wallet-binding comparison below would silently skip, leaving the
3434
3812
  // quote unbound to the wallet that will sign it. This is resolved
@@ -3480,6 +3858,7 @@ EXAMPLES:
3480
3858
 
3481
3859
  const walletResult = await privyClient.getWallet(evmWalletId);
3482
3860
  const walletAddress = walletResult.address;
3861
+ swapWalletAddress = walletAddress;
3483
3862
 
3484
3863
  // Guard the swap target before any RPC call, approval, or signing —
3485
3864
  // whatever `to`/`data` the quote supplied gets signed verbatim.
@@ -3587,11 +3966,17 @@ EXAMPLES:
3587
3966
  }
3588
3967
  const revokeResult = await executeTransaction({ signedTransaction: signedRevoke, chain, simulate: !noSimulate });
3589
3968
  if (revokeResult.status !== 'Success') {
3969
+ const handedOffFailure = hashBearingFailure(revokeResult, `Allowance revoke for ${quoteName}`, 'evm');
3970
+ if (handedOffFailure) {
3971
+ ancillaryHandedOff = true;
3972
+ throw handedOffFailure;
3973
+ }
3590
3974
  log(` ❌ Allowance revoke failed for ${quoteName}: ${revokeResult.error || 'unknown'}`);
3591
3975
  if (qi + 1 < endIndex) log(` Trying next quote...`);
3592
3976
  lastQuoteError = `${quoteName} allowance revoke failed`;
3593
3977
  continue;
3594
3978
  }
3979
+ ancillaryHandedOff = true;
3595
3980
  log(` Waiting for allowance revoke confirmation...`);
3596
3981
  try {
3597
3982
  const { receipt, hash: revokeHash } = await confirmEvmBroadcast(chain, signedRevoke, revokeResult.txHash, 'allowance-revoke');
@@ -3606,10 +3991,7 @@ EXAMPLES:
3606
3991
  try {
3607
3992
  await assertAllowanceRevoked(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress);
3608
3993
  } catch (pollErr) {
3609
- log(` ❌ Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeResult.txHash)}`);
3610
- if (qi + 1 < endIndex) log(` Trying next quote...`);
3611
- lastQuoteError = `${quoteName} allowance revoke verification failed`;
3612
- continue;
3994
+ throw ambiguousBroadcast(`Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeResult.txHash)} Request a fresh quote after verifying the allowance.`);
3613
3995
  }
3614
3996
  await waitForAllowanceTxPropagation();
3615
3997
  }
@@ -3643,6 +4025,11 @@ EXAMPLES:
3643
4025
  }
3644
4026
  const approvalResult = await executeTransaction({ signedTransaction: signedApproval, chain, simulate: !noSimulate });
3645
4027
  if (approvalResult.status !== 'Success') {
4028
+ const handedOffFailure = hashBearingFailure(approvalResult, `Approval for ${quoteName}`, 'evm');
4029
+ if (handedOffFailure) {
4030
+ ancillaryHandedOff = true;
4031
+ throw handedOffFailure;
4032
+ }
3646
4033
  const revokedMsg = shouldRevoke
3647
4034
  ? ' after revoking the prior allowance (now 0)'
3648
4035
  : '';
@@ -3651,6 +4038,7 @@ EXAMPLES:
3651
4038
  lastQuoteError = `${quoteName} approval failed`;
3652
4039
  continue;
3653
4040
  }
4041
+ ancillaryHandedOff = true;
3654
4042
  log(` Waiting for approval confirmation...`);
3655
4043
  try {
3656
4044
  const { receipt, hash: approvalHash } = await confirmEvmBroadcast(chain, signedApproval, approvalResult.txHash, 'allowance-approval');
@@ -3665,10 +4053,7 @@ EXAMPLES:
3665
4053
  try {
3666
4054
  await assertAllowanceAtLeast(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress, approveAmt);
3667
4055
  } catch (pollErr) {
3668
- log(` ❌ Approval tx confirmed but allowance did not reach the required amount for ${quoteName}${shouldRevoke ? ' after revoking the prior allowance (now 0)' : ''}: ${pollErr.message}`);
3669
- if (qi + 1 < endIndex) log(` Trying next quote...`);
3670
- lastQuoteError = `${quoteName} approval verification failed`;
3671
- continue;
4056
+ throw ambiguousBroadcast(`Approval tx confirmed but allowance did not reach the required amount for ${quoteName}${shouldRevoke ? ' after revoking the prior allowance (now 0)' : ''}: ${pollErr.message}. Request a fresh quote after verifying the allowance.`);
3672
4057
  }
3673
4058
  await waitForAllowanceTxPropagation();
3674
4059
  }
@@ -3758,6 +4143,7 @@ EXAMPLES:
3758
4143
  throw new Error("Could not resolve the local wallet's Solana address; cannot confirm the quote was built for this wallet. Refusing to sign.");
3759
4144
  }
3760
4145
  }
4146
+ swapWalletAddress = solanaWalletAddress;
3761
4147
 
3762
4148
  const txBase64 = await normalizeSolanaTransaction(currentQuote.transaction, CHAIN_RPCS.solana, async () => solanaWalletAddress);
3763
4149
 
@@ -3852,6 +4238,7 @@ EXAMPLES:
3852
4238
  if (!wcAddress) {
3853
4239
  throw new CommandError('No WalletConnect session for this chain. Reconnect with `walletconnect connect` and retry.', 'NO_WALLET');
3854
4240
  }
4241
+ swapWalletAddress = wcAddress;
3855
4242
  const isNative = isNativeToken(currentQuote.inputMint);
3856
4243
 
3857
4244
  // Guard the swap target before any RPC call, approval, or signing —
@@ -3942,6 +4329,7 @@ EXAMPLES:
3942
4329
  { allowZero: true },
3943
4330
  );
3944
4331
  revokeTxHash = revokeResult.txHash;
4332
+ if (revokeTxHash) ancillaryHandedOff = true;
3945
4333
  if (!revokeTxHash && revokeResult.signedTransaction) {
3946
4334
  log(` Broadcasting allowance revocation via Trading API...`);
3947
4335
  const broadcastResult = await executeTransaction({
@@ -3950,14 +4338,28 @@ EXAMPLES:
3950
4338
  simulate: !noSimulate,
3951
4339
  });
3952
4340
  if (broadcastResult.status !== 'Success') {
4341
+ const handedOffFailure = hashBearingFailure(broadcastResult, `Allowance revoke for ${quoteName}`, 'evm');
4342
+ if (handedOffFailure) {
4343
+ ancillaryHandedOff = true;
4344
+ throw handedOffFailure;
4345
+ }
3953
4346
  throw new Error(broadcastResult.error || 'broadcast failed');
3954
4347
  }
4348
+ ancillaryHandedOff = true;
3955
4349
  revokeTxHash = assertTxHashMatch(revokeResult.signedTransaction, broadcastResult.txHash, 'allowance-revoke');
3956
4350
  }
3957
4351
  if (!revokeTxHash) {
3958
4352
  throw new Error('Allowance revoke returned no transaction hash and no signed transaction; cannot confirm allowance was cleared');
3959
4353
  }
3960
4354
  } catch (revokeErr) {
4355
+ // A revoke the wallet may already have broadcast must not
4356
+ // fall through: the next candidate would prompt for and
4357
+ // send a swap while this one is still in flight, against an
4358
+ // allowance whose real value is unknown. Re-raise with the
4359
+ // recovery hint the log line below would have carried.
4360
+ if (revokeErr?.broadcastAmbiguous) {
4361
+ throw ambiguousBroadcast(`Allowance revoke for ${quoteName} failed after the wallet was asked to send: ${revokeErr.message}. The revoke may still be live.${allowanceRevokeRecoveryHint(revokeTxHash)}`);
4362
+ }
3961
4363
  if (isFatalBroadcastError(revokeErr)) throw revokeErr;
3962
4364
  log(` ❌ Allowance revoke failed for ${quoteName}: ${revokeErr.message}.${allowanceRevokeRecoveryHint(revokeTxHash)}`);
3963
4365
  if (qi + 1 < endIndex) log(` Trying next quote...`);
@@ -3978,10 +4380,7 @@ EXAMPLES:
3978
4380
  try {
3979
4381
  await assertAllowanceRevoked(chain, currentQuote.inputMint, wcAddress, currentQuote.approvalAddress);
3980
4382
  } catch (pollErr) {
3981
- log(` ❌ Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeTxHash)}`);
3982
- if (qi + 1 < endIndex) log(` Trying next quote...`);
3983
- lastQuoteError = `${quoteName} allowance revoke verification failed`;
3984
- continue;
4383
+ throw ambiguousBroadcast(`Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeTxHash)} Request a fresh quote after verifying the allowance.`);
3985
4384
  }
3986
4385
  await waitForAllowanceTxPropagation();
3987
4386
  }
@@ -3997,6 +4396,7 @@ EXAMPLES:
3997
4396
  approvalCapForQuote(quoteData),
3998
4397
  );
3999
4398
  approvalTxHash = approvalResult.txHash;
4399
+ if (approvalTxHash) ancillaryHandedOff = true;
4000
4400
  if (!approvalTxHash && approvalResult.signedTransaction) {
4001
4401
  // Wallet returned a signed tx instead of broadcasting — broadcast via Trading API
4002
4402
  log(` Broadcasting approval via Trading API...`);
@@ -4006,8 +4406,14 @@ EXAMPLES:
4006
4406
  simulate: !noSimulate,
4007
4407
  });
4008
4408
  if (broadcastResult.status !== 'Success') {
4409
+ const handedOffFailure = hashBearingFailure(broadcastResult, `Approval for ${quoteName}`, 'evm');
4410
+ if (handedOffFailure) {
4411
+ ancillaryHandedOff = true;
4412
+ throw handedOffFailure;
4413
+ }
4009
4414
  throw new Error(broadcastResult.error || 'broadcast failed');
4010
4415
  }
4416
+ ancillaryHandedOff = true;
4011
4417
  approvalTxHash = assertTxHashMatch(approvalResult.signedTransaction, broadcastResult.txHash, 'allowance-approval');
4012
4418
  }
4013
4419
  if (!approvalTxHash) {
@@ -4019,10 +4425,17 @@ EXAMPLES:
4019
4425
  throw new Error('returned no transaction hash and no signed transaction; cannot confirm approval landed');
4020
4426
  }
4021
4427
  } catch (approvalErr) {
4022
- if (isFatalBroadcastError(approvalErr)) throw approvalErr;
4023
4428
  const revokedMsg = shouldRevoke
4024
4429
  ? ' after revoking the prior allowance (now 0)'
4025
4430
  : '';
4431
+ // Same as the revoke above: an approval the wallet may have
4432
+ // broadcast leaves the allowance unknown, so ending here is
4433
+ // the only answer that cannot double-send. The revoked note
4434
+ // matters most on this path — the prior allowance is already 0.
4435
+ if (approvalErr?.broadcastAmbiguous) {
4436
+ throw ambiguousBroadcast(`Approval for ${quoteName} failed${revokedMsg} after the wallet was asked to send: ${approvalErr.message}. The approval may still be live — check the allowance before retrying.`);
4437
+ }
4438
+ if (isFatalBroadcastError(approvalErr)) throw approvalErr;
4026
4439
  log(` ❌ Approval failed for ${quoteName}${revokedMsg}: ${approvalErr.message}`);
4027
4440
  if (qi + 1 < endIndex) log(` Trying next quote...`);
4028
4441
  lastQuoteError = `${quoteName} approval failed`;
@@ -4048,10 +4461,7 @@ EXAMPLES:
4048
4461
  const revokedMsg = shouldRevoke
4049
4462
  ? ' after revoking the prior allowance (now 0)'
4050
4463
  : '';
4051
- log(` ❌ Approval tx confirmed but allowance did not reach the required amount for ${quoteName}${revokedMsg}: ${pollErr.message}`);
4052
- if (qi + 1 < endIndex) log(` Trying next quote...`);
4053
- lastQuoteError = `${quoteName} approval verification failed`;
4054
- continue;
4464
+ throw ambiguousBroadcast(`Approval tx confirmed but allowance did not reach the required amount for ${quoteName}${revokedMsg}: ${pollErr.message}. Request a fresh quote after verifying the allowance.`);
4055
4465
  }
4056
4466
  await waitForAllowanceTxPropagation();
4057
4467
  log('');
@@ -4106,10 +4516,17 @@ EXAMPLES:
4106
4516
  chainId: chainConfig.chainId,
4107
4517
  });
4108
4518
  } catch (wcErr) {
4109
- log(` ❌ WalletConnect transaction failed for ${quoteName}: ${wcErr.message}`);
4110
- if (qi + 1 < endIndex) log(` Trying next quote...`);
4111
- lastQuoteError = `${quoteName}: ${wcErr.message}`;
4112
- continue;
4519
+ // The wallet was already asked to send, and wcExec rejects with a
4520
+ // bare Error(err.message) for EVERY failure — a user rejection, a
4521
+ // 120s approval timeout and a spawn failure are indistinguishable
4522
+ // here. A timeout in particular is the case where the user DID
4523
+ // approve and the wallet DID broadcast while our subprocess gave
4524
+ // up waiting. So this cannot be read as "nothing was sent": it is
4525
+ // ambiguous, and must fail closed rather than sign the next quote
4526
+ // on top of a possibly-live transaction. (This catch used to
4527
+ // `continue`, which bypassed the loop's whole fail-closed path
4528
+ // below — it never reached `catch (quoteErr)`.)
4529
+ throw ambiguousBroadcast(`WalletConnect transaction failed for ${quoteName}: ${wcErr.message} — the wallet may still have broadcast it; check the explorer before retrying.`);
4113
4530
  }
4114
4531
 
4115
4532
  if (wcResult.txHash) {
@@ -4119,6 +4536,18 @@ EXAMPLES:
4119
4536
  // executeTransaction() marker further down.
4120
4537
  markQuoteExecuted(quoteId, { broadcast: { txHash: wcResult.txHash } });
4121
4538
 
4539
+ // Say it out loud when the selected route was bypassed. A wallet
4540
+ // that broadcasts for us hands back a hash instead of signed bytes,
4541
+ // so there is nothing to POST and the swap never reaches
4542
+ // /execution/standard — no server-side outcome tracking for this
4543
+ // trade. Silence here is the staged-rollout failure mode
4544
+ // executionRoute() already guards against at the other end: you
4545
+ // believe you exercised the new route and you did not.
4546
+ if (swapRoute === 'standard') {
4547
+ log(' Note: the wallet broadcast this swap itself, so the standard');
4548
+ log(' execution route was bypassed (no server-side tracking).');
4549
+ }
4550
+
4122
4551
  // Wallet broadcast — verify on-chain
4123
4552
  log(' Verifying on-chain status...');
4124
4553
  try {
@@ -4131,17 +4560,11 @@ EXAMPLES:
4131
4560
  if (receiptErr.code === 'RECEIPT_TIMEOUT') {
4132
4561
  throw new CommandError(`\n ⚠ Transaction was broadcast but NOT confirmed within the wait window.\n Tx Hash: ${wcResult.txHash}\n Explorer: ${chainConfig.explorer}${wcResult.txHash}\n ${receiptErr.message}\n\n The transaction may still be pending — do NOT assume it failed. Check the\n explorer before retrying; retrying may broadcast a second swap.`, 'RECEIPT_TIMEOUT');
4133
4562
  }
4134
- if (isFatalBroadcastError(receiptErr)) throw receiptErr;
4135
- log(`\n ⚠ Transaction was broadcast but REVERTED on-chain!`);
4136
- log(` Tx Hash: ${wcResult.txHash}`);
4137
- log(` Explorer: ${chainConfig.explorer}${wcResult.txHash}`);
4138
- log(` Error: ${receiptErr.message}`);
4139
- if (qi + 1 < endIndex) {
4140
- log(` Trying next quote...`);
4141
- lastQuoteError = `${quoteName} reverted on-chain`;
4142
- continue;
4563
+ if (receiptErr.code === 'TX_REVERTED') {
4564
+ throw new CommandError(`\n ⚠ Transaction was broadcast but REVERTED on-chain!\n Tx Hash: ${wcResult.txHash}\n Explorer: ${chainConfig.explorer}${wcResult.txHash}\n Error: ${receiptErr.message}\n\n No further quote was attempted. Review the transaction, then request a new quote before retrying.`, 'TX_REVERTED');
4143
4565
  }
4144
- throw new CommandError(`\n ⚠ Transaction was broadcast but REVERTED on-chain!\n Tx Hash: ${wcResult.txHash}\n Explorer: ${chainConfig.explorer}${wcResult.txHash}\n Error: ${receiptErr.message}`, 'TX_REVERTED');
4566
+ if (isFatalBroadcastError(receiptErr)) throw receiptErr;
4567
+ throw receiptErr;
4145
4568
  }
4146
4569
 
4147
4570
  log(`\n ✓ Transaction successful!`);
@@ -4180,12 +4603,30 @@ EXAMPLES:
4180
4603
  return undefined; // Success
4181
4604
  }
4182
4605
 
4183
- // Wallet returned signedTransaction — fall through to broadcast via Trading API
4606
+ // Wallet returned signedTransaction — fall through to broadcast via
4607
+ // Trading API.
4608
+ //
4609
+ // Guarded even though it cannot fire today:
4610
+ // sendTransactionViaWalletConnect throws rather than resolving without
4611
+ // one of txHash/signedTransaction, so every reachable shape is handled
4612
+ // above. That invariant lives in another module, though, and the failure
4613
+ // mode if it ever relaxes to a bare return is the worst one here — an
4614
+ // undefined payload POSTs a malformed body and could hide a wallet
4615
+ // broadcast behind the resulting API error. BROADCAST_FAILED is
4616
+ // classified fatal, so the candidate catch rethrows it and the quote
4617
+ // stays claimed instead of prompting for the next candidate.
4618
+ if (!wcResult.signedTransaction) {
4619
+ throw new CommandError(
4620
+ `\n ⚠ WalletConnect returned no transaction hash and no signed transaction for ${quoteName}.\n\n The wallet may still have broadcast this swap. Check the wallet and the\n explorer before retrying — retrying may broadcast a second swap.`,
4621
+ 'BROADCAST_FAILED',
4622
+ );
4623
+ }
4184
4624
  signedTransaction = wcResult.signedTransaction;
4185
4625
 
4186
4626
  } else {
4187
4627
  // EVM: quote.transaction is { to, data, value, gas, gasPrice }
4188
4628
  const walletAddress = exported.evm.address;
4629
+ swapWalletAddress = walletAddress;
4189
4630
 
4190
4631
  // Guard the swap target before any RPC call, approval, or signing —
4191
4632
  // whatever `to`/`data` the quote supplied gets signed verbatim, so
@@ -4298,11 +4739,17 @@ EXAMPLES:
4298
4739
  });
4299
4740
 
4300
4741
  if (revokeResult.status !== 'Success') {
4742
+ const handedOffFailure = hashBearingFailure(revokeResult, `Allowance revoke for ${quoteName}`, 'evm');
4743
+ if (handedOffFailure) {
4744
+ ancillaryHandedOff = true;
4745
+ throw handedOffFailure;
4746
+ }
4301
4747
  log(` ❌ Allowance revoke failed for ${quoteName}: ${revokeResult.error || 'unknown error'}`);
4302
4748
  if (qi + 1 < endIndex) log(` Trying next quote...`);
4303
4749
  lastQuoteError = `${quoteName} allowance revoke failed`;
4304
4750
  continue;
4305
4751
  }
4752
+ ancillaryHandedOff = true;
4306
4753
 
4307
4754
  log(` Waiting for allowance revoke confirmation...`);
4308
4755
  try {
@@ -4318,10 +4765,7 @@ EXAMPLES:
4318
4765
  try {
4319
4766
  await assertAllowanceRevoked(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress);
4320
4767
  } catch (pollErr) {
4321
- log(` ❌ Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeResult.txHash)}`);
4322
- if (qi + 1 < endIndex) log(` Trying next quote...`);
4323
- lastQuoteError = `${quoteName} allowance revoke verification failed`;
4324
- continue;
4768
+ throw ambiguousBroadcast(`Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeResult.txHash)} Request a fresh quote after verifying the allowance.`);
4325
4769
  }
4326
4770
  await waitForAllowanceTxPropagation();
4327
4771
  }
@@ -4348,6 +4792,11 @@ EXAMPLES:
4348
4792
  });
4349
4793
 
4350
4794
  if (approvalResult.status !== 'Success') {
4795
+ const handedOffFailure = hashBearingFailure(approvalResult, `Approval for ${quoteName}`, 'evm');
4796
+ if (handedOffFailure) {
4797
+ ancillaryHandedOff = true;
4798
+ throw handedOffFailure;
4799
+ }
4351
4800
  const revokedMsg = shouldRevoke
4352
4801
  ? ' after revoking the prior allowance (now 0)'
4353
4802
  : '';
@@ -4356,6 +4805,7 @@ EXAMPLES:
4356
4805
  lastQuoteError = `${quoteName} approval failed`;
4357
4806
  continue;
4358
4807
  }
4808
+ ancillaryHandedOff = true;
4359
4809
 
4360
4810
  log(` Waiting for approval confirmation...`);
4361
4811
  try {
@@ -4371,10 +4821,7 @@ EXAMPLES:
4371
4821
  try {
4372
4822
  await assertAllowanceAtLeast(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress, approveAmt);
4373
4823
  } catch (pollErr) {
4374
- log(` ❌ Approval tx confirmed but allowance did not reach the required amount for ${quoteName}${shouldRevoke ? ' after revoking the prior allowance (now 0)' : ''}: ${pollErr.message}`);
4375
- if (qi + 1 < endIndex) log(` Trying next quote...`);
4376
- lastQuoteError = `${quoteName} approval verification failed`;
4377
- continue;
4824
+ throw ambiguousBroadcast(`Approval tx confirmed but allowance did not reach the required amount for ${quoteName}${shouldRevoke ? ' after revoking the prior allowance (now 0)' : ''}: ${pollErr.message}. Request a fresh quote after verifying the allowance.`);
4378
4825
  }
4379
4826
  await waitForAllowanceTxPropagation();
4380
4827
  log('');
@@ -4417,8 +4864,6 @@ EXAMPLES:
4417
4864
  const txData = currentQuote.transaction;
4418
4865
  const finalGas = await resolveEvmSwapGasLimit(currentQuote, { chain, from: walletAddress });
4419
4866
  logEvmSwapGasResolution(log, currentQuote, txData, finalGas);
4420
- if (txData.gasLimit) txData.gasLimit = String(finalGas);
4421
- else txData.gas = String(finalGas);
4422
4867
 
4423
4868
  log(' Fetching nonce...');
4424
4869
  await new Promise(r => setTimeout(r, 1000));
@@ -4431,7 +4876,7 @@ EXAMPLES:
4431
4876
  exported.evm.privateKey,
4432
4877
  chain,
4433
4878
  nonce,
4434
- { maxTxFeeWei },
4879
+ { gasLimit: finalGas, maxTxFeeWei },
4435
4880
  );
4436
4881
  }
4437
4882
 
@@ -4442,12 +4887,18 @@ EXAMPLES:
4442
4887
  simulate: !noSimulate && !gasless,
4443
4888
  };
4444
4889
 
4445
- // Prefer the backend quote id saved from /quote; per-aggregator ids can
4446
- // appear on individual quote metadata and are only a fallback.
4447
- const backendQuoteId =
4448
- quoteData.response?.metadata?.quoteId ?? currentQuote.metadata?.quoteId;
4449
- if (backendQuoteId) {
4450
- execParams.quoteId = backendQuoteId;
4890
+ // The backend quote id, resolved with the route above. The per-quote
4891
+ // fallback here is reachable on the legacy route only, because the
4892
+ // standard route already refused the no-backend-id case before any
4893
+ // signing. That split is deliberate: a per-quote id is minted by the
4894
+ // AGGREGATOR, not the backend (LiFi returns '<uuid>:<index>'), so it
4895
+ // is a different identifier in a different namespace. It is fine as a
4896
+ // correlation hint, and wrong as the key the standard route's
4897
+ // single-flight lock is held on — that request would look
4898
+ // idempotency-protected and would not be.
4899
+ const quoteIdForExecute = backendQuoteId ?? currentQuote.metadata?.quoteId;
4900
+ if (quoteIdForExecute) {
4901
+ execParams.quoteId = quoteIdForExecute;
4451
4902
  }
4452
4903
  // The backend's /execute schema is strict; sending fields it doesn't expect
4453
4904
  // for the (chain × aggregator × gasless) combination causes 502s or
@@ -4482,11 +4933,35 @@ EXAMPLES:
4482
4933
  // can't be deduped at the node level and risks a second solve. For
4483
4934
  // gasless we therefore don't retry: a single POST either succeeds or
4484
4935
  // fails closed (BROADCAST_FAILED marks the quote spent and aborts).
4936
+ if (swapRoute === 'standard') {
4937
+ // Attribution and cross-chain fields the standard route reads from
4938
+ // the body. Attached only here because the legacy schema rejects
4939
+ // some of them (an aggregator on an EVM swap in particular).
4940
+ if (swapWalletAddress) execParams.walletAddress = swapWalletAddress;
4941
+ if (currentQuote.aggregator) execParams.aggregator = currentQuote.aggregator;
4942
+ if (quoteData.toChain && quoteData.toChain !== quoteData.chain) {
4943
+ execParams.isCrossChain = true;
4944
+ execParams.toChain = quoteData.toChain;
4945
+ }
4946
+ }
4947
+
4485
4948
  swapHandedOff = true;
4486
- const result = await executeTransaction(execParams, { retries: gasless ? 0 : undefined });
4949
+ const result = await executeTransaction(execParams, { retries: gasless ? 0 : undefined, route: swapRoute, attemptId });
4487
4950
 
4488
4951
  if (result.status === 'Success') {
4489
- let txId = result.signature || result.txHash;
4952
+ const gaslessEvm = gasless && chainType === 'evm';
4953
+ // `signature` is a Solana field. Reading it on EVM let a stray one
4954
+ // win over the real `txHash` and reach the explorer URL and the
4955
+ // persisted broadcast marker; executeTransaction has already
4956
+ // validated the shape of whichever field is used here.
4957
+ let txId = chainType === 'evm' ? result.txHash : (result.signature || result.txHash);
4958
+ if ((chainType === 'solana' || gaslessEvm) && !txId) {
4959
+ const executionType = gaslessEvm ? 'gasless EVM' : 'Solana';
4960
+ throw ambiguousBroadcast(
4961
+ `The execute API reported success for ${quoteName} without a ${executionType} transaction identifier. The broadcast cannot be verified, so no further quote will be tried. Check the wallet on the explorer before retrying.`,
4962
+ { details: result },
4963
+ );
4964
+ }
4490
4965
  let explorerUrl = chainConfig.explorer + txId;
4491
4966
 
4492
4967
  // The transaction is on-chain (or in flight) the instant the
@@ -4497,13 +4972,51 @@ EXAMPLES:
4497
4972
  // WalletConnect sign-only fallback, and --gasless Relay — every
4498
4973
  // path that reaches this shared broadcast call.
4499
4974
  //
4500
- // Deliberate: a broadcast that later reverts on-chain (the
4501
- // "Trying next quote" path below) still consumes the quote —
4502
- // the revert still burned the nonce, so re-signing this same
4503
- // quote for a retry would race the reverted tx's nonce. This is
4504
- // intentional, not an oversight.
4975
+ // Deliberate: a broadcast that later reverts on-chain still
4976
+ // consumes the quote and ends this invocation. The user must
4977
+ // review that transaction and request a fresh quote explicitly.
4505
4978
  markQuoteExecuted(quoteId, { broadcast: { txHash: txId } });
4506
4979
 
4980
+ // Standard-route soft-fail: the node rejected our broadcast but the
4981
+ // signed tx carries a deterministic hash and may still propagate. The
4982
+ // quote is already burned (marked above), so we do NOT fall through to
4983
+ // the next candidate — that would be the double broadcast this path
4984
+ // exists to avoid. Surface the warning and keep going with the hash.
4985
+ // `broadcastSucceeded` is set by both the EVM and Solana standard
4986
+ // executors; the hash is still ours (the Solana signature, or
4987
+ // keccak256 of the signed EVM bytes), so it stays pollable.
4988
+ if (result.broadcastSucceeded === false) {
4989
+ log(` ⚠ The broadcast was rejected by the node but the transaction may still propagate: ${result.broadcastError || 'no detail returned'}`);
4990
+ log(` ${result.signature ? 'Signature' : 'Tx Hash'}: ${txId}`);
4991
+ log(` Explorer: ${explorerUrl}`);
4992
+ log(` Do NOT re-quote until you have checked the explorer.`);
4993
+ // Say so up front: the receipt poll below runs for up to 3 minutes
4994
+ // and, for a broadcast the node refused, most likely ends in the
4995
+ // RECEIPT_TIMEOUT banner. Without this the warning above is buried
4996
+ // behind a silent wait and a scarier-looking error.
4997
+ if (chainType === 'evm') {
4998
+ log(` Checking for a receipt anyway — this can take up to 3 minutes and may time out.`);
4999
+ } else {
5000
+ // Solana has no receipt poll below to resolve this. The EVM
5001
+ // branch either confirms the hash or fails closed on a timeout;
5002
+ // Solana would fall straight through to "✓ Transaction
5003
+ // successful!" and exit 0 for a broadcast the node refused, so
5004
+ // an agent would record a swap that may never have propagated.
5005
+ // Nothing here verified anything, so do not report success.
5006
+ //
5007
+ // The quote was marked spent above and no candidate fallback
5008
+ // runs from here, so this only changes what we REPORT: a
5009
+ // non-zero exit carrying the signature, instead of a success
5010
+ // banner for an outcome we do not know. Chain-gated rather than
5011
+ // route-gated — if any route hands back broadcastSucceeded:false
5012
+ // on Solana, we still cannot verify it.
5013
+ throw new CommandError(
5014
+ `\n ⚠ The node rejected this broadcast and the outcome could not be verified.\n Signature: ${txId}\n Explorer: ${explorerUrl}\n Error: ${result.broadcastError || 'no detail returned'}\n\n The transaction may still have propagated. Check the explorer before\n re-quoting — retrying may broadcast a second swap.`,
5015
+ 'BROADCAST_FAILED',
5016
+ );
5017
+ }
5018
+ }
5019
+
4507
5020
  // For EVM: verify the tx actually succeeded on-chain
4508
5021
  if (chainType === 'evm') {
4509
5022
  log(' Verifying on-chain status...');
@@ -4543,25 +5056,21 @@ EXAMPLES:
4543
5056
  if (receiptErr.code === 'RECEIPT_TIMEOUT') {
4544
5057
  throw new CommandError(`\n ⚠ Transaction was broadcast but NOT confirmed within the wait window.\n Tx Hash: ${txId || result.txHash}\n Explorer: ${explorerUrl}\n ${receiptErr.message}\n\n The transaction may still be pending — do NOT assume it failed. Check the\n explorer before retrying; retrying may broadcast a second swap against the\n same nonce.`, 'RECEIPT_TIMEOUT');
4545
5058
  }
4546
- if (isFatalBroadcastError(receiptErr)) throw receiptErr;
4547
- log(`\n ⚠ Transaction was broadcast but REVERTED on-chain!`);
4548
- log(` Tx Hash: ${txId || result.txHash}`);
4549
- log(` Explorer: ${explorerUrl}`);
4550
- log(` Error: ${receiptErr.message}`);
4551
- if (qi + 1 < endIndex) {
4552
- log(` Trying next quote...`);
4553
- lastQuoteError = `${quoteName} reverted on-chain`;
4554
- continue;
5059
+ if (receiptErr.code === 'TX_REVERTED') {
5060
+ throw new CommandError(`\n ⚠ Transaction was broadcast but REVERTED on-chain!\n Tx Hash: ${txId || result.txHash}\n Explorer: ${explorerUrl}\n Error: ${receiptErr.message}\n\n No further quote was attempted. Review the transaction, then request a new quote before retrying.`, 'TX_REVERTED');
4555
5061
  }
4556
- throw new CommandError(`\n ⚠ Transaction was broadcast but REVERTED on-chain!\n Tx Hash: ${txId || result.txHash}\n Explorer: ${explorerUrl}\n Error: ${receiptErr.message}\n\n The trading API reported success, but the contract execution failed.\n This can happen due to: stale quotes, insufficient gas, or liquidity changes.`, 'TX_REVERTED');
5062
+ if (isFatalBroadcastError(receiptErr)) throw receiptErr;
5063
+ throw receiptErr;
4557
5064
  }
4558
5065
  }
4559
5066
 
4560
5067
  log(`\n ✓ Transaction successful!`);
4561
5068
  log(` Status: ${result.status}`);
4562
- log(` ${result.signature ? 'Signature' : 'Tx Hash'}: ${txId}`);
5069
+ log(` ${chainType === 'solana' ? 'Signature' : 'Tx Hash'}: ${txId}`);
4563
5070
  log(` Chain: ${chainConfig.name} (${result.chainType})`);
4564
- log(` Broadcaster: ${result.broadcaster}`);
5071
+ // The standard route reports no broadcaster; only print it when the
5072
+ // response actually carries one (the legacy route does).
5073
+ if (result.broadcaster) log(` Broadcaster: ${result.broadcaster}`);
4565
5074
  log(` Explorer: ${explorerUrl}`);
4566
5075
 
4567
5076
  if (result.swapEvents?.length) {
@@ -4605,7 +5114,11 @@ EXAMPLES:
4605
5114
  return undefined; // Success — done
4606
5115
  } else {
4607
5116
  log(`\n ✗ Quote ${quoteName} failed: ${result.status}`);
4608
- if (result.error) log(` Error: ${result.error}`);
5117
+ // The standard route reports a typed failure as `code` (e.g. a
5118
+ // landed revert) with an optional `message`, where the legacy route
5119
+ // used `error`; surface whichever is present.
5120
+ const failReason = result.error || result.message || result.code;
5121
+ if (failReason) log(` Error: ${failReason}`);
4609
5122
  // A non-Success result can still carry a hash — the same
4610
5123
  // /execute response shape (status: 'Failed' + txHash) is
4611
5124
  // observed for approval broadcasts in trading.test.js, so a
@@ -4613,9 +5126,38 @@ EXAMPLES:
4613
5126
  // tell from here whether the hash means the tx actually went
4614
5127
  // out, but the asymmetry favors marking: a needless re-quote
4615
5128
  // is cheaper than a silent double broadcast.
4616
- const failedTxId = result.signature || result.txHash;
4617
- if (failedTxId) markQuoteExecuted(quoteId, { broadcast: { txHash: failedTxId } });
4618
- lastQuoteError = `${quoteName}: ${result.error || result.status}`;
5129
+ const failedTxId = chainType === 'evm'
5130
+ ? result.txHash
5131
+ : (result.signature || result.txHash);
5132
+ if (failedTxId) {
5133
+ markQuoteExecuted(quoteId, { broadcast: { txHash: failedTxId } });
5134
+ throw ambiguousBroadcast(
5135
+ `${quoteName} reported ${result.status} with transaction identifier ${failedTxId}. The transaction may have been broadcast, so no further quote will be tried. Check it on-chain before requesting a fresh quote.`,
5136
+ { details: result },
5137
+ );
5138
+ } else if (!handoffAmbiguous) {
5139
+ // The backend answered, and its answer is "no transaction". That
5140
+ // is the same statement the candidate fallback below already
5141
+ // trusts enough to go sign another transaction against this
5142
+ // quote, so trust it to hand the local claim back too — nothing
5143
+ // left this process. Otherwise a run where every candidate is
5144
+ // rejected this way leaves <quote>.executing.json behind, and the
5145
+ // next execute is refused with "claimed by another execution"
5146
+ // for a quote that was never broadcast and is still good.
5147
+ swapHandedOff = false;
5148
+ }
5149
+ lastQuoteError = `${quoteName}: ${failReason || result.status}`;
5150
+ // Same single-flight reasoning as the receipt-revert path above: on
5151
+ // the standard route a failure CARRYING A HASH has already claimed
5152
+ // this quote server-side, so the next candidate can only conflict. A
5153
+ // failure with no hash is the backend's "provably never broadcast"
5154
+ // shape — it releases the lock, so the fallback stays available.
5155
+ if (swapRoute === 'standard' && failedTxId) {
5156
+ throw new CommandError(
5157
+ `\n ⚠ Transaction was broadcast but did NOT succeed.\n ${result.signature ? 'Signature' : 'Tx Hash'}: ${failedTxId}\n Explorer: ${chainConfig.explorer + failedTxId}\n Error: ${failReason || result.status}\n\n This quote is spent. Request a new one with "nansen trade quote".`,
5158
+ 'TX_REVERTED',
5159
+ );
5160
+ }
4619
5161
  if (qi + 1 < endIndex) log(` Trying next quote...`);
4620
5162
  }
4621
5163
 
@@ -4625,11 +5167,13 @@ EXAMPLES:
4625
5167
  // as spent. The signed tx may already be live on the backend (a 502
4626
5168
  // on the ack, not on the send), so fail closed: mark it here so a
4627
5169
  // later "trade execute --quote <id>" (or an agent auto-retry) is
4628
- // refused before it re-signs under a fresh nonce. No broadcast hash
4629
- // is recorded — we don't have one — which yields loadQuote's generic
4630
- // "may still be pending, check the explorer" message.
5170
+ // refused before it re-signs under a fresh nonce. Preserve a hash
5171
+ // when the application-level failure supplied one; transport
5172
+ // failures have no hash and retain the generic pending warning.
4631
5173
  if (quoteErr?.code === 'BROADCAST_FAILED') {
4632
- markQuoteExecuted(quoteId);
5174
+ markQuoteExecuted(quoteId, quoteErr.txHash
5175
+ ? { broadcast: { txHash: quoteErr.txHash } }
5176
+ : undefined);
4633
5177
  }
4634
5178
  // Post-broadcast failures abort the whole execute — never retry the
4635
5179
  // next quote once a transaction is already out and its outcome is
@@ -4637,6 +5181,25 @@ EXAMPLES:
4637
5181
  // timeout, or an ambiguous broadcast failure). See
4638
5182
  // isFatalBroadcastError.
4639
5183
  if (isFatalBroadcastError(quoteErr)) throw quoteErr;
5184
+ // No HTTP response is trusted as proof of pre-broadcast rejection.
5185
+ // Once this candidate was handed off, any otherwise-unclassified
5186
+ // error is ambiguous and must stop the loop.
5187
+ if (swapHandedOff) {
5188
+ handoffAmbiguous = true;
5189
+ // The swap was already handed to a wallet or the backend, and
5190
+ // nothing in this error proves it stayed put — an uncoded throw is
5191
+ // this client failing to learn the outcome, not the backend saying
5192
+ // "I never sent it". Marking handoffAmbiguous only protected the
5193
+ // CLAIM; the loop still fell through and signed the next candidate
5194
+ // against the same quote. Abort instead, and mark the quote spent
5195
+ // so a later `trade execute --quote <id>` is refused too.
5196
+ //
5197
+ // The paths that legitimately continue are unaffected: failures
5198
+ // detected before handoff never enter this branch, and the
5199
+ // backend's "failed, no transaction" answer never throws at all.
5200
+ markQuoteExecuted(quoteId);
5201
+ throw ambiguousBroadcast(`${quoteName} failed after the transaction was handed off: ${quoteErr.message || quoteErr} — the outcome could not be verified, so no further quote will be tried. Check the wallet on the explorer before retrying.`);
5202
+ }
4640
5203
  const msg = quoteErr.message || '';
4641
5204
  log(` ❌ Quote ${quoteName} failed: ${msg}`);
4642
5205
  if (msg.includes('AccountNotFound') && chainType === 'solana') {
@@ -4656,9 +5219,9 @@ EXAMPLES:
4656
5219
  if (err.details) msg += `\n Details: ${JSON.stringify(err.details)}`;
4657
5220
  throw new CommandError(msg, err.code || 'EXECUTE_ERROR');
4658
5221
  } finally {
4659
- // Hands the quote back only if no swap left this process, or if one
4660
- // did and its executedAt marker was recorded (see claimQuoteForExecution).
4661
- if (quoteClaim) quoteClaim.release({ handedOff: swapHandedOff });
5222
+ // Hands the quote back only if no swap/approval/revoke left this process,
5223
+ // or if an executedAt marker was recorded (see claimQuoteForExecution).
5224
+ if (quoteClaim) quoteClaim.release({ handedOff: swapHandedOff || ancillaryHandedOff });
4662
5225
  }
4663
5226
  },
4664
5227