nansen-cli 2.4.0 → 2.5.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.
@@ -66,6 +66,7 @@ export function readResponseMeta(response) {
66
66
  const planNotice = stringHeader(response, PLAN_NOTICE);
67
67
  const apiKeyNotice = stringHeader(response, API_KEY_NOTICE);
68
68
  const requestId = stringHeader(response, REQUEST_ID);
69
+ const warning = stringHeader(response, 'warning');
69
70
 
70
71
  const meta = {};
71
72
  if (requestId !== null) {
@@ -83,8 +84,9 @@ export function readResponseMeta(response) {
83
84
  // drain — not a wall-clock timestamp.
84
85
  meta.rateLimit = { limit, remaining: rateRemaining, resetSeconds };
85
86
  }
86
- if (upgradeHint !== null || planNotice !== null || apiKeyNotice !== null) {
87
+ if (upgradeHint !== null || planNotice !== null || apiKeyNotice !== null || warning !== null) {
87
88
  meta.notices = {
89
+ ...(warning !== null && { warning }),
88
90
  ...(upgradeHint !== null && { upgradeHint }),
89
91
  ...(planNotice !== null && { planNotice }),
90
92
  ...(apiKeyNotice !== null && { apiKeyNotice }),
@@ -102,11 +104,13 @@ export function readResponseMeta(response) {
102
104
  export function aggregatePaginatedResponseMeta(pages) {
103
105
  if (!Array.isArray(pages) || pages.length === 0) return null;
104
106
 
107
+ const warning = [...new Set(pages.map(page => page.meta?.notices?.warning).filter(Boolean))].join(', ');
105
108
  const livePages = pages.filter(page => !page.cached);
106
109
  const metas = livePages.map(page => page.meta);
107
110
  const present = metas.filter(Boolean);
108
111
  if (livePages.length === 0) {
109
112
  return {
113
+ ...(warning && { notices: { warning } }),
110
114
  credits: { used: 0, remaining: null, cost: 0 },
111
115
  pagination: { pagesFetched: pages.length, livePages: 0, cachedPages: pages.length },
112
116
  };
@@ -134,6 +138,7 @@ export function aggregatePaginatedResponseMeta(pages) {
134
138
 
135
139
  const notices = {};
136
140
  for (const meta of present) Object.assign(notices, meta.notices || {});
141
+ if (warning) notices.warning = warning;
137
142
  if (Object.keys(notices).length > 0) result.notices = notices;
138
143
 
139
144
  result.pagination = {
@@ -147,12 +152,13 @@ export function aggregatePaginatedResponseMeta(pages) {
147
152
  /**
148
153
  * Yield notice strings for any server-set advisory headers.
149
154
  * Each yields a `⚠️ <message>` line for stderr.
150
- * Order: apiKeyNotice (most urgent) → upgradeHint → planNotice.
155
+ * Order: API warning → apiKeyNotice → upgradeHint → planNotice.
151
156
  */
152
157
  export function noticeWarnings(meta) {
153
158
  const notices = meta?.notices;
154
159
  if (!notices) return [];
155
160
  const out = [];
161
+ if (notices.warning) out.push(`⚠️ ${notices.warning}`);
156
162
  if (notices.apiKeyNotice) out.push(`⚠️ ${notices.apiKeyNotice}`);
157
163
  if (notices.upgradeHint) out.push(`ℹ️ ${notices.upgradeHint}`);
158
164
  if (notices.planNotice) out.push(`ℹ️ ${notices.planNotice}`);
package/src/schema.json CHANGED
@@ -176,6 +176,7 @@
176
176
  "order": {
177
177
  "submitsTo": "https://api.hyperliquid.xyz/exchange",
178
178
  "apiEndpoints": [
179
+ "/api/v1/perp/positions",
179
180
  "/api/v1/perp/meta",
180
181
  "/api/v1/perp/builder-fee",
181
182
  "/api/v1/sanctions/screen"
@@ -243,12 +244,24 @@
243
244
  "wallet": {
244
245
  "type": "string",
245
246
  "description": "Wallet name (defaults to the configured default wallet)"
247
+ },
248
+ "dry-run": {
249
+ "type": "boolean",
250
+ "description": "Run the normal validation and read-only lookups (asset metadata, builder fee, open position, compliance screen), print the order plan (coin, side, rounded size, price and type, take-profit/stop-loss, estimated notional, leverage, builder fee), then stop. Nothing is signed or sent to Hyperliquid, no wallet password is needed, and the one-time builder-fee approval is not submitted. Exits 0."
251
+ },
252
+ "yes": {
253
+ "type": "boolean",
254
+ "aliases": [
255
+ "y"
256
+ ],
257
+ "description": "Skip the confirmation prompt (alias: -y, or set NANSEN_YES=1). The prompt is only shown when stdin is an interactive terminal; when stdin is not a terminal (agents, CI, pipes) the command proceeds unprompted whether or not this is passed. Declining the prompt exits 1 with nothing signed."
246
258
  }
247
259
  }
248
260
  },
249
261
  "cancel": {
250
262
  "submitsTo": "https://api.hyperliquid.xyz/exchange",
251
263
  "apiEndpoints": [
264
+ "/api/v1/perp/orders",
252
265
  "/api/v1/perp/meta",
253
266
  "/api/v1/sanctions/screen"
254
267
  ],
@@ -267,6 +280,17 @@
267
280
  "wallet": {
268
281
  "type": "string",
269
282
  "description": "Wallet name"
283
+ },
284
+ "dry-run": {
285
+ "type": "boolean",
286
+ "description": "Run the normal validation and read-only lookups (asset metadata, open orders, compliance screen), print the cancel plan (coin, order id, the matching open order), then stop. Nothing is signed or sent to Hyperliquid and no wallet password is needed. Exits 0."
287
+ },
288
+ "yes": {
289
+ "type": "boolean",
290
+ "aliases": [
291
+ "y"
292
+ ],
293
+ "description": "Skip the confirmation prompt (alias: -y, or set NANSEN_YES=1). The prompt is only shown when stdin is an interactive terminal; when stdin is not a terminal (agents, CI, pipes) the command proceeds unprompted whether or not this is passed. Declining the prompt exits 1 with nothing signed."
270
294
  }
271
295
  }
272
296
  },
@@ -312,12 +336,24 @@
312
336
  "wallet": {
313
337
  "type": "string",
314
338
  "description": "Wallet name"
339
+ },
340
+ "dry-run": {
341
+ "type": "boolean",
342
+ "description": "Run the normal validation and read-only lookups (asset metadata, open position and close-direction check, builder fee, compliance screen), print the close plan (coin, side, rounded size, worst fill price after slippage, estimated notional, open position, builder fee), then stop. Nothing is signed or sent to Hyperliquid, no wallet password is needed, and the one-time builder-fee approval is not submitted. Exits 0, or exits 1 with NO_OPEN_POSITION when the wallet has no open position in that coin. A real close (without --dry-run) does not make this check; Hyperliquid rejects a close with nothing to close."
343
+ },
344
+ "yes": {
345
+ "type": "boolean",
346
+ "aliases": [
347
+ "y"
348
+ ],
349
+ "description": "Skip the confirmation prompt (alias: -y, or set NANSEN_YES=1). The prompt is only shown when stdin is an interactive terminal; when stdin is not a terminal (agents, CI, pipes) the command proceeds unprompted whether or not this is passed. Declining the prompt exits 1 with nothing signed."
315
350
  }
316
351
  }
317
352
  },
318
353
  "leverage": {
319
354
  "submitsTo": "https://api.hyperliquid.xyz/exchange",
320
355
  "apiEndpoints": [
356
+ "/api/v1/perp/positions",
321
357
  "/api/v1/perp/meta",
322
358
  "/api/v1/sanctions/screen"
323
359
  ],
@@ -345,6 +381,17 @@
345
381
  "wallet": {
346
382
  "type": "string",
347
383
  "description": "Wallet name"
384
+ },
385
+ "dry-run": {
386
+ "type": "boolean",
387
+ "description": "Run the normal validation and read-only lookups (asset metadata and maximum leverage, open position, compliance screen), print the leverage plan (coin, leverage, margin type, asset maximum, open position), then stop. Nothing is signed or sent to Hyperliquid and no wallet password is needed. Exits 0."
388
+ },
389
+ "yes": {
390
+ "type": "boolean",
391
+ "aliases": [
392
+ "y"
393
+ ],
394
+ "description": "Skip the confirmation prompt (alias: -y, or set NANSEN_YES=1). The prompt is only shown when stdin is an interactive terminal; when stdin is not a terminal (agents, CI, pipes) the command proceeds unprompted whether or not this is passed. Declining the prompt exits 1 with nothing signed."
348
395
  }
349
396
  }
350
397
  },
@@ -568,6 +615,9 @@
568
615
  },
569
616
  "yes": {
570
617
  "type": "boolean",
618
+ "aliases": [
619
+ "y"
620
+ ],
571
621
  "description": "Skip the confirmation prompt (alias: -y, or set NANSEN_YES=1). The prompt is only shown when stdin is an interactive terminal; when stdin is not a terminal (agents, CI, pipes) the command proceeds unprompted whether or not this is passed. Declining the prompt exits 1 with nothing signed."
572
622
  }
573
623
  },
@@ -2388,14 +2438,6 @@
2388
2438
  },
2389
2439
  "description": "Polymarket prediction market analytics"
2390
2440
  },
2391
- "points": {
2392
- "description": "Nansen Points analytics",
2393
- "subcommands": {
2394
- "leaderboard": {
2395
- "description": "Points leaderboard (unavailable)"
2396
- }
2397
- }
2398
- },
2399
2441
  "chain-rank": {
2400
2442
  "endpoint": "/api/v1/chains/chain-rank",
2401
2443
  "description": "Rank chains by growth metrics",
@@ -3041,7 +3083,11 @@
3041
3083
  },
3042
3084
  "webhook-secret": {
3043
3085
  "type": "string",
3044
- "description": "Signing secret for webhook payload verification (optional, webhook only)"
3086
+ "description": "Signing secret for webhook payload verification (optional, webhook only, minimum 16 characters). Visible in shell history and the process list; prefer --webhook-secret-stdin or the NANSEN_WEBHOOK_SECRET env var. Cannot combine with --webhook-secret-stdin; overrides NANSEN_WEBHOOK_SECRET."
3087
+ },
3088
+ "webhook-secret-stdin": {
3089
+ "type": "boolean",
3090
+ "description": "Read the webhook signing secret from a pipe or redirected file (maximum 4096 bytes; input must close within 30 seconds). Surrounding whitespace is trimmed; the secret is never echoed. Requires --webhook. Cannot combine with --webhook-secret; overrides NANSEN_WEBHOOK_SECRET, which is read only when --webhook is given."
3045
3091
  },
3046
3092
  "data": {
3047
3093
  "type": "string",
@@ -3096,7 +3142,11 @@
3096
3142
  },
3097
3143
  "webhook-secret": {
3098
3144
  "type": "string",
3099
- "description": "Signing secret for webhook payload verification (optional, webhook only)"
3145
+ "description": "Signing secret for webhook payload verification (optional, webhook only, minimum 16 characters). Visible in shell history and the process list; prefer --webhook-secret-stdin or the NANSEN_WEBHOOK_SECRET env var. Cannot combine with --webhook-secret-stdin; overrides NANSEN_WEBHOOK_SECRET."
3146
+ },
3147
+ "webhook-secret-stdin": {
3148
+ "type": "boolean",
3149
+ "description": "Read the webhook signing secret from a pipe or redirected file (maximum 4096 bytes; input must close within 30 seconds). Surrounding whitespace is trimmed; the secret is never echoed. Requires --webhook. Cannot combine with --webhook-secret; overrides NANSEN_WEBHOOK_SECRET, which is read only when --webhook is given."
3100
3150
  },
3101
3151
  "data": {
3102
3152
  "type": "string",
@@ -3273,6 +3323,9 @@
3273
3323
  },
3274
3324
  "yes": {
3275
3325
  "type": "boolean",
3326
+ "aliases": [
3327
+ "y"
3328
+ ],
3276
3329
  "description": "Skip the confirmation prompt (alias: -y, or set NANSEN_YES=1). The prompt is only shown when stdin is an interactive terminal; when stdin is not a terminal (agents, CI, pipes) the command proceeds unprompted whether or not this is passed. Declining the prompt exits 1 with nothing signed."
3277
3330
  }
3278
3331
  },
@@ -3357,6 +3410,17 @@
3357
3410
  "wallet": {
3358
3411
  "type": "string",
3359
3412
  "description": "Wallet name (or \"walletconnect\"/\"wc\")"
3413
+ },
3414
+ "dry-run": {
3415
+ "type": "boolean",
3416
+ "description": "Print a locally validated create intent and stop before limit-order authentication, custom-token metadata RPC lookups, transaction crafting, transaction signing, or order submission. No API request is made and exits 0."
3417
+ },
3418
+ "yes": {
3419
+ "type": "boolean",
3420
+ "aliases": [
3421
+ "y"
3422
+ ],
3423
+ "description": "Skip the create confirmation prompt (alias: -y, or set NANSEN_YES=1). The prompt is only shown when stdin is an interactive terminal; non-TTY automation proceeds unprompted. Declining exits 1 before API requests or signing."
3360
3424
  }
3361
3425
  },
3362
3426
  "chains": [
@@ -3416,6 +3480,17 @@
3416
3480
  "wallet": {
3417
3481
  "type": "string",
3418
3482
  "description": "Wallet name (or \"walletconnect\"/\"wc\")"
3483
+ },
3484
+ "dry-run": {
3485
+ "type": "boolean",
3486
+ "description": "Print a locally validated cancel intent and stop before limit-order authentication, order lookup, signing, confirmation, or requesting/consuming the one-time cancellation transaction. No API request is made and exits 0."
3487
+ },
3488
+ "yes": {
3489
+ "type": "boolean",
3490
+ "aliases": [
3491
+ "y"
3492
+ ],
3493
+ "description": "Skip the cancel confirmation prompt (alias: -y, or set NANSEN_YES=1). The prompt is only shown when stdin is an interactive terminal; non-TTY automation proceeds unprompted. Declining exits 1 before API requests or signing."
3419
3494
  }
3420
3495
  },
3421
3496
  "chains": [
@@ -3455,11 +3530,25 @@
3455
3530
  "description": "Wallet management. x402 auto-payments are guarded by a client-side policy: per-payment USD cap via NANSEN_X402_MAX_AMOUNT (default 1.00; 'unlimited' to disable), an optional cumulative cap on what one CLI process signs via NANSEN_X402_SESSION_MAX_AMOUNT (environment only; unset or 'unlimited' = no limit, an invalid value refuses every payment; a payment the server cleanly rejects is not counted; it resets with every process), and an optional recipient allowlist via NANSEN_X402_ALLOWED_PAYTO (comma-separated addresses). Each auto-payment and its outcome are recorded in ~/.nansen/x402/payments.jsonl.",
3456
3531
  "subcommands": {
3457
3532
  "create": {
3458
- "description": "Create a new wallet. Explicitly blank --name values are rejected for local and Privy wallets.",
3533
+ "description": "Create a new wallet (EVM + Solana). A local wallet needs a password of at least 12 characters from NANSEN_WALLET_PASSWORD (or the password an earlier wallet create saved); the command does not prompt unless --human is passed, and without a password it fails with PASSWORD_REQUIRED. The password is then saved to the OS keychain, or to ~/.nansen/wallets/.credentials (plaintext) when no keychain is available, so later wallet commands find it. If neither can be written, the wallet is still created but the password is not saved, and NANSEN_WALLET_PASSWORD must stay set for every later wallet command. Privy wallets need no password. Explicitly blank --name values are rejected for local and Privy wallets.",
3459
3534
  "options": {
3535
+ "name": {
3536
+ "type": "string",
3537
+ "default": "default",
3538
+ "description": "Wallet name"
3539
+ },
3540
+ "provider": {
3541
+ "type": "string",
3542
+ "enum": ["local", "privy"],
3543
+ "description": "local (default) stores encrypted keys on disk; privy creates a server-side wallet and needs PRIVY_APP_ID and PRIVY_APP_SECRET. NANSEN_WALLET_PROVIDER=privy also selects privy"
3544
+ },
3460
3545
  "unsafe-no-password": {
3461
3546
  "type": "boolean",
3462
3547
  "description": "Skip encryption; private keys are stored unencrypted on disk (local only)"
3548
+ },
3549
+ "human": {
3550
+ "type": "boolean",
3551
+ "description": "Prompt for the password in an interactive terminal when none is set or saved (for humans; agents set NANSEN_WALLET_PASSWORD instead)"
3463
3552
  }
3464
3553
  },
3465
3554
  "examples": [
@@ -3505,7 +3594,7 @@
3505
3594
  ]
3506
3595
  },
3507
3596
  "send": {
3508
- "description": "Send tokens or native currency. Explicitly blank --token and --wallet values are rejected; omit them for native currency and the default wallet.",
3597
+ "description": "Send tokens or native currency. --token takes USDC, USDT or a token contract/mint address. Explicitly blank --token and --wallet values are rejected; omit them for native currency and the default wallet.",
3509
3598
  "options": {
3510
3599
  "to": {
3511
3600
  "type": "string",
@@ -3525,10 +3614,23 @@
3525
3614
  "max": {
3526
3615
  "type": "boolean",
3527
3616
  "description": "Send the entire spendable balance instead of --amount"
3617
+ },
3618
+ "token": {
3619
+ "type": "string",
3620
+ "description": "Token to send: USDC, USDT, or a token contract/mint address. Omit to send the chain's native currency"
3621
+ },
3622
+ "wallet": {
3623
+ "type": "string",
3624
+ "description": "Wallet to send from (default wallet if omitted); walletconnect or wc for a WalletConnect session (EVM only)"
3625
+ },
3626
+ "dry-run": {
3627
+ "type": "boolean",
3628
+ "description": "Preview the transaction without broadcasting it"
3528
3629
  }
3529
3630
  },
3530
3631
  "examples": [
3531
3632
  "nansen wallet send --to <address> --amount 1.5 --chain evm",
3633
+ "nansen wallet send --to <address> --amount 25 --chain base --token USDC",
3532
3634
  "nansen wallet send --to <address> --max --chain solana"
3533
3635
  ]
3534
3636
  },
@@ -3918,6 +4020,10 @@
3918
4020
  "type": "boolean",
3919
4021
  "description": "Format output as human-readable table"
3920
4022
  },
4023
+ "stream": {
4024
+ "type": "boolean",
4025
+ "description": "Print one JSON object per line (NDJSON), one line per result row, instead of the {success, data} envelope (alias: -s). Applies to commands that return data, such as research commands; schema, feedback and commands that print their own text (trade, wallet, perp trading) ignore it. Takes precedence over --format csv, and over --table except for alerts list, which keeps its table. A single object prints as one line; an empty row list or a non-object result prints nothing. Errors are not streamed and print as they would without --stream."
4026
+ },
3921
4027
  "fields": {
3922
4028
  "type": "string",
3923
4029
  "description": "Comma-separated list of fields to include in output"
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Flag names for telemetry events.
3
+ *
4
+ * The argument parser turns a dash-leading value given as a separate argument
5
+ * (`--webhook-secret -abc123`) into a flag named after the value. Telemetry
6
+ * therefore sends only option names the CLI defines for the command being run
7
+ * and replaces every other name with a fixed placeholder, so no user-supplied
8
+ * text can reach analytics through the `flags` list.
9
+ */
10
+
11
+ import { resolveResearchCommand } from './input-validation.js';
12
+
13
+ export const UNKNOWN_FLAG = '--<unknown>';
14
+
15
+ // Single-letter switches the CLI reads directly (help, version, pretty, table,
16
+ // stream, yes). They are not listed as options in the schema.
17
+ const SHORT_SWITCHES = ['h', 'v', 'p', 't', 's', 'y'];
18
+
19
+ // Deprecated top-level commands that run a `trade` subcommand.
20
+ const TRADE_SHORTCUTS = new Set(['quote', 'execute', 'bridge-status']);
21
+
22
+ function addOptionNames(known, options) {
23
+ if (!options || typeof options !== 'object') return;
24
+ for (const [name, spec] of Object.entries(options)) {
25
+ known.add(name);
26
+ if (Array.isArray(spec?.aliases)) {
27
+ for (const alias of spec.aliases) known.add(alias);
28
+ }
29
+ }
30
+ }
31
+
32
+ /** Schema entry for the command line, or null when none matches. */
33
+ function schemaLeaf(schema, command, subArgs) {
34
+ try {
35
+ const research = resolveResearchCommand(schema, command, subArgs);
36
+ if (research) return research.leaf;
37
+ } catch {
38
+ // Unknown research category or subcommand: fall through to the plain walk.
39
+ }
40
+ let node = null;
41
+ let path = subArgs;
42
+ if (Object.hasOwn(schema.commands, command)) {
43
+ node = schema.commands[command];
44
+ } else if (TRADE_SHORTCUTS.has(command) && schema.commands.trade?.subcommands) {
45
+ node = schema.commands.trade;
46
+ path = [command, ...subArgs];
47
+ }
48
+ for (const arg of path) {
49
+ const subs = node?.subcommands;
50
+ if (!subs || typeof arg !== 'string' || !Object.hasOwn(subs, arg)) break;
51
+ node = subs[arg];
52
+ }
53
+ return node;
54
+ }
55
+
56
+ /**
57
+ * Option names (without dashes) that telemetry may report for this command:
58
+ * the matched schema entry's options, the global options and the CLI's own
59
+ * valueless switches.
60
+ */
61
+ export function knownTelemetryFlags(schema, command, subArgs = [], switches = []) {
62
+ const known = new Set([...switches, ...SHORT_SWITCHES]);
63
+ addOptionNames(known, schema.globalOptions);
64
+ addOptionNames(known, schemaLeaf(schema, command, subArgs)?.options);
65
+ return known;
66
+ }
67
+
68
+ /**
69
+ * Map `--name` entries to themselves when the CLI defines them for this
70
+ * command, and to UNKNOWN_FLAG otherwise.
71
+ */
72
+ export function telemetryFlagNames({ schema, command, subArgs = [], switches = [] }, names) {
73
+ const known = knownTelemetryFlags(schema, command, subArgs, switches);
74
+ return names.map(name => (known.has(String(name).replace(/^--/, '')) ? name : UNKNOWN_FLAG));
75
+ }
package/src/trading.js CHANGED
@@ -322,10 +322,14 @@ function fromStandardResponse(body, chainType) {
322
322
  * `ambiguousBroadcast` is the default for every failure after the signed payload
323
323
  * is handed to fetch. An HTTP status describes the response, not whether the
324
324
  * backend forwarded the transaction before producing it: 408/429 and even an
325
- * intermediary-generated 400/409 can arrive after processing began. Until the
326
- * execute API has a documented, authenticated field that explicitly guarantees
327
- * pre-broadcast rejection, no response from this endpoint may authorize signing
328
- * the next candidate.
325
+ * intermediary-generated 400/409 can arrive after processing began, so no
326
+ * non-2xx response may authorize signing the next candidate.
327
+ *
328
+ * The one exception is the standard route's documented pre-broadcast rejection:
329
+ * a 400 carrying a code from STANDARD_PRE_BROADCAST_CODES and no transaction
330
+ * identifier (see isStandardPreBroadcastRejection). That is the same "failed, no
331
+ * transaction" statement the route makes in a 200 body, so it gets the same
332
+ * treatment.
329
333
  */
330
334
  function ambiguousBroadcast(message, { status, details } = {}) {
331
335
  // Deliberately never carries broadcastRuledOut. BROADCAST_FAILED is classified
@@ -333,6 +337,49 @@ function ambiguousBroadcast(message, { status, details } = {}) {
333
337
  return Object.assign(new Error(message), { code: 'BROADCAST_FAILED', status, details });
334
338
  }
335
339
 
340
+ /**
341
+ * Codes the trading API documents as returned before any broadcast on
342
+ * `/execution/standard`. The route answers them as `400 { code, message }` and
343
+ * releases its single-flight lock on the quote, because the swap never left the
344
+ * backend. Kept as an explicit list rather than a pattern: adding a code here
345
+ * lets the candidate loop sign the next quote after it, so it must be a
346
+ * deliberate edit drawn from the API's own published list.
347
+ *
348
+ * A subset of that list, not a copy. `APPROVAL_BROADCAST_FAILED` is left out:
349
+ * the API returns it only when an approval is bundled into the request, and the
350
+ * CLI never bundles one (approvals go out as their own executeTransaction
351
+ * call). The code also says the swap was not sent, not that the approval was
352
+ * not: the API notes the approval may still sit in a mempool. A response with
353
+ * it is therefore unexpected here and stays ambiguous.
354
+ */
355
+ const STANDARD_PRE_BROADCAST_CODES = Object.freeze([
356
+ 'QUOTE_EXPIRED',
357
+ 'INPUT_TRANSFER_FAILED',
358
+ 'SIMULATION_FAILED',
359
+ 'SIMULATION_MIN_RETURN_NOT_REACHED',
360
+ 'INSUFFICIENT_BALANCE',
361
+ ]);
362
+
363
+ const isAbsentTxId = (value) => value === undefined || value === null || value === '';
364
+
365
+ /**
366
+ * True only for the standard route's documented "never broadcast" answer: a 400
367
+ * whose JSON body names a listed code, carries no transaction identifier and
368
+ * has no `success` other than `false`. Anything short of all of that stays ambiguous.
369
+ */
370
+ function isStandardPreBroadcastRejection(status, parsed, body) {
371
+ return status === 400
372
+ && parsed
373
+ && isReadableBody(body)
374
+ && typeof body.code === 'string'
375
+ && STANDARD_PRE_BROADCAST_CODES.includes(body.code)
376
+ && isAbsentTxId(body.txHash)
377
+ && isAbsentTxId(body.signature)
378
+ // The documented body has no `success`; an explicit `false` says the same.
379
+ // Any other value is not this shape, so it stays ambiguous.
380
+ && (body.success === undefined || body.success === false);
381
+ }
382
+
336
383
  /**
337
384
  * A JSON body the branches below can read fields off. JSON.parse also succeeds
338
385
  * on `null`, an array and a bare string or number, none of which carry the
@@ -524,10 +571,26 @@ export async function executeTransaction(params, { retries = 2, retryDelayMs = 1
524
571
  );
525
572
  }
526
573
 
527
- // A non-2xx status does not prove the signed transaction stayed put. The
528
- // backend or an intermediary may have produced the response after forwarding
529
- // it, so preserve any structured error only as diagnostic detail and fail
530
- // closed. Do not allow the candidate loop to sign another transaction.
574
+ // The standard route's documented pre-broadcast rejection. Returned as the
575
+ // same "Failed, no hash" result a 200 `success: false` body produces, so the
576
+ // candidate loop releases the claim and tries the next quote exactly as it
577
+ // already does for that body.
578
+ //
579
+ // First attempt only: a retry follows a 5xx or a dropped connection whose
580
+ // outcome is unknown, and a later "never broadcast" speaks for the retry,
581
+ // not for the earlier POST that may have gone out.
582
+ if (isStandard && attempt === 0 && isStandardPreBroadcastRejection(res.status, parsed, body)) {
583
+ return fromStandardResponse(
584
+ { ...body, success: false, txHash: undefined, signature: undefined },
585
+ chainConfigFor(params.chain)?.type,
586
+ );
587
+ }
588
+
589
+ // Every other non-2xx status does not prove the signed transaction stayed
590
+ // put. The backend or an intermediary may have produced the response after
591
+ // forwarding it, so preserve any structured error only as diagnostic detail
592
+ // and fail closed. Do not allow the candidate loop to sign another
593
+ // transaction.
531
594
  if (!res.ok) {
532
595
  const readableBody = parsed && isReadableBody(body);
533
596
  throw ambiguousBroadcast(