nansen-cli 1.45.0 → 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/CHANGELOG.md +64 -0
- package/README.md +29 -4
- package/package.json +1 -1
- package/skills/nansen-trading/SKILL.md +20 -1
- package/skills/nansen-wallet-keychain-migration/SKILL.md +18 -13
- package/skills/nansen-wallet-manager/SKILL.md +15 -1
- package/src/api.js +118 -26
- package/src/bridge.js +187 -68
- package/src/chain-ids.js +1 -2
- package/src/cli.js +314 -94
- package/src/commands/agent.js +5 -2
- package/src/commands/alerts.js +1 -1
- package/src/commands/mcp.js +2 -2
- package/src/commands/research.js +4 -2
- package/src/ens.js +3 -1
- package/src/execute-guard.js +116 -0
- package/src/limit-order.js +9 -1
- package/src/perp.js +20 -9
- package/src/query-options.js +38 -6
- package/src/response-meta.js +1 -1
- package/src/schema.json +124 -22
- package/src/trading.js +545 -16
- package/src/transfer.js +22 -3
- package/src/wallet.js +133 -3
- package/src/walletconnect-trading.js +5 -3
- package/src/walletconnect-x402.js +9 -5
package/src/trading.js
CHANGED
|
@@ -17,11 +17,13 @@ import { getWalletConnectAddress, sendTransactionViaWalletConnect, sendSolanaTra
|
|
|
17
17
|
import { retrievePassword } from './keychain.js';
|
|
18
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';
|
|
19
19
|
import { readCompactU16 } from './solana-tx.js';
|
|
20
|
+
import { formatPlan, guardExecution, resolveExecuteGuard } from './execute-guard.js';
|
|
20
21
|
export { readCompactU16 };
|
|
21
22
|
import { CHAIN_RPCS } from './rpc-urls.js';
|
|
22
23
|
import { simulateAssetChanges, SwapSimulationError, hasSimulationRpc } from './swap-simulation.js';
|
|
23
24
|
import { simulateSolanaAssetChanges, SolanaSimulationError, hasSolanaSimulationRpc } from './solana-simulation.js';
|
|
24
25
|
import { packageVersion, CommandError, telemetryHeaders, loadConfig } from './api.js';
|
|
26
|
+
import { screenOrThrow } from './perp.js';
|
|
25
27
|
|
|
26
28
|
// ============= Constants =============
|
|
27
29
|
|
|
@@ -793,18 +795,58 @@ export function signEvmTransaction(txData, privateKeyHex, chain, nonce) {
|
|
|
793
795
|
}, privateKeyHex);
|
|
794
796
|
}
|
|
795
797
|
|
|
796
|
-
//
|
|
797
|
-
//
|
|
798
|
-
|
|
799
|
-
if (!txData.gasPrice) {
|
|
800
|
-
throw new Error(
|
|
801
|
-
'Quote supplied no gas price (expected gasPrice or maxFeePerGas), so any signed transaction would be unmineable. Refusing to sign.',
|
|
802
|
-
);
|
|
803
|
-
}
|
|
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);
|
|
804
801
|
|
|
805
802
|
return signLegacyTransaction({ ...common, gasPrice: toHex(txData.gasPrice) }, privateKeyHex);
|
|
806
803
|
}
|
|
807
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
|
+
|
|
808
850
|
/**
|
|
809
851
|
* Canonical EVM transaction hash: keccak256 over the raw signed tx bytes.
|
|
810
852
|
*
|
|
@@ -1613,6 +1655,10 @@ export function buildApprovalTransaction(tokenAddress, spenderAddress, privateKe
|
|
|
1613
1655
|
const chainConfig = CHAIN_MAP[chain];
|
|
1614
1656
|
if (!chainConfig) throw new Error(`Unsupported chain: ${chain}`);
|
|
1615
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
|
+
|
|
1616
1662
|
// Scope the approval to the swap's input amount so a malicious or buggy quote
|
|
1617
1663
|
// can drain at most this one trade, never the wallet's full token balance.
|
|
1618
1664
|
// encodeApproveCalldata enforces a valid 20-byte spender, a bounded (< MAX)
|
|
@@ -1621,7 +1667,7 @@ export function buildApprovalTransaction(tokenAddress, spenderAddress, privateKe
|
|
|
1621
1667
|
|
|
1622
1668
|
const tx = {
|
|
1623
1669
|
nonce,
|
|
1624
|
-
gasPrice: toHex(gasPrice
|
|
1670
|
+
gasPrice: toHex(gasPrice),
|
|
1625
1671
|
gasLimit: '0x186a0', // 100000
|
|
1626
1672
|
to: tokenAddress,
|
|
1627
1673
|
value: '0x0',
|
|
@@ -2019,13 +2065,316 @@ export function formatQuote(quote, index) {
|
|
|
2019
2065
|
return lines.join('\n');
|
|
2020
2066
|
}
|
|
2021
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
|
+
|
|
2022
2344
|
// ============= CLI Command Builder =============
|
|
2023
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
|
+
|
|
2024
2365
|
/**
|
|
2025
2366
|
* Build trading command handlers for CLI integration.
|
|
2026
2367
|
*/
|
|
2027
2368
|
export function buildTradingCommands(deps = {}) {
|
|
2028
|
-
const {
|
|
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;
|
|
2029
2378
|
|
|
2030
2379
|
return {
|
|
2031
2380
|
'quote': async (args, apiInstance, flags, options) => {
|
|
@@ -2094,6 +2443,8 @@ PREREQUISITE:
|
|
|
2094
2443
|
A wallet must be configured before using this command (the trading API builds
|
|
2095
2444
|
a transaction specific to your sender address).
|
|
2096
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)
|
|
2097
2448
|
|
|
2098
2449
|
OPTIONS:
|
|
2099
2450
|
--chain <chain> Source chain: solana, base
|
|
@@ -2370,6 +2721,15 @@ CROSS-CHAIN NOTES (when using --to-chain):
|
|
|
2370
2721
|
if (maxAutoSlippage != null) params.maxAutoSlippagePercent = maxAutoSlippage;
|
|
2371
2722
|
if (swapMode !== 'exactIn') params.swapMode = swapMode;
|
|
2372
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
|
+
|
|
2373
2733
|
const response = await getQuote(params);
|
|
2374
2734
|
|
|
2375
2735
|
if (!response.success || !response.quotes?.length) {
|
|
@@ -2507,6 +2867,7 @@ CROSS-CHAIN NOTES (when using --to-chain):
|
|
|
2507
2867
|
const noRevokeExcessiveAllowance = flags['no-revoke-excessive-allowance'];
|
|
2508
2868
|
const noVerifyOutcome = flags['no-verify-outcome'];
|
|
2509
2869
|
const gasless = Boolean(flags.gasless);
|
|
2870
|
+
const guard = resolveExecuteGuard(flags, { env, isTTY });
|
|
2510
2871
|
// Read the API key for the swap-outcome sim endpoint. It's optional (the
|
|
2511
2872
|
// check degrades to a warning if the endpoint can't authenticate), so a
|
|
2512
2873
|
// malformed config must not crash an in-progress trade — fall back to null.
|
|
@@ -2521,6 +2882,10 @@ CROSS-CHAIN NOTES (when using --to-chain):
|
|
|
2521
2882
|
if (!quoteId) {
|
|
2522
2883
|
throw new CommandError(`Usage: nansen trade execute --quote <quoteId> [options]
|
|
2523
2884
|
|
|
2885
|
+
PREREQUISITE:
|
|
2886
|
+
API access is required for pre-trade compliance screening.
|
|
2887
|
+
Authenticate with: nansen login (or set NANSEN_API_KEY)
|
|
2888
|
+
|
|
2524
2889
|
OPTIONS:
|
|
2525
2890
|
--quote <id> Quote ID from 'nansen quote'
|
|
2526
2891
|
--wallet <name> Wallet name (default: default wallet)
|
|
@@ -2529,9 +2894,20 @@ OPTIONS:
|
|
|
2529
2894
|
--no-revoke-excessive-allowance
|
|
2530
2895
|
Skip auto-revoking an oversized/legacy allowance before re-approving
|
|
2531
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
|
|
2532
2906
|
|
|
2533
2907
|
EXAMPLES:
|
|
2534
|
-
nansen trade execute --quote 1708900000000-abc123
|
|
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');
|
|
2535
2911
|
}
|
|
2536
2912
|
|
|
2537
2913
|
try {
|
|
@@ -2565,6 +2941,123 @@ EXAMPLES:
|
|
|
2565
2941
|
throw new CommandError('❌ No quotes contain transaction data.\n Ensure userWalletAddress was provided when fetching the quote.', 'NO_TRANSACTION');
|
|
2566
2942
|
}
|
|
2567
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
|
+
|
|
2568
3061
|
// Determine if this is a WalletConnect or Privy-signed quote
|
|
2569
3062
|
const isWalletConnect = quoteData.signerType === 'walletconnect'
|
|
2570
3063
|
|| walletName === 'walletconnect' || walletName === 'wc';
|
|
@@ -2572,6 +3065,10 @@ EXAMPLES:
|
|
|
2572
3065
|
|
|
2573
3066
|
let exported = null;
|
|
2574
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;
|
|
2575
3072
|
if (isPrivy) {
|
|
2576
3073
|
// Privy signing -- import + instantiate once for all quotes
|
|
2577
3074
|
const { PrivyClient } = await import('./privy.js');
|
|
@@ -2604,6 +3101,13 @@ EXAMPLES:
|
|
|
2604
3101
|
}
|
|
2605
3102
|
|
|
2606
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
|
+
}
|
|
2607
3111
|
} else {
|
|
2608
3112
|
// Verify WalletConnect session is still active, approved for this
|
|
2609
3113
|
// chain, and its address matches the quote. Chain-scoped (see
|
|
@@ -2628,7 +3132,32 @@ EXAMPLES:
|
|
|
2628
3132
|
: wcAddress.toLowerCase().trim() !== quoteWallet.toLowerCase().trim())) {
|
|
2629
3133
|
throw new CommandError(`Connected wallet (${wcAddress}) doesn't match quote. Get a new quote with --wallet walletconnect`, 'WALLET_MISMATCH');
|
|
2630
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
|
+
);
|
|
2631
3159
|
}
|
|
3160
|
+
await screenOrThrow(apiInstance, screenAddresses);
|
|
2632
3161
|
|
|
2633
3162
|
let lastQuoteError = null;
|
|
2634
3163
|
// Swap targets confirmed to carry contract code in this execute run, so a
|
|
@@ -2637,6 +3166,7 @@ EXAMPLES:
|
|
|
2637
3166
|
const verifiedTargets = new Set();
|
|
2638
3167
|
|
|
2639
3168
|
for (let qi = startIndex; qi < endIndex; qi++) {
|
|
3169
|
+
if (consentedCandidateIndexes && !consentedCandidateIndexes.has(qi)) continue;
|
|
2640
3170
|
const currentQuote = allQuotes[qi];
|
|
2641
3171
|
if (!currentQuote) continue;
|
|
2642
3172
|
|
|
@@ -2808,8 +3338,8 @@ EXAMPLES:
|
|
|
2808
3338
|
}
|
|
2809
3339
|
log(` ✓ Sufficient allowance exists for ${quoteName}, skipping approval`);
|
|
2810
3340
|
} else {
|
|
2811
|
-
const
|
|
2812
|
-
|
|
3341
|
+
const { maxFeePerGas: approvalMaxFee, maxPriorityFeePerGas: approvalPriorityFee } =
|
|
3342
|
+
resolveQuoteEip1559Fees(currentQuote.transaction);
|
|
2813
3343
|
|
|
2814
3344
|
if (shouldRevoke) {
|
|
2815
3345
|
log(` ⚠ Existing allowance (${existingAllowance}) for ${quoteName} is excessive (>${OVERSIZED_ALLOWANCE_MULTIPLIER}x this trade) — revoking before re-approving`);
|
|
@@ -2959,8 +3489,7 @@ EXAMPLES:
|
|
|
2959
3489
|
const nonce = await getEvmNonce(chain, walletAddress);
|
|
2960
3490
|
|
|
2961
3491
|
// Privy signs EIP-1559 (type 2) transactions, so convert gasPrice to EIP-1559 fields
|
|
2962
|
-
const maxFee
|
|
2963
|
-
const priorityFee = txData.maxPriorityFeePerGas || '1000000';
|
|
3492
|
+
const { maxFeePerGas: maxFee, maxPriorityFeePerGas: priorityFee } = resolveQuoteEip1559Fees(txData);
|
|
2964
3493
|
|
|
2965
3494
|
log(' Signing EVM transaction via Privy...');
|
|
2966
3495
|
const signResult = await privyClient.signEvmTransaction(evmWalletId, {
|
|
@@ -3514,7 +4043,7 @@ EXAMPLES:
|
|
|
3514
4043
|
}
|
|
3515
4044
|
log(` ✓ Sufficient allowance exists for ${quoteName}, skipping approval`);
|
|
3516
4045
|
} else {
|
|
3517
|
-
const approvalGasPrice = currentQuote.transaction
|
|
4046
|
+
const approvalGasPrice = resolveQuoteLegacyGasPrice(currentQuote.transaction);
|
|
3518
4047
|
|
|
3519
4048
|
if (shouldRevoke) {
|
|
3520
4049
|
log(` ⚠ Existing allowance (${existingAllowance}) for ${quoteName} is excessive (>${OVERSIZED_ALLOWANCE_MULTIPLIER}x this trade) — revoking before re-approving`);
|