nansen-cli 2.1.0 → 2.3.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
@@ -30,6 +30,28 @@ import { screenOrThrow } from './perp.js';
30
30
 
31
31
  const TRADING_API_URL = process.env.NANSEN_TRADING_API_URL || 'https://trading-api.nansen.ai';
32
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
+
33
55
  // Solana's max transaction wire size (IPv6 MTU minus headers).
34
56
  const SOLANA_MAX_TX_SIZE = 1232;
35
57
 
@@ -199,12 +221,200 @@ export async function getQuote(params) {
199
221
  * @param {boolean} [params.simulate] - Run pre-broadcast simulation
200
222
  * @returns {Promise<object>} Execution result
201
223
  */
202
- 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 (Solana has no locally derived hash), so that call stays
361
+ // 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;
203
412
  const headers = {
204
413
  'Content-Type': 'application/json',
205
414
  'Accept': 'application/json',
206
415
  'User-Agent': CLIENT_USER_AGENT,
207
416
  'X-Client-Type': 'nansen-cli',
417
+ ...(attemptId ? { 'x-trade-attempt-id': attemptId } : {}),
208
418
  ...telemetryHeaders(),
209
419
  };
210
420
  let lastError;
@@ -215,10 +425,10 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
215
425
 
216
426
  let res;
217
427
  try {
218
- res = await fetch(`${TRADING_API_URL}/execute`, {
428
+ res = await fetch(`${TRADING_API_URL}${requestPath}`, {
219
429
  method: 'POST',
220
430
  headers,
221
- body: JSON.stringify(params),
431
+ body: JSON.stringify(requestBody),
222
432
  });
223
433
  } catch (netErr) {
224
434
  // The POST left this process but no response came back (a reset/timeout).
@@ -228,10 +438,7 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
228
438
  // the SAME signed bytes (a byte-identical replay a node dedupes), so a
229
439
  // retry here can't itself double-broadcast; only exhausting them fails
230
440
  // closed at the caller (isFatalBroadcastError → mark the quote spent).
231
- lastError = Object.assign(
232
- new Error(`Execute POST to /execute failed: ${netErr.message}`),
233
- { code: 'BROADCAST_FAILED' }
234
- );
441
+ lastError = ambiguousBroadcast(`Execute POST to ${requestPath} failed: ${netErr.message}`);
235
442
  if (attempt < retries) continue;
236
443
  throw lastError;
237
444
  }
@@ -245,10 +452,7 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
245
452
  // fail closed as BROADCAST_FAILED rather than surface a codeless error the
246
453
  // candidate loop would treat as nonfatal. A retry re-sends byte-identical
247
454
  // bytes a node dedupes.
248
- lastError = Object.assign(
249
- new Error(`Execute response body read failed (status ${res.status}): ${bodyErr.message}`),
250
- { code: 'BROADCAST_FAILED', status: res.status }
251
- );
455
+ lastError = ambiguousBroadcast(`Execute response body read failed (status ${res.status}): ${bodyErr.message}`, { status: res.status });
252
456
  if (res.status >= 500 && attempt < retries) continue;
253
457
  throw lastError;
254
458
  }
@@ -285,32 +489,110 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
285
489
  ? ' This often means the transaction failed simulation — check that you have enough ETH for gas fees.'
286
490
  : ''
287
491
  : '';
288
- lastError = Object.assign(
289
- new Error(`Execute API returned ${res.status} — treating as an ambiguous broadcast failure; the transaction may already be live.${feeHint}`),
290
- { 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) }
291
495
  );
292
496
  // Retry (re-POSTs byte-identical bytes) then fail closed at the caller.
293
497
  if (attempt < retries) continue;
294
498
  throw lastError;
295
499
  }
296
500
 
297
- if (!parsed) {
298
- // Non-JSON on a sub-500 status (a Cloudflare challenge or HTML error
299
- // page). A clean sub-500 HTTP response is a definitive edge/backend
300
- // rejection, so it stays nonfatal and leaves the quote reusable.
301
- lastError = Object.assign(
302
- new Error(`Execute API returned non-JSON response (status ${res.status}). This may be a Cloudflare challenge or server error.`),
303
- { 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) }
304
521
  );
305
- throw lastError;
306
522
  }
307
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.
308
528
  if (!res.ok) {
309
- const code = body.code || 'EXECUTE_ERROR';
310
- const msg = body.message || `Execute request failed with status ${res.status}`;
311
- 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);
312
581
  }
313
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
+
314
596
  return body;
315
597
  }
316
598
  throw lastError;
@@ -571,12 +853,12 @@ function quoteClaimedError(quoteId, claimedPath) {
571
853
  * loaded it before another run executed it (for instance while waiting at the
572
854
  * confirmation prompt) sees that run's `executedAt` here, before signing.
573
855
  *
574
- * `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
575
857
  * transaction left this process, or when one did and `executedAt` was recorded
576
- * (loadQuote then refuses it with the broadcast hashes). A swap that was handed
577
- * off with no recorded marker leaves the quote claimed: a retry is refused
578
- * rather than risk a second broadcast, and the claim goes away with the quote
579
- * 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.
580
862
  *
581
863
  * @param {string} quoteId
582
864
  * @param {function} [readQuote] Validates the claimed quote, including its type.
@@ -1172,39 +1454,41 @@ export async function waitForReceipt(chain, txHash, timeoutMs = 180000, pollMs =
1172
1454
  if (receipt) {
1173
1455
  const status = parseInt(receipt.status, 16);
1174
1456
  if (status !== 1) {
1175
- 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;
1176
1460
  }
1177
1461
  return receipt;
1178
1462
  }
1179
1463
  } catch (e) {
1180
1464
  // Re-throw confirmed on-chain reverts immediately; swallow transient RPC/network errors
1181
- if (e.message?.startsWith('Transaction reverted')) throw e;
1465
+ if (e.code === 'TX_REVERTED') throw e;
1182
1466
  // else: continue polling (pending tx, transient network error, etc.)
1183
1467
  }
1184
1468
  // Receipt not yet available — wait and retry
1185
1469
  await new Promise(r => setTimeout(r, pollMs));
1186
1470
  }
1187
1471
  // A timeout is NOT a confirmed revert: the tx may still be pending under our
1188
- // nonce. Tag it so callers can distinguish "reverted" (safe to try the next
1189
- // quote) from "unconfirmed" (retrying may broadcast a second tx that races
1190
- // 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.
1191
1475
  const timeoutErr = new Error(`Transaction receipt not found after ${timeoutMs}ms. Tx: ${txHash}`);
1192
1476
  timeoutErr.code = 'RECEIPT_TIMEOUT';
1193
1477
  throw timeoutErr;
1194
1478
  }
1195
1479
 
1196
1480
  /**
1197
- * Post-broadcast failures that must abort the whole `execute` rather than fall
1198
- * through to the next quote. Once a transaction is broadcast we hold no evidence
1199
- * about what landed on-chain, so "try the next quote" would sign and broadcast a
1200
- * 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,
1201
1485
  * approval, revoke; Privy/WalletConnect/local-key). Each code is thrown with a
1202
1486
  * rationale at its throw site:
1203
1487
  * - TXHASH_MISMATCH — broadcaster reported a tx we did not sign
1204
1488
  * - INVALID_SIGNED_TX — we cannot even derive a hash for what we broadcast
1205
1489
  * - RECEIPT_TIMEOUT — receipt never landed; the tx may still be pending, so
1206
1490
  * retrying would race a second tx against the same nonce
1207
- * (a confirmed on-chain revert is NOT this — it may retry)
1491
+ * - TX_REVERTED — receipt confirmed failure; stop and require a new quote
1208
1492
  * - BROADCAST_FAILED — /execute returned an uninterpretable response (non-JSON,
1209
1493
  * typically a 502/503 after all retries) AFTER we POSTed
1210
1494
  * the signed tx. A dropped ack is indistinguishable from
@@ -1216,10 +1500,20 @@ export async function waitForReceipt(chain, txHash, timeoutMs = 180000, pollMs =
1216
1500
  * @returns {boolean}
1217
1501
  */
1218
1502
  function isFatalBroadcastError(err) {
1219
- 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'
1220
1509
  || err?.code === 'INVALID_SIGNED_TX'
1221
1510
  || err?.code === 'RECEIPT_TIMEOUT'
1222
- || 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';
1223
1517
  }
1224
1518
 
1225
1519
  /**
@@ -1358,7 +1652,7 @@ function toRpcHexValue(value) {
1358
1652
  * guards: the cheap eth_call sim answers "will it revert", this answers "does the
1359
1653
  * outcome match intent" (see assertSwapOutcome in trade-validation.js).
1360
1654
  *
1361
- * EVM-only, and on its own gate independent of --no-simulate/gasless. Runs for
1655
+ * EVM-only, and on its own gate independent of --no-simulate. Runs for
1362
1656
  * cross-chain bridges too — assertSwapOutcome skips only the output-arrival
1363
1657
  * assertion internally, since the output lands on the destination chain and a
1364
1658
  * source-chain simulation can't observe it; the input-outflow and no-sibling-
@@ -2307,7 +2601,6 @@ export async function buildTradeExecutionPlan({
2307
2601
  quoteIndex = 0,
2308
2602
  quoteCount = 1,
2309
2603
  walletAddress = null,
2310
- gasless = false,
2311
2604
  noSimulate = false,
2312
2605
  noVerifyOutcome = false,
2313
2606
  probe = false,
@@ -2352,8 +2645,6 @@ export async function buildTradeExecutionPlan({
2352
2645
  if (probe && chainConfig.type === 'evm') {
2353
2646
  if (noSimulate) {
2354
2647
  simulation = 'skipped (--no-simulate)';
2355
- } else if (gasless) {
2356
- simulation = 'skipped (--gasless routes through the solver)';
2357
2648
  } else if (approvalPending) {
2358
2649
  simulation = 'skipped — runs after the approval transaction lands';
2359
2650
  } else {
@@ -2387,7 +2678,6 @@ export async function buildTradeExecutionPlan({
2387
2678
  ['Trading fee', quote.tradingFeeInUsd ? `$${quote.tradingFeeInUsd}` : null],
2388
2679
  ['Network fee', quote.networkFeeInUsd ? `$${quote.networkFeeInUsd}` : null],
2389
2680
  ['Approval', approval],
2390
- ['Gas', gasless ? 'paid by the solver (--gasless)' : null],
2391
2681
  ['Simulation', simulation],
2392
2682
  ['Outcome check', noVerifyOutcome ? 'off (--no-verify-outcome)' : 'on, before broadcast'],
2393
2683
  ]);
@@ -2409,27 +2699,12 @@ async function preflightTradeExecutionCandidate({
2409
2699
  chain,
2410
2700
  chainConfig,
2411
2701
  walletAddress,
2412
- isWalletConnect,
2413
- gasless,
2414
2702
  noSimulate,
2415
2703
  noVerifyOutcome,
2416
2704
  api,
2417
2705
  verifiedTargets,
2418
2706
  log,
2419
2707
  }) {
2420
- if (gasless && quote.aggregator !== 'relay') {
2421
- throw new CommandError(
2422
- `--gasless is only supported for Relay quotes, not "${quote.aggregator}".`,
2423
- 'GASLESS_UNSUPPORTED_AGGREGATOR',
2424
- );
2425
- }
2426
- if (gasless && isWalletConnect) {
2427
- throw new CommandError(
2428
- 'Gasless swaps are not supported via WalletConnect. Use a local or Privy wallet.',
2429
- 'GASLESS_UNSUPPORTED_WALLET',
2430
- );
2431
- }
2432
-
2433
2708
  if (!walletAddress) {
2434
2709
  throw new CommandError(
2435
2710
  'The cached quote has no signer address, so it cannot be validated safely. Request a new quote.',
@@ -2531,7 +2806,7 @@ async function preflightTradeExecutionCandidate({
2531
2806
  // approval cannot reproduce that future state and reports the deferral in
2532
2807
  // its plan instead.
2533
2808
  if (!approvalPending) {
2534
- if (!noSimulate && !gasless) {
2809
+ if (!noSimulate) {
2535
2810
  const tx = quote.transaction;
2536
2811
  const sim = await simulateEvmCall(chain, {
2537
2812
  from: walletAddress,
@@ -3037,10 +3312,8 @@ CROSS-CHAIN NOTES (when using --to-chain):
3037
3312
  response.quotes.forEach((q, i) => log(formatQuote(q, i)));
3038
3313
 
3039
3314
  // Gas balance validation — check that the wallet has enough native token for gas.
3040
- // High-value trades (>= $10) can use gasless/solver-paid routes and bypass this check.
3041
3315
  try {
3042
- const tradeValueUsd = response.quotes[0]?.inUsdValue;
3043
- await validateGasBalance({ chain, walletAddress, tradeValueUsd });
3316
+ await validateGasBalance({ chain, walletAddress });
3044
3317
  } catch (gasErr) {
3045
3318
  throw new CommandError(`Error: ${gasErr.message}`, 'INSUFFICIENT_GAS');
3046
3319
  }
@@ -3103,7 +3376,18 @@ CROSS-CHAIN NOTES (when using --to-chain):
3103
3376
  const noSimulate = flags['no-simulate'];
3104
3377
  const noRevokeExcessiveAllowance = flags['no-revoke-excessive-allowance'];
3105
3378
  const noVerifyOutcome = flags['no-verify-outcome'];
3106
- const gasless = Boolean(flags.gasless);
3379
+ // --gasless is gone. The deprecated broadcast route it posted to validates
3380
+ // its body strictly and has never accepted `gasless` or `steps`, so every
3381
+ // gasless swap was rejected with "Unrecognized keys" before broadcast, on
3382
+ // every chain. Rejected loudly rather than ignored: a script that still
3383
+ // passes it asked the solver to pay, and silently paying its own gas
3384
+ // instead is not a substitution we should make for it.
3385
+ if (flags.gasless) {
3386
+ throw new CommandError(
3387
+ '--gasless has been removed: the backend never accepted gasless swaps from the CLI, so the flag failed before broadcast on every chain. Re-run without it — the wallet pays its own gas.',
3388
+ 'GASLESS_REMOVED',
3389
+ );
3390
+ }
3107
3391
  // Parsed before the quote is touched so a typo can't consume it. A bare
3108
3392
  // --max-tx-fee lands in flags, not options, so it would otherwise read as
3109
3393
  // "not given" and silently apply the default cap.
@@ -3127,7 +3411,6 @@ OPTIONS:
3127
3411
  --no-verify-outcome Skip swap-outcome verification (balance-delta check)
3128
3412
  --no-revoke-excessive-allowance
3129
3413
  Skip auto-revoking an oversized/legacy allowance before re-approving
3130
- --gasless Relay-only: have Relay's solver pay gas (no WalletConnect)
3131
3414
  --max-tx-fee <eth> Most one transaction may pay for gas (fee cap x gas limit).
3132
3415
  Default 1 ETH; 0 disables the check.
3133
3416
  --dry-run Validate and print what would be sent, then stop.
@@ -3148,9 +3431,18 @@ EXAMPLES:
3148
3431
 
3149
3432
  let quoteClaim = null;
3150
3433
  // Set just before the swap transaction leaves this process (the Trading
3151
- // API broadcast, or a WalletConnect wallet that may broadcast it), so the
3152
- // claim is only handed back when no swap can be in flight.
3434
+ // API broadcast, or a WalletConnect wallet that may broadcast it).
3153
3435
  let swapHandedOff = false;
3436
+ // Approval and allowance-revoke transactions can leave before the swap.
3437
+ // Keep this sticky once any such broadcast is acknowledged: if receipt,
3438
+ // hash, or allowance verification later fails, the cached quote must not
3439
+ // become reusable while the wallet's allowance state is unknown.
3440
+ let ancillaryHandedOff = false;
3441
+ // Sticky across candidates: set once any attempt ends without the backend
3442
+ // telling us whether it broadcast. An explicit "failed, no hash" response
3443
+ // clears swapHandedOff for its own attempt, but it says nothing about an
3444
+ // earlier attempt that threw mid-POST — so that one has to keep the claim.
3445
+ let handoffAmbiguous = false;
3154
3446
  try {
3155
3447
  const quoteData = loadQuote(quoteId);
3156
3448
  // The quote command stores the chain exactly as the user typed it
@@ -3164,6 +3456,35 @@ EXAMPLES:
3164
3456
  const chainConfig = resolveChain(chain);
3165
3457
  const chainType = chainConfig.type;
3166
3458
 
3459
+
3460
+ // One correlation id per execute invocation, reused across the swap POST
3461
+ // and its internal retries so the backend can tie an execution to a single
3462
+ // user attempt rather than counting each retry as a new one.
3463
+ const attemptId = crypto.randomUUID();
3464
+ // Resolved once here, before any signing, so an unrecognised route value
3465
+ // aborts the command instead of surfacing mid-loop as a per-quote failure.
3466
+ const configuredRoute = executionRoute();
3467
+ // Named apart from configuredRoute because the WalletConnect branch —
3468
+ // which may never reach the broadcast call — also has to know which route
3469
+ // is in force.
3470
+ const swapRoute = configuredRoute;
3471
+
3472
+ // The standard route keys its per-quote single-flight lock on the backend
3473
+ // quote id, so a submission without one claims duplicate protection and
3474
+ // has none. Every live /quote response carries
3475
+ // response.metadata.quoteId, so reaching this is shape drift or a
3476
+ // hand-edited quote file, never a routine swap — the cost of stopping is
3477
+ // a re-quote, the cost of proceeding is an unprotected broadcast, and the
3478
+ // local claim is per-machine and does not replace it. Checked here, with
3479
+ // the route itself, so it refuses before anything is signed instead of
3480
+ // surfacing mid-loop as a per-candidate failure.
3481
+ const backendQuoteId = quoteData.response?.metadata?.quoteId;
3482
+ if (swapRoute === 'standard' && !backendQuoteId) {
3483
+ throw new CommandError(
3484
+ `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.`,
3485
+ 'MISSING_QUOTE_ID',
3486
+ );
3487
+ }
3167
3488
  const allQuotes = quoteData.response.quotes || [];
3168
3489
  if (!allQuotes.length) {
3169
3490
  throw new CommandError('❌ No quote data found', 'NO_QUOTES');
@@ -3202,8 +3523,6 @@ EXAMPLES:
3202
3523
  .map((quote, index) => ({ quote, index }))
3203
3524
  .filter(({ quote, index }) => index >= startIndex && index < endIndex && quote?.transaction);
3204
3525
  const shouldPreflightPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
3205
- const planUsesWalletConnect = quoteData.signerType === 'walletconnect'
3206
- || walletName === 'walletconnect' || walletName === 'wc';
3207
3526
  if (guard.dryRun) {
3208
3527
  // The live signer is intentionally unavailable here: dry-run reaches
3209
3528
  // this gate before wallet material or a WalletConnect session is
@@ -3239,8 +3558,6 @@ EXAMPLES:
3239
3558
  chain,
3240
3559
  chainConfig,
3241
3560
  walletAddress: planWallet,
3242
- isWalletConnect: planUsesWalletConnect,
3243
- gasless,
3244
3561
  noSimulate,
3245
3562
  noVerifyOutcome,
3246
3563
  api: apiInstance,
@@ -3279,7 +3596,6 @@ EXAMPLES:
3279
3596
  quoteIndex: index,
3280
3597
  quoteCount: allQuotes.length,
3281
3598
  walletAddress: planWallet,
3282
- gasless,
3283
3599
  noSimulate,
3284
3600
  noVerifyOutcome,
3285
3601
  probe: true,
@@ -3435,20 +3751,6 @@ EXAMPLES:
3435
3751
  }
3436
3752
 
3437
3753
  const isRelay = currentQuote.aggregator === 'relay';
3438
- if (gasless) {
3439
- if (!isRelay) {
3440
- throw new CommandError(
3441
- `--gasless is only supported for Relay quotes. Selected quote ${quoteName} is from "${currentQuote.aggregator}". Re-run with --quote-index to pin a Relay quote, or omit --gasless.`,
3442
- 'GASLESS_UNSUPPORTED_AGGREGATOR'
3443
- );
3444
- }
3445
- if (isWalletConnect) {
3446
- throw new CommandError(
3447
- 'Gasless swaps are not supported via WalletConnect (mobile wallets typically auto-broadcast, breaking the gasless flow). Use a local or Privy wallet.',
3448
- 'GASLESS_UNSUPPORTED_WALLET'
3449
- );
3450
- }
3451
- }
3452
3754
 
3453
3755
  log(`\nExecuting trade on ${chainConfig.name}...`);
3454
3756
  if (endIndex - startIndex > 1) {
@@ -3460,6 +3762,10 @@ EXAMPLES:
3460
3762
  try {
3461
3763
  let signedTransaction;
3462
3764
  let requestId;
3765
+ // The signer address, hoisted out of the per-signer branches below so
3766
+ // the shared broadcast can send it as the standard-route attribution
3767
+ // field (the branch-local address vars are out of scope there).
3768
+ let swapWalletAddress;
3463
3769
 
3464
3770
  if (chainType === 'solana' && isPrivy) {
3465
3771
  // Solana via Privy: sign the serialized transaction
@@ -3467,6 +3773,7 @@ EXAMPLES:
3467
3773
  if (!solWalletId) throw new Error('No Solana Privy wallet ID in quote');
3468
3774
  const walletResult = await privyClient.getWallet(solWalletId);
3469
3775
  const walletAddress = walletResult.address;
3776
+ swapWalletAddress = walletAddress;
3470
3777
  // Fail closed if the signer address doesn't resolve: without it the
3471
3778
  // wallet-binding comparison below would silently skip, leaving the
3472
3779
  // quote unbound to the wallet that will sign it. This is resolved
@@ -3518,6 +3825,7 @@ EXAMPLES:
3518
3825
 
3519
3826
  const walletResult = await privyClient.getWallet(evmWalletId);
3520
3827
  const walletAddress = walletResult.address;
3828
+ swapWalletAddress = walletAddress;
3521
3829
 
3522
3830
  // Guard the swap target before any RPC call, approval, or signing —
3523
3831
  // whatever `to`/`data` the quote supplied gets signed verbatim.
@@ -3625,11 +3933,17 @@ EXAMPLES:
3625
3933
  }
3626
3934
  const revokeResult = await executeTransaction({ signedTransaction: signedRevoke, chain, simulate: !noSimulate });
3627
3935
  if (revokeResult.status !== 'Success') {
3936
+ const handedOffFailure = hashBearingFailure(revokeResult, `Allowance revoke for ${quoteName}`, 'evm');
3937
+ if (handedOffFailure) {
3938
+ ancillaryHandedOff = true;
3939
+ throw handedOffFailure;
3940
+ }
3628
3941
  log(` ❌ Allowance revoke failed for ${quoteName}: ${revokeResult.error || 'unknown'}`);
3629
3942
  if (qi + 1 < endIndex) log(` Trying next quote...`);
3630
3943
  lastQuoteError = `${quoteName} allowance revoke failed`;
3631
3944
  continue;
3632
3945
  }
3946
+ ancillaryHandedOff = true;
3633
3947
  log(` Waiting for allowance revoke confirmation...`);
3634
3948
  try {
3635
3949
  const { receipt, hash: revokeHash } = await confirmEvmBroadcast(chain, signedRevoke, revokeResult.txHash, 'allowance-revoke');
@@ -3644,10 +3958,7 @@ EXAMPLES:
3644
3958
  try {
3645
3959
  await assertAllowanceRevoked(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress);
3646
3960
  } catch (pollErr) {
3647
- log(` ❌ Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeResult.txHash)}`);
3648
- if (qi + 1 < endIndex) log(` Trying next quote...`);
3649
- lastQuoteError = `${quoteName} allowance revoke verification failed`;
3650
- continue;
3961
+ 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.`);
3651
3962
  }
3652
3963
  await waitForAllowanceTxPropagation();
3653
3964
  }
@@ -3681,6 +3992,11 @@ EXAMPLES:
3681
3992
  }
3682
3993
  const approvalResult = await executeTransaction({ signedTransaction: signedApproval, chain, simulate: !noSimulate });
3683
3994
  if (approvalResult.status !== 'Success') {
3995
+ const handedOffFailure = hashBearingFailure(approvalResult, `Approval for ${quoteName}`, 'evm');
3996
+ if (handedOffFailure) {
3997
+ ancillaryHandedOff = true;
3998
+ throw handedOffFailure;
3999
+ }
3684
4000
  const revokedMsg = shouldRevoke
3685
4001
  ? ' after revoking the prior allowance (now 0)'
3686
4002
  : '';
@@ -3689,6 +4005,7 @@ EXAMPLES:
3689
4005
  lastQuoteError = `${quoteName} approval failed`;
3690
4006
  continue;
3691
4007
  }
4008
+ ancillaryHandedOff = true;
3692
4009
  log(` Waiting for approval confirmation...`);
3693
4010
  try {
3694
4011
  const { receipt, hash: approvalHash } = await confirmEvmBroadcast(chain, signedApproval, approvalResult.txHash, 'allowance-approval');
@@ -3703,17 +4020,14 @@ EXAMPLES:
3703
4020
  try {
3704
4021
  await assertAllowanceAtLeast(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress, approveAmt);
3705
4022
  } catch (pollErr) {
3706
- log(` ❌ Approval tx confirmed but allowance did not reach the required amount for ${quoteName}${shouldRevoke ? ' after revoking the prior allowance (now 0)' : ''}: ${pollErr.message}`);
3707
- if (qi + 1 < endIndex) log(` Trying next quote...`);
3708
- lastQuoteError = `${quoteName} approval verification failed`;
3709
- continue;
4023
+ 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.`);
3710
4024
  }
3711
4025
  await waitForAllowanceTxPropagation();
3712
4026
  }
3713
4027
  }
3714
4028
 
3715
4029
  // Pre-flight simulation
3716
- if (!noSimulate && !gasless) {
4030
+ if (!noSimulate) {
3717
4031
  const sim = await simulateEvmCall(chain, {
3718
4032
  from: walletAddress,
3719
4033
  to: currentQuote.transaction.to,
@@ -3729,8 +4043,8 @@ EXAMPLES:
3729
4043
  }
3730
4044
 
3731
4045
  // Verify the swap's simulated on-chain outcome matches intent.
3732
- // Its own gate (runs even when --no-simulate/gasless skip the
3733
- // cheap revert check above); degrades with a warning if no
4046
+ // Its own gate (runs even when --no-simulate skips the cheap
4047
+ // revert check above); degrades with a warning if no
3734
4048
  // simulation endpoint is available.
3735
4049
  if (!noVerifyOutcome) {
3736
4050
  const outcome = await verifySwapOutcome({ chain, from: walletAddress, quote: currentQuote, quoteData, api: apiInstance, log });
@@ -3796,6 +4110,7 @@ EXAMPLES:
3796
4110
  throw new Error("Could not resolve the local wallet's Solana address; cannot confirm the quote was built for this wallet. Refusing to sign.");
3797
4111
  }
3798
4112
  }
4113
+ swapWalletAddress = solanaWalletAddress;
3799
4114
 
3800
4115
  const txBase64 = await normalizeSolanaTransaction(currentQuote.transaction, CHAIN_RPCS.solana, async () => solanaWalletAddress);
3801
4116
 
@@ -3890,6 +4205,7 @@ EXAMPLES:
3890
4205
  if (!wcAddress) {
3891
4206
  throw new CommandError('No WalletConnect session for this chain. Reconnect with `walletconnect connect` and retry.', 'NO_WALLET');
3892
4207
  }
4208
+ swapWalletAddress = wcAddress;
3893
4209
  const isNative = isNativeToken(currentQuote.inputMint);
3894
4210
 
3895
4211
  // Guard the swap target before any RPC call, approval, or signing —
@@ -3980,6 +4296,7 @@ EXAMPLES:
3980
4296
  { allowZero: true },
3981
4297
  );
3982
4298
  revokeTxHash = revokeResult.txHash;
4299
+ if (revokeTxHash) ancillaryHandedOff = true;
3983
4300
  if (!revokeTxHash && revokeResult.signedTransaction) {
3984
4301
  log(` Broadcasting allowance revocation via Trading API...`);
3985
4302
  const broadcastResult = await executeTransaction({
@@ -3988,14 +4305,28 @@ EXAMPLES:
3988
4305
  simulate: !noSimulate,
3989
4306
  });
3990
4307
  if (broadcastResult.status !== 'Success') {
4308
+ const handedOffFailure = hashBearingFailure(broadcastResult, `Allowance revoke for ${quoteName}`, 'evm');
4309
+ if (handedOffFailure) {
4310
+ ancillaryHandedOff = true;
4311
+ throw handedOffFailure;
4312
+ }
3991
4313
  throw new Error(broadcastResult.error || 'broadcast failed');
3992
4314
  }
4315
+ ancillaryHandedOff = true;
3993
4316
  revokeTxHash = assertTxHashMatch(revokeResult.signedTransaction, broadcastResult.txHash, 'allowance-revoke');
3994
4317
  }
3995
4318
  if (!revokeTxHash) {
3996
4319
  throw new Error('Allowance revoke returned no transaction hash and no signed transaction; cannot confirm allowance was cleared');
3997
4320
  }
3998
4321
  } catch (revokeErr) {
4322
+ // A revoke the wallet may already have broadcast must not
4323
+ // fall through: the next candidate would prompt for and
4324
+ // send a swap while this one is still in flight, against an
4325
+ // allowance whose real value is unknown. Re-raise with the
4326
+ // recovery hint the log line below would have carried.
4327
+ if (revokeErr?.broadcastAmbiguous) {
4328
+ throw ambiguousBroadcast(`Allowance revoke for ${quoteName} failed after the wallet was asked to send: ${revokeErr.message}. The revoke may still be live.${allowanceRevokeRecoveryHint(revokeTxHash)}`);
4329
+ }
3999
4330
  if (isFatalBroadcastError(revokeErr)) throw revokeErr;
4000
4331
  log(` ❌ Allowance revoke failed for ${quoteName}: ${revokeErr.message}.${allowanceRevokeRecoveryHint(revokeTxHash)}`);
4001
4332
  if (qi + 1 < endIndex) log(` Trying next quote...`);
@@ -4016,10 +4347,7 @@ EXAMPLES:
4016
4347
  try {
4017
4348
  await assertAllowanceRevoked(chain, currentQuote.inputMint, wcAddress, currentQuote.approvalAddress);
4018
4349
  } catch (pollErr) {
4019
- log(` ❌ Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeTxHash)}`);
4020
- if (qi + 1 < endIndex) log(` Trying next quote...`);
4021
- lastQuoteError = `${quoteName} allowance revoke verification failed`;
4022
- continue;
4350
+ throw ambiguousBroadcast(`Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeTxHash)} Request a fresh quote after verifying the allowance.`);
4023
4351
  }
4024
4352
  await waitForAllowanceTxPropagation();
4025
4353
  }
@@ -4035,6 +4363,7 @@ EXAMPLES:
4035
4363
  approvalCapForQuote(quoteData),
4036
4364
  );
4037
4365
  approvalTxHash = approvalResult.txHash;
4366
+ if (approvalTxHash) ancillaryHandedOff = true;
4038
4367
  if (!approvalTxHash && approvalResult.signedTransaction) {
4039
4368
  // Wallet returned a signed tx instead of broadcasting — broadcast via Trading API
4040
4369
  log(` Broadcasting approval via Trading API...`);
@@ -4044,8 +4373,14 @@ EXAMPLES:
4044
4373
  simulate: !noSimulate,
4045
4374
  });
4046
4375
  if (broadcastResult.status !== 'Success') {
4376
+ const handedOffFailure = hashBearingFailure(broadcastResult, `Approval for ${quoteName}`, 'evm');
4377
+ if (handedOffFailure) {
4378
+ ancillaryHandedOff = true;
4379
+ throw handedOffFailure;
4380
+ }
4047
4381
  throw new Error(broadcastResult.error || 'broadcast failed');
4048
4382
  }
4383
+ ancillaryHandedOff = true;
4049
4384
  approvalTxHash = assertTxHashMatch(approvalResult.signedTransaction, broadcastResult.txHash, 'allowance-approval');
4050
4385
  }
4051
4386
  if (!approvalTxHash) {
@@ -4057,10 +4392,17 @@ EXAMPLES:
4057
4392
  throw new Error('returned no transaction hash and no signed transaction; cannot confirm approval landed');
4058
4393
  }
4059
4394
  } catch (approvalErr) {
4060
- if (isFatalBroadcastError(approvalErr)) throw approvalErr;
4061
4395
  const revokedMsg = shouldRevoke
4062
4396
  ? ' after revoking the prior allowance (now 0)'
4063
4397
  : '';
4398
+ // Same as the revoke above: an approval the wallet may have
4399
+ // broadcast leaves the allowance unknown, so ending here is
4400
+ // the only answer that cannot double-send. The revoked note
4401
+ // matters most on this path — the prior allowance is already 0.
4402
+ if (approvalErr?.broadcastAmbiguous) {
4403
+ 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.`);
4404
+ }
4405
+ if (isFatalBroadcastError(approvalErr)) throw approvalErr;
4064
4406
  log(` ❌ Approval failed for ${quoteName}${revokedMsg}: ${approvalErr.message}`);
4065
4407
  if (qi + 1 < endIndex) log(` Trying next quote...`);
4066
4408
  lastQuoteError = `${quoteName} approval failed`;
@@ -4086,10 +4428,7 @@ EXAMPLES:
4086
4428
  const revokedMsg = shouldRevoke
4087
4429
  ? ' after revoking the prior allowance (now 0)'
4088
4430
  : '';
4089
- log(` ❌ Approval tx confirmed but allowance did not reach the required amount for ${quoteName}${revokedMsg}: ${pollErr.message}`);
4090
- if (qi + 1 < endIndex) log(` Trying next quote...`);
4091
- lastQuoteError = `${quoteName} approval verification failed`;
4092
- continue;
4431
+ 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.`);
4093
4432
  }
4094
4433
  await waitForAllowanceTxPropagation();
4095
4434
  log('');
@@ -4097,7 +4436,7 @@ EXAMPLES:
4097
4436
  }
4098
4437
 
4099
4438
  // Pre-flight simulation
4100
- if (!noSimulate && !gasless) {
4439
+ if (!noSimulate) {
4101
4440
  const txData = currentQuote.transaction;
4102
4441
  const sim = await simulateEvmCall(chain, {
4103
4442
  from: wcAddress,
@@ -4114,8 +4453,8 @@ EXAMPLES:
4114
4453
  }
4115
4454
 
4116
4455
  // Verify the swap's simulated on-chain outcome matches intent. Its
4117
- // own gate: runs even when --no-simulate/gasless skip the cheap
4118
- // eth_call revert check above; degrades with a warning when no
4456
+ // own gate: runs even when --no-simulate skips the cheap eth_call
4457
+ // revert check above; degrades with a warning when no
4119
4458
  // simulation endpoint is set.
4120
4459
  if (!noVerifyOutcome) {
4121
4460
  const outcome = await verifySwapOutcome({ chain, from: wcAddress, quote: currentQuote, quoteData, api: apiInstance, log });
@@ -4144,10 +4483,17 @@ EXAMPLES:
4144
4483
  chainId: chainConfig.chainId,
4145
4484
  });
4146
4485
  } catch (wcErr) {
4147
- log(` ❌ WalletConnect transaction failed for ${quoteName}: ${wcErr.message}`);
4148
- if (qi + 1 < endIndex) log(` Trying next quote...`);
4149
- lastQuoteError = `${quoteName}: ${wcErr.message}`;
4150
- continue;
4486
+ // The wallet was already asked to send, and wcExec rejects with a
4487
+ // bare Error(err.message) for EVERY failure — a user rejection, a
4488
+ // 120s approval timeout and a spawn failure are indistinguishable
4489
+ // here. A timeout in particular is the case where the user DID
4490
+ // approve and the wallet DID broadcast while our subprocess gave
4491
+ // up waiting. So this cannot be read as "nothing was sent": it is
4492
+ // ambiguous, and must fail closed rather than sign the next quote
4493
+ // on top of a possibly-live transaction. (This catch used to
4494
+ // `continue`, which bypassed the loop's whole fail-closed path
4495
+ // below — it never reached `catch (quoteErr)`.)
4496
+ throw ambiguousBroadcast(`WalletConnect transaction failed for ${quoteName}: ${wcErr.message} — the wallet may still have broadcast it; check the explorer before retrying.`);
4151
4497
  }
4152
4498
 
4153
4499
  if (wcResult.txHash) {
@@ -4157,6 +4503,18 @@ EXAMPLES:
4157
4503
  // executeTransaction() marker further down.
4158
4504
  markQuoteExecuted(quoteId, { broadcast: { txHash: wcResult.txHash } });
4159
4505
 
4506
+ // Say it out loud when the selected route was bypassed. A wallet
4507
+ // that broadcasts for us hands back a hash instead of signed bytes,
4508
+ // so there is nothing to POST and the swap never reaches
4509
+ // /execution/standard — no server-side outcome tracking for this
4510
+ // trade. Silence here is the staged-rollout failure mode
4511
+ // executionRoute() already guards against at the other end: you
4512
+ // believe you exercised the new route and you did not.
4513
+ if (swapRoute === 'standard') {
4514
+ log(' Note: the wallet broadcast this swap itself, so the standard');
4515
+ log(' execution route was bypassed (no server-side tracking).');
4516
+ }
4517
+
4160
4518
  // Wallet broadcast — verify on-chain
4161
4519
  log(' Verifying on-chain status...');
4162
4520
  try {
@@ -4169,17 +4527,11 @@ EXAMPLES:
4169
4527
  if (receiptErr.code === 'RECEIPT_TIMEOUT') {
4170
4528
  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');
4171
4529
  }
4172
- if (isFatalBroadcastError(receiptErr)) throw receiptErr;
4173
- log(`\n ⚠ Transaction was broadcast but REVERTED on-chain!`);
4174
- log(` Tx Hash: ${wcResult.txHash}`);
4175
- log(` Explorer: ${chainConfig.explorer}${wcResult.txHash}`);
4176
- log(` Error: ${receiptErr.message}`);
4177
- if (qi + 1 < endIndex) {
4178
- log(` Trying next quote...`);
4179
- lastQuoteError = `${quoteName} reverted on-chain`;
4180
- continue;
4530
+ if (receiptErr.code === 'TX_REVERTED') {
4531
+ 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');
4181
4532
  }
4182
- 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');
4533
+ if (isFatalBroadcastError(receiptErr)) throw receiptErr;
4534
+ throw receiptErr;
4183
4535
  }
4184
4536
 
4185
4537
  log(`\n ✓ Transaction successful!`);
@@ -4218,12 +4570,30 @@ EXAMPLES:
4218
4570
  return undefined; // Success
4219
4571
  }
4220
4572
 
4221
- // Wallet returned signedTransaction — fall through to broadcast via Trading API
4573
+ // Wallet returned signedTransaction — fall through to broadcast via
4574
+ // Trading API.
4575
+ //
4576
+ // Guarded even though it cannot fire today:
4577
+ // sendTransactionViaWalletConnect throws rather than resolving without
4578
+ // one of txHash/signedTransaction, so every reachable shape is handled
4579
+ // above. That invariant lives in another module, though, and the failure
4580
+ // mode if it ever relaxes to a bare return is the worst one here — an
4581
+ // undefined payload POSTs a malformed body and could hide a wallet
4582
+ // broadcast behind the resulting API error. BROADCAST_FAILED is
4583
+ // classified fatal, so the candidate catch rethrows it and the quote
4584
+ // stays claimed instead of prompting for the next candidate.
4585
+ if (!wcResult.signedTransaction) {
4586
+ throw new CommandError(
4587
+ `\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.`,
4588
+ 'BROADCAST_FAILED',
4589
+ );
4590
+ }
4222
4591
  signedTransaction = wcResult.signedTransaction;
4223
4592
 
4224
4593
  } else {
4225
4594
  // EVM: quote.transaction is { to, data, value, gas, gasPrice }
4226
4595
  const walletAddress = exported.evm.address;
4596
+ swapWalletAddress = walletAddress;
4227
4597
 
4228
4598
  // Guard the swap target before any RPC call, approval, or signing —
4229
4599
  // whatever `to`/`data` the quote supplied gets signed verbatim, so
@@ -4336,11 +4706,17 @@ EXAMPLES:
4336
4706
  });
4337
4707
 
4338
4708
  if (revokeResult.status !== 'Success') {
4709
+ const handedOffFailure = hashBearingFailure(revokeResult, `Allowance revoke for ${quoteName}`, 'evm');
4710
+ if (handedOffFailure) {
4711
+ ancillaryHandedOff = true;
4712
+ throw handedOffFailure;
4713
+ }
4339
4714
  log(` ❌ Allowance revoke failed for ${quoteName}: ${revokeResult.error || 'unknown error'}`);
4340
4715
  if (qi + 1 < endIndex) log(` Trying next quote...`);
4341
4716
  lastQuoteError = `${quoteName} allowance revoke failed`;
4342
4717
  continue;
4343
4718
  }
4719
+ ancillaryHandedOff = true;
4344
4720
 
4345
4721
  log(` Waiting for allowance revoke confirmation...`);
4346
4722
  try {
@@ -4356,10 +4732,7 @@ EXAMPLES:
4356
4732
  try {
4357
4733
  await assertAllowanceRevoked(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress);
4358
4734
  } catch (pollErr) {
4359
- log(` ❌ Revoke tx confirmed but allowance was not cleared for ${quoteName}: ${pollErr.message}.${allowanceRevokeRecoveryHint(revokeResult.txHash)}`);
4360
- if (qi + 1 < endIndex) log(` Trying next quote...`);
4361
- lastQuoteError = `${quoteName} allowance revoke verification failed`;
4362
- continue;
4735
+ 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.`);
4363
4736
  }
4364
4737
  await waitForAllowanceTxPropagation();
4365
4738
  }
@@ -4386,6 +4759,11 @@ EXAMPLES:
4386
4759
  });
4387
4760
 
4388
4761
  if (approvalResult.status !== 'Success') {
4762
+ const handedOffFailure = hashBearingFailure(approvalResult, `Approval for ${quoteName}`, 'evm');
4763
+ if (handedOffFailure) {
4764
+ ancillaryHandedOff = true;
4765
+ throw handedOffFailure;
4766
+ }
4389
4767
  const revokedMsg = shouldRevoke
4390
4768
  ? ' after revoking the prior allowance (now 0)'
4391
4769
  : '';
@@ -4394,6 +4772,7 @@ EXAMPLES:
4394
4772
  lastQuoteError = `${quoteName} approval failed`;
4395
4773
  continue;
4396
4774
  }
4775
+ ancillaryHandedOff = true;
4397
4776
 
4398
4777
  log(` Waiting for approval confirmation...`);
4399
4778
  try {
@@ -4409,10 +4788,7 @@ EXAMPLES:
4409
4788
  try {
4410
4789
  await assertAllowanceAtLeast(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress, approveAmt);
4411
4790
  } catch (pollErr) {
4412
- log(` ❌ Approval tx confirmed but allowance did not reach the required amount for ${quoteName}${shouldRevoke ? ' after revoking the prior allowance (now 0)' : ''}: ${pollErr.message}`);
4413
- if (qi + 1 < endIndex) log(` Trying next quote...`);
4414
- lastQuoteError = `${quoteName} approval verification failed`;
4415
- continue;
4791
+ 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.`);
4416
4792
  }
4417
4793
  await waitForAllowanceTxPropagation();
4418
4794
  log('');
@@ -4422,7 +4798,7 @@ EXAMPLES:
4422
4798
  // Pre-flight simulation (EVM only) — catch logic reverts before spending gas
4423
4799
  // Runs AFTER approval so eth_call sees the current allowance state
4424
4800
  // Simulates WITHOUT gas limit to check swap logic; gas re-estimation is separate
4425
- if (!noSimulate && !gasless) {
4801
+ if (!noSimulate) {
4426
4802
  const txData = currentQuote.transaction;
4427
4803
  const sim = await simulateEvmCall(chain, {
4428
4804
  from: walletAddress,
@@ -4439,8 +4815,8 @@ EXAMPLES:
4439
4815
  }
4440
4816
 
4441
4817
  // Verify the swap's simulated on-chain outcome matches intent. Its
4442
- // own gate: runs even when --no-simulate/gasless skip the cheap
4443
- // eth_call revert check above; degrades with a warning when no
4818
+ // own gate: runs even when --no-simulate skips the cheap eth_call
4819
+ // revert check above; degrades with a warning when no
4444
4820
  // simulation endpoint is set.
4445
4821
  if (!noVerifyOutcome) {
4446
4822
  const outcome = await verifySwapOutcome({ chain, from: walletAddress, quote: currentQuote, quoteData, api: apiInstance, log });
@@ -4471,22 +4847,28 @@ EXAMPLES:
4471
4847
  );
4472
4848
  }
4473
4849
 
4474
- log(gasless ? ' Forwarding to Relay solver (gasless)...' : ' Broadcasting...');
4850
+ log(' Broadcasting...');
4475
4851
  const execParams = {
4476
4852
  signedTransaction,
4477
4853
  chain,
4478
- simulate: !noSimulate && !gasless,
4854
+ simulate: !noSimulate,
4479
4855
  };
4480
4856
 
4481
- // Prefer the backend quote id saved from /quote; per-aggregator ids can
4482
- // appear on individual quote metadata and are only a fallback.
4483
- const backendQuoteId =
4484
- quoteData.response?.metadata?.quoteId ?? currentQuote.metadata?.quoteId;
4485
- if (backendQuoteId) {
4486
- execParams.quoteId = backendQuoteId;
4857
+ // The backend quote id, resolved with the route above. The per-quote
4858
+ // fallback here is reachable on the legacy route only, because the
4859
+ // standard route already refused the no-backend-id case before any
4860
+ // signing. That split is deliberate: a per-quote id is minted by the
4861
+ // AGGREGATOR, not the backend (LiFi returns '<uuid>:<index>'), so it
4862
+ // is a different identifier in a different namespace. It is fine as a
4863
+ // correlation hint, and wrong as the key the standard route's
4864
+ // single-flight lock is held on — that request would look
4865
+ // idempotency-protected and would not be.
4866
+ const quoteIdForExecute = backendQuoteId ?? currentQuote.metadata?.quoteId;
4867
+ if (quoteIdForExecute) {
4868
+ execParams.quoteId = quoteIdForExecute;
4487
4869
  }
4488
- // The backend's /execute schema is strict; sending fields it doesn't expect
4489
- // for the (chain × aggregator × gasless) combination causes 502s or
4870
+ // The backend's /execute schema is strict; sending fields it doesn't
4871
+ // expect for the (chain × aggregator) combination causes 502s or
4490
4872
  // "Unrecognized keys" rejections. The matrix we've validated against the
4491
4873
  // live backend:
4492
4874
  // - EVM signed (any aggregator): no aggregator/requestId fields.
@@ -4495,78 +4877,113 @@ EXAMPLES:
4495
4877
  // intent resolution.
4496
4878
  // - Solana signed (Relay): omit requestId — backend tries to look it up
4497
4879
  // as a Jupiter intent and 502s.
4498
- // - Gasless (EVM): aggregator + gasless + steps + requestId.
4499
- // - Gasless (Solana): currently rejected by the backend ("Unrecognized
4500
- // keys"); we still send the gasless envelope and let the backend
4501
- // surface the error so users notice when support lands.
4502
- if (gasless) {
4503
- execParams.aggregator = 'relay';
4504
- execParams.gasless = true;
4505
- const gaslessRequestId = requestId || currentQuote.metadata?.requestId;
4506
- if (gaslessRequestId) execParams.requestId = gaslessRequestId;
4507
- if (currentQuote.metadata?.steps) execParams.steps = currentQuote.metadata.steps;
4508
- } else if (requestId && !isRelay) {
4880
+ if (requestId && !isRelay) {
4509
4881
  execParams.requestId = requestId; // Solana Jupiter Ultra
4510
4882
  }
4511
4883
 
4512
- // A retry re-POSTs the signed payload. For a normal swap that's a
4513
- // byte-identical replay the node dedupes, so retrying an ambiguous
4514
- // 5xx/network failure can't itself double-broadcast. But a --gasless
4515
- // Relay swap sends a signed AUTHORIZATION, and Relay's solver
4516
- // broadcasts its OWN wrapping tx from it (the returned txHash is not
4517
- // our bytes) — so a re-POST after the solver already picked it up
4518
- // can't be deduped at the node level and risks a second solve. For
4519
- // gasless we therefore don't retry: a single POST either succeeds or
4520
- // fails closed (BROADCAST_FAILED marks the quote spent and aborts).
4884
+ // A retry re-POSTs the signed payload. Every remaining execution mode
4885
+ // sends our own signed bytes, so that is a byte-identical replay the
4886
+ // node dedupes: retrying an ambiguous 5xx/network failure cannot itself
4887
+ // double-broadcast.
4888
+ if (swapRoute === 'standard') {
4889
+ // Attribution and cross-chain fields the standard route reads from
4890
+ // the body. Attached only here because the legacy schema rejects
4891
+ // some of them (an aggregator on an EVM swap in particular).
4892
+ if (swapWalletAddress) execParams.walletAddress = swapWalletAddress;
4893
+ if (currentQuote.aggregator) execParams.aggregator = currentQuote.aggregator;
4894
+ if (quoteData.toChain && quoteData.toChain !== quoteData.chain) {
4895
+ execParams.isCrossChain = true;
4896
+ execParams.toChain = quoteData.toChain;
4897
+ }
4898
+ }
4899
+
4521
4900
  swapHandedOff = true;
4522
- const result = await executeTransaction(execParams, { retries: gasless ? 0 : undefined });
4901
+ const result = await executeTransaction(execParams, { route: swapRoute, attemptId });
4523
4902
 
4524
4903
  if (result.status === 'Success') {
4525
- let txId = result.signature || result.txHash;
4904
+ // `signature` is a Solana field. Reading it on EVM let a stray one
4905
+ // win over the real `txHash` and reach the explorer URL and the
4906
+ // persisted broadcast marker; executeTransaction has already
4907
+ // validated the shape of whichever field is used here.
4908
+ let txId = chainType === 'evm' ? result.txHash : (result.signature || result.txHash);
4909
+ if (chainType === 'solana' && !txId) {
4910
+ throw ambiguousBroadcast(
4911
+ `The execute API reported success for ${quoteName} without a Solana transaction identifier. The broadcast cannot be verified, so no further quote will be tried. Check the wallet on the explorer before retrying.`,
4912
+ { details: result },
4913
+ );
4914
+ }
4526
4915
  let explorerUrl = chainConfig.explorer + txId;
4527
4916
 
4528
4917
  // The transaction is on-chain (or in flight) the instant the
4529
4918
  // Trading API accepts it — the quote is spent here, before the
4530
4919
  // on-chain verification below can throw RECEIPT_TIMEOUT (or
4531
4920
  // anything else) and abort this function. Covers local EVM,
4532
- // Privy EVM, Privy Solana, local/WalletConnect Solana, the
4533
- // WalletConnect sign-only fallback, and --gasless Relay — every
4534
- // path that reaches this shared broadcast call.
4921
+ // Privy EVM, Privy Solana, local/WalletConnect Solana and the
4922
+ // WalletConnect sign-only fallback — every path that reaches this
4923
+ // shared broadcast call.
4535
4924
  //
4536
- // Deliberate: a broadcast that later reverts on-chain (the
4537
- // "Trying next quote" path below) still consumes the quote —
4538
- // the revert still burned the nonce, so re-signing this same
4539
- // quote for a retry would race the reverted tx's nonce. This is
4540
- // intentional, not an oversight.
4925
+ // Deliberate: a broadcast that later reverts on-chain still
4926
+ // consumes the quote and ends this invocation. The user must
4927
+ // review that transaction and request a fresh quote explicitly.
4541
4928
  markQuoteExecuted(quoteId, { broadcast: { txHash: txId } });
4542
4929
 
4930
+ // Standard-route soft-fail: the node rejected our broadcast but the
4931
+ // signed tx carries a deterministic hash and may still propagate. The
4932
+ // quote is already burned (marked above), so we do NOT fall through to
4933
+ // the next candidate — that would be the double broadcast this path
4934
+ // exists to avoid. Surface the warning and keep going with the hash.
4935
+ // `broadcastSucceeded` is set by both the EVM and Solana standard
4936
+ // executors; the hash is still ours (the Solana signature, or
4937
+ // keccak256 of the signed EVM bytes), so it stays pollable.
4938
+ if (result.broadcastSucceeded === false) {
4939
+ log(` ⚠ The broadcast was rejected by the node but the transaction may still propagate: ${result.broadcastError || 'no detail returned'}`);
4940
+ log(` ${result.signature ? 'Signature' : 'Tx Hash'}: ${txId}`);
4941
+ log(` Explorer: ${explorerUrl}`);
4942
+ log(` Do NOT re-quote until you have checked the explorer.`);
4943
+ // Say so up front: the receipt poll below runs for up to 3 minutes
4944
+ // and, for a broadcast the node refused, most likely ends in the
4945
+ // RECEIPT_TIMEOUT banner. Without this the warning above is buried
4946
+ // behind a silent wait and a scarier-looking error.
4947
+ if (chainType === 'evm') {
4948
+ log(` Checking for a receipt anyway — this can take up to 3 minutes and may time out.`);
4949
+ } else {
4950
+ // Solana has no receipt poll below to resolve this. The EVM
4951
+ // branch either confirms the hash or fails closed on a timeout;
4952
+ // Solana would fall straight through to "✓ Transaction
4953
+ // successful!" and exit 0 for a broadcast the node refused, so
4954
+ // an agent would record a swap that may never have propagated.
4955
+ // Nothing here verified anything, so do not report success.
4956
+ //
4957
+ // The quote was marked spent above and no candidate fallback
4958
+ // runs from here, so this only changes what we REPORT: a
4959
+ // non-zero exit carrying the signature, instead of a success
4960
+ // banner for an outcome we do not know. Chain-gated rather than
4961
+ // route-gated — if any route hands back broadcastSucceeded:false
4962
+ // on Solana, we still cannot verify it.
4963
+ throw new CommandError(
4964
+ `\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.`,
4965
+ 'BROADCAST_FAILED',
4966
+ );
4967
+ }
4968
+ }
4969
+
4543
4970
  // For EVM: verify the tx actually succeeded on-chain
4544
4971
  if (chainType === 'evm') {
4545
4972
  log(' Verifying on-chain status...');
4546
- // Non-gasless: derive our local hash up front, OUTSIDE the receipt-poll
4547
- // try below. A hex-validation failure here means no poll ever ran, so it
4548
- // must surface as itself — not as the "REVERTED on-chain" diagnostic that
4549
- // catch is reserved for. (Gasless has no local hash to bind to: the Relay
4550
- // solver wraps and broadcasts its own tx, so result.txHash legitimately is
4551
- // not the hash of the bytes we signed.)
4552
- if (!gasless) {
4553
- try {
4554
- txId = evmTxHash(signedTransaction);
4555
- } catch (hashErr) {
4556
- throw new CommandError(`Cannot derive local tx hash for ${quoteName}: ${hashErr.message}`, 'INVALID_SIGNED_TX');
4557
- }
4558
- explorerUrl = chainConfig.explorer + txId;
4973
+ // Derive our local hash up front, OUTSIDE the receipt-poll try
4974
+ // below. A hex-validation failure here means no poll ever ran, so it
4975
+ // must surface as itself — not as the "REVERTED on-chain" diagnostic
4976
+ // that catch is reserved for.
4977
+ try {
4978
+ txId = evmTxHash(signedTransaction);
4979
+ } catch (hashErr) {
4980
+ throw new CommandError(`Cannot derive local tx hash for ${quoteName}: ${hashErr.message}`, 'INVALID_SIGNED_TX');
4559
4981
  }
4982
+ explorerUrl = chainConfig.explorer + txId;
4560
4983
  try {
4561
- if (gasless) {
4562
- // If the solver reported no hash there is nothing to poll — skip
4563
- // rather than block on eth_getTransactionReceipt(undefined).
4564
- if (result.txHash) await waitForReceipt(chain, result.txHash);
4565
- } else {
4566
- const { hash } = await confirmEvmBroadcast(chain, signedTransaction, result.txHash);
4567
- txId = hash;
4568
- explorerUrl = chainConfig.explorer + txId;
4569
- }
4984
+ const { hash } = await confirmEvmBroadcast(chain, signedTransaction, result.txHash);
4985
+ txId = hash;
4986
+ explorerUrl = chainConfig.explorer + txId;
4570
4987
  } catch (receiptErr) {
4571
4988
  // A receipt TIMEOUT is not a confirmed revert: the tx was
4572
4989
  // broadcast and may still be pending under our nonce. Retrying
@@ -4579,25 +4996,21 @@ EXAMPLES:
4579
4996
  if (receiptErr.code === 'RECEIPT_TIMEOUT') {
4580
4997
  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');
4581
4998
  }
4582
- if (isFatalBroadcastError(receiptErr)) throw receiptErr;
4583
- log(`\n ⚠ Transaction was broadcast but REVERTED on-chain!`);
4584
- log(` Tx Hash: ${txId || result.txHash}`);
4585
- log(` Explorer: ${explorerUrl}`);
4586
- log(` Error: ${receiptErr.message}`);
4587
- if (qi + 1 < endIndex) {
4588
- log(` Trying next quote...`);
4589
- lastQuoteError = `${quoteName} reverted on-chain`;
4590
- continue;
4999
+ if (receiptErr.code === 'TX_REVERTED') {
5000
+ 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');
4591
5001
  }
4592
- 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');
5002
+ if (isFatalBroadcastError(receiptErr)) throw receiptErr;
5003
+ throw receiptErr;
4593
5004
  }
4594
5005
  }
4595
5006
 
4596
5007
  log(`\n ✓ Transaction successful!`);
4597
5008
  log(` Status: ${result.status}`);
4598
- log(` ${result.signature ? 'Signature' : 'Tx Hash'}: ${txId}`);
5009
+ log(` ${chainType === 'solana' ? 'Signature' : 'Tx Hash'}: ${txId}`);
4599
5010
  log(` Chain: ${chainConfig.name} (${result.chainType})`);
4600
- log(` Broadcaster: ${result.broadcaster}`);
5011
+ // The standard route reports no broadcaster; only print it when the
5012
+ // response actually carries one (the legacy route does).
5013
+ if (result.broadcaster) log(` Broadcaster: ${result.broadcaster}`);
4601
5014
  log(` Explorer: ${explorerUrl}`);
4602
5015
 
4603
5016
  if (result.swapEvents?.length) {
@@ -4641,7 +5054,11 @@ EXAMPLES:
4641
5054
  return undefined; // Success — done
4642
5055
  } else {
4643
5056
  log(`\n ✗ Quote ${quoteName} failed: ${result.status}`);
4644
- if (result.error) log(` Error: ${result.error}`);
5057
+ // The standard route reports a typed failure as `code` (e.g. a
5058
+ // landed revert) with an optional `message`, where the legacy route
5059
+ // used `error`; surface whichever is present.
5060
+ const failReason = result.error || result.message || result.code;
5061
+ if (failReason) log(` Error: ${failReason}`);
4645
5062
  // A non-Success result can still carry a hash — the same
4646
5063
  // /execute response shape (status: 'Failed' + txHash) is
4647
5064
  // observed for approval broadcasts in trading.test.js, so a
@@ -4649,9 +5066,38 @@ EXAMPLES:
4649
5066
  // tell from here whether the hash means the tx actually went
4650
5067
  // out, but the asymmetry favors marking: a needless re-quote
4651
5068
  // is cheaper than a silent double broadcast.
4652
- const failedTxId = result.signature || result.txHash;
4653
- if (failedTxId) markQuoteExecuted(quoteId, { broadcast: { txHash: failedTxId } });
4654
- lastQuoteError = `${quoteName}: ${result.error || result.status}`;
5069
+ const failedTxId = chainType === 'evm'
5070
+ ? result.txHash
5071
+ : (result.signature || result.txHash);
5072
+ if (failedTxId) {
5073
+ markQuoteExecuted(quoteId, { broadcast: { txHash: failedTxId } });
5074
+ throw ambiguousBroadcast(
5075
+ `${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.`,
5076
+ { details: result },
5077
+ );
5078
+ } else if (!handoffAmbiguous) {
5079
+ // The backend answered, and its answer is "no transaction". That
5080
+ // is the same statement the candidate fallback below already
5081
+ // trusts enough to go sign another transaction against this
5082
+ // quote, so trust it to hand the local claim back too — nothing
5083
+ // left this process. Otherwise a run where every candidate is
5084
+ // rejected this way leaves <quote>.executing.json behind, and the
5085
+ // next execute is refused with "claimed by another execution"
5086
+ // for a quote that was never broadcast and is still good.
5087
+ swapHandedOff = false;
5088
+ }
5089
+ lastQuoteError = `${quoteName}: ${failReason || result.status}`;
5090
+ // Same single-flight reasoning as the receipt-revert path above: on
5091
+ // the standard route a failure CARRYING A HASH has already claimed
5092
+ // this quote server-side, so the next candidate can only conflict. A
5093
+ // failure with no hash is the backend's "provably never broadcast"
5094
+ // shape — it releases the lock, so the fallback stays available.
5095
+ if (swapRoute === 'standard' && failedTxId) {
5096
+ throw new CommandError(
5097
+ `\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".`,
5098
+ 'TX_REVERTED',
5099
+ );
5100
+ }
4655
5101
  if (qi + 1 < endIndex) log(` Trying next quote...`);
4656
5102
  }
4657
5103
 
@@ -4661,11 +5107,13 @@ EXAMPLES:
4661
5107
  // as spent. The signed tx may already be live on the backend (a 502
4662
5108
  // on the ack, not on the send), so fail closed: mark it here so a
4663
5109
  // later "trade execute --quote <id>" (or an agent auto-retry) is
4664
- // refused before it re-signs under a fresh nonce. No broadcast hash
4665
- // is recorded — we don't have one — which yields loadQuote's generic
4666
- // "may still be pending, check the explorer" message.
5110
+ // refused before it re-signs under a fresh nonce. Preserve a hash
5111
+ // when the application-level failure supplied one; transport
5112
+ // failures have no hash and retain the generic pending warning.
4667
5113
  if (quoteErr?.code === 'BROADCAST_FAILED') {
4668
- markQuoteExecuted(quoteId);
5114
+ markQuoteExecuted(quoteId, quoteErr.txHash
5115
+ ? { broadcast: { txHash: quoteErr.txHash } }
5116
+ : undefined);
4669
5117
  }
4670
5118
  // Post-broadcast failures abort the whole execute — never retry the
4671
5119
  // next quote once a transaction is already out and its outcome is
@@ -4673,6 +5121,25 @@ EXAMPLES:
4673
5121
  // timeout, or an ambiguous broadcast failure). See
4674
5122
  // isFatalBroadcastError.
4675
5123
  if (isFatalBroadcastError(quoteErr)) throw quoteErr;
5124
+ // No HTTP response is trusted as proof of pre-broadcast rejection.
5125
+ // Once this candidate was handed off, any otherwise-unclassified
5126
+ // error is ambiguous and must stop the loop.
5127
+ if (swapHandedOff) {
5128
+ handoffAmbiguous = true;
5129
+ // The swap was already handed to a wallet or the backend, and
5130
+ // nothing in this error proves it stayed put — an uncoded throw is
5131
+ // this client failing to learn the outcome, not the backend saying
5132
+ // "I never sent it". Marking handoffAmbiguous only protected the
5133
+ // CLAIM; the loop still fell through and signed the next candidate
5134
+ // against the same quote. Abort instead, and mark the quote spent
5135
+ // so a later `trade execute --quote <id>` is refused too.
5136
+ //
5137
+ // The paths that legitimately continue are unaffected: failures
5138
+ // detected before handoff never enter this branch, and the
5139
+ // backend's "failed, no transaction" answer never throws at all.
5140
+ markQuoteExecuted(quoteId);
5141
+ 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.`);
5142
+ }
4676
5143
  const msg = quoteErr.message || '';
4677
5144
  log(` ❌ Quote ${quoteName} failed: ${msg}`);
4678
5145
  if (msg.includes('AccountNotFound') && chainType === 'solana') {
@@ -4692,9 +5159,9 @@ EXAMPLES:
4692
5159
  if (err.details) msg += `\n Details: ${JSON.stringify(err.details)}`;
4693
5160
  throw new CommandError(msg, err.code || 'EXECUTE_ERROR');
4694
5161
  } finally {
4695
- // Hands the quote back only if no swap left this process, or if one
4696
- // did and its executedAt marker was recorded (see claimQuoteForExecution).
4697
- if (quoteClaim) quoteClaim.release({ handedOff: swapHandedOff });
5162
+ // Hands the quote back only if no swap/approval/revoke left this process,
5163
+ // or if an executedAt marker was recorded (see claimQuoteForExecution).
5164
+ if (quoteClaim) quoteClaim.release({ handedOff: swapHandedOff || ancillaryHandedOff });
4698
5165
  }
4699
5166
  },
4700
5167