nansen-cli 1.44.3 → 1.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/trading.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * Zero external dependencies — uses Node.js built-in crypto only.
6
6
  */
7
7
 
8
+ import { rejectBlankOption } from './query-options.js';
8
9
  import crypto from 'crypto';
9
10
  import fs from 'fs';
10
11
  import path from 'path';
@@ -16,11 +17,13 @@ import { getWalletConnectAddress, sendTransactionViaWalletConnect, sendSolanaTra
16
17
  import { retrievePassword } from './keychain.js';
17
18
  import { validateQuoteInput, validateBalance, resolvePercentAmount, validateGasBalance, encodeApproveCalldata, assertValidApprovalSpender, assertQuoteMatchesRequest, assertSwapCalldataNotBareTransfer, assertSwapOutcome, assertSolanaInstructionsSafe, assertSolanaSwapOutcome, approvalAmountForSwap, needsAllowanceRevoke, OVERSIZED_ALLOWANCE_MULTIPLIER, EVM_BRIDGE_NATIVE_FEE_SLACK, isBridgeRequest } from './trade-validation.js';
18
19
  import { readCompactU16 } from './solana-tx.js';
20
+ import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
19
21
  export { readCompactU16 };
20
22
  import { CHAIN_RPCS } from './rpc-urls.js';
21
23
  import { simulateAssetChanges, SwapSimulationError, hasSimulationRpc } from './swap-simulation.js';
22
24
  import { simulateSolanaAssetChanges, SolanaSimulationError, hasSolanaSimulationRpc } from './solana-simulation.js';
23
25
  import { packageVersion, CommandError, telemetryHeaders, loadConfig } from './api.js';
26
+ import { screenOrThrow } from './perp.js';
24
27
 
25
28
  // ============= Constants =============
26
29
 
@@ -792,18 +795,58 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce) {
792
795
  }, privateKeyHex);
793
796
  }
794
797
 
795
- // Previously this fell back to a gasPrice of 1 wei, which signs a transaction
796
- // that can never be mined and burns the nonce. Refuse instead: a quote with no
797
- // fee information at all is a bug upstream, not something to sign through.
798
- if (!txData.gasPrice) {
799
- throw new Error(
800
- 'Quote supplied no gas price (expected gasPrice or maxFeePerGas), so any signed transaction would be unmineable. Refusing to sign.',
801
- );
802
- }
798
+ // A gasPrice-only quote stays a legacy transaction; a quote with no fee
799
+ // information at all is refused (see NO_QUOTE_FEE_MESSAGE).
800
+ if (!txData.gasPrice) throw new Error(NO_QUOTE_FEE_MESSAGE);
803
801
 
804
802
  return signLegacyTransaction({ ...common, gasPrice: toHex(txData.gasPrice) }, privateKeyHex);
805
803
  }
806
804
 
805
+ // Previously the signers fell back to a hardcoded gas price (1 wei here, then
806
+ // 1,000,000 wei = 0.001 gwei in the Privy/approval paths), which signs a
807
+ // transaction that can never be mined and leaves the nonce stuck for every
808
+ // later attempt. Refuse instead: a quote with no fee information at all is a
809
+ // bug upstream, not something to sign through. signEvmTransaction refuses it
810
+ // directly; the Privy swap path and the approval/revoke transactions that
811
+ // precede a swap resolve their fee fields through the two helpers below so the
812
+ // refusal is uniform.
813
+ const NO_QUOTE_FEE_MESSAGE =
814
+ 'Quote supplied no gas price (expected gasPrice or maxFeePerGas), so any signed transaction would be unmineable. Refusing to sign.';
815
+
816
+ /**
817
+ * Resolve the fee fields for an EIP-1559 (type 2) signer from a quote's
818
+ * transaction. A legacy-only quote (gasPrice, no maxFeePerGas) is lifted into
819
+ * type 2 by using gasPrice as the fee cap. A zero priority fee is a valid choice
820
+ * but not a sane default, so it falls back to the fee cap rather than to
821
+ * nothing when the quote omits it.
822
+ *
823
+ * @param {object} txData - Quote transaction fields
824
+ * @returns {{ maxFeePerGas: string|number, maxPriorityFeePerGas: string|number }}
825
+ * @throws {Error} when the quote carries neither maxFeePerGas nor gasPrice
826
+ */
827
+ export function resolveQuoteEip1559Fees(txData) {
828
+ const maxFeePerGas = txData?.maxFeePerGas || txData?.gasPrice;
829
+ if (!maxFeePerGas) throw new Error(NO_QUOTE_FEE_MESSAGE);
830
+ return {
831
+ maxFeePerGas,
832
+ maxPriorityFeePerGas: txData.maxPriorityFeePerGas || maxFeePerGas,
833
+ };
834
+ }
835
+
836
+ /**
837
+ * Resolve the gas price for a legacy (type 0) signer from a quote's
838
+ * transaction. An EIP-1559-only quote is flattened to its fee cap.
839
+ *
840
+ * @param {object} txData - Quote transaction fields
841
+ * @returns {string|number} gas price in wei
842
+ * @throws {Error} when the quote carries neither gasPrice nor maxFeePerGas
843
+ */
844
+ export function resolveQuoteLegacyGasPrice(txData) {
845
+ const gasPrice = txData?.gasPrice || txData?.maxFeePerGas;
846
+ if (!gasPrice) throw new Error(NO_QUOTE_FEE_MESSAGE);
847
+ return gasPrice;
848
+ }
849
+
807
850
  /**
808
851
  * Canonical EVM transaction hash: keccak256 over the raw signed tx bytes.
809
852
  *
@@ -1612,6 +1655,10 @@ export function buildApprovalTransaction(tokenAddress, spenderAddress, privateKe
1612
1655
  const chainConfig = CHAIN_MAP[chain];
1613
1656
  if (!chainConfig) throw new Error(`Unsupported chain: ${chain}`);
1614
1657
 
1658
+ // An approval broadcast at a placeholder fee never mines and blocks the swap
1659
+ // behind it, so require a real gas price the same way signEvmTransaction does.
1660
+ if (!gasPrice) throw new Error(NO_QUOTE_FEE_MESSAGE);
1661
+
1615
1662
  // Scope the approval to the swap's input amount so a malicious or buggy quote
1616
1663
  // can drain at most this one trade, never the wallet's full token balance.
1617
1664
  // encodeApproveCalldata enforces a valid 20-byte spender, a bounded (< MAX)
@@ -1620,7 +1667,7 @@ export function buildApprovalTransaction(tokenAddress, spenderAddress, privateKe
1620
1667
 
1621
1668
  const tx = {
1622
1669
  nonce,
1623
- gasPrice: toHex(gasPrice || '1000000'),
1670
+ gasPrice: toHex(gasPrice),
1624
1671
  gasLimit: '0x186a0', // 100000
1625
1672
  to: tokenAddress,
1626
1673
  value: '0x0',
@@ -2018,16 +2065,325 @@ export function formatQuote(quote, index) {
2018
2065
  return lines.join('\n');
2019
2066
  }
2020
2067
 
2068
+ // ============= Execution plan (--dry-run / confirmation) =============
2069
+
2070
+ /**
2071
+ * Describe the swap `trade execute` is about to sign, for the confirmation
2072
+ * prompt and for --dry-run. Reads only the cached quote and (on a dry run)
2073
+ * read-only RPC state — it never touches wallet material, so a dry run works
2074
+ * on a locked wallet and cannot sign anything.
2075
+ *
2076
+ * `probe` runs the extra read-only checks that only make sense when the user
2077
+ * asked for a preview: the current ERC-20 allowance and the pre-broadcast
2078
+ * revert simulation. Both degrade to a note if the endpoint is unavailable.
2079
+ */
2080
+ export async function buildTradeExecutionPlan({
2081
+ quoteId,
2082
+ quoteData,
2083
+ quote,
2084
+ chainConfig,
2085
+ quoteIndex = 0,
2086
+ quoteCount = 1,
2087
+ walletAddress = null,
2088
+ gasless = false,
2089
+ noSimulate = false,
2090
+ noVerifyOutcome = false,
2091
+ probe = false,
2092
+ }) {
2093
+ const request = quoteData.request || {};
2094
+ const chain = quoteData.chain;
2095
+ const isNative = isNativeToken(quote.inputMint);
2096
+ const spender = quote.approvalAddress && quote.approvalAddress !== '' && !isNative
2097
+ ? quote.approvalAddress
2098
+ : null;
2099
+
2100
+ let approval = isNative ? 'not required (native token input)' : 'not required';
2101
+ let approvalPending = false;
2102
+ if (spender) {
2103
+ const approveAmt = approvalAmountForSwap({
2104
+ inputAmount: quote.inputAmount || quote.inAmount || '0',
2105
+ swapMode: quoteData.swapMode,
2106
+ slippage: quoteData.slippage,
2107
+ });
2108
+ approval = `required → ${spender} (scoped to ${approveAmt} base units)`;
2109
+ approvalPending = true;
2110
+ if (probe && walletAddress) {
2111
+ try {
2112
+ const existing = await checkErc20Allowance(chain, quote.inputMint, walletAddress, spender);
2113
+ if (existing >= approveAmt) {
2114
+ approval = `already granted to ${spender} (${existing} base units) — no approval transaction needed`;
2115
+ approvalPending = false;
2116
+ } else {
2117
+ approval += `; current allowance is ${existing}`;
2118
+ }
2119
+ } catch (err) {
2120
+ approval += `; current allowance could not be read (${err.message})`;
2121
+ }
2122
+ }
2123
+ }
2124
+
2125
+ // The revert simulation reads the CURRENT chain state, so it is only
2126
+ // meaningful once the router can actually pull the input token. With an
2127
+ // approval still outstanding it would report a revert that the real run
2128
+ // never hits, so say so instead of simulating.
2129
+ let simulation = null;
2130
+ if (probe && chainConfig.type === 'evm') {
2131
+ if (noSimulate) {
2132
+ simulation = 'skipped (--no-simulate)';
2133
+ } else if (gasless) {
2134
+ simulation = 'skipped (--gasless routes through the solver)';
2135
+ } else if (approvalPending) {
2136
+ simulation = 'skipped — runs after the approval transaction lands';
2137
+ } else {
2138
+ try {
2139
+ const tx = quote.transaction || {};
2140
+ const sim = await simulateEvmCall(chain, {
2141
+ from: walletAddress,
2142
+ to: tx.to,
2143
+ data: tx.data,
2144
+ value: tx.value ? '0x' + BigInt(tx.value).toString(16) : '0x0',
2145
+ });
2146
+ simulation = sim.success ? 'passed' : `❌ FAILED: ${sim.reason}`;
2147
+ } catch (err) {
2148
+ simulation = `could not run (${err.message})`;
2149
+ }
2150
+ }
2151
+ }
2152
+
2153
+ const toChain = quoteData.toChain;
2154
+ const route = toChain && toChain !== chain
2155
+ ? `${chainConfig.name} → ${resolveChain(toChain).name}`
2156
+ : chainConfig.name;
2157
+
2158
+ return formatPlan(`Trade plan — ${route}`, [
2159
+ ['Quote', `${quoteId}${quote.aggregator ? ` via ${quote.aggregator}` : ''}${quoteCount > 1 ? ` (quote ${quoteIndex + 1} of ${quoteCount})` : ''}`],
2160
+ ['Sell', `${quote.inAmount ?? quote.inputAmount ?? '?'} base units of ${request.fromToken || quote.inputMint}`],
2161
+ ['Buy', `~${quote.outAmount ?? '?'} base units of ${request.toToken || quote.outputMint}`],
2162
+ ['Max spend', request.maxInputAmount ? `${request.maxInputAmount} base units` : null],
2163
+ ['Wallet', walletAddress || 'the wallet this quote was created for'],
2164
+ ['Recipient', request.recipient || null],
2165
+ ['Trading fee', quote.tradingFeeInUsd ? `$${quote.tradingFeeInUsd}` : null],
2166
+ ['Network fee', quote.networkFeeInUsd ? `$${quote.networkFeeInUsd}` : null],
2167
+ ['Approval', approval],
2168
+ ['Gas', gasless ? 'paid by the solver (--gasless)' : null],
2169
+ ['Simulation', simulation],
2170
+ ['Outcome check', noVerifyOutcome ? 'off (--no-verify-outcome)' : 'on, before broadcast'],
2171
+ ]);
2172
+ }
2173
+
2174
+ /**
2175
+ * Run every execute validation that can be completed from a cached quote,
2176
+ * public signer address, and read-only RPC calls. This intentionally does not
2177
+ * resolve signing credentials, sign, broadcast, or consume the quote.
2178
+ *
2179
+ * Real execution repeats signer binding with the independently resolved live
2180
+ * signer later. The preview uses the immutable signer saved with the request;
2181
+ * this gives --dry-run the same transaction/intent checks without requiring a
2182
+ * wallet password, Privy secret, or WalletConnect session.
2183
+ */
2184
+ async function preflightTradeExecutionCandidate({
2185
+ quoteData,
2186
+ quote,
2187
+ chain,
2188
+ chainConfig,
2189
+ walletAddress,
2190
+ isWalletConnect,
2191
+ gasless,
2192
+ noSimulate,
2193
+ noVerifyOutcome,
2194
+ apiKey,
2195
+ verifiedTargets,
2196
+ log,
2197
+ }) {
2198
+ if (gasless && quote.aggregator !== 'relay') {
2199
+ throw new CommandError(
2200
+ `--gasless is only supported for Relay quotes, not "${quote.aggregator}".`,
2201
+ 'GASLESS_UNSUPPORTED_AGGREGATOR',
2202
+ );
2203
+ }
2204
+ if (gasless && isWalletConnect) {
2205
+ throw new CommandError(
2206
+ 'Gasless swaps are not supported via WalletConnect. Use a local or Privy wallet.',
2207
+ 'GASLESS_UNSUPPORTED_WALLET',
2208
+ );
2209
+ }
2210
+
2211
+ if (!walletAddress) {
2212
+ throw new CommandError(
2213
+ 'The cached quote has no signer address, so it cannot be validated safely. Request a new quote.',
2214
+ 'WALLET_MISMATCH',
2215
+ );
2216
+ }
2217
+
2218
+ if (chainConfig.type === 'solana') {
2219
+ assertCompleteSolanaRequestIntent(quoteData.request);
2220
+ assertQuoteMatchesRequest(quoteData.request, quote, {
2221
+ chain,
2222
+ walletAddress,
2223
+ slippage: quoteData.slippage,
2224
+ });
2225
+ const txBase64 = await normalizeSolanaTransaction(
2226
+ quote.transaction,
2227
+ CHAIN_RPCS.solana,
2228
+ async () => walletAddress,
2229
+ );
2230
+ assertSolanaInstructionsSafe(txBase64, { walletAddress });
2231
+ if (!noVerifyOutcome) {
2232
+ const outcome = await verifySolanaSwapOutcome({
2233
+ chain,
2234
+ walletAddress,
2235
+ txBase64,
2236
+ quote,
2237
+ quoteData,
2238
+ log,
2239
+ });
2240
+ if (!outcome.proceed) {
2241
+ throw new CommandError(
2242
+ `Swap-outcome verification failed: ${outcome.reason}`,
2243
+ 'OUTCOME_VERIFICATION_FAILED',
2244
+ );
2245
+ }
2246
+ }
2247
+ return;
2248
+ }
2249
+
2250
+ await validateSwapTarget(chain, quote.transaction.to, quote.inputMint, { verifiedTargets });
2251
+ assertCompleteEvmRequestIntent(quoteData.request);
2252
+ assertQuoteMatchesRequest(quoteData.request, quote, {
2253
+ chain,
2254
+ walletAddress,
2255
+ slippage: quoteData.slippage,
2256
+ });
2257
+ assertSwapCalldataNotBareTransfer(quote.transaction.data);
2258
+
2259
+ const nativeInput = isNativeToken(quote.inputMint);
2260
+ const txValue = BigInt(quote.transaction.value || '0');
2261
+ if (nativeInput) {
2262
+ const expectedValue = BigInt(quote.inAmount || quote.inputAmount || '0');
2263
+ if (txValue !== expectedValue) {
2264
+ throw new CommandError(
2265
+ `Transaction value mismatch: tx.value=${txValue}, expected=${expectedValue}`,
2266
+ 'AMOUNT_MISMATCH',
2267
+ );
2268
+ }
2269
+ } else {
2270
+ const bridgeFeeAllowed = quoteData?.request
2271
+ && isBridgeRequest(quoteData.request)
2272
+ && txValue <= EVM_BRIDGE_NATIVE_FEE_SLACK;
2273
+ if (txValue > 0n && !bridgeFeeAllowed) {
2274
+ throw new CommandError(
2275
+ `ERC-20 swap has unexpected non-zero tx.value (${txValue}).`,
2276
+ 'AMOUNT_MISMATCH',
2277
+ );
2278
+ }
2279
+ }
2280
+
2281
+ let approvalPending = false;
2282
+ if (quote.approvalAddress && quote.approvalAddress !== '' && !nativeInput) {
2283
+ assertUsableSpender(quote.approvalAddress);
2284
+ const inputAmount = BigInt(quote.inputAmount || quote.inAmount || '0');
2285
+ const approveAmt = approvalAmountForSwap({
2286
+ inputAmount,
2287
+ swapMode: quoteData.swapMode,
2288
+ slippage: quoteData.slippage,
2289
+ });
2290
+ if (approveAmt <= 0n) {
2291
+ throw new CommandError('Quote has a zero input amount, so its approval cannot be scoped safely.', 'INVALID_AMOUNT');
2292
+ }
2293
+ // Exercise the same spender/amount/cap encoder used immediately before a
2294
+ // real approval is signed, but discard the calldata.
2295
+ encodeApproveCalldata(quote.approvalAddress, approveAmt, {
2296
+ maxAllowance: approvalCapForQuote(quoteData),
2297
+ });
2298
+ const existingAllowance = await checkErc20Allowance(
2299
+ chain,
2300
+ quote.inputMint,
2301
+ walletAddress,
2302
+ quote.approvalAddress,
2303
+ );
2304
+ approvalPending = existingAllowance < approveAmt;
2305
+ }
2306
+
2307
+ // These checks require the router to be able to pull the input token. A real
2308
+ // execute runs them after its approval lands; a preview with an outstanding
2309
+ // approval cannot reproduce that future state and reports the deferral in
2310
+ // its plan instead.
2311
+ if (!approvalPending) {
2312
+ if (!noSimulate && !gasless) {
2313
+ const tx = quote.transaction;
2314
+ const sim = await simulateEvmCall(chain, {
2315
+ from: walletAddress,
2316
+ to: tx.to,
2317
+ data: tx.data,
2318
+ value: tx.value ? '0x' + BigInt(tx.value).toString(16) : '0x0',
2319
+ });
2320
+ if (!sim.success) {
2321
+ throw new CommandError(`Pre-broadcast simulation failed: ${sim.reason}`, 'SIMULATION_FAILED');
2322
+ }
2323
+ }
2324
+ if (!noVerifyOutcome) {
2325
+ const outcome = await verifySwapOutcome({
2326
+ chain,
2327
+ from: walletAddress,
2328
+ quote,
2329
+ quoteData,
2330
+ apiKey,
2331
+ log,
2332
+ });
2333
+ if (!outcome.proceed) {
2334
+ throw new CommandError(
2335
+ `Swap-outcome verification failed: ${outcome.reason}`,
2336
+ 'OUTCOME_VERIFICATION_FAILED',
2337
+ );
2338
+ }
2339
+ }
2340
+ await resolveEvmSwapGasLimit(quote, { chain, from: walletAddress });
2341
+ }
2342
+ }
2343
+
2021
2344
  // ============= CLI Command Builder =============
2022
2345
 
2346
+ // Addresses a swap must clear compliance screening for: the wallet that signs
2347
+ // plus any distinct destination wallet. Blanks are dropped and duplicates
2348
+ // removed — case-insensitively for EVM addresses, exactly for base58 (Solana
2349
+ // addresses are case-sensitive, so two strings differing only in case are
2350
+ // different wallets). Exported for tests.
2351
+ export function tradeScreeningAddresses(...addresses) {
2352
+ const seen = new Set();
2353
+ const out = [];
2354
+ for (const raw of addresses) {
2355
+ if (!raw) continue;
2356
+ const address = String(raw);
2357
+ const key = /^0x[0-9a-f]{40}$/i.test(address) ? address.toLowerCase() : address;
2358
+ if (seen.has(key)) continue;
2359
+ seen.add(key);
2360
+ out.push(address);
2361
+ }
2362
+ return out;
2363
+ }
2364
+
2023
2365
  /**
2024
2366
  * Build trading command handlers for CLI integration.
2025
2367
  */
2026
2368
  export function buildTradingCommands(deps = {}) {
2027
- const { log = console.log } = deps;
2369
+ const {
2370
+ log = console.log,
2371
+ // Injected so the confirmation prompt (and whether there is anyone to
2372
+ // answer it) can be driven in tests without a terminal.
2373
+ promptFn,
2374
+ confirmationLog = log,
2375
+ isTTY = false,
2376
+ env = process.env,
2377
+ } = deps;
2028
2378
 
2029
2379
  return {
2030
2380
  'quote': async (args, apiInstance, flags, options) => {
2381
+ for (const [name, example] of [
2382
+ ['swap-mode', 'exactIn'], ['wallet', '<name>'], ['to-chain', 'solana'],
2383
+ ['aggregator', 'relay'], ['amount-unit', 'base'],
2384
+ ]) {
2385
+ rejectBlankOption(options[name], name, example);
2386
+ }
2031
2387
  const chain = options.chain || args[0];
2032
2388
  const toChainRaw = options['to-chain'];
2033
2389
  const fromRaw = options.from || options['from-token'] || args[1];
@@ -2061,6 +2417,15 @@ export function buildTradingCommands(deps = {}) {
2061
2417
  // can't become a 300% slippage tolerance.
2062
2418
  for (const [optName, optVal] of [['slippage', slippage], ['max-auto-slippage', maxAutoSlippage]]) {
2063
2419
  if (optVal == null) continue;
2420
+ // A blank value must not read as "not supplied": `Number('')` is 0, which
2421
+ // would pass the range check below and satisfy the exactOut cap
2422
+ // requirement even though the caller supplied no number.
2423
+ if (typeof optVal === 'string' && optVal.trim() === '') {
2424
+ throw new CommandError(
2425
+ `Invalid --${optName} "". Use a decimal between 0 and 1 (e.g. 0.03 for 3%).`,
2426
+ 'INVALID_SLIPPAGE'
2427
+ );
2428
+ }
2064
2429
  const n = Number(optVal);
2065
2430
  if (!Number.isFinite(n) || n < 0 || n > 1) {
2066
2431
  throw new CommandError(
@@ -2078,6 +2443,8 @@ PREREQUISITE:
2078
2443
  A wallet must be configured before using this command (the trading API builds
2079
2444
  a transaction specific to your sender address).
2080
2445
  Set one up with: nansen wallet create
2446
+ API access is required for pre-trade compliance screening.
2447
+ Authenticate with: nansen login (or set NANSEN_API_KEY)
2081
2448
 
2082
2449
  OPTIONS:
2083
2450
  --chain <chain> Source chain: solana, base
@@ -2349,11 +2716,20 @@ CROSS-CHAIN NOTES (when using --to-chain):
2349
2716
  }
2350
2717
  }
2351
2718
  }
2352
- if (slippage) params.slippagePercent = slippage;
2719
+ if (slippage != null) params.slippagePercent = slippage;
2353
2720
  if (autoSlippage) params.autoSlippage = true;
2354
- if (maxAutoSlippage) params.maxAutoSlippagePercent = maxAutoSlippage;
2721
+ if (maxAutoSlippage != null) params.maxAutoSlippagePercent = maxAutoSlippage;
2355
2722
  if (swapMode !== 'exactIn') params.swapMode = swapMode;
2356
2723
 
2724
+ // Compliance screen before the quote request — the same fail-closed
2725
+ // check `bridge` and `perp` run. Quotes are fetched from the trading
2726
+ // backend directly, so nothing else screens this path; refuse here so a
2727
+ // flagged wallet never receives a signable quote. Screens the signing
2728
+ // wallet plus any distinct destination wallet (--to-wallet or the
2729
+ // auto-derived cross-chain destination). Throws SANCTIONED for a hit
2730
+ // and SCREENING_UNAVAILABLE if the check itself cannot complete.
2731
+ await screenOrThrow(apiInstance, tradeScreeningAddresses(walletAddress, params.toWalletAddress));
2732
+
2357
2733
  const response = await getQuote(params);
2358
2734
 
2359
2735
  if (!response.success || !response.quotes?.length) {
@@ -2484,12 +2860,14 @@ CROSS-CHAIN NOTES (when using --to-chain):
2484
2860
  },
2485
2861
 
2486
2862
  'execute': async (args, apiInstance, flags, options) => {
2863
+ rejectBlankOption(options.wallet, 'wallet', '<name>');
2487
2864
  const quoteId = options.quote || options['quote-id'] || args[0];
2488
2865
  const walletName = options.wallet;
2489
2866
  const noSimulate = flags['no-simulate'];
2490
2867
  const noRevokeExcessiveAllowance = flags['no-revoke-excessive-allowance'];
2491
2868
  const noVerifyOutcome = flags['no-verify-outcome'];
2492
2869
  const gasless = Boolean(flags.gasless);
2870
+ const guard = resolveExecuteGuard(flags, { env, isTTY });
2493
2871
  // Read the API key for the swap-outcome sim endpoint. It's optional (the
2494
2872
  // check degrades to a warning if the endpoint can't authenticate), so a
2495
2873
  // malformed config must not crash an in-progress trade — fall back to null.
@@ -2504,6 +2882,10 @@ CROSS-CHAIN NOTES (when using --to-chain):
2504
2882
  if (!quoteId) {
2505
2883
  throw new CommandError(`Usage: nansen trade execute --quote <quoteId> [options]
2506
2884
 
2885
+ PREREQUISITE:
2886
+ API access is required for pre-trade compliance screening.
2887
+ Authenticate with: nansen login (or set NANSEN_API_KEY)
2888
+
2507
2889
  OPTIONS:
2508
2890
  --quote <id> Quote ID from 'nansen quote'
2509
2891
  --wallet <name> Wallet name (default: default wallet)
@@ -2512,9 +2894,20 @@ OPTIONS:
2512
2894
  --no-revoke-excessive-allowance
2513
2895
  Skip auto-revoking an oversized/legacy allowance before re-approving
2514
2896
  --gasless Relay-only: have Relay's solver pay gas (no WalletConnect)
2897
+ --dry-run Validate and print what would be sent, then stop.
2898
+ Nothing is signed or broadcast and the quote stays usable.
2899
+ --yes, -y Skip the confirmation prompt (same as NANSEN_YES=1).
2900
+ The prompt only appears when stdin is a terminal; agents,
2901
+ CI and pipes are never prompted, with or without --yes.
2902
+
2903
+ EXIT CODES:
2904
+ 0 broadcast succeeded, or the dry run completed
2905
+ 1 declined at the confirmation prompt, or the execution failed
2515
2906
 
2516
2907
  EXAMPLES:
2517
- nansen trade execute --quote 1708900000000-abc123`, 'MISSING_ARGS');
2908
+ nansen trade execute --quote 1708900000000-abc123
2909
+ nansen trade execute --quote 1708900000000-abc123 --dry-run
2910
+ nansen trade execute --quote 1708900000000-abc123 --yes`, 'MISSING_ARGS');
2518
2911
  }
2519
2912
 
2520
2913
  try {
@@ -2548,6 +2941,123 @@ EXAMPLES:
2548
2941
  throw new CommandError('❌ No quotes contain transaction data.\n Ensure userWalletAddress was provided when fetching the quote.', 'NO_TRANSACTION');
2549
2942
  }
2550
2943
 
2944
+ // ── Acknowledgement gate: --dry-run / --yes ──────────────────────
2945
+ // Deliberately placed before any wallet material is loaded and before
2946
+ // the first approval transaction: a dry run needs no password and can
2947
+ // sign nothing, and a declined confirmation cannot have put an
2948
+ // approval on-chain. See src/execute-guard.js for the TTY rules.
2949
+ // Execution falls back across candidates when one fails before a
2950
+ // definitive broadcast. Consent must therefore cover every candidate
2951
+ // that may be signed, rather than displaying only the first one and
2952
+ // silently broadcasting a different fallback quote later.
2953
+ const planCandidates = allQuotes
2954
+ .map((quote, index) => ({ quote, index }))
2955
+ .filter(({ quote, index }) => index >= startIndex && index < endIndex && quote?.transaction);
2956
+ const shouldPreflightPlan = guard.dryRun || (guard.isTTY && !guard.assumeYes);
2957
+ const planUsesWalletConnect = quoteData.signerType === 'walletconnect'
2958
+ || walletName === 'walletconnect' || walletName === 'wc';
2959
+ if (guard.dryRun) {
2960
+ // The live signer is intentionally unavailable here: dry-run reaches
2961
+ // this gate before wallet material or a WalletConnect session is
2962
+ // resolved. Screen the public signer recorded in the cached request
2963
+ // (or legacy response metadata) plus its distinct recipient for the
2964
+ // preview. Real execution resolves the live signer below and screens
2965
+ // it again immediately before signing.
2966
+ const previewScreenAddresses = tradeScreeningAddresses(
2967
+ quoteData.request?.walletAddress || quoteData.response?.metadata?.userWalletAddress,
2968
+ quoteData.request?.recipient,
2969
+ );
2970
+ if (!previewScreenAddresses.length) {
2971
+ throw new CommandError(
2972
+ `Quote "${quoteId}" does not record which wallet it was built for, so it cannot be screened. Request a fresh quote with "nansen trade quote".`,
2973
+ 'SCREENING_UNAVAILABLE',
2974
+ );
2975
+ }
2976
+ await screenOrThrow(apiInstance, previewScreenAddresses);
2977
+ }
2978
+ const verifiedPlanTargets = new Set();
2979
+ const validatedPlanCandidates = [];
2980
+ let lastPreflightError = null;
2981
+ for (const candidate of planCandidates) {
2982
+ const planWallet = quoteData.request?.walletAddress
2983
+ || quoteData.response?.metadata?.userWalletAddress
2984
+ || candidate.quote.transaction?.from
2985
+ || null;
2986
+ try {
2987
+ if (shouldPreflightPlan) {
2988
+ await preflightTradeExecutionCandidate({
2989
+ quoteData,
2990
+ quote: candidate.quote,
2991
+ chain,
2992
+ chainConfig,
2993
+ walletAddress: planWallet,
2994
+ isWalletConnect: planUsesWalletConnect,
2995
+ gasless,
2996
+ noSimulate,
2997
+ noVerifyOutcome,
2998
+ apiKey,
2999
+ verifiedTargets: verifiedPlanTargets,
3000
+ log,
3001
+ });
3002
+ }
3003
+ validatedPlanCandidates.push(candidate);
3004
+ } catch (error) {
3005
+ lastPreflightError = error;
3006
+ }
3007
+ }
3008
+ if (!validatedPlanCandidates.length) {
3009
+ throw new CommandError(
3010
+ `\n❌ All quotes failed sign-free preflight. Last error: ${lastPreflightError?.message || 'unknown'}\n`,
3011
+ 'ALL_QUOTES_FAILED',
3012
+ );
3013
+ }
3014
+ // Non-interactive/--yes execution never consumes the plan, so avoid
3015
+ // building display strings (and their optional read-only probes) on
3016
+ // that unchanged automation path. guardExecution safely ignores the
3017
+ // empty plan whenever no preview or prompt is active.
3018
+ let plan = '';
3019
+ if (shouldPreflightPlan) {
3020
+ const plans = [];
3021
+ for (const { quote, index } of validatedPlanCandidates) {
3022
+ const planWallet = quoteData.request?.walletAddress
3023
+ || quoteData.response?.metadata?.userWalletAddress
3024
+ || quote.transaction?.from
3025
+ || null;
3026
+ plans.push(await buildTradeExecutionPlan({
3027
+ quoteId,
3028
+ quoteData,
3029
+ quote,
3030
+ chainConfig,
3031
+ quoteIndex: index,
3032
+ quoteCount: allQuotes.length,
3033
+ walletAddress: planWallet,
3034
+ gasless,
3035
+ noSimulate,
3036
+ noVerifyOutcome,
3037
+ probe: true,
3038
+ }));
3039
+ }
3040
+ const fallbackNotice = validatedPlanCandidates.length > 1
3041
+ ? '\n The CLI may try these candidates in order until one broadcasts successfully.'
3042
+ : '';
3043
+ plan = `${plans.join('\n')}${fallbackNotice}`;
3044
+ }
3045
+ // An interactive user only consented to candidates that passed the
3046
+ // sign-free preflight and appeared in this plan. Do not later retry a
3047
+ // candidate omitted after a transient or deterministic preflight
3048
+ // failure; it could otherwise recover and broadcast unseen.
3049
+ const consentedCandidateIndexes = shouldPreflightPlan
3050
+ ? new Set(validatedPlanCandidates.map(({ index }) => index))
3051
+ : null;
3052
+ const proceed = await guardExecution({
3053
+ plan,
3054
+ ...guard,
3055
+ promptFn,
3056
+ log,
3057
+ confirmationLog,
3058
+ });
3059
+ if (!proceed) return undefined;
3060
+
2551
3061
  // Determine if this is a WalletConnect or Privy-signed quote
2552
3062
  const isWalletConnect = quoteData.signerType === 'walletconnect'
2553
3063
  || walletName === 'walletconnect' || walletName === 'wc';
@@ -2555,6 +3065,10 @@ EXAMPLES:
2555
3065
 
2556
3066
  let exported = null;
2557
3067
  let privyClient = null;
3068
+ // The wallet resolved before the per-quote loop, for the pre-signing
3069
+ // compliance screen below. Stays null for Privy, whose address is
3070
+ // fetched from the provider inside the loop.
3071
+ let signerAddress = null;
2558
3072
  if (isPrivy) {
2559
3073
  // Privy signing -- import + instantiate once for all quotes
2560
3074
  const { PrivyClient } = await import('./privy.js');
@@ -2587,6 +3101,13 @@ EXAMPLES:
2587
3101
  }
2588
3102
 
2589
3103
  exported = exportWallet(effectiveWalletName, password);
3104
+ signerAddress = chainType === 'solana' ? exported.solana?.address : exported.evm?.address;
3105
+ // A wallet file with no key for this chain can neither sign nor be
3106
+ // screened. Refuse here with the same actionable message the signing
3107
+ // branch gives, rather than a generic "cannot be screened".
3108
+ if (!signerAddress) {
3109
+ throw new Error(`Could not resolve the local wallet's ${chainType === 'solana' ? 'Solana' : 'EVM'} address; cannot confirm the quote was built for this wallet. Refusing to sign.`);
3110
+ }
2590
3111
  } else {
2591
3112
  // Verify WalletConnect session is still active, approved for this
2592
3113
  // chain, and its address matches the quote. Chain-scoped (see
@@ -2611,7 +3132,32 @@ EXAMPLES:
2611
3132
  : wcAddress.toLowerCase().trim() !== quoteWallet.toLowerCase().trim())) {
2612
3133
  throw new CommandError(`Connected wallet (${wcAddress}) doesn't match quote. Get a new quote with --wallet walletconnect`, 'WALLET_MISMATCH');
2613
3134
  }
3135
+ signerAddress = wcAddress;
3136
+ }
3137
+
3138
+ // Compliance screen immediately before signing, mirroring `bridge
3139
+ // execute`: a quote stays valid for up to an hour and the signed
3140
+ // transaction is broadcast with no further check, so this is the last
3141
+ // gate before funds move. Every signing branch below refuses to sign
3142
+ // unless the wallet it resolves is `request.walletAddress`
3143
+ // (assertQuoteMatchesRequest), so that wallet — together with the
3144
+ // signer resolved above and any distinct destination wallet — is every
3145
+ // address this run can move funds from or to. Runs once, outside the
3146
+ // per-quote loop, so a refusal is final rather than "try next quote".
3147
+ // Throws SANCTIONED for a hit and SCREENING_UNAVAILABLE if the check
3148
+ // itself cannot complete; nothing is signed in either case.
3149
+ const screenAddresses = tradeScreeningAddresses(
3150
+ signerAddress,
3151
+ quoteData.request?.walletAddress,
3152
+ quoteData.request?.recipient,
3153
+ );
3154
+ if (!screenAddresses.length) {
3155
+ throw new CommandError(
3156
+ `Quote "${quoteId}" does not record which wallet it was built for, so it cannot be screened. Request a fresh quote with "nansen trade quote".`,
3157
+ 'SCREENING_UNAVAILABLE',
3158
+ );
2614
3159
  }
3160
+ await screenOrThrow(apiInstance, screenAddresses);
2615
3161
 
2616
3162
  let lastQuoteError = null;
2617
3163
  // Swap targets confirmed to carry contract code in this execute run, so a
@@ -2620,6 +3166,7 @@ EXAMPLES:
2620
3166
  const verifiedTargets = new Set();
2621
3167
 
2622
3168
  for (let qi = startIndex; qi < endIndex; qi++) {
3169
+ if (consentedCandidateIndexes && !consentedCandidateIndexes.has(qi)) continue;
2623
3170
  const currentQuote = allQuotes[qi];
2624
3171
  if (!currentQuote) continue;
2625
3172
 
@@ -2791,8 +3338,8 @@ EXAMPLES:
2791
3338
  }
2792
3339
  log(` ✓ Sufficient allowance exists for ${quoteName}, skipping approval`);
2793
3340
  } else {
2794
- const approvalMaxFee = currentQuote.transaction?.maxFeePerGas || currentQuote.transaction?.gasPrice || '1000000';
2795
- const approvalPriorityFee = currentQuote.transaction?.maxPriorityFeePerGas || '1000000';
3341
+ const { maxFeePerGas: approvalMaxFee, maxPriorityFeePerGas: approvalPriorityFee } =
3342
+ resolveQuoteEip1559Fees(currentQuote.transaction);
2796
3343
 
2797
3344
  if (shouldRevoke) {
2798
3345
  log(` ⚠ Existing allowance (${existingAllowance}) for ${quoteName} is excessive (>${OVERSIZED_ALLOWANCE_MULTIPLIER}x this trade) — revoking before re-approving`);
@@ -2942,8 +3489,7 @@ EXAMPLES:
2942
3489
  const nonce = await getEvmNonce(chain, walletAddress);
2943
3490
 
2944
3491
  // Privy signs EIP-1559 (type 2) transactions, so convert gasPrice to EIP-1559 fields
2945
- const maxFee = txData.maxFeePerGas || txData.gasPrice || '1000000';
2946
- const priorityFee = txData.maxPriorityFeePerGas || '1000000';
3492
+ const { maxFeePerGas: maxFee, maxPriorityFeePerGas: priorityFee } = resolveQuoteEip1559Fees(txData);
2947
3493
 
2948
3494
  log(' Signing EVM transaction via Privy...');
2949
3495
  const signResult = await privyClient.signEvmTransaction(evmWalletId, {
@@ -3497,7 +4043,7 @@ EXAMPLES:
3497
4043
  }
3498
4044
  log(` ✓ Sufficient allowance exists for ${quoteName}, skipping approval`);
3499
4045
  } else {
3500
- const approvalGasPrice = currentQuote.transaction?.gasPrice || currentQuote.transaction?.maxFeePerGas || '1000000';
4046
+ const approvalGasPrice = resolveQuoteLegacyGasPrice(currentQuote.transaction);
3501
4047
 
3502
4048
  if (shouldRevoke) {
3503
4049
  log(` ⚠ Existing allowance (${existingAllowance}) for ${quoteName} is excessive (>${OVERSIZED_ALLOWANCE_MULTIPLIER}x this trade) — revoking before re-approving`);