nansen-cli 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/package.json +1 -1
- package/src/schema.json +1 -1
- package/src/trading.js +647 -120
- package/src/walletconnect-trading.js +50 -13
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
|
-
|
|
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;
|
|
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}
|
|
428
|
+
res = await fetch(`${TRADING_API_URL}${requestPath}`, {
|
|
219
429
|
method: 'POST',
|
|
220
430
|
headers,
|
|
221
|
-
body: JSON.stringify(
|
|
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 =
|
|
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 =
|
|
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 =
|
|
289
|
-
|
|
290
|
-
{
|
|
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
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
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
|
|
310
|
-
|
|
311
|
-
|
|
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
|
|
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
|
|
577
|
-
* off with no recorded marker leaves the quote claimed:
|
|
578
|
-
* rather than risk
|
|
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
|
-
|
|
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.
|
|
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" (
|
|
1189
|
-
//
|
|
1190
|
-
//
|
|
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
|
|
1198
|
-
* through to the next quote.
|
|
1199
|
-
*
|
|
1200
|
-
*
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
/**
|
|
@@ -3148,9 +3442,18 @@ EXAMPLES:
|
|
|
3148
3442
|
|
|
3149
3443
|
let quoteClaim = null;
|
|
3150
3444
|
// Set just before the swap transaction leaves this process (the Trading
|
|
3151
|
-
// API broadcast, or a WalletConnect wallet that may broadcast it)
|
|
3152
|
-
// claim is only handed back when no swap can be in flight.
|
|
3445
|
+
// API broadcast, or a WalletConnect wallet that may broadcast it).
|
|
3153
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;
|
|
3154
3457
|
try {
|
|
3155
3458
|
const quoteData = loadQuote(quoteId);
|
|
3156
3459
|
// The quote command stores the chain exactly as the user typed it
|
|
@@ -3164,6 +3467,38 @@ EXAMPLES:
|
|
|
3164
3467
|
const chainConfig = resolveChain(chain);
|
|
3165
3468
|
const chainType = chainConfig.type;
|
|
3166
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
|
+
}
|
|
3167
3502
|
const allQuotes = quoteData.response.quotes || [];
|
|
3168
3503
|
if (!allQuotes.length) {
|
|
3169
3504
|
throw new CommandError('❌ No quote data found', 'NO_QUOTES');
|
|
@@ -3460,6 +3795,10 @@ EXAMPLES:
|
|
|
3460
3795
|
try {
|
|
3461
3796
|
let signedTransaction;
|
|
3462
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;
|
|
3463
3802
|
|
|
3464
3803
|
if (chainType === 'solana' && isPrivy) {
|
|
3465
3804
|
// Solana via Privy: sign the serialized transaction
|
|
@@ -3467,6 +3806,7 @@ EXAMPLES:
|
|
|
3467
3806
|
if (!solWalletId) throw new Error('No Solana Privy wallet ID in quote');
|
|
3468
3807
|
const walletResult = await privyClient.getWallet(solWalletId);
|
|
3469
3808
|
const walletAddress = walletResult.address;
|
|
3809
|
+
swapWalletAddress = walletAddress;
|
|
3470
3810
|
// Fail closed if the signer address doesn't resolve: without it the
|
|
3471
3811
|
// wallet-binding comparison below would silently skip, leaving the
|
|
3472
3812
|
// quote unbound to the wallet that will sign it. This is resolved
|
|
@@ -3518,6 +3858,7 @@ EXAMPLES:
|
|
|
3518
3858
|
|
|
3519
3859
|
const walletResult = await privyClient.getWallet(evmWalletId);
|
|
3520
3860
|
const walletAddress = walletResult.address;
|
|
3861
|
+
swapWalletAddress = walletAddress;
|
|
3521
3862
|
|
|
3522
3863
|
// Guard the swap target before any RPC call, approval, or signing —
|
|
3523
3864
|
// whatever `to`/`data` the quote supplied gets signed verbatim.
|
|
@@ -3625,11 +3966,17 @@ EXAMPLES:
|
|
|
3625
3966
|
}
|
|
3626
3967
|
const revokeResult = await executeTransaction({ signedTransaction: signedRevoke, chain, simulate: !noSimulate });
|
|
3627
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
|
+
}
|
|
3628
3974
|
log(` ❌ Allowance revoke failed for ${quoteName}: ${revokeResult.error || 'unknown'}`);
|
|
3629
3975
|
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
3630
3976
|
lastQuoteError = `${quoteName} allowance revoke failed`;
|
|
3631
3977
|
continue;
|
|
3632
3978
|
}
|
|
3979
|
+
ancillaryHandedOff = true;
|
|
3633
3980
|
log(` Waiting for allowance revoke confirmation...`);
|
|
3634
3981
|
try {
|
|
3635
3982
|
const { receipt, hash: revokeHash } = await confirmEvmBroadcast(chain, signedRevoke, revokeResult.txHash, 'allowance-revoke');
|
|
@@ -3644,10 +3991,7 @@ EXAMPLES:
|
|
|
3644
3991
|
try {
|
|
3645
3992
|
await assertAllowanceRevoked(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress);
|
|
3646
3993
|
} catch (pollErr) {
|
|
3647
|
-
|
|
3648
|
-
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
3649
|
-
lastQuoteError = `${quoteName} allowance revoke verification failed`;
|
|
3650
|
-
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.`);
|
|
3651
3995
|
}
|
|
3652
3996
|
await waitForAllowanceTxPropagation();
|
|
3653
3997
|
}
|
|
@@ -3681,6 +4025,11 @@ EXAMPLES:
|
|
|
3681
4025
|
}
|
|
3682
4026
|
const approvalResult = await executeTransaction({ signedTransaction: signedApproval, chain, simulate: !noSimulate });
|
|
3683
4027
|
if (approvalResult.status !== 'Success') {
|
|
4028
|
+
const handedOffFailure = hashBearingFailure(approvalResult, `Approval for ${quoteName}`, 'evm');
|
|
4029
|
+
if (handedOffFailure) {
|
|
4030
|
+
ancillaryHandedOff = true;
|
|
4031
|
+
throw handedOffFailure;
|
|
4032
|
+
}
|
|
3684
4033
|
const revokedMsg = shouldRevoke
|
|
3685
4034
|
? ' after revoking the prior allowance (now 0)'
|
|
3686
4035
|
: '';
|
|
@@ -3689,6 +4038,7 @@ EXAMPLES:
|
|
|
3689
4038
|
lastQuoteError = `${quoteName} approval failed`;
|
|
3690
4039
|
continue;
|
|
3691
4040
|
}
|
|
4041
|
+
ancillaryHandedOff = true;
|
|
3692
4042
|
log(` Waiting for approval confirmation...`);
|
|
3693
4043
|
try {
|
|
3694
4044
|
const { receipt, hash: approvalHash } = await confirmEvmBroadcast(chain, signedApproval, approvalResult.txHash, 'allowance-approval');
|
|
@@ -3703,10 +4053,7 @@ EXAMPLES:
|
|
|
3703
4053
|
try {
|
|
3704
4054
|
await assertAllowanceAtLeast(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress, approveAmt);
|
|
3705
4055
|
} catch (pollErr) {
|
|
3706
|
-
|
|
3707
|
-
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
3708
|
-
lastQuoteError = `${quoteName} approval verification failed`;
|
|
3709
|
-
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.`);
|
|
3710
4057
|
}
|
|
3711
4058
|
await waitForAllowanceTxPropagation();
|
|
3712
4059
|
}
|
|
@@ -3796,6 +4143,7 @@ EXAMPLES:
|
|
|
3796
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.");
|
|
3797
4144
|
}
|
|
3798
4145
|
}
|
|
4146
|
+
swapWalletAddress = solanaWalletAddress;
|
|
3799
4147
|
|
|
3800
4148
|
const txBase64 = await normalizeSolanaTransaction(currentQuote.transaction, CHAIN_RPCS.solana, async () => solanaWalletAddress);
|
|
3801
4149
|
|
|
@@ -3890,6 +4238,7 @@ EXAMPLES:
|
|
|
3890
4238
|
if (!wcAddress) {
|
|
3891
4239
|
throw new CommandError('No WalletConnect session for this chain. Reconnect with `walletconnect connect` and retry.', 'NO_WALLET');
|
|
3892
4240
|
}
|
|
4241
|
+
swapWalletAddress = wcAddress;
|
|
3893
4242
|
const isNative = isNativeToken(currentQuote.inputMint);
|
|
3894
4243
|
|
|
3895
4244
|
// Guard the swap target before any RPC call, approval, or signing —
|
|
@@ -3980,6 +4329,7 @@ EXAMPLES:
|
|
|
3980
4329
|
{ allowZero: true },
|
|
3981
4330
|
);
|
|
3982
4331
|
revokeTxHash = revokeResult.txHash;
|
|
4332
|
+
if (revokeTxHash) ancillaryHandedOff = true;
|
|
3983
4333
|
if (!revokeTxHash && revokeResult.signedTransaction) {
|
|
3984
4334
|
log(` Broadcasting allowance revocation via Trading API...`);
|
|
3985
4335
|
const broadcastResult = await executeTransaction({
|
|
@@ -3988,14 +4338,28 @@ EXAMPLES:
|
|
|
3988
4338
|
simulate: !noSimulate,
|
|
3989
4339
|
});
|
|
3990
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
|
+
}
|
|
3991
4346
|
throw new Error(broadcastResult.error || 'broadcast failed');
|
|
3992
4347
|
}
|
|
4348
|
+
ancillaryHandedOff = true;
|
|
3993
4349
|
revokeTxHash = assertTxHashMatch(revokeResult.signedTransaction, broadcastResult.txHash, 'allowance-revoke');
|
|
3994
4350
|
}
|
|
3995
4351
|
if (!revokeTxHash) {
|
|
3996
4352
|
throw new Error('Allowance revoke returned no transaction hash and no signed transaction; cannot confirm allowance was cleared');
|
|
3997
4353
|
}
|
|
3998
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
|
+
}
|
|
3999
4363
|
if (isFatalBroadcastError(revokeErr)) throw revokeErr;
|
|
4000
4364
|
log(` ❌ Allowance revoke failed for ${quoteName}: ${revokeErr.message}.${allowanceRevokeRecoveryHint(revokeTxHash)}`);
|
|
4001
4365
|
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
@@ -4016,10 +4380,7 @@ EXAMPLES:
|
|
|
4016
4380
|
try {
|
|
4017
4381
|
await assertAllowanceRevoked(chain, currentQuote.inputMint, wcAddress, currentQuote.approvalAddress);
|
|
4018
4382
|
} catch (pollErr) {
|
|
4019
|
-
|
|
4020
|
-
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
4021
|
-
lastQuoteError = `${quoteName} allowance revoke verification failed`;
|
|
4022
|
-
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.`);
|
|
4023
4384
|
}
|
|
4024
4385
|
await waitForAllowanceTxPropagation();
|
|
4025
4386
|
}
|
|
@@ -4035,6 +4396,7 @@ EXAMPLES:
|
|
|
4035
4396
|
approvalCapForQuote(quoteData),
|
|
4036
4397
|
);
|
|
4037
4398
|
approvalTxHash = approvalResult.txHash;
|
|
4399
|
+
if (approvalTxHash) ancillaryHandedOff = true;
|
|
4038
4400
|
if (!approvalTxHash && approvalResult.signedTransaction) {
|
|
4039
4401
|
// Wallet returned a signed tx instead of broadcasting — broadcast via Trading API
|
|
4040
4402
|
log(` Broadcasting approval via Trading API...`);
|
|
@@ -4044,8 +4406,14 @@ EXAMPLES:
|
|
|
4044
4406
|
simulate: !noSimulate,
|
|
4045
4407
|
});
|
|
4046
4408
|
if (broadcastResult.status !== 'Success') {
|
|
4409
|
+
const handedOffFailure = hashBearingFailure(broadcastResult, `Approval for ${quoteName}`, 'evm');
|
|
4410
|
+
if (handedOffFailure) {
|
|
4411
|
+
ancillaryHandedOff = true;
|
|
4412
|
+
throw handedOffFailure;
|
|
4413
|
+
}
|
|
4047
4414
|
throw new Error(broadcastResult.error || 'broadcast failed');
|
|
4048
4415
|
}
|
|
4416
|
+
ancillaryHandedOff = true;
|
|
4049
4417
|
approvalTxHash = assertTxHashMatch(approvalResult.signedTransaction, broadcastResult.txHash, 'allowance-approval');
|
|
4050
4418
|
}
|
|
4051
4419
|
if (!approvalTxHash) {
|
|
@@ -4057,10 +4425,17 @@ EXAMPLES:
|
|
|
4057
4425
|
throw new Error('returned no transaction hash and no signed transaction; cannot confirm approval landed');
|
|
4058
4426
|
}
|
|
4059
4427
|
} catch (approvalErr) {
|
|
4060
|
-
if (isFatalBroadcastError(approvalErr)) throw approvalErr;
|
|
4061
4428
|
const revokedMsg = shouldRevoke
|
|
4062
4429
|
? ' after revoking the prior allowance (now 0)'
|
|
4063
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;
|
|
4064
4439
|
log(` ❌ Approval failed for ${quoteName}${revokedMsg}: ${approvalErr.message}`);
|
|
4065
4440
|
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
4066
4441
|
lastQuoteError = `${quoteName} approval failed`;
|
|
@@ -4086,10 +4461,7 @@ EXAMPLES:
|
|
|
4086
4461
|
const revokedMsg = shouldRevoke
|
|
4087
4462
|
? ' after revoking the prior allowance (now 0)'
|
|
4088
4463
|
: '';
|
|
4089
|
-
|
|
4090
|
-
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
4091
|
-
lastQuoteError = `${quoteName} approval verification failed`;
|
|
4092
|
-
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.`);
|
|
4093
4465
|
}
|
|
4094
4466
|
await waitForAllowanceTxPropagation();
|
|
4095
4467
|
log('');
|
|
@@ -4144,10 +4516,17 @@ EXAMPLES:
|
|
|
4144
4516
|
chainId: chainConfig.chainId,
|
|
4145
4517
|
});
|
|
4146
4518
|
} catch (wcErr) {
|
|
4147
|
-
|
|
4148
|
-
|
|
4149
|
-
|
|
4150
|
-
|
|
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.`);
|
|
4151
4530
|
}
|
|
4152
4531
|
|
|
4153
4532
|
if (wcResult.txHash) {
|
|
@@ -4157,6 +4536,18 @@ EXAMPLES:
|
|
|
4157
4536
|
// executeTransaction() marker further down.
|
|
4158
4537
|
markQuoteExecuted(quoteId, { broadcast: { txHash: wcResult.txHash } });
|
|
4159
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
|
+
|
|
4160
4551
|
// Wallet broadcast — verify on-chain
|
|
4161
4552
|
log(' Verifying on-chain status...');
|
|
4162
4553
|
try {
|
|
@@ -4169,17 +4560,11 @@ EXAMPLES:
|
|
|
4169
4560
|
if (receiptErr.code === 'RECEIPT_TIMEOUT') {
|
|
4170
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');
|
|
4171
4562
|
}
|
|
4172
|
-
if (
|
|
4173
|
-
|
|
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;
|
|
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');
|
|
4181
4565
|
}
|
|
4182
|
-
|
|
4566
|
+
if (isFatalBroadcastError(receiptErr)) throw receiptErr;
|
|
4567
|
+
throw receiptErr;
|
|
4183
4568
|
}
|
|
4184
4569
|
|
|
4185
4570
|
log(`\n ✓ Transaction successful!`);
|
|
@@ -4218,12 +4603,30 @@ EXAMPLES:
|
|
|
4218
4603
|
return undefined; // Success
|
|
4219
4604
|
}
|
|
4220
4605
|
|
|
4221
|
-
// Wallet returned signedTransaction — fall through to broadcast via
|
|
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
|
+
}
|
|
4222
4624
|
signedTransaction = wcResult.signedTransaction;
|
|
4223
4625
|
|
|
4224
4626
|
} else {
|
|
4225
4627
|
// EVM: quote.transaction is { to, data, value, gas, gasPrice }
|
|
4226
4628
|
const walletAddress = exported.evm.address;
|
|
4629
|
+
swapWalletAddress = walletAddress;
|
|
4227
4630
|
|
|
4228
4631
|
// Guard the swap target before any RPC call, approval, or signing —
|
|
4229
4632
|
// whatever `to`/`data` the quote supplied gets signed verbatim, so
|
|
@@ -4336,11 +4739,17 @@ EXAMPLES:
|
|
|
4336
4739
|
});
|
|
4337
4740
|
|
|
4338
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
|
+
}
|
|
4339
4747
|
log(` ❌ Allowance revoke failed for ${quoteName}: ${revokeResult.error || 'unknown error'}`);
|
|
4340
4748
|
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
4341
4749
|
lastQuoteError = `${quoteName} allowance revoke failed`;
|
|
4342
4750
|
continue;
|
|
4343
4751
|
}
|
|
4752
|
+
ancillaryHandedOff = true;
|
|
4344
4753
|
|
|
4345
4754
|
log(` Waiting for allowance revoke confirmation...`);
|
|
4346
4755
|
try {
|
|
@@ -4356,10 +4765,7 @@ EXAMPLES:
|
|
|
4356
4765
|
try {
|
|
4357
4766
|
await assertAllowanceRevoked(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress);
|
|
4358
4767
|
} catch (pollErr) {
|
|
4359
|
-
|
|
4360
|
-
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
4361
|
-
lastQuoteError = `${quoteName} allowance revoke verification failed`;
|
|
4362
|
-
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.`);
|
|
4363
4769
|
}
|
|
4364
4770
|
await waitForAllowanceTxPropagation();
|
|
4365
4771
|
}
|
|
@@ -4386,6 +4792,11 @@ EXAMPLES:
|
|
|
4386
4792
|
});
|
|
4387
4793
|
|
|
4388
4794
|
if (approvalResult.status !== 'Success') {
|
|
4795
|
+
const handedOffFailure = hashBearingFailure(approvalResult, `Approval for ${quoteName}`, 'evm');
|
|
4796
|
+
if (handedOffFailure) {
|
|
4797
|
+
ancillaryHandedOff = true;
|
|
4798
|
+
throw handedOffFailure;
|
|
4799
|
+
}
|
|
4389
4800
|
const revokedMsg = shouldRevoke
|
|
4390
4801
|
? ' after revoking the prior allowance (now 0)'
|
|
4391
4802
|
: '';
|
|
@@ -4394,6 +4805,7 @@ EXAMPLES:
|
|
|
4394
4805
|
lastQuoteError = `${quoteName} approval failed`;
|
|
4395
4806
|
continue;
|
|
4396
4807
|
}
|
|
4808
|
+
ancillaryHandedOff = true;
|
|
4397
4809
|
|
|
4398
4810
|
log(` Waiting for approval confirmation...`);
|
|
4399
4811
|
try {
|
|
@@ -4409,10 +4821,7 @@ EXAMPLES:
|
|
|
4409
4821
|
try {
|
|
4410
4822
|
await assertAllowanceAtLeast(chain, currentQuote.inputMint, walletAddress, currentQuote.approvalAddress, approveAmt);
|
|
4411
4823
|
} catch (pollErr) {
|
|
4412
|
-
|
|
4413
|
-
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
4414
|
-
lastQuoteError = `${quoteName} approval verification failed`;
|
|
4415
|
-
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.`);
|
|
4416
4825
|
}
|
|
4417
4826
|
await waitForAllowanceTxPropagation();
|
|
4418
4827
|
log('');
|
|
@@ -4478,12 +4887,18 @@ EXAMPLES:
|
|
|
4478
4887
|
simulate: !noSimulate && !gasless,
|
|
4479
4888
|
};
|
|
4480
4889
|
|
|
4481
|
-
//
|
|
4482
|
-
//
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
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;
|
|
4487
4902
|
}
|
|
4488
4903
|
// The backend's /execute schema is strict; sending fields it doesn't expect
|
|
4489
4904
|
// for the (chain × aggregator × gasless) combination causes 502s or
|
|
@@ -4518,11 +4933,35 @@ EXAMPLES:
|
|
|
4518
4933
|
// can't be deduped at the node level and risks a second solve. For
|
|
4519
4934
|
// gasless we therefore don't retry: a single POST either succeeds or
|
|
4520
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
|
+
|
|
4521
4948
|
swapHandedOff = true;
|
|
4522
|
-
const result = await executeTransaction(execParams, { retries: gasless ? 0 : undefined });
|
|
4949
|
+
const result = await executeTransaction(execParams, { retries: gasless ? 0 : undefined, route: swapRoute, attemptId });
|
|
4523
4950
|
|
|
4524
4951
|
if (result.status === 'Success') {
|
|
4525
|
-
|
|
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
|
+
}
|
|
4526
4965
|
let explorerUrl = chainConfig.explorer + txId;
|
|
4527
4966
|
|
|
4528
4967
|
// The transaction is on-chain (or in flight) the instant the
|
|
@@ -4533,13 +4972,51 @@ EXAMPLES:
|
|
|
4533
4972
|
// WalletConnect sign-only fallback, and --gasless Relay — every
|
|
4534
4973
|
// path that reaches this shared broadcast call.
|
|
4535
4974
|
//
|
|
4536
|
-
// Deliberate: a broadcast that later reverts on-chain
|
|
4537
|
-
//
|
|
4538
|
-
//
|
|
4539
|
-
// quote for a retry would race the reverted tx's nonce. This is
|
|
4540
|
-
// 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.
|
|
4541
4978
|
markQuoteExecuted(quoteId, { broadcast: { txHash: txId } });
|
|
4542
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
|
+
|
|
4543
5020
|
// For EVM: verify the tx actually succeeded on-chain
|
|
4544
5021
|
if (chainType === 'evm') {
|
|
4545
5022
|
log(' Verifying on-chain status...');
|
|
@@ -4579,25 +5056,21 @@ EXAMPLES:
|
|
|
4579
5056
|
if (receiptErr.code === 'RECEIPT_TIMEOUT') {
|
|
4580
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');
|
|
4581
5058
|
}
|
|
4582
|
-
if (
|
|
4583
|
-
|
|
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;
|
|
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');
|
|
4591
5061
|
}
|
|
4592
|
-
|
|
5062
|
+
if (isFatalBroadcastError(receiptErr)) throw receiptErr;
|
|
5063
|
+
throw receiptErr;
|
|
4593
5064
|
}
|
|
4594
5065
|
}
|
|
4595
5066
|
|
|
4596
5067
|
log(`\n ✓ Transaction successful!`);
|
|
4597
5068
|
log(` Status: ${result.status}`);
|
|
4598
|
-
log(` ${
|
|
5069
|
+
log(` ${chainType === 'solana' ? 'Signature' : 'Tx Hash'}: ${txId}`);
|
|
4599
5070
|
log(` Chain: ${chainConfig.name} (${result.chainType})`);
|
|
4600
|
-
|
|
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}`);
|
|
4601
5074
|
log(` Explorer: ${explorerUrl}`);
|
|
4602
5075
|
|
|
4603
5076
|
if (result.swapEvents?.length) {
|
|
@@ -4641,7 +5114,11 @@ EXAMPLES:
|
|
|
4641
5114
|
return undefined; // Success — done
|
|
4642
5115
|
} else {
|
|
4643
5116
|
log(`\n ✗ Quote ${quoteName} failed: ${result.status}`);
|
|
4644
|
-
|
|
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}`);
|
|
4645
5122
|
// A non-Success result can still carry a hash — the same
|
|
4646
5123
|
// /execute response shape (status: 'Failed' + txHash) is
|
|
4647
5124
|
// observed for approval broadcasts in trading.test.js, so a
|
|
@@ -4649,9 +5126,38 @@ EXAMPLES:
|
|
|
4649
5126
|
// tell from here whether the hash means the tx actually went
|
|
4650
5127
|
// out, but the asymmetry favors marking: a needless re-quote
|
|
4651
5128
|
// is cheaper than a silent double broadcast.
|
|
4652
|
-
const failedTxId =
|
|
4653
|
-
|
|
4654
|
-
|
|
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
|
+
}
|
|
4655
5161
|
if (qi + 1 < endIndex) log(` Trying next quote...`);
|
|
4656
5162
|
}
|
|
4657
5163
|
|
|
@@ -4661,11 +5167,13 @@ EXAMPLES:
|
|
|
4661
5167
|
// as spent. The signed tx may already be live on the backend (a 502
|
|
4662
5168
|
// on the ack, not on the send), so fail closed: mark it here so a
|
|
4663
5169
|
// later "trade execute --quote <id>" (or an agent auto-retry) is
|
|
4664
|
-
// refused before it re-signs under a fresh nonce.
|
|
4665
|
-
//
|
|
4666
|
-
//
|
|
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.
|
|
4667
5173
|
if (quoteErr?.code === 'BROADCAST_FAILED') {
|
|
4668
|
-
markQuoteExecuted(quoteId
|
|
5174
|
+
markQuoteExecuted(quoteId, quoteErr.txHash
|
|
5175
|
+
? { broadcast: { txHash: quoteErr.txHash } }
|
|
5176
|
+
: undefined);
|
|
4669
5177
|
}
|
|
4670
5178
|
// Post-broadcast failures abort the whole execute — never retry the
|
|
4671
5179
|
// next quote once a transaction is already out and its outcome is
|
|
@@ -4673,6 +5181,25 @@ EXAMPLES:
|
|
|
4673
5181
|
// timeout, or an ambiguous broadcast failure). See
|
|
4674
5182
|
// isFatalBroadcastError.
|
|
4675
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
|
+
}
|
|
4676
5203
|
const msg = quoteErr.message || '';
|
|
4677
5204
|
log(` ❌ Quote ${quoteName} failed: ${msg}`);
|
|
4678
5205
|
if (msg.includes('AccountNotFound') && chainType === 'solana') {
|
|
@@ -4692,9 +5219,9 @@ EXAMPLES:
|
|
|
4692
5219
|
if (err.details) msg += `\n Details: ${JSON.stringify(err.details)}`;
|
|
4693
5220
|
throw new CommandError(msg, err.code || 'EXECUTE_ERROR');
|
|
4694
5221
|
} finally {
|
|
4695
|
-
// Hands the quote back only if no swap left this process,
|
|
4696
|
-
//
|
|
4697
|
-
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 });
|
|
4698
5225
|
}
|
|
4699
5226
|
},
|
|
4700
5227
|
|