Skip to main content

nautilus_blockchain/execution/
client.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::{
17    collections::{HashMap, HashSet},
18    fmt::Debug,
19    ops::RangeInclusive,
20    str::FromStr,
21    sync::Arc,
22    time::{Duration, SystemTime, UNIX_EPOCH},
23};
24
25use alloy::{
26    primitives::{
27        Address, B256, Bytes, I256, U256,
28        aliases::{U24, U160},
29        keccak256,
30    },
31    signers::local::PrivateKeySigner,
32    sol_types::SolCall,
33};
34use anyhow::Context;
35use async_trait::async_trait;
36use nautilus_common::{
37    clients::ExecutionClient,
38    live::runner::get_exec_event_sender,
39    messages::execution::{
40        BatchCancelOrders, CancelAllOrders, CancelOrder, GenerateFillReports,
41        GenerateOrderStatusReport, GenerateOrderStatusReports, GeneratePositionStatusReports,
42        ModifyOrder, QueryAccount, QueryOrder, SubmitOrder, SubmitOrderList,
43    },
44};
45use nautilus_core::{
46    Params, UUID4, UnixNanos, datetime::NANOSECONDS_IN_SECOND, hex, time::get_atomic_clock_realtime,
47};
48use nautilus_live::{
49    ExecutionClientCore, ExecutionEventEmitter,
50    task::{TaskGroup, TaskGroupGuard},
51};
52use nautilus_model::{
53    accounts::AccountAny,
54    defi::{
55        DexType, Pool, PoolIdentifier, SharedChain, Token,
56        data::block::{BLOCK_SCOPED_SNAPSHOT_INDEX, BlockPosition},
57        pool_analysis::quote::SwapQuote,
58        validation::validate_address,
59        wallet::{TokenBalance, WalletBalance},
60    },
61    enums::{LiquiditySide, OmsType, OrderSide, OrderStatus, OrderType},
62    events::{OrderCanceled, OrderDeniedReason, OrderEventAny, OrderFilled, OrderRejected},
63    identifiers::{AccountId, ClientId, ClientOrderId, InstrumentId, TradeId, Venue, VenueOrderId},
64    orders::{Order, OrderAny},
65    reports::{ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport},
66    types::{
67        AccountBalance, Currency, MarginBalance, Money, Price, Quantity, fixed::FIXED_PRECISION,
68    },
69};
70use parking_lot::Mutex;
71use zeroize::Zeroizing;
72
73use crate::{
74    cache::{
75        BlockchainCache,
76        database::{
77            BlockchainCacheDatabase, ExecutionFinalityTransition, ExecutionNonceAssignment,
78            ExecutionPayloadCheck, ExecutionPayloadLease, ExecutionReplacementScan,
79            ExecutionVerificationBatch, ExecutionVerificationBootstrap,
80            ExecutionVerificationDecision, ExecutionVerificationMigration,
81            ExecutionVerificationMigrationRecord, ExecutionVerificationMigrationSnapshot,
82            ExecutionVerifiedHeader, reservation_failure_proven_not_committed,
83        },
84        rows::{ExecutionIntentInsert, ExecutionIntentRow, ExecutionTransactionHashRow},
85    },
86    config::{
87        BlockchainContractRole, BlockchainDeploymentManifest, BlockchainExecutionClientConfig,
88    },
89    contracts::{
90        erc20::{ERC20, Erc20Contract},
91        uniswap_v3_quote::UniswapV3Quote,
92        uniswap_v3_swap::{UniswapV3Factory, UniswapV3RouterState, UniswapV3SwapRouter},
93        weth::WETH9,
94    },
95    execution::{
96        preflight::{
97            BlockchainPreflightReport, ContractCodeCheck, PoolPreflightCheck, TokenPreflightCheck,
98        },
99        sealing::{
100            PayloadKeySet, PayloadPolicy, authenticate_payload, authenticate_payload_identity,
101            authenticate_retained_payload, payload_context, payload_context_identity,
102            persisted_call_fields, retained_payload_requires_policy,
103        },
104        transaction::{
105            TransactionPurpose, TransactionStatus, build_eip1559_transaction, compute_max_fee,
106            decode_signed_transaction, derive_fees, derive_gas_limit, sign_eip1559_transaction,
107        },
108    },
109    rpc::{
110        error::BroadcastError,
111        http::{BlockchainHttpRpcClient, EXECUTION_RPC_TIMEOUT_SECS},
112        log as rpc_log,
113        types::{RpcCallType, RpcTransaction, RpcTransactionReceipt},
114        verification::{
115            VerificationCoordinator, VerificationOutcome, Verified, VerifiedBlockHeader,
116            VerifiedCallTrace, VerifiedSimulation,
117        },
118    },
119};
120
121const RECEIPT_POLL_INTERVAL: Duration = Duration::from_secs(1);
122const MAX_PAYLOAD_OPERATION_BATCH_SIZE: usize = 1_000;
123const BPS_DENOMINATOR: u32 = 10_000;
124/// Denial reason for order-list submissions, which have no on-chain execution route.
125const ORDER_LIST_UNSUPPORTED: &str =
126    "Order lists are not supported; submit each order individually";
127/// Rejection reason for order modifications, which immutable on-chain swaps cannot support.
128const ORDER_MODIFY_UNSUPPORTED: &str = "Order modification is not supported";
129/// Rejection reason for order cancellations, which immutable on-chain swaps cannot support.
130const ORDER_CANCEL_UNSUPPORTED: &str = "Order cancellation is not supported";
131
132/// Error for venue report probes that cannot answer without implying absence.
133const VENUE_EXECUTION_REPORTS_UNSUPPORTED: &str =
134    "Venue execution reports are not supported on the blockchain execution client";
135const MAX_REPLACEMENT_SCAN_BLOCKS: u64 = 4_096;
136
137/// Execution client for blockchain interactions including balance tracking and order execution.
138#[derive(Debug)]
139pub struct BlockchainExecutionClient {
140    core: ExecutionClientCore,
141    emitter: ExecutionEventEmitter,
142    cache: BlockchainCache,
143    config: BlockchainExecutionClientConfig,
144    chain: SharedChain,
145    wallet_address: Address,
146    signer: Option<Arc<PrivateKeySigner>>,
147    payload_keys: Option<Arc<PayloadKeySet>>,
148    router_addresses: Vec<Address>,
149    transaction_limits: TransactionLimits,
150    weth_address: Address,
151    in_flight: Arc<Mutex<Option<InFlightSlot>>>,
152    wallet_balance: Arc<Mutex<WalletBalance>>,
153    erc20_contract: Erc20Contract,
154    http_rpc_client: Arc<BlockchainHttpRpcClient>,
155    verification: VerificationCoordinator,
156    pending_tasks: TaskGroup,
157}
158
159impl BlockchainExecutionClient {
160    /// Creates a new [`BlockchainExecutionClient`] instance for the specified configuration.
161    ///
162    /// # Errors
163    ///
164    /// Returns an error if selections contain duplicates, transaction limits are missing or
165    /// invalid, independent verification is missing or conflicts with the configured chain,
166    /// the deployment manifest, provider topology, a configured address, or a token pair is invalid,
167    /// the router allowlist is empty, or the slippage bounds are inconsistent or not below 100%.
168    pub fn new(
169        core_client: ExecutionClientCore,
170        config: BlockchainExecutionClientConfig,
171    ) -> anyhow::Result<Self> {
172        config.validate()?;
173
174        let transaction_limits = Self::transaction_limits(&config)?;
175        let chain = Arc::new(config.chain.clone());
176        let cache = BlockchainCache::new(Arc::clone(&chain));
177        let http_rpc_client = Arc::new(BlockchainHttpRpcClient::new(
178            config.http_rpc_url.clone().into_inner(),
179            config.rpc_requests_per_second,
180            None,
181        )?);
182
183        let verification_config = config.verification.as_ref().ok_or_else(|| {
184            anyhow::anyhow!("Independent Blockchain execution verification is required")
185        })?;
186        anyhow::ensure!(
187            verification_config.chain_anchor.chain_id == config.chain.chain_id,
188            "Verification chain anchor ID does not match the configured chain"
189        );
190        anyhow::ensure!(
191            verification_config.chain_anchor.chain_name == config.chain.name.to_string(),
192            "Verification chain anchor name does not match the configured chain"
193        );
194        let verification = VerificationCoordinator::new(
195            Arc::clone(&http_rpc_client),
196            config.http_rpc_url.expose_secret(),
197            verification_config,
198            config.rpc_requests_per_second,
199        )?;
200        let wallet_address = validate_address(config.wallet_address.as_str())?;
201        let erc20_contract = Erc20Contract::new_with_timeout(
202            Arc::clone(&http_rpc_client),
203            Some(EXECUTION_RPC_TIMEOUT_SECS),
204            true,
205        );
206
207        let router_addresses = config
208            .router_addresses
209            .iter()
210            .map(|address| validate_address(address.as_str()))
211            .collect::<anyhow::Result<Vec<_>>>()?;
212        if router_addresses.is_empty() {
213            anyhow::bail!("`router_addresses` must contain at least one router address");
214        }
215        let weth_address = validate_address(config.weth_address.as_str())?;
216        Self::validate_manifest_contracts(&config, &router_addresses, weth_address)?;
217
218        let mut token_universe = HashSet::new();
219
220        if let Some(specified_tokens) = &config.tokens {
221            for token in specified_tokens {
222                let token_address = validate_address(token.as_str())?;
223                token_universe.insert(token_address);
224            }
225        }
226        let wallet_balance = WalletBalance::new(token_universe);
227        let emitter = ExecutionEventEmitter::new(
228            get_atomic_clock_realtime(),
229            core_client.trader_id,
230            core_client.account_id,
231            core_client.account_type,
232            core_client.base_currency,
233        );
234
235        let pending_tasks = TaskGroup::new();
236
237        let client = Self {
238            core: core_client,
239            emitter,
240            wallet_balance: Arc::new(Mutex::new(wallet_balance)),
241            chain,
242            cache,
243            config,
244            signer: None,
245            payload_keys: None,
246            router_addresses,
247            transaction_limits,
248            weth_address,
249            in_flight: Arc::new(Mutex::new(None)),
250            erc20_contract,
251            http_rpc_client,
252            verification,
253            wallet_address,
254            pending_tasks,
255        };
256
257        client.register_migration_check();
258        Ok(client)
259    }
260
261    fn register_migration_check(&self) {
262        let database = self.cache.database.clone();
263        let options = self.config.postgres_cache_database_config.clone();
264        let in_flight = Arc::clone(&self.in_flight);
265        self.core.cache().register_defi_execution_check(
266            self.core.client_id,
267            self.chain.chain_id,
268            move |instrument_id| {
269                anyhow::ensure!(
270                    in_flight.lock().is_none(),
271                    "Blockchain submissions must stop before legacy instrument replacement"
272                );
273                anyhow::ensure!(
274                    database.is_some() || options.is_some(),
275                    "No authoritative execution store is configured for {instrument_id}"
276                );
277                let database = database.clone();
278                let options = options.clone();
279                let (sender, receiver) = std::sync::mpsc::sync_channel(1);
280
281                nautilus_common::live::get_runtime().spawn(async move {
282                    let result = async {
283                        let database = match database {
284                            Some(database) => database,
285                            None => {
286                                BlockchainCacheDatabase::connect(
287                                    options.expect("execution store checked").into(),
288                                )
289                                .await?
290                            }
291                        };
292
293                        database.check_instrument_migration(instrument_id).await
294                    }
295                    .await;
296
297                    let _ = sender.send(result);
298                });
299
300                let on_runtime = tokio::runtime::Handle::try_current().is_ok_and(|handle| {
301                    handle.id() == nautilus_common::live::get_runtime().handle().id()
302                });
303
304                if on_runtime {
305                    tokio::task::block_in_place(|| receiver.recv())?
306                } else {
307                    receiver.recv()?
308                }
309            },
310        );
311    }
312
313    fn transaction_limits(
314        config: &BlockchainExecutionClientConfig,
315    ) -> anyhow::Result<TransactionLimits> {
316        let (
317            Some(allowed_token_pairs),
318            Some(slippage_bps),
319            Some(max_slippage_bps),
320            Some(max_order_amount),
321            Some(deadline_seconds),
322            Some(max_quote_age_blocks),
323            Some(receipt_timeout_secs),
324        ) = (
325            &config.allowed_token_pairs,
326            config.slippage_bps,
327            config.max_slippage_bps,
328            config.max_order_amount,
329            config.deadline_seconds,
330            config.max_quote_age_blocks,
331            config.receipt_timeout_secs,
332        )
333        else {
334            anyhow::bail!(
335                "Blockchain execution transaction limits are required: allowed_token_pairs, slippage_bps, max_slippage_bps, max_order_amount, deadline_seconds, max_quote_age_blocks, receipt_timeout_secs"
336            );
337        };
338
339        let mut parsed_pairs = HashSet::with_capacity(allowed_token_pairs.len());
340        for (token_in, token_out) in allowed_token_pairs {
341            parsed_pairs.insert((
342                validate_address(token_in.as_str())?,
343                validate_address(token_out.as_str())?,
344            ));
345        }
346
347        let quote_spend_limits = config.quote_spend_limits.as_deref().unwrap_or_default();
348        let mut parsed_quote_spend_limits = HashMap::with_capacity(quote_spend_limits.len());
349        for limit in quote_spend_limits {
350            let token_in = validate_address(limit.token_in.as_str())?;
351            let token_out = validate_address(limit.token_out.as_str())?;
352            let spend_token = validate_address(limit.spend_token.as_str())?;
353
354            if !parsed_pairs.contains(&(token_in, token_out)) {
355                anyhow::bail!(
356                    "Quote spend limit pair {token_in} -> {token_out} is not in the `allowed_token_pairs` allowlist"
357                );
358            }
359
360            if spend_token != token_in {
361                anyhow::bail!(
362                    "Quote spend limit for {token_in} -> {token_out} is denominated in {spend_token}; `spend_token` must match `token_in`"
363                );
364            }
365
366            if limit.max_amount.is_empty()
367                || !limit.max_amount.bytes().all(|byte| byte.is_ascii_digit())
368            {
369                anyhow::bail!(
370                    "Quote spend limit `max_amount` '{}' must be a base-10 unsigned integer string",
371                    limit.max_amount
372                );
373            }
374            let max_amount = U256::from_str(&limit.max_amount).map_err(|_| {
375                anyhow::anyhow!(
376                    "Quote spend limit `max_amount` '{}' exceeds the U256 range",
377                    limit.max_amount
378                )
379            })?;
380            let ceiling = QuoteSpendCeiling {
381                spend_token,
382                spend_token_decimals: limit.spend_token_decimals,
383                max_amount,
384            };
385
386            if parsed_quote_spend_limits
387                .insert((token_in, token_out), ceiling)
388                .is_some()
389            {
390                anyhow::bail!(
391                    "Duplicate quote spend limit for token pair {token_in} -> {token_out}"
392                );
393            }
394        }
395
396        if slippage_bps > max_slippage_bps {
397            anyhow::bail!(
398                "`slippage_bps` {slippage_bps} exceeds `max_slippage_bps` {max_slippage_bps}"
399            );
400        }
401
402        if max_slippage_bps >= BPS_DENOMINATOR {
403            anyhow::bail!("`max_slippage_bps` {max_slippage_bps} must be below {BPS_DENOMINATOR}");
404        }
405
406        if !(1..=4_095).contains(&max_quote_age_blocks) {
407            anyhow::bail!("`max_quote_age_blocks` must be in 1..=4095");
408        }
409
410        Ok(TransactionLimits {
411            allowed_token_pairs: parsed_pairs,
412            quote_spend_limits: parsed_quote_spend_limits,
413            slippage_bps,
414            max_slippage_bps,
415            max_order_amount,
416            deadline_seconds,
417            max_quote_age_blocks,
418            receipt_timeout_secs,
419        })
420    }
421
422    fn validate_manifest_contracts(
423        config: &BlockchainExecutionClientConfig,
424        routers: &[Address],
425        weth: Address,
426    ) -> anyhow::Result<()> {
427        let verification = config.verification.as_ref().ok_or_else(|| {
428            anyhow::anyhow!("Independent Blockchain execution verification is required")
429        })?;
430        let manifest = &verification.deployment_manifest;
431        let role_addresses = |role| {
432            manifest
433                .contracts
434                .iter()
435                .filter(|contract| contract.role == role)
436                .map(|contract| {
437                    Address::from_str(&contract.address)
438                        .map_err(|_| anyhow::anyhow!("Deployment manifest address is invalid"))
439                })
440                .collect::<anyhow::Result<HashSet<_>>>()
441        };
442        let singleton = |role, description: &str| {
443            let addresses = role_addresses(role)?;
444            anyhow::ensure!(
445                addresses.len() == 1,
446                "Deployment manifest must contain exactly one {description} contract"
447            );
448            Ok(*addresses.iter().next().expect("singleton role address"))
449        };
450
451        let configured_routers = routers.iter().copied().collect::<HashSet<_>>();
452        anyhow::ensure!(
453            role_addresses(BlockchainContractRole::Router)? == configured_routers,
454            "Deployment manifest router set does not match `router_addresses`"
455        );
456        anyhow::ensure!(
457            singleton(BlockchainContractRole::WrappedNative, "wrapped native")? == weth,
458            "Deployment manifest wrapped native contract does not match `weth_address`"
459        );
460        let factory = singleton(BlockchainContractRole::Factory, "factory")?;
461        let registered_factory =
462            crate::exchanges::get_dex_extended(config.chain.name, &DexType::UniswapV3)
463                .map(|dex| dex.factory)
464                .ok_or_else(|| {
465                    anyhow::anyhow!(
466                        "No registered Uniswap V3 deployment for chain {}",
467                        config.chain.name
468                    )
469                })?;
470        anyhow::ensure!(
471            factory == registered_factory,
472            "Deployment manifest factory does not match the registered Uniswap V3 factory"
473        );
474        let quote_contract = singleton(BlockchainContractRole::Quote, "quote")?;
475
476        let mut token_decimals = HashMap::new();
477
478        for token in &manifest.tokens {
479            let address = Address::from_str(&token.address)
480                .map_err(|_| anyhow::anyhow!("Deployment manifest token address is invalid"))?;
481            anyhow::ensure!(
482                token_decimals.insert(address, token.decimals).is_none(),
483                "Deployment manifest contains a duplicate token identity"
484            );
485        }
486        anyhow::ensure!(
487            token_decimals.contains_key(&weth),
488            "Deployment manifest has no wrapped native token identity"
489        );
490
491        if let Some(tokens) = &config.tokens {
492            for token in tokens {
493                let address = validate_address(token)?;
494                anyhow::ensure!(
495                    token_decimals.contains_key(&address),
496                    "Configured token {address} has no deployment manifest identity"
497                );
498            }
499        }
500
501        for (token_in, token_out) in config.allowed_token_pairs.as_deref().unwrap_or_default() {
502            let token_in = validate_address(token_in)?;
503            let token_out = validate_address(token_out)?;
504            anyhow::ensure!(
505                token_in != token_out
506                    && token_decimals.contains_key(&token_in)
507                    && token_decimals.contains_key(&token_out),
508                "Allowed token pair {token_in} -> {token_out} is not fully pinned by the deployment manifest"
509            );
510        }
511
512        for limit in config.quote_spend_limits.as_deref().unwrap_or_default() {
513            let spend_token = validate_address(&limit.spend_token)?;
514            anyhow::ensure!(
515                token_decimals.get(&spend_token) == Some(&limit.spend_token_decimals),
516                "Quote spend limit decimals do not match the deployment manifest"
517            );
518        }
519
520        let pool_contracts = role_addresses(BlockchainContractRole::Pool)?;
521
522        for pool in &manifest.pools {
523            let pool_address = Address::from_str(&pool.address)
524                .map_err(|_| anyhow::anyhow!("Deployment manifest pool address is invalid"))?;
525            let pool_factory = Address::from_str(&pool.factory)
526                .map_err(|_| anyhow::anyhow!("Deployment manifest pool factory is invalid"))?;
527            let pool_quote = Address::from_str(&pool.quote_contract).map_err(|_| {
528                anyhow::anyhow!("Deployment manifest pool quote contract is invalid")
529            })?;
530            anyhow::ensure!(
531                pool_contracts.contains(&pool_address)
532                    && pool_factory == factory
533                    && pool_quote == quote_contract,
534                "Deployment manifest pool does not use the pinned pool, factory, and quote identities"
535            );
536        }
537        Ok(())
538    }
539
540    async fn fetch_native_currency_balance(&self) -> anyhow::Result<Money> {
541        let balance_u256 = self
542            .http_rpc_client
543            .get_balance_with_timeout(&self.wallet_address, None, Some(EXECUTION_RPC_TIMEOUT_SECS))
544            .await?;
545
546        let native_currency = self.chain.native_currency();
547
548        Money::from_u256(balance_u256, native_currency).map_err(Into::into)
549    }
550
551    async fn fetch_token_balance(
552        &mut self,
553        token_address: &Address,
554    ) -> anyhow::Result<TokenBalance> {
555        let token = if let Some(token) = self.cache.get_token(token_address) {
556            token.to_owned()
557        } else {
558            let token_info = self.erc20_contract.fetch_token_info(token_address).await?;
559            let token = Token::new(
560                Arc::clone(&self.chain),
561                *token_address,
562                token_info.name,
563                token_info.symbol,
564                token_info.decimals,
565            );
566            self.cache.add_token(token.clone()).await?;
567            token
568        };
569
570        let amount = self
571            .erc20_contract
572            .balance_of(token_address, &self.wallet_address)
573            .await?;
574        let token_balance = TokenBalance::new(amount, token);
575
576        // TODO: Use price oracle here and cache, to get the latest price then convert to USD
577        // then use token_balance.set_amount_usd(amount_usd) to set the amount_usd value.
578
579        Ok(token_balance)
580    }
581
582    /// Refreshes and publishes all native currency and tracked ERC-20 balances.
583    async fn refresh_wallet_balances(&mut self) -> anyhow::Result<()> {
584        let (wallet_balance, balances) = self.fetch_wallet_balances().await?;
585        self.generate_account_state(
586            balances,
587            vec![],
588            true,
589            get_atomic_clock_realtime().get_time_ns(),
590            None,
591        )?;
592        *self.wallet_balance.lock() = wallet_balance;
593        Ok(())
594    }
595
596    async fn fetch_wallet_balances(
597        &mut self,
598    ) -> anyhow::Result<(WalletBalance, Vec<AccountBalance>)> {
599        let native_currency_balance = self.fetch_native_currency_balance().await?;
600        let token_universe = self.wallet_balance.lock().token_universe.clone();
601        let mut token_addresses = token_universe.iter().copied().collect::<Vec<_>>();
602        token_addresses.sort_unstable();
603
604        let mut token_balances = Vec::with_capacity(token_addresses.len());
605        for token_address in token_addresses {
606            let token_balance = self
607                .fetch_token_balance(&token_address)
608                .await
609                .with_context(|| format!("failed to fetch token balance for {token_address}"))?;
610            token_balances.push(token_balance);
611        }
612
613        let mut wallet_balance = WalletBalance::new(token_universe);
614        let balances = wallet_balance.replace_balances(native_currency_balance, token_balances)?;
615        log::debug!(
616            "Refreshed wallet balance with {} account balances",
617            balances.len()
618        );
619        Ok((wallet_balance, balances))
620    }
621
622    /// Runs a read-only execution preflight for the pool selected by `instrument_id`.
623    ///
624    /// Verifies the RPC chain ID against configuration, deployed bytecode at the router, pool,
625    /// and token addresses, wallet native and token balances, exact router allowance of the
626    /// pool's base (input) token, and current fee conditions. Changes no state.
627    ///
628    /// # Errors
629    ///
630    /// Returns an error if the instrument ID cannot be resolved to a cached Uniswap V3 pool
631    /// on the client's chain, or if any RPC call fails. On-chain readiness failures are
632    /// reported in the returned [`BlockchainPreflightReport`], not as errors.
633    pub async fn preflight(
634        &self,
635        instrument_id: &InstrumentId,
636    ) -> anyhow::Result<BlockchainPreflightReport> {
637        let pool = self.resolve_pool(instrument_id)?;
638        let base_token = pool.get_base_token().clone();
639        let quote_token = pool.get_quote_token().clone();
640
641        let actual_chain_id = self.http_rpc_client.chain_id().await?;
642
643        let pool_code = self.http_rpc_client.get_code(&pool.address).await?;
644        let pool_check = PoolPreflightCheck {
645            instrument_id: pool.instrument_id,
646            address: pool.address,
647            has_deployed_code: !pool_code.is_empty(),
648            fee: pool.fee,
649            base_token: base_token.address,
650            quote_token: quote_token.address,
651        };
652
653        let mut routers = Vec::with_capacity(self.router_addresses.len());
654        for router in &self.router_addresses {
655            let code = self.http_rpc_client.get_code(router).await?;
656            routers.push(ContractCodeCheck {
657                address: *router,
658                has_deployed_code: !code.is_empty(),
659            });
660        }
661
662        let mut tokens = Vec::with_capacity(2);
663
664        for token in [&base_token, &quote_token] {
665            let code = self.http_rpc_client.get_code(&token.address).await?;
666            let wallet_balance = self
667                .erc20_contract
668                .balance_of(&token.address, &self.wallet_address)
669                .await?;
670
671            let mut router_allowances = Vec::new();
672            if token.address == base_token.address {
673                router_allowances.reserve(self.router_addresses.len());
674                for router in &self.router_addresses {
675                    let amount = self
676                        .erc20_contract
677                        .allowance(&token.address, &self.wallet_address, router)
678                        .await?;
679                    router_allowances.push((*router, amount));
680                }
681            }
682
683            tokens.push(TokenPreflightCheck {
684                address: token.address,
685                symbol: token.symbol.clone(),
686                has_deployed_code: !code.is_empty(),
687                wallet_balance,
688                router_allowances,
689            });
690        }
691
692        let native_balance_wei = self
693            .http_rpc_client
694            .get_balance_with_timeout(&self.wallet_address, None, Some(EXECUTION_RPC_TIMEOUT_SECS))
695            .await?;
696
697        let latest_block = self.http_rpc_client.latest_block().await?;
698        let base_fee_per_gas_wei = latest_block.base_fee_per_gas.ok_or_else(|| {
699            anyhow::anyhow!("Latest block {} has no base fee", latest_block.number)
700        })?;
701        let max_priority_fee_per_gas_wei = self.http_rpc_client.max_priority_fee_per_gas().await?;
702        let derived_max_fee_per_gas_wei = compute_max_fee(
703            base_fee_per_gas_wei,
704            max_priority_fee_per_gas_wei,
705            self.config.base_fee_buffer_bps,
706        )?;
707
708        Ok(BlockchainPreflightReport::new(
709            u64::from(self.chain.chain_id),
710            actual_chain_id,
711            pool_check,
712            routers,
713            tokens,
714            native_balance_wei,
715            base_fee_per_gas_wei,
716            max_priority_fee_per_gas_wei,
717            derived_max_fee_per_gas_wei,
718            u128::from(self.config.max_fee_per_gas_wei),
719        ))
720    }
721
722    /// Wraps native currency into the wrapped native token via a WETH `deposit()`
723    /// transaction carrying `amount_wei` of native value.
724    ///
725    /// This is an explicit operator operation; it never runs inside `submit_order`.
726    ///
727    /// # Errors
728    ///
729    /// Returns an error if the amount is zero, the WETH target is not a deployed ERC-20 contract,
730    /// the client is not connected, another transaction is in flight, no durable store is
731    /// configured, the WETH balance does not increase by `amount_wei`, or any RPC, policy, signing,
732    /// persistence, or broadcast step fails. A persistence failure after signing, or a failed
733    /// postcondition after finality, leaves the in-flight slot occupied.
734    #[allow(
735        clippy::large_futures,
736        reason = "keeps transaction verification futures inline without additional boxing"
737    )]
738    pub async fn wrap(&mut self, amount_wei: U256) -> anyhow::Result<B256> {
739        if amount_wei.is_zero() {
740            anyhow::bail!("Wrap amount must be positive");
741        }
742
743        self.ensure_transaction_ready(TransactionPurpose::Wrap)?;
744
745        let calldata = WETH9::depositCall {}.abi_encode();
746        let executor = self.transaction_executor()?;
747        let included = executor
748            .transact(
749                SystemTime::now(),
750                self.weth_address,
751                amount_wei,
752                Bytes::from(calldata),
753                TransactionPurpose::Wrap,
754                None,
755                TransactionAuthorization::Wrap {
756                    weth: self.weth_address,
757                },
758            )
759            .await?;
760        let postconditions =
761            verify_wrap_balance_increase(&executor, &self.weth_address, amount_wei, &included)
762                .await?;
763        executor
764            .commit_verified_finality(&included, TransactionStatus::Finalized, &postconditions)
765            .await?;
766        executor
767            .database
768            .mark_execution_event_emitted(included.intent_id, "terminal")
769            .await?;
770        executor.release_slot();
771
772        Ok(included.tx_hash)
773    }
774
775    /// Approves an allowlisted SwapRouter to spend `amount` of `token` via an ERC-20
776    /// `approve` transaction. Zero always revokes the allowance. For nonzero requests,
777    /// `unlimited_approval` changes the target to `U256::MAX`.
778    ///
779    /// This is an explicit operator operation; it never runs inside `submit_order`.
780    ///
781    /// # Errors
782    ///
783    /// Returns an error if the router or token fails policy and deployment checks, a nonzero
784    /// allowance was not cleared first, approval simulation returns false or malformed data, the
785    /// client is not connected, another transaction is in flight, no durable store is configured,
786    /// the resulting allowance differs from the target, or any RPC, signing, persistence, or
787    /// broadcast step fails. A persistence failure after signing, or a failed postcondition after
788    /// finality, leaves the in-flight slot occupied.
789    #[allow(
790        clippy::large_futures,
791        reason = "keeps transaction verification futures inline without additional boxing"
792    )]
793    pub async fn approve(
794        &mut self,
795        token: Address,
796        amount: U256,
797        router: Address,
798    ) -> anyhow::Result<B256> {
799        if !self.router_addresses.contains(&router) {
800            anyhow::bail!("Router {router} is not in the configured `router_addresses` allowlist");
801        }
802
803        if !amount.is_zero()
804            && !self
805                .transaction_limits
806                .allowed_token_pairs
807                .iter()
808                .any(|(token_in, _)| *token_in == token)
809        {
810            anyhow::bail!(
811                "Token {token} is not an input token in the configured `allowed_token_pairs`"
812            );
813        }
814
815        self.ensure_transaction_ready(TransactionPurpose::Approve)?;
816
817        let approval_amount = if amount.is_zero() {
818            U256::ZERO
819        } else if self.config.unlimited_approval {
820            U256::MAX
821        } else {
822            amount
823        };
824        let calldata = ERC20::approveCall {
825            spender: router,
826            amount: approval_amount,
827        }
828        .abi_encode();
829
830        let executor = self.transaction_executor()?;
831        let included = executor
832            .transact(
833                SystemTime::now(),
834                token,
835                U256::ZERO,
836                Bytes::from(calldata),
837                TransactionPurpose::Approve,
838                None,
839                TransactionAuthorization::Approve {
840                    token,
841                    router,
842                    amount: approval_amount,
843                },
844            )
845            .await?;
846        let postconditions =
847            verify_approve_allowance(&executor, &token, &router, approval_amount, &included)
848                .await?;
849        executor
850            .commit_verified_finality(&included, TransactionStatus::Finalized, &postconditions)
851            .await?;
852        executor
853            .database
854            .mark_execution_event_emitted(included.intent_id, "terminal")
855            .await?;
856        executor.release_slot();
857
858        Ok(included.tx_hash)
859    }
860
861    fn uniswap_v3_factory(&self) -> anyhow::Result<Address> {
862        crate::exchanges::get_dex_extended(self.chain.name, &DexType::UniswapV3)
863            .map(|dex| dex.factory)
864            .ok_or_else(|| {
865                anyhow::anyhow!(
866                    "No registered Uniswap V3 deployment for chain {}",
867                    self.chain.name
868                )
869            })
870    }
871
872    fn resolve_pool(&self, instrument_id: &InstrumentId) -> anyhow::Result<Pool> {
873        let (blockchain, dex_type) = instrument_id.venue.parse_dex()?;
874        if blockchain != self.chain.name {
875            anyhow::bail!(
876                "Pool venue chain {blockchain} does not match the client chain {}",
877                self.chain.name
878            );
879        }
880
881        if dex_type != DexType::UniswapV3 {
882            anyhow::bail!("Unsupported DEX type {dex_type}; only UniswapV3 is supported");
883        }
884
885        let pool_identifier = PoolIdentifier::new_checked(instrument_id.symbol.as_str())?;
886        if !pool_identifier.is_address() {
887            anyhow::bail!(
888                "Pool identifier {pool_identifier} is a pool ID; only address identifiers are supported"
889            );
890        }
891
892        let pool = self
893            .core
894            .cache()
895            .pool(instrument_id)
896            .cloned()
897            .ok_or_else(|| {
898                anyhow::anyhow!(
899                    "Unknown pool {instrument_id}; not found in the shared engine cache"
900                )
901            })?;
902
903        if pool.token0.get_token_priority() == pool.token1.get_token_priority() {
904            anyhow::bail!(
905                "Pool {instrument_id} tokens share a token priority; base and quote orientation is ambiguous"
906            );
907        }
908
909        Ok(pool)
910    }
911
912    /// Authenticates every persisted signed transaction in this execution database.
913    ///
914    /// Run this while the execution client is disconnected. The check takes a stable table lock,
915    /// reads in bounded batches, and returns counts, deployment identity, key IDs, and database
916    /// roles with direct ownership or `SELECT` grants.
917    ///
918    /// # Errors
919    ///
920    /// Returns an error if storage state is inconsistent, keys are missing, or a payload cannot be
921    /// opened and authenticated against its durable intent.
922    pub async fn check_payload_storage(
923        &self,
924        batch_size: usize,
925    ) -> anyhow::Result<PayloadStorageCheck> {
926        let batch_size = validate_payload_operation_batch_size(batch_size)?;
927        let database = self.payload_operation_database().await?;
928        let keys = self.load_payload_keys()?;
929        database
930            .check_execution_payload_storage(keys.as_ref(), None, batch_size)
931            .await
932            .map(Into::into)
933    }
934
935    /// Activates or resumes protected signed-transaction storage for this execution database.
936    ///
937    /// Run this while the execution client is disconnected. A full payload check must succeed
938    /// before a later execution connection is permitted.
939    ///
940    /// # Errors
941    ///
942    /// Returns an error if the client is connected, an active key or deployment identity is
943    /// unavailable, or any stored payload cannot be migrated and authenticated.
944    pub async fn protect_payload_storage(&self) -> anyhow::Result<()> {
945        let database = self.payload_operation_database().await?;
946        database.ensure_execution_transaction_schema().await?;
947        let keys = self
948            .load_payload_keys()?
949            .ok_or_else(|| anyhow::anyhow!("Payload protection requires an active payload key"))?;
950        database.ensure_execution_payload_storage(&keys).await
951    }
952
953    /// Rewraps all protected payloads in this execution database with the configured active key.
954    ///
955    /// The prior active key must remain configured as a retired key until this method and a
956    /// subsequent full check both succeed.
957    ///
958    /// # Errors
959    ///
960    /// Returns an error if the client is connected, storage is not protected, required keys are
961    /// unavailable, or any bounded rewrap batch fails authentication.
962    pub async fn rewrap_payload_storage(&self, batch_size: usize) -> anyhow::Result<()> {
963        let batch_size = validate_payload_operation_batch_size(batch_size)?;
964        let database = self.payload_operation_database().await?;
965        let keys = self
966            .load_payload_keys()?
967            .ok_or_else(|| anyhow::anyhow!("Payload rewrap requires an active payload key"))?;
968        database
969            .rewrap_execution_payload_storage(&keys, batch_size)
970            .await
971    }
972
973    /// Restores authenticated plaintext payloads and removes protection from this database.
974    ///
975    /// This incident-only operation is resumable. Keep the complete key set configured until it
976    /// succeeds and the unprotected database passes a full payload check.
977    ///
978    /// # Errors
979    ///
980    /// Returns an error if the client is connected, storage is not protected, required keys are
981    /// unavailable, or any bounded rollback batch fails authentication.
982    pub async fn rollback_payload_storage(&self, batch_size: usize) -> anyhow::Result<()> {
983        let batch_size = validate_payload_operation_batch_size(batch_size)?;
984        let database = self.payload_operation_database().await?;
985        let keys = self
986            .load_payload_keys()?
987            .ok_or_else(|| anyhow::anyhow!("Payload rollback requires an active payload key"))?;
988        database
989            .rollback_execution_payload_storage(&keys, batch_size)
990            .await
991    }
992
993    async fn payload_operation_database(&self) -> anyhow::Result<BlockchainCacheDatabase> {
994        anyhow::ensure!(
995            !self.core.is_connected(),
996            "Disconnect the execution client before payload storage operations"
997        );
998
999        if let Some(database) = &self.cache.database {
1000            return Ok(database.clone());
1001        }
1002        let options = self
1003            .config
1004            .postgres_cache_database_config
1005            .as_ref()
1006            .ok_or_else(|| anyhow::anyhow!("No Postgres cache database is configured"))?;
1007        BlockchainCacheDatabase::connect(options.clone().into())
1008            .await
1009            .context("failed to connect to the execution database")
1010    }
1011
1012    fn load_payload_keys(&self) -> anyhow::Result<Option<PayloadKeySet>> {
1013        PayloadKeySet::load(
1014            self.config.payload_key_env.as_deref(),
1015            &self.config.payload_key_retired_env,
1016            self.config.payload_deployment_id.as_deref(),
1017        )
1018    }
1019
1020    fn payload_policy(&self) -> PayloadPolicy {
1021        PayloadPolicy {
1022            chain_id: self.chain.chain_id,
1023            signer: self.wallet_address,
1024            gas_limit: self.config.gas_limit,
1025            max_fee_per_gas: self.config.max_fee_per_gas_wei,
1026        }
1027    }
1028
1029    fn transaction_executor(&self) -> anyhow::Result<TransactionExecutor> {
1030        let database = self.cache.database.clone().ok_or_else(|| {
1031            anyhow::anyhow!("No durable store configured; refusing to submit a transaction")
1032        })?;
1033        let signer = self
1034            .signer
1035            .clone()
1036            .ok_or_else(|| anyhow::anyhow!("Signer not initialized; connect the client first"))?;
1037        let payload_keys = self.payload_keys.clone().ok_or_else(|| {
1038            anyhow::anyhow!("Protected payload keys are not initialized; connect the client first")
1039        })?;
1040        let verification_config = self
1041            .config
1042            .verification
1043            .as_ref()
1044            .expect("verification config validated at construction");
1045        let identities = std::iter::once(&verification_config.authoritative)
1046            .chain(
1047                verification_config
1048                    .verifiers
1049                    .iter()
1050                    .map(|provider| &provider.identity),
1051            )
1052            .collect::<Vec<_>>();
1053
1054        Ok(TransactionExecutor {
1055            http_rpc_client: Arc::clone(&self.http_rpc_client),
1056            verification: self.verification.clone(),
1057            manifest_version: verification_config.manifest_version.clone(),
1058            manifest_digest: verification_config.manifest_digest.clone(),
1059            deployment_manifest: Arc::new(verification_config.deployment_manifest.clone()),
1060            provider_ids: identities
1061                .iter()
1062                .map(|identity| identity.provider_id.clone())
1063                .collect(),
1064            operator_ids: identities
1065                .iter()
1066                .map(|identity| identity.operator_id.clone())
1067                .collect(),
1068            failure_domain_ids: identities
1069                .iter()
1070                .flat_map(|identity| identity.failure_domain_ids.iter().cloned())
1071                .collect(),
1072            database,
1073            signer,
1074            payload_keys,
1075            in_flight: Arc::clone(&self.in_flight),
1076            wallet_balance: Arc::clone(&self.wallet_balance),
1077            account_id: self.core.account_id,
1078            wallet_address: self.wallet_address,
1079            chain_id: self.chain.chain_id,
1080            max_fee_per_gas_wei: self.config.max_fee_per_gas_wei,
1081            base_fee_buffer_bps: self.config.base_fee_buffer_bps,
1082            gas_limit: self.config.gas_limit,
1083            gas_buffer_bps: self.config.gas_buffer_bps,
1084            receipt_timeout: receipt_timeout(self.transaction_limits.receipt_timeout_secs),
1085            receipt_max_polls: receipt_max_polls(self.transaction_limits.receipt_timeout_secs),
1086        })
1087    }
1088
1089    fn restore_swap_plan(&self, intent: &ExecutionIntentRow) -> anyhow::Result<SwapPlan> {
1090        let client_order_id = ClientOrderId::new_checked(
1091            intent
1092                .client_order_id
1093                .as_deref()
1094                .ok_or_else(|| anyhow::anyhow!("Persisted swap intent has no client order ID"))?,
1095        )?;
1096        let order = self
1097            .core
1098            .cache()
1099            .try_order_owned(&client_order_id)
1100            .with_context(|| {
1101                format!(
1102                    "Cannot reconcile swap intent {} because order {client_order_id} is not restored",
1103                    intent.id
1104                )
1105            })?;
1106        let instrument_id = InstrumentId::from_str(
1107            intent
1108                .instrument_id
1109                .as_deref()
1110                .ok_or_else(|| anyhow::anyhow!("Persisted swap intent has no instrument ID"))?,
1111        )?;
1112        anyhow::ensure!(
1113            order.instrument_id() == instrument_id,
1114            "Persisted swap instrument {instrument_id} does not match restored order instrument {}",
1115            order.instrument_id()
1116        );
1117        anyhow::ensure!(
1118            intent.trader_id.as_deref() == Some(order.trader_id().as_str()),
1119            "Persisted swap trader does not match restored order"
1120        );
1121        anyhow::ensure!(
1122            intent.strategy_id.as_deref() == Some(order.strategy_id().as_str()),
1123            "Persisted swap strategy does not match restored order"
1124        );
1125        anyhow::ensure!(
1126            intent.account_id.as_deref() == Some(self.core.account_id.as_str()),
1127            "Persisted swap account does not match execution client account"
1128        );
1129
1130        let pool = self.resolve_pool(&instrument_id)?;
1131        let pool_address = Address::from_str(
1132            intent
1133                .pool_address
1134                .as_deref()
1135                .ok_or_else(|| anyhow::anyhow!("Persisted swap intent has no pool address"))?,
1136        )?;
1137        anyhow::ensure!(
1138            pool.address == pool_address,
1139            "Persisted pool {pool_address} does not match restored pool {}",
1140            pool.address
1141        );
1142        let amount_in = U256::from_str(
1143            intent
1144                .amount_in
1145                .as_deref()
1146                .ok_or_else(|| anyhow::anyhow!("Persisted swap intent has no input amount"))?,
1147        )?;
1148        let fee = U24::try_from(
1149            pool.fee
1150                .ok_or_else(|| anyhow::anyhow!("Restored pool {instrument_id} has no fee"))?,
1151        )?;
1152        let quote_token = pool.get_quote_token();
1153        let quote_currency = quote_token.currency()?;
1154        let (token_in, token_out) = swap_token_pair(
1155            order.order_side(),
1156            pool.get_base_token().address,
1157            quote_token.address,
1158        );
1159        let factory = self.uniswap_v3_factory()?;
1160        anyhow::ensure!(
1161            pool.dex.factory == factory,
1162            "Restored pool {instrument_id} references factory {}, expected registered factory {factory}",
1163            pool.dex.factory
1164        );
1165
1166        Ok(SwapPlan {
1167            order,
1168            quote_currency,
1169            pool,
1170            instrument_id,
1171            pool_address,
1172            router: Address::from_str(&intent.transaction_to)?,
1173            factory,
1174            weth: self.weth_address,
1175            token_in,
1176            token_out,
1177            fee,
1178            amount_in,
1179            min_amount_out: U256::ZERO,
1180            slippage_bps: 0,
1181            quote_spend_ceiling: None,
1182            profiler_position: None,
1183        })
1184    }
1185
1186    #[allow(
1187        clippy::large_futures,
1188        reason = "keeps transaction verification futures inline without additional boxing"
1189    )]
1190    async fn reconcile_unresolved_execution(&self) -> anyhow::Result<()> {
1191        let database = self.cache.database.clone().ok_or_else(|| {
1192            anyhow::anyhow!("No durable store configured for execution reconciliation")
1193        })?;
1194        let _payload_lease = database
1195            .acquire_execution_payload_lease(self.payload_keys.as_deref().ok_or_else(|| {
1196                anyhow::anyhow!("Protected payload keys are required for execution recovery")
1197            })?)
1198            .await?;
1199        let wallet_address = self.wallet_address.to_string();
1200        anyhow::ensure!(
1201            !database
1202                .has_recoverable_signed_execution(self.chain.chain_id, &wallet_address)
1203                .await?,
1204            "A recoverable execution for wallet {} retains signed transaction bytes; refusing to reuse its nonce without explicit recovery",
1205            self.wallet_address
1206        );
1207        let Some(intent) = database
1208            .get_active_execution_intent(self.chain.chain_id, &wallet_address)
1209            .await?
1210        else {
1211            return Ok(());
1212        };
1213        anyhow::ensure!(
1214            intent.schema_version == crate::execution::transaction::EXECUTION_SCHEMA_VERSION,
1215            "Execution intent {} uses unsupported schema version {}",
1216            intent.id,
1217            intent.schema_version
1218        );
1219
1220        if intent.status == "prepared" {
1221            database
1222                .mark_execution_intent_recoverable(intent.id)
1223                .await?;
1224            release_preparing_slot(&self.in_flight);
1225            return Ok(());
1226        }
1227
1228        let purpose = TransactionPurpose::parse(&intent.purpose).ok_or_else(|| {
1229            anyhow::anyhow!(
1230                "Execution intent {} has unknown purpose {}",
1231                intent.id,
1232                intent.purpose
1233            )
1234        })?;
1235        let nonce = intent
1236            .nonce
1237            .ok_or_else(|| anyhow::anyhow!("Active execution intent {} has no nonce", intent.id))?;
1238        *self.in_flight.lock() = Some(InFlightSlot::Recovering(RecoveryTransaction {
1239            intent_id: intent.id,
1240            nonce,
1241            purpose,
1242        }));
1243        let hashes = database.get_execution_transaction_hashes(intent.id).await?;
1244        let current = current_execution_hash(intent.id, &hashes)?;
1245        let tx_hash = B256::from_str(&current.transaction_hash).with_context(|| {
1246            format!(
1247                "Execution intent {} has invalid transaction hash {}",
1248                intent.id, current.transaction_hash
1249            )
1250        })?;
1251        let policy = PayloadPolicy {
1252            chain_id: self.chain.chain_id,
1253            signer: self.wallet_address,
1254            gas_limit: self.config.gas_limit,
1255            max_fee_per_gas: self.config.max_fee_per_gas_wei,
1256        };
1257        let mut authenticated_payloads = HashMap::new();
1258        let mut current_payload = None;
1259
1260        for hash in &hashes {
1261            anyhow::ensure!(
1262                hash.intent_id == intent.id,
1263                "Persisted transaction row references intent {}, expected {}",
1264                hash.intent_id,
1265                intent.id
1266            );
1267            anyhow::ensure!(
1268                hash.chain_id == self.chain.chain_id,
1269                "Persisted transaction row chain ID {} does not match configured chain ID {}",
1270                hash.chain_id,
1271                self.chain.chain_id
1272            );
1273
1274            if !hash.payload_expected {
1275                anyhow::ensure!(
1276                    hash.raw_transaction.is_none() && hash.sealed_transaction.is_none(),
1277                    "Replacement transaction {} unexpectedly retains signed bytes",
1278                    hash.transaction_hash
1279                );
1280                continue;
1281            }
1282            let raw_transaction = open_execution_payload(
1283                self.payload_keys
1284                    .as_deref()
1285                    .expect("payload keys checked above"),
1286                policy,
1287                &intent,
1288                hash,
1289                "recovery",
1290            )
1291            .map_err(|e| {
1292                anyhow::anyhow!(
1293                    "Execution intent {} signed transaction {} failed authentication: {e}",
1294                    intent.id,
1295                    hash.transaction_hash
1296                )
1297            })?;
1298            let authenticated_hash = B256::from_str(&hash.transaction_hash).with_context(|| {
1299                format!(
1300                    "Execution intent {} has invalid transaction hash {}",
1301                    intent.id, hash.transaction_hash
1302                )
1303            })?;
1304            anyhow::ensure!(
1305                authenticated_payloads
1306                    .insert(authenticated_hash, raw_transaction.clone())
1307                    .is_none(),
1308                "Execution intent {} has duplicate authenticated transaction hash {}",
1309                intent.id,
1310                hash.transaction_hash
1311            );
1312
1313            if hash.id == current.id {
1314                current_payload = Some(raw_transaction);
1315            }
1316        }
1317        anyhow::ensure!(
1318            !authenticated_payloads.is_empty(),
1319            "Execution intent {} has no persisted signed transaction bytes",
1320            intent.id
1321        );
1322
1323        if intent.status == "broadcast" {
1324            anyhow::ensure!(
1325                current_payload.is_some(),
1326                "Broadcast execution intent {} has no persisted signed transaction bytes",
1327                intent.id
1328            );
1329        }
1330
1331        if intent.status == "signed" {
1332            anyhow::bail!(
1333                "Execution intent {} has a signed transaction {} that was not authorized for broadcast; its nonce remains reserved pending explicit recovery",
1334                intent.id,
1335                tx_hash
1336            );
1337        }
1338
1339        *self.in_flight.lock() = Some(InFlightSlot::AwaitingFinality(InFlightTransaction {
1340            intent_id: intent.id,
1341            nonce,
1342            tx_hash,
1343            purpose,
1344        }));
1345
1346        let plan = if purpose == TransactionPurpose::Swap {
1347            Some(self.restore_swap_plan(&intent)?)
1348        } else {
1349            None
1350        };
1351
1352        if let Some(plan) = &plan
1353            && !intent.acknowledgement_emitted
1354        {
1355            if plan.order.ts_submitted().is_none() {
1356                self.emitter.emit_order_submitted(&plan.order);
1357            }
1358            database
1359                .mark_execution_event_emitted(intent.id, "acknowledgement")
1360                .await?;
1361        }
1362
1363        let executor = self.transaction_executor()?;
1364        let mut prepared = PreparedTransaction {
1365            intent_id: intent.id,
1366            created_block: intent.created_block,
1367            nonce,
1368            tx_hash,
1369            raw_tx: current_payload.unwrap_or_default(),
1370            payload_lease: None,
1371        };
1372
1373        let finality_already_committed = matches!(intent.status.as_str(), "finalized" | "reverted");
1374        if !finality_already_committed {
1375            match executor
1376                .authorize_rebroadcast(&prepared, &intent, purpose)
1377                .await?
1378            {
1379                ReconciliationAuthorization::Rebroadcast => {
1380                    match executor.broadcast(&prepared).await? {
1381                        BroadcastOutcome::Accepted => {}
1382                        BroadcastOutcome::Ambiguous(message) => log::warn!("{message}"),
1383                    }
1384                }
1385                ReconciliationAuthorization::Retain => {
1386                    log::warn!(
1387                        "Rebroadcast of transaction {} was suppressed by verified reconciliation state",
1388                        prepared.tx_hash
1389                    );
1390                }
1391                ReconciliationAuthorization::ScanReplacement(head) => {
1392                    let Some((replacement_hash, replacement_payload)) = executor
1393                        .scan_canonical_replacement(&intent, nonce, head, &authenticated_payloads)
1394                        .await?
1395                    else {
1396                        log::warn!(
1397                            "Canonical replacement scan for intent {} reached its bounded verified window",
1398                            intent.id
1399                        );
1400                        return Ok(());
1401                    };
1402                    prepared.tx_hash = replacement_hash;
1403                    prepared.raw_tx = replacement_payload;
1404                    *self.in_flight.lock() =
1405                        Some(InFlightSlot::AwaitingFinality(InFlightTransaction {
1406                            intent_id: intent.id,
1407                            nonce,
1408                            tx_hash: replacement_hash,
1409                            purpose,
1410                        }));
1411                }
1412            }
1413        }
1414        let outcome = if finality_already_committed {
1415            let receipt = verified_value(
1416                executor.verification.verify_receipt(&tx_hash).await,
1417                "persisted terminal receipt",
1418            )?;
1419            let finality = executor
1420                .receipt_is_stably_finalized(&receipt)
1421                .await?
1422                .ok_or_else(|| {
1423                    anyhow::anyhow!(
1424                        "Persisted terminal transaction {tx_hash} is not stable at the finalized boundary"
1425                    )
1426                })?;
1427            let included = IncludedTransaction {
1428                intent_id: intent.id,
1429                nonce,
1430                tx_hash,
1431                block_number: receipt.block_number,
1432                receipt,
1433                finality,
1434            };
1435
1436            if intent.status == "finalized" {
1437                InclusionOutcome::Finalized(included)
1438            } else {
1439                InclusionOutcome::Reverted(included)
1440            }
1441        } else {
1442            executor.await_finality(&prepared).await?
1443        };
1444
1445        match outcome {
1446            InclusionOutcome::Finalized(mut included) => {
1447                let trace_purpose = match (&plan, purpose) {
1448                    (Some(plan), TransactionPurpose::Swap) => match plan.order.order_side() {
1449                        OrderSide::Sell => "swap_sell",
1450                        OrderSide::Buy => "swap_buy",
1451                    },
1452                    (None, TransactionPurpose::Wrap) => "wrap",
1453                    (None, TransactionPurpose::Approve) => "approve",
1454                    _ => anyhow::bail!("Restored transaction purpose is inconsistent"),
1455                };
1456                included.finality.decisions.extend(
1457                    verify_finalized_transaction(
1458                        &included,
1459                        &intent,
1460                        nonce,
1461                        &prepared.raw_tx,
1462                        &executor,
1463                        trace_purpose,
1464                    )
1465                    .await?,
1466                );
1467
1468                if let Some(plan) = plan {
1469                    let fill = validate_finalized_swap_fill(&plan, &included)?;
1470                    let wallet =
1471                        load_verified_wallet_after_fill(&plan, &included, &executor).await?;
1472                    if !finality_already_committed {
1473                        executor
1474                            .commit_verified_finality(
1475                                &included,
1476                                TransactionStatus::Finalized,
1477                                &wallet.decisions,
1478                            )
1479                            .await?;
1480                    }
1481                    complete_finalized_swap(
1482                        &plan,
1483                        intent.id,
1484                        included.tx_hash,
1485                        fill,
1486                        wallet,
1487                        &executor,
1488                        &self.emitter,
1489                    )
1490                    .await?;
1491                    executor.release_slot();
1492                } else {
1493                    let postconditions = self
1494                        .verify_recovered_operator_transaction(
1495                            &intent, purpose, &included, &executor,
1496                        )
1497                        .await?;
1498
1499                    if !finality_already_committed {
1500                        executor
1501                            .commit_verified_finality(
1502                                &included,
1503                                TransactionStatus::Finalized,
1504                                &postconditions,
1505                            )
1506                            .await?;
1507                    }
1508                    database
1509                        .mark_execution_event_emitted(intent.id, "terminal")
1510                        .await?;
1511                    executor.release_slot();
1512                }
1513            }
1514            InclusionOutcome::Reverted(mut included) => {
1515                let trace_purpose = match (&plan, purpose) {
1516                    (Some(plan), TransactionPurpose::Swap) => match plan.order.order_side() {
1517                        OrderSide::Sell => "swap_sell",
1518                        OrderSide::Buy => "swap_buy",
1519                    },
1520                    (None, TransactionPurpose::Wrap) => "wrap",
1521                    (None, TransactionPurpose::Approve) => "approve",
1522                    _ => anyhow::bail!("Restored transaction purpose is inconsistent"),
1523                };
1524                included.finality.decisions.extend(
1525                    verify_finalized_transaction(
1526                        &included,
1527                        &intent,
1528                        nonce,
1529                        &prepared.raw_tx,
1530                        &executor,
1531                        trace_purpose,
1532                    )
1533                    .await?,
1534                );
1535
1536                if !finality_already_committed {
1537                    executor
1538                        .commit_verified_finality(&included, TransactionStatus::Reverted, &[])
1539                        .await?;
1540                }
1541
1542                if let Some(plan) = plan
1543                    && plan.order.status() != OrderStatus::Rejected
1544                {
1545                    send_reverted_order(&self.emitter, &plan.order, &included)?;
1546                }
1547                database
1548                    .mark_execution_event_emitted(intent.id, "terminal")
1549                    .await?;
1550                executor.release_slot();
1551            }
1552            InclusionOutcome::Pending(message) => log::warn!("{message}"),
1553        }
1554        Ok(())
1555    }
1556
1557    /// Revalidates a restored wrap or approve against the finalized signer-nonce transaction
1558    /// and reruns the live postcondition before the restored intent may report success.
1559    ///
1560    /// Fails closed: any identity mismatch or unproven postcondition returns an error, which
1561    /// keeps the in-flight signer slot occupied, leaves the intent active, and fails connect.
1562    async fn verify_recovered_operator_transaction(
1563        &self,
1564        intent: &ExecutionIntentRow,
1565        purpose: TransactionPurpose,
1566        included: &IncludedTransaction,
1567        executor: &TransactionExecutor,
1568    ) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
1569        let (to, input, value) = persisted_call_fields(intent)?;
1570
1571        match purpose {
1572            TransactionPurpose::Wrap => {
1573                verify_wrap_balance_increase(executor, &to, value, included).await
1574            }
1575            TransactionPurpose::Approve => {
1576                let call = ERC20::approveCall::abi_decode(&input)
1577                    .with_context(|| "persisted approve calldata is invalid")?;
1578                verify_approve_allowance(executor, &to, &call.spender, call.amount, included).await
1579            }
1580            TransactionPurpose::Swap => {
1581                unreachable!("swap intents restore a swap plan")
1582            }
1583        }
1584    }
1585
1586    fn ensure_transaction_ready(&self, purpose: TransactionPurpose) -> anyhow::Result<()> {
1587        if !self.core.is_connected() {
1588            anyhow::bail!("Blockchain execution client is not connected");
1589        }
1590
1591        {
1592            let slot = self.in_flight.lock();
1593            if let Some(in_flight) = *slot {
1594                return Err(in_flight_limit_error(&in_flight));
1595            }
1596        }
1597
1598        if !self.cache.has_database() {
1599            anyhow::bail!(
1600                "No durable store configured; refusing to submit a {} transaction",
1601                purpose.as_str()
1602            );
1603        }
1604        Ok(())
1605    }
1606
1607    /// Validates a submit-order command against the configured policy and builds the swap plan.
1608    ///
1609    /// Local checks run first: pool resolution, order semantics, allowlists, amount and
1610    /// slippage limits, and the quote derived from the live pool profiler. Infrastructure
1611    /// readiness (connection, in-flight slot, durable store, signer) follows. Chain state is
1612    /// verified in the spawned task before signing.
1613    fn prepare_swap(&self, cmd: &SubmitOrder, order: &OrderAny) -> anyhow::Result<SwapPlan> {
1614        let instrument_id = order.instrument_id();
1615        let pool = self.resolve_pool(&instrument_id)?;
1616
1617        if order.order_type() != OrderType::Market {
1618            anyhow::bail!(
1619                "Unsupported order type {}; only Market is supported",
1620                order.order_type()
1621            );
1622        }
1623
1624        if !matches!(order.order_side(), OrderSide::Buy | OrderSide::Sell) {
1625            anyhow::bail!(
1626                "Unsupported order side {}; only Buy and Sell are supported",
1627                order.order_side()
1628            );
1629        }
1630
1631        if order.is_quote_quantity() {
1632            anyhow::bail!(OrderDeniedReason::unsupported_quote_quantity());
1633        }
1634
1635        let fee = pool
1636            .fee
1637            .ok_or_else(|| anyhow::anyhow!("Pool {instrument_id} has no fee tier"))?;
1638        let fee = U24::try_from(fee)
1639            .map_err(|_| anyhow::anyhow!("Pool {instrument_id} fee {fee} exceeds uint24"))?;
1640
1641        let base_token = pool.get_base_token();
1642        let quote_token = pool.get_quote_token();
1643        let quote_currency = quote_token.currency()?;
1644        let (token_in, token_out) =
1645            swap_token_pair(order.order_side(), base_token.address, quote_token.address);
1646
1647        if !self
1648            .transaction_limits
1649            .allowed_token_pairs
1650            .contains(&(token_in, token_out))
1651        {
1652            anyhow::bail!(
1653                "Token pair {token_in} -> {token_out} is not in the `allowed_token_pairs` allowlist"
1654            );
1655        }
1656
1657        let base_amount = quantity_to_raw_amount(order.quantity(), base_token.decimals)?;
1658        if base_amount > U256::from(self.transaction_limits.max_order_amount) {
1659            anyhow::bail!(
1660                "Order amount {base_amount} exceeds the configured `max_order_amount` {}",
1661                self.transaction_limits.max_order_amount
1662            );
1663        }
1664
1665        let slippage_bps = match cmd
1666            .params
1667            .as_ref()
1668            .and_then(|params| params.get_u64("slippage_bps"))
1669        {
1670            Some(value) => u32::try_from(value).map_err(|_| {
1671                anyhow::anyhow!("slippage_bps parameter {value} exceeds the u32 range")
1672            })?,
1673            None => self.transaction_limits.slippage_bps,
1674        };
1675
1676        if slippage_bps > self.transaction_limits.max_slippage_bps {
1677            anyhow::bail!(
1678                "Slippage {slippage_bps} bps exceeds the configured `max_slippage_bps` {}",
1679                self.transaction_limits.max_slippage_bps
1680            );
1681        }
1682
1683        let quote_spend_ceiling = if order.order_side() == OrderSide::Buy {
1684            let ceiling = self
1685                .transaction_limits
1686                .quote_spend_limits
1687                .get(&(token_in, token_out))
1688                .ok_or_else(|| {
1689                    anyhow::anyhow!(
1690                        "No `quote_spend_limits` entry for BUY token pair {token_in} -> {token_out}"
1691                    )
1692                })?;
1693            anyhow::ensure!(
1694                ceiling.spend_token == quote_token.address,
1695                "Quote spend limit for {token_in} -> {token_out} is denominated in {}, expected quote token {}",
1696                ceiling.spend_token,
1697                quote_token.address
1698            );
1699            anyhow::ensure!(
1700                ceiling.spend_token_decimals == quote_token.decimals,
1701                "Quote spend limit for token {} uses {} decimals, expected pool quote-token decimals {}",
1702                ceiling.spend_token,
1703                ceiling.spend_token_decimals,
1704                quote_token.decimals
1705            );
1706            Some(ceiling)
1707        } else {
1708            None
1709        };
1710
1711        let profiler = self
1712            .core
1713            .cache()
1714            .pool_profiler(&instrument_id)
1715            .cloned()
1716            .ok_or_else(|| {
1717                anyhow::anyhow!(
1718                    "No pool profiler for {instrument_id}; an active data subscription is required to quote the swap"
1719                )
1720            })?;
1721
1722        if !profiler.is_initialized {
1723            anyhow::bail!("Pool profiler for {instrument_id} is not initialized");
1724        }
1725        let profiler_position = profiler.last_processed_event.clone().ok_or_else(|| {
1726            anyhow::anyhow!("Pool profiler for {instrument_id} has processed no events")
1727        })?;
1728
1729        let zero_for_one = token_in == pool.token0.address;
1730        let (amount_in, quoted_amount_out) = match order.order_side() {
1731            OrderSide::Sell => {
1732                let quote = profiler
1733                    .swap_exact_in(base_amount, zero_for_one, None)
1734                    .map_err(|e| anyhow::anyhow!("Swap quote failed for {instrument_id}: {e}"))?;
1735                let amount_filled = if zero_for_one {
1736                    quote.amount0
1737                } else {
1738                    quote.amount1
1739                };
1740
1741                if amount_filled != I256::from(base_amount) {
1742                    anyhow::bail!(
1743                        "Local quote for {instrument_id} filled {amount_filled} of the {base_amount} order amount; pool liquidity cannot fill the order"
1744                    );
1745                }
1746                (base_amount, exact_output_amount(&quote, zero_for_one)?)
1747            }
1748            OrderSide::Buy => {
1749                let quote = profiler
1750                    .swap_exact_out(base_amount, zero_for_one, None)
1751                    .map_err(|e| anyhow::anyhow!("Swap quote failed for {instrument_id}: {e}"))?;
1752                let amount_in = quote.get_input_amount();
1753                if amount_in.is_zero() {
1754                    anyhow::bail!("Local quote for {instrument_id} produced a zero quote input");
1755                }
1756                let ceiling = quote_spend_ceiling.ok_or_else(|| {
1757                    anyhow::anyhow!(
1758                        "No `quote_spend_limits` entry for BUY token pair {token_in} -> {token_out}"
1759                    )
1760                })?;
1761
1762                if amount_in > ceiling.max_amount {
1763                    anyhow::bail!(
1764                        "BUY quote amount {amount_in} exceeds the configured `quote_spend_limits` maximum {} for {token_in} -> {token_out}",
1765                        ceiling.max_amount
1766                    );
1767                }
1768                (amount_in, base_amount)
1769            }
1770        };
1771        let min_amount_out = derive_min_amount_out(quoted_amount_out, slippage_bps)?;
1772
1773        self.ensure_transaction_ready(TransactionPurpose::Swap)?;
1774
1775        if self.signer.is_none() {
1776            anyhow::bail!("Signer not initialized; connect the client first");
1777        }
1778
1779        let pool_address = pool.address;
1780        let factory = self.uniswap_v3_factory()?;
1781        anyhow::ensure!(
1782            pool.dex.factory == factory,
1783            "Pool {instrument_id} references factory {}, expected registered factory {factory}",
1784            pool.dex.factory
1785        );
1786
1787        Ok(SwapPlan {
1788            order: order.clone(),
1789            pool,
1790            quote_currency,
1791            instrument_id,
1792            pool_address,
1793            router: self.router_addresses[0],
1794            factory,
1795            weth: self.weth_address,
1796            token_in,
1797            token_out,
1798            fee,
1799            amount_in,
1800            min_amount_out,
1801            slippage_bps,
1802            quote_spend_ceiling: quote_spend_ceiling.copied(),
1803            profiler_position: Some(profiler_position),
1804        })
1805    }
1806}
1807
1808/// Result of authenticating every persisted signed transaction in one execution database.
1809#[derive(Debug, Clone, PartialEq, Eq)]
1810pub struct PayloadStorageCheck {
1811    /// Whether payload protection is active.
1812    pub protected: bool,
1813    /// Durable deployment identity when protection is active.
1814    pub deployment_id: Option<String>,
1815    /// Rows which still contain plaintext signed transaction bytes.
1816    pub plaintext_rows: u64,
1817    /// Signed transaction rows which require a payload.
1818    pub original_rows: u64,
1819    /// Canonical replacement rows whose original bytes are unavailable.
1820    pub replacement_rows: u64,
1821    /// Payload rows successfully opened and authenticated.
1822    pub authenticated_rows: u64,
1823    /// Key IDs referenced by protected payloads.
1824    pub key_ids: Vec<String>,
1825    /// Database roles with direct table ownership or `SELECT` grants.
1826    pub read_roles: Vec<String>,
1827}
1828
1829impl From<ExecutionPayloadCheck> for PayloadStorageCheck {
1830    fn from(value: ExecutionPayloadCheck) -> Self {
1831        Self {
1832            protected: value.protected,
1833            deployment_id: value.deployment_id,
1834            plaintext_rows: value.plaintext_rows,
1835            original_rows: value.original_rows,
1836            replacement_rows: value.replacement_rows,
1837            authenticated_rows: value.authenticated_rows,
1838            key_ids: value.key_ids,
1839            read_roles: value.read_roles,
1840        }
1841    }
1842}
1843
1844// A broadcast transaction awaiting finality, occupying the single in-flight slot.
1845#[derive(Debug, Clone, Copy)]
1846struct InFlightTransaction {
1847    intent_id: i64,
1848    nonce: u64,
1849    tx_hash: B256,
1850    purpose: TransactionPurpose,
1851}
1852
1853#[derive(Debug, Clone, Copy)]
1854struct RecoveryTransaction {
1855    intent_id: i64,
1856    nonce: u64,
1857    purpose: TransactionPurpose,
1858}
1859
1860/// The single in-flight transaction slot.
1861///
1862/// The slot is claimed before any preparation RPC call so the `pending` nonce read stays
1863/// authoritative: a second transaction is rejected before it can sign. A claim is released
1864/// only when preparation fails before signing; from persistence onward the slot is never
1865/// released on failure, because the database may have committed before its acknowledgement
1866/// was lost.
1867#[derive(Debug, Clone, Copy)]
1868enum InFlightSlot {
1869    /// Claimed before preparation; no signed transaction exists yet.
1870    Preparing(TransactionPurpose),
1871    /// Restored durable ownership retained while persisted transaction data is authenticated.
1872    Recovering(RecoveryTransaction),
1873    /// Signed, persisted, and awaiting finality.
1874    AwaitingFinality(InFlightTransaction),
1875}
1876
1877#[derive(Debug, Clone)]
1878struct IncludedTransaction {
1879    intent_id: i64,
1880    nonce: u64,
1881    tx_hash: B256,
1882    block_number: u64,
1883    receipt: RpcTransactionReceipt,
1884    finality: StableFinality,
1885}
1886
1887#[derive(Debug, Clone)]
1888struct StableFinality {
1889    decisions: Vec<ExecutionVerificationDecision>,
1890    inclusion_header: ExecutionVerifiedHeader,
1891    finalized_headers: Vec<ExecutionVerifiedHeader>,
1892}
1893
1894#[derive(Debug, Clone, Copy)]
1895enum TransactionAuthorization {
1896    Wrap {
1897        weth: Address,
1898    },
1899    Approve {
1900        token: Address,
1901        router: Address,
1902        amount: U256,
1903    },
1904}
1905
1906/// The single-in-flight limit error naming the transaction currently occupying the slot.
1907fn in_flight_limit_error(slot: &InFlightSlot) -> anyhow::Error {
1908    match slot {
1909        InFlightSlot::Preparing(purpose) => anyhow::anyhow!(
1910            "A {} transaction is being prepared; at most one transaction can be in flight",
1911            purpose.as_str()
1912        ),
1913        InFlightSlot::Recovering(recovery) => anyhow::anyhow!(
1914            "Execution intent {} ({}, nonce {}) retains signer ownership pending recovery; at most one transaction can be in flight",
1915            recovery.intent_id,
1916            recovery.purpose.as_str(),
1917            recovery.nonce
1918        ),
1919        InFlightSlot::AwaitingFinality(in_flight) => anyhow::anyhow!(
1920            "Transaction {} (intent {}, {}, nonce {}) is still awaiting finality; at most one transaction can be in flight",
1921            in_flight.tx_hash,
1922            in_flight.intent_id,
1923            in_flight.purpose.as_str(),
1924            in_flight.nonce
1925        ),
1926    }
1927}
1928
1929/// Releases a pre-signature slot claim when the slot is still in the preparing state.
1930///
1931/// Aborted or failed preparation can leave a claim behind; because no signed transaction
1932/// exists for a preparing slot, releasing it cannot strand a broadcastable signature.
1933fn release_preparing_slot(in_flight: &Mutex<Option<InFlightSlot>>) {
1934    let mut slot = in_flight.lock();
1935    if matches!(*slot, Some(InFlightSlot::Preparing(_))) {
1936        *slot = None;
1937    }
1938}
1939
1940fn release_preparing_if_reservation_not_committed(
1941    in_flight: &Mutex<Option<InFlightSlot>>,
1942    error: &anyhow::Error,
1943) {
1944    if reservation_failure_proven_not_committed(error) {
1945        release_preparing_slot(in_flight);
1946    }
1947}
1948
1949#[derive(Debug)]
1950struct TransactionLimits {
1951    allowed_token_pairs: HashSet<(Address, Address)>,
1952    quote_spend_limits: HashMap<(Address, Address), QuoteSpendCeiling>,
1953    slippage_bps: u32,
1954    max_slippage_bps: u32,
1955    max_order_amount: u64,
1956    deadline_seconds: u64,
1957    max_quote_age_blocks: u64,
1958    receipt_timeout_secs: u64,
1959}
1960
1961#[derive(Debug, Clone, Copy)]
1962struct QuoteSpendCeiling {
1963    spend_token: Address,
1964    spend_token_decimals: u8,
1965    max_amount: U256,
1966}
1967
1968/// A locally signed EIP-1559 transaction ready for persist-before-broadcast.
1969struct PreparedTransaction {
1970    intent_id: i64,
1971    created_block: u64,
1972    nonce: u64,
1973    tx_hash: B256,
1974    raw_tx: Vec<u8>,
1975    payload_lease: Option<ExecutionPayloadLease>,
1976}
1977
1978impl Debug for PreparedTransaction {
1979    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1980        f.debug_struct(stringify!(PreparedTransaction))
1981            .field("intent_id", &self.intent_id)
1982            .field("created_block", &self.created_block)
1983            .field("nonce", &self.nonce)
1984            .field("tx_hash", &self.tx_hash)
1985            .field("raw_tx", &"<redacted>")
1986            .field(
1987                "payload_lease",
1988                &self.payload_lease.as_ref().map(|_| "held"),
1989            )
1990            .finish()
1991    }
1992}
1993
1994/// The classified outcome of a broadcast attempt.
1995#[derive(Debug)]
1996enum BroadcastOutcome {
1997    /// The node accepted the transaction (or reported it already known).
1998    Accepted,
1999    /// Acceptance is uncertain; the persisted record stays active and the slot occupied.
2000    Ambiguous(String),
2001}
2002
2003/// The classified outcome of awaiting transaction finality.
2004#[derive(Debug)]
2005enum InclusionOutcome {
2006    /// Canonical successful receipt observed through a stable finalized boundary.
2007    Finalized(IncludedTransaction),
2008    /// Canonical failed receipt observed through a stable finalized boundary.
2009    Reverted(IncludedTransaction),
2010    /// No receipt arrived within the poll budget or observation failed; the record stays
2011    /// pending and the in-flight slot occupied.
2012    Pending(String),
2013}
2014
2015enum ReconciliationAuthorization {
2016    Rebroadcast,
2017    Retain,
2018    ScanReplacement(VerifiedBlockHeader),
2019}
2020
2021fn verified_value<T>(outcome: VerificationOutcome<T>, context: &str) -> anyhow::Result<T> {
2022    required_verification(outcome, context).map(|verified| verified.value)
2023}
2024
2025fn required_verification<T>(
2026    outcome: VerificationOutcome<T>,
2027    context: &str,
2028) -> anyhow::Result<Verified<T>> {
2029    match outcome {
2030        VerificationOutcome::Verified(verified) => Ok(verified),
2031        VerificationOutcome::Disagreement(_) => {
2032            anyhow::bail!("{context} verification disagreed")
2033        }
2034        VerificationOutcome::Unavailable(_) => {
2035            anyhow::bail!("{context} verification is unavailable")
2036        }
2037        VerificationOutcome::Retryable(_) => {
2038            anyhow::bail!("{context} verification is retryable")
2039        }
2040        VerificationOutcome::LocallyInvalid(_) => {
2041            anyhow::bail!("{context} verification is locally invalid")
2042        }
2043    }
2044}
2045
2046fn validate_transaction_authorization(
2047    authorization: Option<&TransactionAuthorization>,
2048    to: Address,
2049    value: U256,
2050    input: &[u8],
2051) -> anyhow::Result<()> {
2052    match authorization {
2053        None => Ok(()),
2054        Some(TransactionAuthorization::Wrap { weth }) => {
2055            anyhow::ensure!(
2056                to == *weth && !value.is_zero() && input == WETH9::depositCall::SELECTOR,
2057                "Wrap authorization does not match the transaction call"
2058            );
2059            Ok(())
2060        }
2061        Some(TransactionAuthorization::Approve {
2062            token,
2063            router,
2064            amount,
2065        }) => {
2066            let expected = ERC20::approveCall {
2067                spender: *router,
2068                amount: *amount,
2069            }
2070            .abi_encode();
2071            anyhow::ensure!(
2072                to == *token && value.is_zero() && input == expected,
2073                "Approve authorization does not match the transaction call"
2074            );
2075            Ok(())
2076        }
2077    }
2078}
2079
2080fn verification_decision<T>(
2081    verified: &Verified<T>,
2082    height_start: Option<u64>,
2083    height_end: Option<u64>,
2084) -> ExecutionVerificationDecision {
2085    ExecutionVerificationDecision {
2086        read_class: verified.read.as_str(),
2087        height_start,
2088        height_end,
2089        normalized_value_digest: verified.normalized_value_digest.to_string(),
2090    }
2091}
2092
2093fn parse_verified_header(header: &ExecutionVerifiedHeader) -> anyhow::Result<VerifiedBlockHeader> {
2094    Ok(VerifiedBlockHeader {
2095        number: header.number,
2096        hash: B256::from_str(&header.hash).context("Durable finalized header hash is invalid")?,
2097        parent_hash: B256::from_str(&header.parent_hash)
2098            .context("Durable finalized parent hash is invalid")?,
2099        timestamp: header.timestamp,
2100        base_fee_per_gas: header.base_fee_per_gas,
2101    })
2102}
2103
2104fn durable_verified_header(header: &VerifiedBlockHeader) -> ExecutionVerifiedHeader {
2105    ExecutionVerifiedHeader {
2106        number: header.number,
2107        hash: header.hash.to_string(),
2108        parent_hash: header.parent_hash.to_string(),
2109        timestamp: header.timestamp,
2110        base_fee_per_gas: header.base_fee_per_gas,
2111    }
2112}
2113
2114/// Shared execution context driving the EIP-1559 transaction pipeline.
2115///
2116/// Wrap, approve, and swap submissions share one implementation so the chain, fee, gas,
2117/// signing, persistence, and broadcast policy cannot drift between operator transactions
2118/// and order flow. Carries only `Send` state so order submission can run on a spawned task
2119/// after the synchronous trait method returns.
2120#[derive(Debug, Clone)]
2121struct TransactionExecutor {
2122    http_rpc_client: Arc<BlockchainHttpRpcClient>,
2123    verification: VerificationCoordinator,
2124    manifest_version: String,
2125    manifest_digest: String,
2126    deployment_manifest: Arc<BlockchainDeploymentManifest>,
2127    provider_ids: Vec<String>,
2128    operator_ids: Vec<String>,
2129    failure_domain_ids: Vec<String>,
2130    database: BlockchainCacheDatabase,
2131    signer: Arc<PrivateKeySigner>,
2132    payload_keys: Arc<PayloadKeySet>,
2133    in_flight: Arc<Mutex<Option<InFlightSlot>>>,
2134    wallet_balance: Arc<Mutex<WalletBalance>>,
2135    account_id: AccountId,
2136    wallet_address: Address,
2137    chain_id: u32,
2138    max_fee_per_gas_wei: u64,
2139    base_fee_buffer_bps: u32,
2140    gas_limit: u64,
2141    gas_buffer_bps: u32,
2142    receipt_timeout: Duration,
2143    receipt_max_polls: u32,
2144}
2145
2146impl TransactionExecutor {
2147    /// Builds, signs, persists, and broadcasts an EIP-1559 transaction, then awaits finality.
2148    ///
2149    /// Order of operations: claim the in-flight slot, chain ID verification, nonce and fee and
2150    /// gas policy checks, local signing, persist-before-broadcast, broadcast, inclusion
2151    /// observation. The persisted record guarantees a signed transaction is never forgotten.
2152    #[expect(
2153        clippy::too_many_arguments,
2154        reason = "Transaction fields and trusted clock input stay explicit"
2155    )]
2156    #[allow(
2157        clippy::large_futures,
2158        reason = "keeps transaction verification futures inline without additional boxing"
2159    )]
2160    async fn transact(
2161        &self,
2162        now: SystemTime,
2163        to: Address,
2164        value: U256,
2165        input: Bytes,
2166        purpose: TransactionPurpose,
2167        client_order_id: Option<ClientOrderId>,
2168        authorization: TransactionAuthorization,
2169    ) -> anyhow::Result<IncludedTransaction> {
2170        self.claim_slot(purpose)?;
2171
2172        let now_unix_secs = match unix_secs_since_epoch(now) {
2173            Ok(now_unix_secs) => now_unix_secs,
2174            Err(e) => {
2175                release_preparing_slot(&self.in_flight);
2176                return Err(e);
2177            }
2178        };
2179
2180        let decision_header = match required_verification(
2181            self.verification
2182                .verify_decision_header(now_unix_secs)
2183                .await,
2184            "operator decision header",
2185        ) {
2186            Ok(header) => header,
2187            Err(e) => {
2188                release_preparing_slot(&self.in_flight);
2189                return Err(e);
2190            }
2191        };
2192        let created_block = decision_header.value.number;
2193        let intent = ExecutionIntentInsert {
2194            chain_id: self.chain_id,
2195            wallet_address: self.wallet_address.to_string(),
2196            purpose: purpose.as_str().to_string(),
2197            client_order_id: client_order_id.map(|id| id.to_string()),
2198            trader_id: None,
2199            strategy_id: None,
2200            account_id: None,
2201            instrument_id: None,
2202            pool_address: None,
2203            transaction_to: to.to_string(),
2204            transaction_input: hex::encode_prefixed(&input),
2205            transaction_value: value.to_string(),
2206            amount_in: None,
2207            created_block,
2208        };
2209        let intent = match self.database.reserve_execution_intent(&intent).await {
2210            Ok(intent) => intent,
2211            Err(e) => {
2212                release_preparing_if_reservation_not_committed(&self.in_flight, &e);
2213                return Err(e);
2214            }
2215        };
2216        let prepared = match self
2217            .prepare_and_sign(
2218                intent.id,
2219                intent.created_block,
2220                to,
2221                value,
2222                input,
2223                &authorization,
2224                decision_header,
2225            )
2226            .await
2227        {
2228            Ok(prepared) => prepared,
2229            Err(e) => {
2230                if self
2231                    .database
2232                    .mark_execution_intent_recoverable(intent.id)
2233                    .await
2234                    .is_ok()
2235                {
2236                    release_preparing_slot(&self.in_flight);
2237                }
2238                return Err(e);
2239            }
2240        };
2241        self.fill_and_persist(&prepared, purpose).await?;
2242
2243        match self.broadcast(&prepared).await? {
2244            BroadcastOutcome::Accepted => {}
2245            BroadcastOutcome::Ambiguous(message) => log::warn!("{message}"),
2246        }
2247
2248        match self.await_finality(&prepared).await? {
2249            InclusionOutcome::Finalized(mut included) => {
2250                included.finality.decisions.extend(
2251                    verify_finalized_transaction(
2252                        &included,
2253                        &intent,
2254                        prepared.nonce,
2255                        &prepared.raw_tx,
2256                        self,
2257                        purpose.as_str(),
2258                    )
2259                    .await?,
2260                );
2261                Ok(included)
2262            }
2263            InclusionOutcome::Reverted(mut included) => {
2264                included.finality.decisions.extend(
2265                    verify_finalized_transaction(
2266                        &included,
2267                        &intent,
2268                        prepared.nonce,
2269                        &prepared.raw_tx,
2270                        self,
2271                        purpose.as_str(),
2272                    )
2273                    .await?,
2274                );
2275                self.commit_verified_finality(&included, TransactionStatus::Reverted, &[])
2276                    .await?;
2277                self.database
2278                    .mark_execution_event_emitted(prepared.intent_id, "terminal")
2279                    .await?;
2280                self.release_slot();
2281                anyhow::bail!("Transaction {} reverted on-chain", included.tx_hash)
2282            }
2283            InclusionOutcome::Pending(message) => anyhow::bail!(message),
2284        }
2285    }
2286
2287    /// Claims the single in-flight slot before any preparation RPC call, so the `pending`
2288    /// nonce read stays authoritative: a second transaction is rejected before it can sign.
2289    fn claim_slot(&self, purpose: TransactionPurpose) -> anyhow::Result<()> {
2290        let mut slot = self.in_flight.lock();
2291        if let Some(in_flight) = *slot {
2292            return Err(in_flight_limit_error(&in_flight));
2293        }
2294        *slot = Some(InFlightSlot::Preparing(purpose));
2295        Ok(())
2296    }
2297
2298    /// Runs the read-only pre-signing pipeline: chain ID verification, nonce selection, fee
2299    /// and gas policy checks, transaction building, and local signing.
2300    #[expect(
2301        clippy::too_many_arguments,
2302        reason = "Security-critical transaction fields stay explicit at the signing boundary"
2303    )]
2304    #[allow(
2305        clippy::large_futures,
2306        reason = "keeps transaction verification futures inline without additional boxing"
2307    )]
2308    async fn prepare_and_sign(
2309        &self,
2310        intent_id: i64,
2311        created_block: u64,
2312        to: Address,
2313        value: U256,
2314        input: Bytes,
2315        authorization: &TransactionAuthorization,
2316        decision_header: Verified<VerifiedBlockHeader>,
2317    ) -> anyhow::Result<PreparedTransaction> {
2318        self.prepare_and_sign_with_anchors(
2319            intent_id,
2320            created_block,
2321            to,
2322            value,
2323            input,
2324            None,
2325            Some(authorization),
2326            Some(decision_header),
2327        )
2328        .await
2329    }
2330
2331    #[allow(
2332        clippy::large_futures,
2333        reason = "keeps transaction verification futures inline without additional boxing"
2334    )]
2335    async fn prepare_and_sign_swap(
2336        &self,
2337        intent_id: i64,
2338        created_block: u64,
2339        to: Address,
2340        value: U256,
2341        input: Bytes,
2342        anchors: &SwapQuoteAnchors,
2343    ) -> anyhow::Result<PreparedTransaction> {
2344        self.prepare_and_sign_with_anchors(
2345            intent_id,
2346            created_block,
2347            to,
2348            value,
2349            input,
2350            Some(anchors),
2351            None,
2352            None,
2353        )
2354        .await
2355    }
2356
2357    #[expect(
2358        clippy::too_many_arguments,
2359        reason = "Security-critical transaction fields and verification anchors stay explicit"
2360    )]
2361    #[allow(
2362        clippy::large_futures,
2363        reason = "keeps transaction verification futures inline without additional boxing"
2364    )]
2365    async fn prepare_and_sign_with_anchors(
2366        &self,
2367        intent_id: i64,
2368        created_block: u64,
2369        to: Address,
2370        value: U256,
2371        input: Bytes,
2372        swap_anchors: Option<&SwapQuoteAnchors>,
2373        authorization: Option<&TransactionAuthorization>,
2374        decision_header: Option<Verified<VerifiedBlockHeader>>,
2375    ) -> anyhow::Result<PreparedTransaction> {
2376        let expected_chain_id = u64::from(self.chain_id);
2377        let chain_id_verification = required_verification(
2378            self.verification.verify_chain_id().await,
2379            "pre-sign chain ID",
2380        )?;
2381        let actual_chain_id = chain_id_verification.value;
2382        anyhow::ensure!(
2383            actual_chain_id == expected_chain_id,
2384            "Verified chain ID does not match the transaction chain"
2385        );
2386        let decision_header_verification = if let Some(anchors) = swap_anchors {
2387            required_verification(
2388                self.verification.verify_block(anchors.state.number).await,
2389                "pre-sign swap decision header reread",
2390            )?
2391        } else {
2392            match decision_header {
2393                Some(verified) => verified,
2394                None => {
2395                    let now_unix_secs = current_unix_secs()?;
2396                    required_verification(
2397                        self.verification
2398                            .verify_decision_header(now_unix_secs)
2399                            .await,
2400                        "pre-sign decision header",
2401                    )?
2402                }
2403            }
2404        };
2405        let decision_header = decision_header_verification.value;
2406
2407        if let Some(anchors) = swap_anchors {
2408            anyhow::ensure!(
2409                decision_header == anchors.state,
2410                "Verified swap decision header changed before signing"
2411            );
2412        }
2413        let decision_ancestry = self.verify_decision_ancestry(decision_header).await?;
2414        validate_transaction_authorization(authorization, to, value, &input)?;
2415        let deployment_verification = required_verification(
2416            self.verification
2417                .verify_deployment_manifest(&self.deployment_manifest, decision_header.number)
2418                .await,
2419            "pre-sign deployment manifest",
2420        )?;
2421        let authorization_decisions = match authorization {
2422            Some(authorization) => {
2423                self.verify_transaction_authorization(authorization, decision_header.number)
2424                    .await?
2425            }
2426            None => Vec::new(),
2427        };
2428        let base_fee_per_gas_wei = decision_header.base_fee_per_gas.ok_or_else(|| {
2429            anyhow::anyhow!(
2430                "Verified decision block {} has no base fee",
2431                decision_header.number
2432            )
2433        })?;
2434        let priority_fee_verification = required_verification(
2435            self.verification.verify_priority_fee().await,
2436            "pre-sign priority fee",
2437        )?;
2438        let priority_fee_per_gas_wei = priority_fee_verification.value;
2439        let (max_fee_per_gas, max_priority_fee_per_gas) = derive_fees(
2440            base_fee_per_gas_wei,
2441            priority_fee_per_gas_wei,
2442            self.base_fee_buffer_bps,
2443            u128::from(self.max_fee_per_gas_wei),
2444        )?;
2445        let gas_estimate_verification = required_verification(
2446            self.verification
2447                .verify_gas_estimate(
2448                    &self.wallet_address,
2449                    &to,
2450                    value,
2451                    &input,
2452                    decision_header.number,
2453                )
2454                .await,
2455            "pre-sign gas estimate",
2456        )?;
2457        let gas_estimate = gas_estimate_verification.value;
2458        let gas_limit = derive_gas_limit(gas_estimate, self.gas_buffer_bps, self.gas_limit)?;
2459        let max_gas_cost = U256::from(gas_limit)
2460            .checked_mul(U256::from(max_fee_per_gas))
2461            .ok_or_else(|| anyhow::anyhow!("Maximum gas cost overflow"))?;
2462        let max_transaction_cost = value
2463            .checked_add(max_gas_cost)
2464            .ok_or_else(|| anyhow::anyhow!("Maximum transaction cost overflow"))?;
2465        let native_balance_verification = required_verification(
2466            self.verification
2467                .verify_balance(&self.wallet_address, decision_header.number)
2468                .await,
2469            "pre-sign native balance",
2470        )?;
2471        let native_balance = native_balance_verification.value;
2472
2473        if native_balance < max_transaction_cost {
2474            anyhow::bail!(
2475                "Native currency balance {native_balance} wei is below maximum transaction cost {max_transaction_cost} wei"
2476            );
2477        }
2478        let decision_height = Some(decision_header.number);
2479        let mut decisions = vec![
2480            verification_decision(&chain_id_verification, None, None),
2481            verification_decision(
2482                &decision_header_verification,
2483                decision_height,
2484                decision_height,
2485            ),
2486            verification_decision(&deployment_verification, decision_height, decision_height),
2487            verification_decision(&priority_fee_verification, None, None),
2488            verification_decision(&gas_estimate_verification, decision_height, decision_height),
2489            verification_decision(
2490                &native_balance_verification,
2491                decision_height,
2492                decision_height,
2493            ),
2494        ];
2495        decisions.extend(decision_ancestry);
2496        decisions.extend(authorization_decisions);
2497        if let Some(anchors) = swap_anchors {
2498            decisions.extend(self.verify_swap_anchors_before_sign(anchors).await?);
2499            decisions.extend(anchors.precondition_decisions.iter().cloned());
2500        } else {
2501            decisions.extend(self.verify_pre_sign_header_fence(decision_header).await?);
2502        }
2503        let canonical_nonce_verification = required_verification(
2504            self.verification
2505                .verify_transaction_count(&self.wallet_address, decision_header.number)
2506                .await,
2507            "pre-sign canonical nonce reread",
2508        )?;
2509        let pending_nonce_verification = required_verification(
2510            self.verification
2511                .verify_pending_transaction_count(&self.wallet_address)
2512                .await,
2513            "pre-sign pending nonce reread",
2514        )?;
2515        anyhow::ensure!(
2516            pending_nonce_verification.value == canonical_nonce_verification.value,
2517            "Pending nonce does not match the verified canonical nonce"
2518        );
2519        let nonce = canonical_nonce_verification.value;
2520        decisions.push(verification_decision(
2521            &canonical_nonce_verification,
2522            decision_height,
2523            decision_height,
2524        ));
2525        decisions.push(verification_decision(
2526            &pending_nonce_verification,
2527            None,
2528            None,
2529        ));
2530        let tx = build_eip1559_transaction(
2531            expected_chain_id,
2532            nonce,
2533            gas_limit,
2534            max_fee_per_gas,
2535            max_priority_fee_per_gas,
2536            to,
2537            value,
2538            input,
2539        );
2540        let wallet_address = self.wallet_address.to_string();
2541        self.database
2542            .assign_execution_intent_nonce_verified(&ExecutionNonceAssignment {
2543                intent_id,
2544                chain_id: self.chain_id,
2545                wallet_address: &wallet_address,
2546                nonce,
2547                manifest_version: &self.manifest_version,
2548                manifest_digest: &self.manifest_digest,
2549                provider_ids: &self.provider_ids,
2550                operator_ids: &self.operator_ids,
2551                failure_domain_ids: &self.failure_domain_ids,
2552                decisions: &decisions,
2553            })
2554            .await?;
2555        let payload_lease = self
2556            .database
2557            .acquire_execution_payload_lease(&self.payload_keys)
2558            .await?;
2559        let (tx_hash, raw_tx) = sign_eip1559_transaction(tx, &self.signer).await?;
2560
2561        Ok(PreparedTransaction {
2562            intent_id,
2563            created_block,
2564            nonce,
2565            tx_hash,
2566            raw_tx,
2567            payload_lease: Some(payload_lease),
2568        })
2569    }
2570
2571    async fn verify_pre_sign_header_fence(
2572        &self,
2573        target: VerifiedBlockHeader,
2574    ) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
2575        let checkpoint = required_verification(
2576            self.verification.verify_checkpoint().await,
2577            "pre-sign checkpoint reread",
2578        )?;
2579        let header = required_verification(
2580            self.verification.verify_block(target.number).await,
2581            "pre-sign decision header reread",
2582        )?;
2583        anyhow::ensure!(
2584            header.value == target,
2585            "Decision header changed before signing"
2586        );
2587        Ok(vec![
2588            verification_decision(
2589                &checkpoint,
2590                Some(checkpoint.value.number),
2591                Some(checkpoint.value.number),
2592            ),
2593            verification_decision(&header, Some(target.number), Some(target.number)),
2594        ])
2595    }
2596
2597    async fn verify_decision_ancestry(
2598        &self,
2599        target: VerifiedBlockHeader,
2600    ) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
2601        let checkpoint = required_verification(
2602            self.verification.verify_checkpoint().await,
2603            "pre-sign checkpoint",
2604        )?;
2605        anyhow::ensure!(
2606            checkpoint.value.number <= target.number,
2607            "Pre-sign decision header precedes the trusted checkpoint"
2608        );
2609        let mut decisions = vec![verification_decision(
2610            &checkpoint,
2611            Some(checkpoint.value.number),
2612            Some(checkpoint.value.number),
2613        )];
2614        let wallet_address = self.wallet_address.to_string();
2615        let position = self
2616            .database
2617            .load_execution_verification_position(
2618                self.chain_id,
2619                &wallet_address,
2620                &self.manifest_version,
2621                &self.manifest_digest,
2622            )
2623            .await?
2624            .ok_or_else(|| anyhow::anyhow!("Execution verification ledger is not initialized"))?;
2625        let durable_tip = parse_verified_header(&position.finalized_tip)?;
2626        anyhow::ensure!(
2627            durable_tip.number >= checkpoint.value.number && durable_tip.number <= target.number,
2628            "Pre-sign decision header does not extend the durable finalized header tip"
2629        );
2630        let durable_tip_verification = required_verification(
2631            self.verification.verify_block(durable_tip.number).await,
2632            "pre-sign durable finalized tip",
2633        )?;
2634        anyhow::ensure!(
2635            durable_tip_verification.value == durable_tip,
2636            "Durable finalized header tip conflicts with independent sources"
2637        );
2638
2639        if durable_tip != checkpoint.value {
2640            decisions.push(verification_decision(
2641                &durable_tip_verification,
2642                Some(durable_tip.number),
2643                Some(durable_tip.number),
2644            ));
2645        }
2646        let mut cursor = durable_tip;
2647        while cursor.number < target.number {
2648            let end = cursor.number.saturating_add(4_096).min(target.number);
2649            let start = cursor.number.saturating_add(1);
2650            let ancestry = required_verification(
2651                self.verification.verify_header_window(cursor, end).await,
2652                "pre-sign decision ancestry",
2653            )?;
2654            cursor = *ancestry
2655                .value
2656                .last()
2657                .expect("nonempty decision ancestry advances the cursor");
2658            decisions.push(verification_decision(&ancestry, Some(start), Some(end)));
2659        }
2660        anyhow::ensure!(
2661            cursor == target,
2662            "Pre-sign decision header conflicts with its trusted ancestry"
2663        );
2664        Ok(decisions)
2665    }
2666
2667    async fn verify_transaction_authorization(
2668        &self,
2669        authorization: &TransactionAuthorization,
2670        block: u64,
2671    ) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
2672        match *authorization {
2673            TransactionAuthorization::Wrap { weth } => {
2674                let call = ERC20::balanceOfCall {
2675                    account: self.wallet_address,
2676                }
2677                .abi_encode();
2678                let balance = required_verification(
2679                    self.verification
2680                        .verify_decoded_call(None, &weth, U256::ZERO, &call, block, |result| {
2681                            ERC20::balanceOfCall::abi_decode_returns(result).map_err(Into::into)
2682                        })
2683                        .await,
2684                    "pre-sign wrapped token probe",
2685                )?;
2686                Ok(vec![verification_decision(
2687                    &balance,
2688                    Some(block),
2689                    Some(block),
2690                )])
2691            }
2692            TransactionAuthorization::Approve {
2693                token,
2694                router,
2695                amount,
2696            } => {
2697                let allowance_call = ERC20::allowanceCall {
2698                    owner: self.wallet_address,
2699                    spender: router,
2700                }
2701                .abi_encode();
2702                let allowance = required_verification(
2703                    self.verification
2704                        .verify_decoded_call(
2705                            None,
2706                            &token,
2707                            U256::ZERO,
2708                            &allowance_call,
2709                            block,
2710                            |result| {
2711                                ERC20::allowanceCall::abi_decode_returns(result).map_err(Into::into)
2712                            },
2713                        )
2714                        .await,
2715                    "pre-sign router allowance",
2716                )?;
2717                anyhow::ensure!(
2718                    allowance.value.is_zero() || amount.is_zero(),
2719                    "Router allowance for token {token} is already {}; approve zero before setting a new nonzero allowance",
2720                    allowance.value
2721                );
2722
2723                let approve_call = ERC20::approveCall {
2724                    spender: router,
2725                    amount,
2726                }
2727                .abi_encode();
2728                let simulation = required_verification(
2729                    self.verification
2730                        .verify_decoded_simulation(
2731                            &self.wallet_address,
2732                            &token,
2733                            U256::ZERO,
2734                            &approve_call,
2735                            block,
2736                            |result| {
2737                                if result.is_empty() {
2738                                    Ok(true)
2739                                } else {
2740                                    ERC20::approveCall::abi_decode_returns_validate(result)
2741                                        .map_err(Into::into)
2742                                }
2743                            },
2744                        )
2745                        .await,
2746                    "pre-sign approval simulation",
2747                )?;
2748
2749                match &simulation.value {
2750                    VerifiedSimulation::Succeeded(true) => {}
2751                    VerifiedSimulation::Succeeded(false) => {
2752                        anyhow::bail!("ERC-20 approve returned false for token {token}")
2753                    }
2754                    VerifiedSimulation::Denied => {
2755                        anyhow::bail!("ERC-20 approve simulation reverted for token {token}")
2756                    }
2757                }
2758                Ok(vec![
2759                    verification_decision(&allowance, Some(block), Some(block)),
2760                    verification_decision(&simulation, Some(block), Some(block)),
2761                ])
2762            }
2763        }
2764    }
2765
2766    async fn verify_swap_anchors_before_sign(
2767        &self,
2768        anchors: &SwapQuoteAnchors,
2769    ) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
2770        let checkpoint = required_verification(
2771            self.verification.verify_checkpoint().await,
2772            "pre-sign checkpoint reread",
2773        )?;
2774        let watermark = required_verification(
2775            self.verification
2776                .verify_block(anchors.watermark.number)
2777                .await,
2778            "pre-sign profiler watermark reread",
2779        )?;
2780        anyhow::ensure!(
2781            watermark.value == anchors.watermark,
2782            "Pool state header changed before signing"
2783        );
2784        let ancestry = required_verification(
2785            self.verification
2786                .verify_header_window(watermark.value, anchors.state.number)
2787                .await,
2788            "pre-sign profiler ancestry reread",
2789        )?;
2790
2791        if let Some(last) = ancestry.value.last() {
2792            anyhow::ensure!(
2793                *last == anchors.state,
2794                "Swap decision header changed in the pre-sign ancestry reread"
2795            );
2796        } else {
2797            anyhow::ensure!(
2798                watermark.value == anchors.state,
2799                "Empty pre-sign ancestry does not end at the swap decision header"
2800            );
2801        }
2802        let quote = match anchors.quote_kind {
2803            SwapQuoteKind::ExactInput(amount_in) => required_verification(
2804                self.verification
2805                    .verify_quote_exact_input_single(
2806                        &anchors.quote_contract,
2807                        anchors.token_in,
2808                        anchors.token_out,
2809                        amount_in,
2810                        anchors.fee,
2811                        anchors.state.number,
2812                    )
2813                    .await,
2814                "pre-sign exact-input quote reread",
2815            )?,
2816            SwapQuoteKind::ExactOutput(amount_out) => required_verification(
2817                self.verification
2818                    .verify_quote_exact_output_single(
2819                        &anchors.quote_contract,
2820                        anchors.token_in,
2821                        anchors.token_out,
2822                        amount_out,
2823                        anchors.fee,
2824                        anchors.state.number,
2825                    )
2826                    .await,
2827                "pre-sign exact-output quote reread",
2828            )?,
2829        };
2830        anyhow::ensure!(
2831            quote.value == anchors.quote,
2832            "Independent swap quote changed before signing"
2833        );
2834        Ok(vec![
2835            verification_decision(
2836                &checkpoint,
2837                Some(checkpoint.value.number),
2838                Some(checkpoint.value.number),
2839            ),
2840            verification_decision(
2841                &watermark,
2842                Some(anchors.watermark.number),
2843                Some(anchors.watermark.number),
2844            ),
2845            verification_decision(
2846                &ancestry,
2847                Some(anchors.watermark.number),
2848                Some(anchors.state.number),
2849            ),
2850            verification_decision(
2851                &quote,
2852                Some(anchors.state.number),
2853                Some(anchors.state.number),
2854            ),
2855        ])
2856    }
2857
2858    /// Fills the claimed slot with the signed transaction and persists the pending record
2859    /// before broadcast.
2860    ///
2861    /// The slot is filled before the cancellable write: PostgreSQL may commit before this
2862    /// future resumes, so cancellation cannot safely restore the pre-transaction state. A
2863    /// persistence failure leaves the slot occupied because commit acknowledgement is
2864    /// ambiguous.
2865    async fn fill_and_persist(
2866        &self,
2867        prepared: &PreparedTransaction,
2868        purpose: TransactionPurpose,
2869    ) -> anyhow::Result<()> {
2870        {
2871            let mut slot = self.in_flight.lock();
2872            *slot = Some(InFlightSlot::AwaitingFinality(InFlightTransaction {
2873                intent_id: prepared.intent_id,
2874                nonce: prepared.nonce,
2875                tx_hash: prepared.tx_hash,
2876                purpose,
2877            }));
2878        }
2879
2880        let tx_hash = prepared.tx_hash;
2881        let transaction_hash = tx_hash.to_string();
2882        let policy = self.payload_policy();
2883        let intent = self
2884            .database
2885            .get_execution_intent(prepared.intent_id)
2886            .await?;
2887        authenticate_payload_identity(
2888            &prepared.raw_tx,
2889            &intent,
2890            &transaction_hash,
2891            self.chain_id,
2892            policy,
2893        )
2894        .with_context(|| format!("Newly signed transaction {tx_hash} failed authentication"))?;
2895
2896        self.database
2897            .reserve_execution_payload_seal(&self.payload_keys)
2898            .await?;
2899        let context = payload_context_identity(
2900            &intent,
2901            &transaction_hash,
2902            self.chain_id,
2903            self.payload_keys.deployment_id(),
2904        )?;
2905        let envelope = self.payload_keys.seal(&prepared.raw_tx, &context)?;
2906        let row = self
2907            .database
2908            .add_execution_transaction_envelope(
2909                prepared.intent_id,
2910                self.chain_id,
2911                &transaction_hash,
2912                &envelope,
2913            )
2914            .await
2915        .map_err(|e| {
2916            anyhow::anyhow!(
2917                "Failed to persist transaction {tx_hash}: {e}; the in-flight slot stays occupied"
2918            )
2919        })?;
2920        let stored = open_execution_payload(
2921            &self.payload_keys,
2922            policy,
2923            &intent,
2924            &row,
2925            "initial persistence",
2926        )?;
2927        anyhow::ensure!(
2928            stored == prepared.raw_tx,
2929            "Persisted transaction {tx_hash} does not match the signed bytes"
2930        );
2931        Ok(())
2932    }
2933
2934    fn payload_policy(&self) -> PayloadPolicy {
2935        PayloadPolicy {
2936            chain_id: self.chain_id,
2937            signer: self.wallet_address,
2938            gas_limit: self.gas_limit,
2939            max_fee_per_gas: self.max_fee_per_gas_wei,
2940        }
2941    }
2942
2943    #[allow(
2944        clippy::large_futures,
2945        reason = "keeps transaction verification futures inline without additional boxing"
2946    )]
2947    async fn authorize_rebroadcast(
2948        &self,
2949        prepared: &PreparedTransaction,
2950        intent: &ExecutionIntentRow,
2951        purpose: TransactionPurpose,
2952    ) -> anyhow::Result<ReconciliationAuthorization> {
2953        let now_unix_secs = current_unix_secs()?;
2954        let decision_header = required_verification(
2955            self.verification
2956                .verify_decision_header(now_unix_secs)
2957                .await,
2958            "rebroadcast decision header",
2959        )?;
2960        let block = decision_header.value.number;
2961        let mut decisions = vec![verification_decision(
2962            &decision_header,
2963            Some(block),
2964            Some(block),
2965        )];
2966        decisions.extend(self.verify_decision_ancestry(decision_header.value).await?);
2967        let deployment = required_verification(
2968            self.verification
2969                .verify_deployment_manifest(&self.deployment_manifest, block)
2970                .await,
2971            "rebroadcast deployment manifest",
2972        )?;
2973        decisions.push(verification_decision(&deployment, Some(block), Some(block)));
2974        let canonical_nonce = required_verification(
2975            self.verification
2976                .verify_transaction_count(&self.wallet_address, block)
2977                .await,
2978            "rebroadcast canonical nonce",
2979        )?;
2980        decisions.push(verification_decision(
2981            &canonical_nonce,
2982            Some(block),
2983            Some(block),
2984        ));
2985        let pending_nonce = required_verification(
2986            self.verification
2987                .verify_reconciliation_pending_transaction_count(
2988                    &self.wallet_address,
2989                    prepared.nonce,
2990                )
2991                .await,
2992            "rebroadcast pending nonce",
2993        )?;
2994        decisions.push(verification_decision(&pending_nonce, None, None));
2995        let receipt_absence = required_verification(
2996            self.verification
2997                .verify_receipt_absence(&prepared.tx_hash)
2998                .await,
2999            "rebroadcast receipt absence",
3000        )?;
3001        decisions.push(verification_decision(&receipt_absence, None, None));
3002
3003        let next_nonce = prepared
3004            .nonce
3005            .checked_add(1)
3006            .ok_or_else(|| anyhow::anyhow!("Owned signer nonce overflow"))?;
3007        anyhow::ensure!(
3008            (prepared.nonce..=next_nonce).contains(&pending_nonce.value),
3009            "Pending nonce {} is outside the owned reconciliation range {}..={next_nonce}",
3010            pending_nonce.value,
3011            prepared.nonce
3012        );
3013        anyhow::ensure!(
3014            (prepared.nonce..=next_nonce).contains(&canonical_nonce.value),
3015            "Canonical nonce {} is outside the owned reconciliation range {}..={next_nonce}",
3016            canonical_nonce.value,
3017            prepared.nonce
3018        );
3019
3020        if !receipt_absence.value {
3021            self.persist_rebroadcast_decisions(intent.id, prepared.nonce, &decisions)
3022                .await?;
3023            return Ok(ReconciliationAuthorization::Retain);
3024        }
3025
3026        if canonical_nonce.value == next_nonce {
3027            self.persist_rebroadcast_decisions(intent.id, prepared.nonce, &decisions)
3028                .await?;
3029            return Ok(ReconciliationAuthorization::ScanReplacement(
3030                decision_header.value,
3031            ));
3032        }
3033
3034        let (to, input, value) = persisted_call_fields(intent)?;
3035        let authorized = match purpose {
3036            TransactionPurpose::Wrap => {
3037                let simulation = required_verification(
3038                    self.verification
3039                        .verify_decoded_simulation(
3040                            &self.wallet_address,
3041                            &to,
3042                            value,
3043                            &input,
3044                            block,
3045                            |result| Ok(result.is_empty()),
3046                        )
3047                        .await,
3048                    "rebroadcast wrap simulation",
3049                )?;
3050                let authorized = matches!(&simulation.value, VerifiedSimulation::Succeeded(true));
3051                decisions.push(verification_decision(&simulation, Some(block), Some(block)));
3052                authorized
3053            }
3054            TransactionPurpose::Approve => {
3055                let simulation = required_verification(
3056                    self.verification
3057                        .verify_decoded_simulation(
3058                            &self.wallet_address,
3059                            &to,
3060                            value,
3061                            &input,
3062                            block,
3063                            |result| {
3064                                if result.is_empty() {
3065                                    Ok(true)
3066                                } else {
3067                                    ERC20::approveCall::abi_decode_returns_validate(result)
3068                                        .map_err(Into::into)
3069                                }
3070                            },
3071                        )
3072                        .await,
3073                    "rebroadcast approve simulation",
3074                )?;
3075                let authorized = matches!(&simulation.value, VerifiedSimulation::Succeeded(true));
3076                decisions.push(verification_decision(&simulation, Some(block), Some(block)));
3077                authorized
3078            }
3079            TransactionPurpose::Swap => {
3080                let call = UniswapV3SwapRouter::exactInputSingleCall::abi_decode(&input)
3081                    .with_context(|| "persisted swap calldata is invalid")?;
3082
3083                if U256::from(decision_header.value.timestamp) > call.params.deadline {
3084                    false
3085                } else {
3086                    let simulation = required_verification(
3087                        self.verification
3088                            .verify_decoded_simulation(
3089                                &self.wallet_address,
3090                                &to,
3091                                value,
3092                                &input,
3093                                block,
3094                                |result| {
3095                                    UniswapV3SwapRouter::exactInputSingleCall::abi_decode_returns(
3096                                        result,
3097                                    )
3098                                    .map_err(Into::into)
3099                                },
3100                            )
3101                            .await,
3102                        "rebroadcast swap simulation",
3103                    )?;
3104                    let authorized = match &simulation.value {
3105                        VerifiedSimulation::Succeeded(amount_out) => {
3106                            *amount_out >= call.params.amountOutMinimum
3107                        }
3108                        VerifiedSimulation::Denied => false,
3109                    };
3110                    decisions.push(verification_decision(&simulation, Some(block), Some(block)));
3111                    authorized
3112                }
3113            }
3114        };
3115        self.persist_rebroadcast_decisions(intent.id, prepared.nonce, &decisions)
3116            .await?;
3117        Ok(if authorized {
3118            ReconciliationAuthorization::Rebroadcast
3119        } else {
3120            ReconciliationAuthorization::Retain
3121        })
3122    }
3123
3124    async fn scan_canonical_replacement(
3125        &self,
3126        intent: &ExecutionIntentRow,
3127        nonce: u64,
3128        head: VerifiedBlockHeader,
3129        authenticated_payloads: &HashMap<B256, Vec<u8>>,
3130    ) -> anyhow::Result<Option<(B256, Vec<u8>)>> {
3131        let wallet_address = self.wallet_address.to_string();
3132        let cursor = self
3133            .database
3134            .load_execution_replacement_cursor(
3135                intent.id,
3136                self.chain_id,
3137                &wallet_address,
3138                nonce,
3139                &self.manifest_digest,
3140            )
3141            .await?;
3142        let start = cursor.as_ref().map_or(intent.created_block, |header| {
3143            header.number.saturating_add(1)
3144        });
3145        anyhow::ensure!(
3146            start <= head.number,
3147            "Canonical nonce advanced without an authenticated signer transaction in the scanned canonical range"
3148        );
3149        let scan_range = replacement_scan_range(start, head.number)?;
3150        let end = *scan_range.end();
3151        let mut decisions = Vec::new();
3152        let mut blocks = Vec::new();
3153
3154        if let Some(cursor) = cursor.as_ref() {
3155            let parent = parse_verified_header(cursor)?;
3156            let window = required_verification(
3157                self.verification
3158                    .verify_replacement_window(parent, end)
3159                    .await,
3160                "canonical replacement window",
3161            )?;
3162            decisions.push(verification_decision(&window, Some(start), Some(end)));
3163            blocks = window.value;
3164        } else {
3165            let start_header = required_verification(
3166                self.verification.verify_block(start).await,
3167                "canonical replacement start header",
3168            )?;
3169            decisions.push(verification_decision(
3170                &start_header,
3171                Some(start),
3172                Some(start),
3173            ));
3174            let start_block = required_verification(
3175                self.verification.verify_replacement_block(start).await,
3176                "canonical replacement start block",
3177            )?;
3178            anyhow::ensure!(
3179                VerifiedBlockHeader::from(start_block.value.clone()) == start_header.value,
3180                "Replacement block conflicts with its canonical header"
3181            );
3182            decisions.push(verification_decision(
3183                &start_block,
3184                Some(start),
3185                Some(start),
3186            ));
3187            blocks.push(start_block.value);
3188
3189            if end > start {
3190                let window = required_verification(
3191                    self.verification
3192                        .verify_replacement_window(start_header.value, end)
3193                        .await,
3194                    "canonical replacement window",
3195                )?;
3196                decisions.push(verification_decision(&window, Some(start + 1), Some(end)));
3197                blocks.extend(window.value);
3198            }
3199        }
3200
3201        let scanned_tip = blocks
3202            .last()
3203            .map(|block| VerifiedBlockHeader::from(block.clone()))
3204            .ok_or_else(|| anyhow::anyhow!("Verified replacement scan returned no blocks"))?;
3205        if end == head.number {
3206            anyhow::ensure!(
3207                scanned_tip == head,
3208                "Replacement scan tip conflicts with the verified canonical head"
3209            );
3210        }
3211        let mut candidates = blocks
3212            .iter()
3213            .flat_map(|block| block.transactions.iter())
3214            .filter(|transaction| {
3215                transaction.from == self.wallet_address && transaction.nonce == nonce
3216            });
3217        let candidate = candidates.next();
3218        anyhow::ensure!(
3219            candidates.next().is_none(),
3220            "Canonical replacement scan found duplicate signer-nonce transactions"
3221        );
3222
3223        let finalized_cursor = self
3224            .database
3225            .load_execution_verified_header(
3226                self.chain_id,
3227                &wallet_address,
3228                end,
3229                &self.manifest_digest,
3230            )
3231            .await?;
3232
3233        if let Some(cursor) = finalized_cursor.as_ref() {
3234            anyhow::ensure!(
3235                parse_verified_header(cursor)? == scanned_tip,
3236                "Replacement scan conflicts with the durable finalized header ledger"
3237            );
3238        }
3239
3240        let mut mismatch = None;
3241        let matched = candidate.and_then(|transaction| {
3242            let Some(raw_transaction) = authenticated_payloads.get(&transaction.hash).cloned()
3243            else {
3244                mismatch = Some(anyhow::anyhow!(
3245                    "Canonical signer-nonce transaction {} has no authenticated retained payload",
3246                    transaction.hash
3247                ));
3248                return None;
3249            };
3250
3251            if let Err(e) = validate_rpc_transaction_matches_payload(transaction, &raw_transaction)
3252            {
3253                mismatch = Some(e.context(format!(
3254                    "Canonical signer-nonce transaction {} failed authenticated payload validation",
3255                    transaction.hash
3256                )));
3257                return None;
3258            }
3259            Some((transaction.hash, raw_transaction))
3260        });
3261        let matched_hash = matched.as_ref().map(|(hash, _)| hash.to_string());
3262        self.database
3263            .record_execution_replacement_scan(&ExecutionReplacementScan {
3264                intent_id: intent.id,
3265                chain_id: self.chain_id,
3266                wallet_address: &wallet_address,
3267                nonce,
3268                finalized_cursor: finalized_cursor.as_ref(),
3269                matched_transaction_hash: matched_hash.as_deref(),
3270                manifest_version: &self.manifest_version,
3271                manifest_digest: &self.manifest_digest,
3272                provider_ids: &self.provider_ids,
3273                operator_ids: &self.operator_ids,
3274                failure_domain_ids: &self.failure_domain_ids,
3275                decisions: &decisions,
3276            })
3277            .await?;
3278
3279        if let Some(e) = mismatch {
3280            return Err(e);
3281        }
3282
3283        if matched.is_none() && end == head.number {
3284            anyhow::bail!(
3285                "Canonical nonce advanced without an authenticated signer transaction in the canonical range"
3286            );
3287        }
3288        Ok(matched)
3289    }
3290
3291    async fn persist_rebroadcast_decisions(
3292        &self,
3293        intent_id: i64,
3294        nonce: u64,
3295        decisions: &[ExecutionVerificationDecision],
3296    ) -> anyhow::Result<()> {
3297        let wallet_address = self.wallet_address.to_string();
3298        self.database
3299            .record_execution_verification_batch(&ExecutionVerificationBatch {
3300                intent_id,
3301                chain_id: self.chain_id,
3302                wallet_address: &wallet_address,
3303                nonce,
3304                decision_class: "rebroadcast",
3305                manifest_version: &self.manifest_version,
3306                manifest_digest: &self.manifest_digest,
3307                provider_ids: &self.provider_ids,
3308                operator_ids: &self.operator_ids,
3309                failure_domain_ids: &self.failure_domain_ids,
3310                decisions,
3311            })
3312            .await
3313    }
3314
3315    async fn broadcast(&self, prepared: &PreparedTransaction) -> anyhow::Result<BroadcastOutcome> {
3316        let tx_hash = prepared.tx_hash;
3317
3318        self.database
3319            .record_execution_status(
3320                prepared.intent_id,
3321                &tx_hash.to_string(),
3322                TransactionStatus::Broadcast,
3323                None,
3324                None,
3325                None,
3326                None,
3327                None,
3328            )
3329            .await
3330            .map_err(|e| {
3331                anyhow::anyhow!(
3332                    "Failed to persist broadcast attempt for transaction {tx_hash}: {e}; the in-flight slot stays occupied"
3333                )
3334            })?;
3335
3336        match self
3337            .http_rpc_client
3338            .send_raw_transaction(&prepared.raw_tx, &tx_hash)
3339            .await
3340        {
3341            Ok(broadcast_hash) => {
3342                if broadcast_hash != tx_hash {
3343                    // The node acknowledged a different hash: acceptance of the signed
3344                    // transaction is unverified, so reconcile through the persisted record
3345                    // rather than poll a hash that cannot match the chain
3346                    return Ok(BroadcastOutcome::Ambiguous(format!(
3347                        "Broadcast of transaction {tx_hash} returned a differing hash {broadcast_hash}; the persisted record reconciles instead of rebroadcasting"
3348                    )));
3349                }
3350                Ok(BroadcastOutcome::Accepted)
3351            }
3352            Err(BroadcastError::TimeoutAfterSend) => Ok(BroadcastOutcome::Ambiguous(format!(
3353                "Broadcast of transaction {tx_hash} timed out after send; the persisted record reconciles instead of rebroadcasting"
3354            ))),
3355            Err(BroadcastError::Failed(message)) => {
3356                // Transport or response failure: acceptance is ambiguous (the failure may also
3357                // predate dispatch; see BroadcastError::Failed), so occupy the slot and
3358                // reconcile rather than risk a rebroadcast
3359                Ok(BroadcastOutcome::Ambiguous(format!(
3360                    "Broadcast of transaction {tx_hash} failed ambiguously ({message}); the persisted record reconciles instead of rebroadcasting"
3361                )))
3362            }
3363            Err(error @ BroadcastError::Rejected { .. }) => {
3364                Ok(BroadcastOutcome::Ambiguous(format!(
3365                    "Broadcast of transaction {tx_hash} was rejected ({error}); the signed hash remains occupied until canonical nonce reconciliation"
3366                )))
3367            }
3368        }
3369    }
3370
3371    /// Polls until the receipt is canonical at a stable finalized boundary.
3372    #[allow(
3373        clippy::large_futures,
3374        reason = "keeps transaction verification futures inline without additional boxing"
3375    )]
3376    async fn await_finality(
3377        &self,
3378        prepared: &PreparedTransaction,
3379    ) -> anyhow::Result<InclusionOutcome> {
3380        let tx_hash = prepared.tx_hash;
3381        let deadline = tokio::time::Instant::now() + self.receipt_timeout;
3382
3383        for attempt in 0..self.receipt_max_polls {
3384            if tokio::time::Instant::now() >= deadline {
3385                break;
3386            }
3387
3388            if attempt > 0 {
3389                tokio::time::sleep(RECEIPT_POLL_INTERVAL).await;
3390            }
3391
3392            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
3393            let receipt_result =
3394                match tokio::time::timeout(remaining, self.verification.verify_receipt(&tx_hash))
3395                    .await
3396                {
3397                    Ok(result) => result,
3398                    Err(_) => break,
3399                };
3400
3401            match receipt_result {
3402                VerificationOutcome::Verified(verified_receipt) => {
3403                    let receipt = &verified_receipt.value;
3404                    let canonical_verification = required_verification(
3405                        self.verification.verify_block(receipt.block_number).await,
3406                        "receipt inclusion header",
3407                    )?;
3408                    let canonical = canonical_verification.value;
3409
3410                    if canonical.hash != receipt.block_hash {
3411                        continue;
3412                    }
3413
3414                    if let Some(mut finality) = self.receipt_is_stably_finalized(receipt).await? {
3415                        finality.decisions.insert(
3416                            0,
3417                            verification_decision(
3418                                &canonical_verification,
3419                                Some(receipt.block_number),
3420                                Some(receipt.block_number),
3421                            ),
3422                        );
3423                        finality.decisions.insert(
3424                            0,
3425                            verification_decision(
3426                                &verified_receipt,
3427                                Some(receipt.block_number),
3428                                Some(receipt.block_number),
3429                            ),
3430                        );
3431                        let included = IncludedTransaction {
3432                            intent_id: prepared.intent_id,
3433                            nonce: prepared.nonce,
3434                            tx_hash,
3435                            block_number: receipt.block_number,
3436                            receipt: receipt.clone(),
3437                            finality,
3438                        };
3439                        return if receipt.status {
3440                            Ok(InclusionOutcome::Finalized(included))
3441                        } else {
3442                            Ok(InclusionOutcome::Reverted(included))
3443                        };
3444                    }
3445                }
3446                VerificationOutcome::Retryable(_) => {}
3447                VerificationOutcome::Disagreement(_) => {
3448                    return Ok(InclusionOutcome::Pending(format!(
3449                        "Receipt verification disagreed for transaction {tx_hash}; the intent stays occupied for reconciliation"
3450                    )));
3451                }
3452                VerificationOutcome::Unavailable(_) => {
3453                    log::warn!(
3454                        "Finality poll {}/{} for transaction {tx_hash} was unavailable",
3455                        attempt + 1,
3456                        self.receipt_max_polls
3457                    );
3458                }
3459                VerificationOutcome::LocallyInvalid(_) => {
3460                    anyhow::bail!(
3461                        "Receipt verification is locally invalid for transaction {tx_hash}"
3462                    );
3463                }
3464            }
3465        }
3466
3467        self.database
3468            .record_execution_status(
3469                prepared.intent_id,
3470                &tx_hash.to_string(),
3471                TransactionStatus::Dropped,
3472                None,
3473                None,
3474                None,
3475                None,
3476                None,
3477            )
3478            .await?;
3479        Ok(InclusionOutcome::Pending(format!(
3480            "Timed out awaiting finality of transaction {tx_hash}; the intent stays occupied for reconciliation"
3481        )))
3482    }
3483
3484    async fn receipt_is_stably_finalized(
3485        &self,
3486        receipt: &RpcTransactionReceipt,
3487    ) -> anyhow::Result<Option<StableFinality>> {
3488        let finalized_verification = match self.verification.verify_finalized_header().await {
3489            VerificationOutcome::Verified(verified) => verified,
3490            VerificationOutcome::Retryable(_) | VerificationOutcome::Unavailable(_) => {
3491                return Ok(None);
3492            }
3493            VerificationOutcome::Disagreement(_) => {
3494                anyhow::bail!("Finalized header verification disagreed")
3495            }
3496            VerificationOutcome::LocallyInvalid(_) => {
3497                anyhow::bail!("Finalized header verification is locally invalid")
3498            }
3499        };
3500        let finalized = finalized_verification.value;
3501        if finalized.number < receipt.block_number {
3502            return Ok(None);
3503        }
3504
3505        let checkpoint_verification = required_verification(
3506            self.verification.verify_checkpoint().await,
3507            "finality checkpoint reread",
3508        )?;
3509        let checkpoint = checkpoint_verification.value;
3510        let mut decisions = vec![verification_decision(
3511            &checkpoint_verification,
3512            Some(checkpoint.number),
3513            Some(checkpoint.number),
3514        )];
3515        let position = self
3516            .database
3517            .load_execution_verification_position(
3518                self.chain_id,
3519                &self.wallet_address.to_string(),
3520                &self.manifest_version,
3521                &self.manifest_digest,
3522            )
3523            .await?
3524            .ok_or_else(|| anyhow::anyhow!("Execution verification ledger is not initialized"))?;
3525        let durable_tip = parse_verified_header(&position.finalized_tip)?;
3526        anyhow::ensure!(
3527            durable_tip.number >= checkpoint.number,
3528            "Durable finalized header tip precedes the trusted checkpoint"
3529        );
3530        let mut finalized_headers = vec![durable_tip];
3531        let durable_tip_verification = required_verification(
3532            self.verification.verify_block(durable_tip.number).await,
3533            "finality durable header tip",
3534        )?;
3535        anyhow::ensure!(
3536            durable_tip_verification.value == durable_tip,
3537            "Durable finalized header tip conflicts with independent sources"
3538        );
3539        decisions.push(verification_decision(
3540            &durable_tip_verification,
3541            Some(durable_tip.number),
3542            Some(durable_tip.number),
3543        ));
3544        anyhow::ensure!(
3545            finalized.number >= durable_tip.number,
3546            "Verified finalized height regressed below the durable finalized header tip"
3547        );
3548        let mut ancestry_cursor = durable_tip;
3549        while ancestry_cursor.number < finalized.number {
3550            let end = ancestry_cursor
3551                .number
3552                .saturating_add(4_096)
3553                .min(finalized.number);
3554            let start = ancestry_cursor.number.saturating_add(1);
3555            let ancestry_verification = required_verification(
3556                self.verification
3557                    .verify_header_window(ancestry_cursor, end)
3558                    .await,
3559                "finality ancestry",
3560            )?;
3561            let ancestry = &ancestry_verification.value;
3562            ancestry_cursor = *ancestry
3563                .last()
3564                .expect("nonempty finality ancestry advances the cursor");
3565            decisions.push(verification_decision(
3566                &ancestry_verification,
3567                Some(start),
3568                Some(end),
3569            ));
3570            finalized_headers.extend(ancestry.iter().copied());
3571        }
3572        anyhow::ensure!(
3573            ancestry_cursor == finalized,
3574            "Finalized header conflicts with its verified ancestry"
3575        );
3576
3577        let canonical_again_verification = required_verification(
3578            self.verification.verify_block(receipt.block_number).await,
3579            "finality inclusion header reread",
3580        )?;
3581        let canonical_again = canonical_again_verification.value;
3582        let finalized_again_verification = required_verification(
3583            self.verification.verify_block(finalized.number).await,
3584            "finalized header reread",
3585        )?;
3586        let finalized_again = finalized_again_verification.value;
3587        anyhow::ensure!(
3588            canonical_again.hash == receipt.block_hash && finalized_again == finalized,
3589            "Finality verification disagreed with the receipt or finalized header"
3590        );
3591        decisions.extend([
3592            verification_decision(
3593                &finalized_verification,
3594                Some(finalized.number),
3595                Some(finalized.number),
3596            ),
3597            verification_decision(
3598                &canonical_again_verification,
3599                Some(receipt.block_number),
3600                Some(receipt.block_number),
3601            ),
3602            verification_decision(
3603                &finalized_again_verification,
3604                Some(finalized.number),
3605                Some(finalized.number),
3606            ),
3607        ]);
3608        Ok(Some(StableFinality {
3609            decisions,
3610            inclusion_header: durable_verified_header(&canonical_again),
3611            finalized_headers: finalized_headers
3612                .iter()
3613                .map(durable_verified_header)
3614                .collect(),
3615        }))
3616    }
3617
3618    async fn commit_verified_finality(
3619        &self,
3620        included: &IncludedTransaction,
3621        status: TransactionStatus,
3622        verified_postconditions: &[ExecutionVerificationDecision],
3623    ) -> anyhow::Result<()> {
3624        anyhow::ensure!(
3625            matches!(
3626                status,
3627                TransactionStatus::Finalized | TransactionStatus::Reverted
3628            ) && included.receipt.status == (status == TransactionStatus::Finalized),
3629            "Finality status conflicts with the verified transaction receipt"
3630        );
3631        let mut decisions = included.finality.decisions.clone();
3632        decisions.extend_from_slice(verified_postconditions);
3633        let wallet_address = self.wallet_address.to_string();
3634        let transaction_hash = included.tx_hash.to_string();
3635        let block_hash = included.receipt.block_hash.to_string();
3636        let effective_gas_price = included.receipt.effective_gas_price.to_string();
3637        self.database
3638            .record_execution_finality_verified(&ExecutionFinalityTransition {
3639                intent_id: included.intent_id,
3640                chain_id: self.chain_id,
3641                wallet_address: &wallet_address,
3642                nonce: included.nonce,
3643                transaction_hash: &transaction_hash,
3644                status,
3645                block_number: included.block_number,
3646                block_hash: &block_hash,
3647                receipt_success: included.receipt.status,
3648                gas_used: included.receipt.gas_used,
3649                effective_gas_price: &effective_gas_price,
3650                manifest_version: &self.manifest_version,
3651                manifest_digest: &self.manifest_digest,
3652                provider_ids: &self.provider_ids,
3653                operator_ids: &self.operator_ids,
3654                failure_domain_ids: &self.failure_domain_ids,
3655                decisions: &decisions,
3656                finalized_headers: &included.finality.finalized_headers,
3657            })
3658            .await
3659    }
3660
3661    fn release_slot(&self) {
3662        *self.in_flight.lock() = None;
3663    }
3664}
3665
3666fn replacement_scan_range(from_block: u64, head_block: u64) -> anyhow::Result<RangeInclusive<u64>> {
3667    anyhow::ensure!(
3668        head_block >= from_block,
3669        "Canonical head {head_block} is behind execution creation block {from_block}"
3670    );
3671    let max_end = from_block.saturating_add(MAX_REPLACEMENT_SCAN_BLOCKS - 1);
3672    Ok(from_block..=head_block.min(max_end))
3673}
3674
3675fn current_unix_secs() -> anyhow::Result<u64> {
3676    unix_secs_since_epoch(SystemTime::now())
3677}
3678
3679fn unix_secs_since_epoch(now: SystemTime) -> anyhow::Result<u64> {
3680    now.duration_since(UNIX_EPOCH)
3681        .map_err(|_| anyhow::anyhow!("Trusted host clock precedes the Unix epoch"))
3682        .map(|duration| duration.as_secs())
3683}
3684
3685fn validate_payload_operation_batch_size(batch_size: usize) -> anyhow::Result<i64> {
3686    anyhow::ensure!(
3687        (1..=MAX_PAYLOAD_OPERATION_BATCH_SIZE).contains(&batch_size),
3688        "Payload operation batch size must be between 1 and {MAX_PAYLOAD_OPERATION_BATCH_SIZE}"
3689    );
3690    Ok(i64::try_from(batch_size).expect("bounded payload batch size fits i64"))
3691}
3692
3693fn current_execution_hash(
3694    intent_id: i64,
3695    hashes: &[ExecutionTransactionHashRow],
3696) -> anyhow::Result<&ExecutionTransactionHashRow> {
3697    let mut current = hashes.iter().filter(|row| row.current);
3698    let row = current
3699        .next()
3700        .ok_or_else(|| anyhow::anyhow!("Execution intent {intent_id} has no current hash"))?;
3701    anyhow::ensure!(
3702        current.next().is_none(),
3703        "Execution intent {intent_id} has more than one current hash"
3704    );
3705    Ok(row)
3706}
3707
3708fn open_execution_payload(
3709    keys: &PayloadKeySet,
3710    policy: PayloadPolicy,
3711    intent: &ExecutionIntentRow,
3712    hash: &ExecutionTransactionHashRow,
3713    reason: &str,
3714) -> anyhow::Result<Vec<u8>> {
3715    anyhow::ensure!(
3716        hash.payload_expected,
3717        "Execution transaction {} has no signed payload",
3718        hash.transaction_hash
3719    );
3720    anyhow::ensure!(
3721        hash.raw_transaction.is_none(),
3722        "Protected execution transaction {} contains plaintext",
3723        hash.transaction_hash
3724    );
3725    let envelope = hash.sealed_transaction.as_deref().ok_or_else(|| {
3726        anyhow::anyhow!(
3727            "Protected execution transaction {} has no sealed payload",
3728            hash.transaction_hash
3729        )
3730    })?;
3731    let context = payload_context(intent, hash, keys.deployment_id())?;
3732    let raw_transaction = keys.unseal(envelope, &context)?;
3733    log::info!(
3734        "Unsealed execution payload for intent {} transaction {} during {reason}",
3735        intent.id,
3736        hash.transaction_hash
3737    );
3738    authenticate_retained_payload(&raw_transaction, intent, hash, keys.deployment_id())?;
3739    if retained_payload_requires_policy(intent, hash, policy)? {
3740        authenticate_payload(&raw_transaction, intent, hash, policy, keys.deployment_id())
3741            .with_context(|| {
3742                format!(
3743                    "execution intent {} transaction {} violates current execution policy",
3744                    intent.id, hash.transaction_hash
3745                )
3746            })?;
3747    }
3748    Ok(raw_transaction)
3749}
3750
3751fn receipt_max_polls(receipt_timeout_secs: u64) -> u32 {
3752    u32::try_from(receipt_timeout_secs.max(1)).unwrap_or(u32::MAX)
3753}
3754
3755fn receipt_timeout(receipt_timeout_secs: u64) -> Duration {
3756    Duration::from_secs(receipt_timeout_secs.clamp(1, u64::from(u32::MAX)))
3757}
3758
3759/// A fully validated swap ready for asynchronous dispatch.
3760#[derive(Debug)]
3761struct SwapPlan {
3762    order: OrderAny,
3763    pool: Pool,
3764    quote_currency: Currency,
3765    instrument_id: InstrumentId,
3766    pool_address: Address,
3767    router: Address,
3768    factory: Address,
3769    weth: Address,
3770    token_in: Address,
3771    token_out: Address,
3772    fee: U24,
3773    amount_in: U256,
3774    min_amount_out: U256,
3775    slippage_bps: u32,
3776    quote_spend_ceiling: Option<QuoteSpendCeiling>,
3777    profiler_position: Option<BlockPosition>,
3778}
3779
3780#[derive(Debug, Clone)]
3781struct SwapQuoteAnchors {
3782    watermark: VerifiedBlockHeader,
3783    state: VerifiedBlockHeader,
3784    quote_contract: Address,
3785    token_in: Address,
3786    token_out: Address,
3787    fee: U24,
3788    quote_kind: SwapQuoteKind,
3789    quote: UniswapV3Quote,
3790    precondition_decisions: Vec<ExecutionVerificationDecision>,
3791}
3792
3793#[derive(Debug, Clone, Copy)]
3794enum SwapQuoteKind {
3795    ExactInput(U256),
3796    ExactOutput(U256),
3797}
3798
3799/// Executes a validated swap plan: read-only pre-trade checks, signing, persistence,
3800/// broadcast, and finality observation.
3801///
3802/// Emits only events justified by known transaction state: `OrderDenied` before the
3803/// transaction exists, `OrderSubmitted` after broadcast acceptance, and `OrderRejected` on
3804/// a definitive node rejection or an on-chain revert. No fill is emitted at broadcast or
3805/// first inclusion; fills arrive with finality reconciliation. Ambiguous outcomes keep the
3806/// order submitted untouched while the persisted record reconciles. The client retains
3807/// unresolved submissions, so an exhausted in-flight check leaves the order submitted.
3808#[allow(
3809    clippy::large_futures,
3810    reason = "keeps transaction verification futures inline without additional boxing"
3811)]
3812async fn execute_swap(
3813    mut plan: SwapPlan,
3814    executor: TransactionExecutor,
3815    emitter: ExecutionEventEmitter,
3816    max_quote_age_blocks: u64,
3817    deadline_seconds: u64,
3818) -> anyhow::Result<()> {
3819    let order = &plan.order;
3820
3821    if let Err(e) = executor.claim_slot(TransactionPurpose::Swap) {
3822        emitter.emit_order_denied(order, &e.to_string());
3823        return Ok(());
3824    }
3825
3826    let Some(profiler_position) = plan.profiler_position.as_ref() else {
3827        release_preparing_slot(&executor.in_flight);
3828        emitter.emit_order_denied(order, "Pool profiler has no quote provenance");
3829        return Ok(());
3830    };
3831    let mut swap_anchors = match validate_swap_quote(
3832        profiler_position,
3833        &plan,
3834        max_quote_age_blocks,
3835        &executor.verification,
3836        &executor.deployment_manifest,
3837    )
3838    .await
3839    {
3840        Ok(anchors) => anchors,
3841        Err(e) => {
3842            release_preparing_slot(&executor.in_flight);
3843            emitter.emit_order_denied(order, &e.to_string());
3844            return Ok(());
3845        }
3846    };
3847    let (amount_in, min_amount_out) = match verified_swap_amounts(&plan, swap_anchors.quote) {
3848        Ok(amounts) => amounts,
3849        Err(e) => {
3850            release_preparing_slot(&executor.in_flight);
3851            emitter.emit_order_denied(order, &e.to_string());
3852            return Ok(());
3853        }
3854    };
3855    plan.amount_in = amount_in;
3856    plan.min_amount_out = min_amount_out;
3857    let deadline = match swap_anchors.state.timestamp.checked_add(deadline_seconds) {
3858        Some(deadline) => deadline,
3859        None => {
3860            release_preparing_slot(&executor.in_flight);
3861            emitter.emit_order_denied(
3862                order,
3863                &format!(
3864                    "Swap deadline overflow: anchor timestamp {} plus `deadline_seconds` {deadline_seconds} exceeds u64",
3865                    swap_anchors.state.timestamp
3866                ),
3867            );
3868            return Ok(());
3869        }
3870    };
3871
3872    swap_anchors.precondition_decisions =
3873        match check_swap_preconditions(&plan, swap_anchors.state.number, &executor).await {
3874            Ok(decisions) => decisions,
3875            Err(e) => {
3876                release_preparing_slot(&executor.in_flight);
3877                emitter.emit_order_denied(order, &e.to_string());
3878                return Ok(());
3879            }
3880        };
3881
3882    let calldata = UniswapV3SwapRouter::exactInputSingleCall {
3883        params: UniswapV3SwapRouter::ExactInputSingleParams {
3884            tokenIn: plan.token_in,
3885            tokenOut: plan.token_out,
3886            fee: plan.fee,
3887            recipient: executor.wallet_address,
3888            deadline: U256::from(deadline),
3889            amountIn: plan.amount_in,
3890            amountOutMinimum: plan.min_amount_out,
3891            sqrtPriceLimitX96: U160::ZERO,
3892        },
3893    }
3894    .abi_encode();
3895
3896    let calldata = Bytes::from(calldata);
3897    let intent = ExecutionIntentInsert {
3898        chain_id: executor.chain_id,
3899        wallet_address: executor.wallet_address.to_string(),
3900        purpose: TransactionPurpose::Swap.as_str().to_string(),
3901        client_order_id: Some(order.client_order_id().to_string()),
3902        trader_id: Some(order.trader_id().to_string()),
3903        strategy_id: Some(order.strategy_id().to_string()),
3904        account_id: Some(executor.account_id.to_string()),
3905        instrument_id: Some(plan.instrument_id.to_string()),
3906        pool_address: Some(plan.pool_address.to_string()),
3907        transaction_to: plan.router.to_string(),
3908        transaction_input: hex::encode_prefixed(&calldata),
3909        transaction_value: U256::ZERO.to_string(),
3910        amount_in: Some(plan.amount_in.to_string()),
3911        created_block: swap_anchors.state.number,
3912    };
3913    let intent = match executor.database.reserve_execution_intent(&intent).await {
3914        Ok(intent) => intent,
3915        Err(e) => {
3916            release_preparing_if_reservation_not_committed(&executor.in_flight, &e);
3917            emitter.emit_order_denied(order, &e.to_string());
3918            return Ok(());
3919        }
3920    };
3921    let prepared = match executor
3922        .prepare_and_sign_swap(
3923            intent.id,
3924            intent.created_block,
3925            plan.router,
3926            U256::ZERO,
3927            calldata,
3928            &swap_anchors,
3929        )
3930        .await
3931    {
3932        Ok(prepared) => prepared,
3933        Err(e) => {
3934            if executor
3935                .database
3936                .mark_execution_intent_recoverable(intent.id)
3937                .await
3938                .is_ok()
3939            {
3940                release_preparing_slot(&executor.in_flight);
3941            }
3942            emitter.emit_order_denied(order, &e.to_string());
3943            return Ok(());
3944        }
3945    };
3946
3947    if let Err(e) = executor
3948        .fill_and_persist(&prepared, TransactionPurpose::Swap)
3949        .await
3950    {
3951        emitter.emit_order_denied(order, &e.to_string());
3952        return Ok(());
3953    }
3954
3955    let broadcast = executor.broadcast(&prepared).await?;
3956    emitter.emit_order_submitted(order);
3957    executor
3958        .database
3959        .mark_execution_event_emitted(intent.id, "acknowledgement")
3960        .await?;
3961
3962    if let BroadcastOutcome::Ambiguous(message) = broadcast {
3963        log::warn!("{message}");
3964    }
3965
3966    let trace_purpose = match plan.order.order_side() {
3967        OrderSide::Sell => "swap_sell",
3968        OrderSide::Buy => "swap_buy",
3969    };
3970
3971    match executor.await_finality(&prepared).await? {
3972        InclusionOutcome::Finalized(mut included) => {
3973            included.finality.decisions.extend(
3974                verify_finalized_transaction(
3975                    &included,
3976                    &intent,
3977                    prepared.nonce,
3978                    &prepared.raw_tx,
3979                    &executor,
3980                    trace_purpose,
3981                )
3982                .await?,
3983            );
3984            let fill = validate_finalized_swap_fill(&plan, &included)?;
3985            let wallet = load_verified_wallet_after_fill(&plan, &included, &executor).await?;
3986            executor
3987                .commit_verified_finality(
3988                    &included,
3989                    TransactionStatus::Finalized,
3990                    &wallet.decisions,
3991                )
3992                .await?;
3993            complete_finalized_swap(
3994                &plan,
3995                intent.id,
3996                included.tx_hash,
3997                fill,
3998                wallet,
3999                &executor,
4000                &emitter,
4001            )
4002            .await?;
4003            executor.release_slot();
4004            Ok(())
4005        }
4006        InclusionOutcome::Reverted(mut included) => {
4007            included.finality.decisions.extend(
4008                verify_finalized_transaction(
4009                    &included,
4010                    &intent,
4011                    prepared.nonce,
4012                    &prepared.raw_tx,
4013                    &executor,
4014                    trace_purpose,
4015                )
4016                .await?,
4017            );
4018            executor
4019                .commit_verified_finality(&included, TransactionStatus::Reverted, &[])
4020                .await?;
4021            send_reverted_order(&emitter, order, &included)?;
4022            executor
4023                .database
4024                .mark_execution_event_emitted(intent.id, "terminal")
4025                .await?;
4026            executor.release_slot();
4027            Ok(())
4028        }
4029        InclusionOutcome::Pending(message) => anyhow::bail!(message),
4030    }
4031}
4032
4033async fn validate_swap_quote(
4034    position: &BlockPosition,
4035    plan: &SwapPlan,
4036    max_age_blocks: u64,
4037    verification: &VerificationCoordinator,
4038    manifest: &BlockchainDeploymentManifest,
4039) -> anyhow::Result<SwapQuoteAnchors> {
4040    let block_hash = position.block_hash.as_deref().ok_or_else(|| {
4041        anyhow::anyhow!(
4042            "Pool state at block {} has no ingestion-time block hash; refresh the profiler before execution",
4043            position.number
4044        )
4045    })?;
4046    let expected_block_hash = B256::from_str(block_hash)
4047        .with_context(|| format!("Invalid profiler block hash {block_hash}"))?;
4048    let now_unix_secs = current_unix_secs()?;
4049    let head = verified_value(
4050        verification.verify_decision_header(now_unix_secs).await,
4051        "swap decision header",
4052    )?;
4053    validate_quote_age(position.number, head.number, max_age_blocks)?;
4054    let canonical_block = verified_value(
4055        verification.verify_block(position.number).await,
4056        "profiler watermark header",
4057    )?;
4058    anyhow::ensure!(
4059        canonical_block.hash == expected_block_hash,
4060        "Pool state block {} changed from {} to {}; refresh the profiler before execution",
4061        position.number,
4062        expected_block_hash,
4063        canonical_block.hash
4064    );
4065
4066    let snapshot_transaction = position.transaction_index == BLOCK_SCOPED_SNAPSHOT_INDEX;
4067    let snapshot_log = position.log_index == BLOCK_SCOPED_SNAPSHOT_INDEX;
4068    anyhow::ensure!(
4069        snapshot_transaction == snapshot_log,
4070        "Pool state at block {} has an invalid partial snapshot watermark",
4071        position.number
4072    );
4073
4074    if snapshot_transaction {
4075        let snapshot_hash = B256::from_str(&position.transaction_hash)
4076            .with_context(|| "Invalid block-scoped snapshot hash")?;
4077        anyhow::ensure!(
4078            snapshot_hash == expected_block_hash,
4079            "Block-scoped snapshot hash {snapshot_hash} does not match ingestion hash {expected_block_hash}"
4080        );
4081    } else {
4082        validate_profiler_event_verified(
4083            position,
4084            expected_block_hash,
4085            plan.pool_address,
4086            &plan.pool,
4087            verification,
4088        )
4089        .await?;
4090    }
4091
4092    let ancestry = verified_value(
4093        verification
4094            .verify_header_window(canonical_block, head.number)
4095            .await,
4096        "profiler-to-decision ancestry",
4097    )?;
4098
4099    if let Some(last) = ancestry.last() {
4100        anyhow::ensure!(
4101            *last == head,
4102            "Swap decision header conflicts with profiler ancestry"
4103        );
4104    } else {
4105        anyhow::ensure!(
4106            canonical_block == head,
4107            "Empty profiler ancestry does not end at the decision header"
4108        );
4109    }
4110    verified_value(
4111        verification
4112            .verify_deployment_manifest(manifest, head.number)
4113            .await,
4114        "swap deployment manifest",
4115    )?;
4116    let quote_contract = validate_manifest_pool(plan, manifest)?;
4117    let quote_kind = match plan.order.order_side() {
4118        OrderSide::Sell => SwapQuoteKind::ExactInput(quantity_to_raw_amount(
4119            plan.order.quantity(),
4120            plan.pool.get_base_token().decimals,
4121        )?),
4122        OrderSide::Buy => SwapQuoteKind::ExactOutput(quantity_to_raw_amount(
4123            plan.order.quantity(),
4124            plan.pool.get_base_token().decimals,
4125        )?),
4126    };
4127    let quote = verified_value(
4128        verify_swap_quote(verification, quote_contract, plan, quote_kind, head.number).await,
4129        "independent swap quote",
4130    )?;
4131
4132    Ok(SwapQuoteAnchors {
4133        watermark: canonical_block,
4134        state: head,
4135        quote_contract,
4136        token_in: plan.token_in,
4137        token_out: plan.token_out,
4138        fee: plan.fee,
4139        quote_kind,
4140        quote,
4141        precondition_decisions: Vec::new(),
4142    })
4143}
4144
4145async fn verify_swap_quote(
4146    verification: &VerificationCoordinator,
4147    quote_contract: Address,
4148    plan: &SwapPlan,
4149    kind: SwapQuoteKind,
4150    block: u64,
4151) -> VerificationOutcome<UniswapV3Quote> {
4152    match kind {
4153        SwapQuoteKind::ExactInput(amount_in) => {
4154            verification
4155                .verify_quote_exact_input_single(
4156                    &quote_contract,
4157                    plan.token_in,
4158                    plan.token_out,
4159                    amount_in,
4160                    plan.fee,
4161                    block,
4162                )
4163                .await
4164        }
4165        SwapQuoteKind::ExactOutput(amount_out) => {
4166            verification
4167                .verify_quote_exact_output_single(
4168                    &quote_contract,
4169                    plan.token_in,
4170                    plan.token_out,
4171                    amount_out,
4172                    plan.fee,
4173                    block,
4174                )
4175                .await
4176        }
4177    }
4178}
4179
4180fn verified_swap_amounts(plan: &SwapPlan, quote: UniswapV3Quote) -> anyhow::Result<(U256, U256)> {
4181    anyhow::ensure!(
4182        !quote.amount.is_zero(),
4183        "Independent swap quote returned zero"
4184    );
4185    let base_amount =
4186        quantity_to_raw_amount(plan.order.quantity(), plan.pool.get_base_token().decimals)?;
4187    let slippage_bps = plan.slippage_bps;
4188    match plan.order.order_side() {
4189        OrderSide::Sell => Ok((
4190            base_amount,
4191            derive_min_amount_out(quote.amount, slippage_bps)?,
4192        )),
4193        OrderSide::Buy => {
4194            let ceiling = plan.quote_spend_ceiling.ok_or_else(|| {
4195                anyhow::anyhow!(
4196                    "No quote spend ceiling for BUY token pair {} -> {}",
4197                    plan.token_in,
4198                    plan.token_out
4199                )
4200            })?;
4201            anyhow::ensure!(
4202                quote.amount <= ceiling.max_amount,
4203                "BUY quote amount {} exceeds the configured quote-spend maximum {} for {} -> {}",
4204                quote.amount,
4205                ceiling.max_amount,
4206                plan.token_in,
4207                plan.token_out
4208            );
4209            Ok((
4210                quote.amount,
4211                derive_min_amount_out(base_amount, slippage_bps)?,
4212            ))
4213        }
4214    }
4215}
4216
4217fn validate_manifest_pool(
4218    plan: &SwapPlan,
4219    manifest: &BlockchainDeploymentManifest,
4220) -> anyhow::Result<Address> {
4221    let matching = manifest
4222        .pools
4223        .iter()
4224        .filter(|pool| Address::from_str(&pool.address).ok() == Some(plan.pool_address))
4225        .collect::<Vec<_>>();
4226    anyhow::ensure!(
4227        matching.len() == 1,
4228        "Pool {} does not have exactly one deployment manifest definition",
4229        plan.pool_address
4230    );
4231    let pool = matching[0];
4232    let token0 = Address::from_str(&pool.token0)?;
4233    let token1 = Address::from_str(&pool.token1)?;
4234    let factory = Address::from_str(&pool.factory)?;
4235    let quote_contract = Address::from_str(&pool.quote_contract)?;
4236    anyhow::ensure!(
4237        token0 == plan.pool.token0.address
4238            && token1 == plan.pool.token1.address
4239            && pool.fee == plan.pool.fee.expect("validated pool fee")
4240            && factory == plan.factory,
4241        "Cached pool {} does not match its deployment manifest identity",
4242        plan.pool_address
4243    );
4244
4245    for token in [&plan.pool.token0, &plan.pool.token1] {
4246        let identities = manifest
4247            .tokens
4248            .iter()
4249            .filter(|identity| Address::from_str(&identity.address).ok() == Some(token.address))
4250            .collect::<Vec<_>>();
4251        anyhow::ensure!(
4252            identities.len() == 1,
4253            "Token {} does not have exactly one deployment manifest identity",
4254            token.address
4255        );
4256        let identity = identities[0];
4257        anyhow::ensure!(
4258            identity.name == token.name
4259                && identity.symbol == token.symbol
4260                && identity.decimals == token.decimals,
4261            "Cached token {} does not match its deployment manifest identity",
4262            token.address
4263        );
4264        let expected_role = if token.address == plan.pool.get_base_token().address {
4265            "base"
4266        } else {
4267            "quote"
4268        };
4269        anyhow::ensure!(
4270            matches!(identity.asset_role.as_str(), "both") || identity.asset_role == expected_role,
4271            "Token {} is not permitted as the pool {expected_role} asset",
4272            token.address
4273        );
4274    }
4275    Ok(quote_contract)
4276}
4277
4278async fn validate_profiler_event_verified(
4279    position: &BlockPosition,
4280    expected_block_hash: B256,
4281    pool_address: Address,
4282    pool: &Pool,
4283    verification: &VerificationCoordinator,
4284) -> anyhow::Result<()> {
4285    let transaction_hash = B256::from_str(&position.transaction_hash).with_context(|| {
4286        format!(
4287            "Invalid profiler transaction hash {}",
4288            position.transaction_hash
4289        )
4290    })?;
4291    let receipt = verified_value(
4292        verification.verify_receipt(&transaction_hash).await,
4293        "profiler watermark receipt",
4294    )?;
4295    anyhow::ensure!(
4296        receipt.status,
4297        "Profiler transaction did not execute successfully"
4298    );
4299    anyhow::ensure!(
4300        receipt.transaction_hash == transaction_hash,
4301        "Profiler receipt transaction hash does not match its ingestion watermark"
4302    );
4303    anyhow::ensure!(
4304        receipt.block_number == position.number
4305            && receipt.block_hash == expected_block_hash
4306            && receipt.transaction_index == u64::from(position.transaction_index),
4307        "Profiler receipt position does not match its ingestion watermark"
4308    );
4309    let matching_logs = receipt
4310        .logs
4311        .iter()
4312        .filter(|log| rpc_log::extract_log_index(log).ok() == Some(position.log_index))
4313        .collect::<Vec<_>>();
4314    anyhow::ensure!(
4315        matching_logs.len() == 1,
4316        "Profiler receipt contains {} logs at global index {}; expected exactly one",
4317        matching_logs.len(),
4318        position.log_index
4319    );
4320    let log = matching_logs[0];
4321    let log_transaction_hash = B256::from_str(&rpc_log::extract_transaction_hash(log)?)
4322        .with_context(|| "Invalid profiler log transaction hash")?;
4323    let log_block_hash = log
4324        .block_hash
4325        .as_deref()
4326        .ok_or_else(|| anyhow::anyhow!("Profiler log has no block hash"))?;
4327    anyhow::ensure!(
4328        !log.removed
4329            && log_transaction_hash == transaction_hash
4330            && rpc_log::extract_block_number(log)? == position.number
4331            && rpc_log::extract_transaction_index(log)? == position.transaction_index
4332            && B256::from_str(log_block_hash)? == expected_block_hash,
4333        "Profiler log position does not match its ingestion watermark"
4334    );
4335    anyhow::ensure!(
4336        rpc_log::extract_address(log)? == pool_address,
4337        "Profiler watermark log did not come from expected pool {pool_address}"
4338    );
4339    let signature = log
4340        .topics
4341        .first()
4342        .ok_or_else(|| anyhow::anyhow!("Profiler watermark log has no event signature"))?;
4343    let supported =
4344        profiler_event_signatures(pool).any(|expected| expected.eq_ignore_ascii_case(signature));
4345    anyhow::ensure!(
4346        supported,
4347        "Profiler watermark log has an unsupported event signature"
4348    );
4349    Ok(())
4350}
4351
4352fn profiler_event_signatures(pool: &Pool) -> impl Iterator<Item = &str> {
4353    [
4354        Some(pool.dex.swap_created_event.as_ref()),
4355        Some(pool.dex.mint_created_event.as_ref()),
4356        Some(pool.dex.burn_created_event.as_ref()),
4357        Some(pool.dex.collect_created_event.as_ref()),
4358        pool.dex.flash_created_event.as_deref(),
4359        pool.dex.fee_protocol_update_event.as_deref(),
4360        pool.dex.fee_protocol_collect_event.as_deref(),
4361    ]
4362    .into_iter()
4363    .flatten()
4364}
4365
4366fn validate_quote_age(
4367    profiler_block: u64,
4368    latest_block: u64,
4369    max_age_blocks: u64,
4370) -> anyhow::Result<()> {
4371    anyhow::ensure!(
4372        profiler_block <= latest_block,
4373        "Pool state at block {profiler_block} is ahead of the latest block {latest_block}; the execution RPC endpoint lags the data feed"
4374    );
4375    let quote_age = latest_block - profiler_block;
4376    anyhow::ensure!(
4377        quote_age <= max_age_blocks,
4378        "Stale quote: pool state at block {profiler_block}, latest block {latest_block}, exceeds `max_quote_age_blocks` {max_age_blocks}"
4379    );
4380    Ok(())
4381}
4382
4383fn validate_rpc_transaction_matches_payload(
4384    transaction: &RpcTransaction,
4385    raw_transaction: &[u8],
4386) -> anyhow::Result<()> {
4387    let signed = decode_signed_transaction(raw_transaction)?;
4388    anyhow::ensure!(
4389        transaction.hash == signed.hash
4390            && transaction.from == signed.signer
4391            && transaction.nonce == signed.nonce
4392            && transaction.chain_id == Some(signed.chain_id)
4393            && transaction.transaction_type == Some(2)
4394            && transaction.to == Some(signed.to)
4395            && transaction.input == signed.input
4396            && transaction.value == signed.value
4397            && transaction.gas == Some(signed.gas_limit)
4398            && transaction.max_fee_per_gas == Some(U256::from(signed.max_fee_per_gas))
4399            && transaction.max_priority_fee_per_gas
4400                == Some(U256::from(signed.max_priority_fee_per_gas)),
4401        "Verified transaction fields differ from the authenticated signed payload"
4402    );
4403    Ok(())
4404}
4405
4406#[allow(
4407    clippy::large_futures,
4408    reason = "keeps transaction verification futures inline without additional boxing"
4409)]
4410async fn verify_finalized_transaction(
4411    included: &IncludedTransaction,
4412    intent: &ExecutionIntentRow,
4413    nonce: u64,
4414    raw_transaction: &[u8],
4415    executor: &TransactionExecutor,
4416    trace_purpose: &str,
4417) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
4418    verify_finalized_transaction_identity(
4419        included,
4420        intent,
4421        nonce,
4422        raw_transaction,
4423        &executor.verification,
4424        executor.wallet_address,
4425        executor.chain_id,
4426        &executor.deployment_manifest,
4427        trace_purpose,
4428    )
4429    .await
4430}
4431
4432#[expect(clippy::too_many_arguments)]
4433async fn verify_finalized_transaction_identity(
4434    included: &IncludedTransaction,
4435    intent: &ExecutionIntentRow,
4436    nonce: u64,
4437    raw_transaction: &[u8],
4438    verification: &VerificationCoordinator,
4439    wallet_address: Address,
4440    chain_id: u32,
4441    deployment_manifest: &BlockchainDeploymentManifest,
4442    trace_purpose: &str,
4443) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
4444    let transaction_verification = required_verification(
4445        verification.verify_transaction(&included.tx_hash).await,
4446        "finalized transaction",
4447    )?;
4448    let transaction = &transaction_verification.value;
4449    let signed = decode_signed_transaction(raw_transaction)?;
4450    let (expected_to, expected_input, expected_value) = persisted_call_fields(intent)?;
4451    anyhow::ensure!(
4452        included.receipt.transaction_hash == included.tx_hash
4453            && signed.hash == included.tx_hash
4454            && signed.signer == wallet_address
4455            && signed.chain_id == u64::from(chain_id)
4456            && signed.nonce == nonce
4457            && signed.to == expected_to
4458            && signed.input == expected_input
4459            && signed.value == expected_value,
4460        "Finalized transaction does not match the authenticated signed payload and persisted intent"
4461    );
4462    validate_rpc_transaction_matches_payload(transaction, raw_transaction)
4463        .context("finalized transaction identity mismatch")?;
4464
4465    let trace_verification = required_verification(
4466        verification.verify_call_trace(&included.tx_hash).await,
4467        "finalized call trace",
4468    )?;
4469    validate_call_trace(
4470        &trace_verification.value,
4471        &signed,
4472        included.receipt.status,
4473        trace_purpose,
4474        deployment_manifest,
4475    )?;
4476    let deployment_verification = required_verification(
4477        verification
4478            .verify_deployment_manifest(deployment_manifest, included.block_number)
4479            .await,
4480        "inclusion deployment manifest",
4481    )?;
4482
4483    Ok(vec![
4484        verification_decision(
4485            &transaction_verification,
4486            Some(included.block_number),
4487            Some(included.block_number),
4488        ),
4489        verification_decision(
4490            &trace_verification,
4491            Some(included.block_number),
4492            Some(included.block_number),
4493        ),
4494        verification_decision(
4495            &deployment_verification,
4496            Some(included.block_number),
4497            Some(included.block_number),
4498        ),
4499    ])
4500}
4501
4502fn validate_call_trace(
4503    trace: &VerifiedCallTrace,
4504    signed: &crate::execution::transaction::DecodedSignedTransaction,
4505    receipt_success: bool,
4506    purpose: &str,
4507    manifest: &BlockchainDeploymentManifest,
4508) -> anyhow::Result<()> {
4509    anyhow::ensure!(
4510        trace.call_type == RpcCallType::Call
4511            && trace.from == signed.signer
4512            && trace.to == Some(signed.to)
4513            && trace.value == signed.value
4514            && trace.input_digest == keccak256(&signed.input)
4515            && trace.success == receipt_success,
4516        "Verified call-trace root differs from the authenticated transaction"
4517    );
4518    validate_internal_calls(&trace.calls, signed.to, purpose, manifest)
4519}
4520
4521fn validate_internal_calls(
4522    calls: &[VerifiedCallTrace],
4523    caller_context: Address,
4524    purpose: &str,
4525    manifest: &BlockchainDeploymentManifest,
4526) -> anyhow::Result<()> {
4527    for call in calls {
4528        anyhow::ensure!(
4529            call.from == caller_context,
4530            "Verified call trace child has an invalid caller context"
4531        );
4532        let target = call.to.ok_or_else(|| {
4533            anyhow::anyhow!("Verified call trace contains an operation without a target")
4534        })?;
4535        let call_type = match call.call_type {
4536            RpcCallType::Call => "call",
4537            RpcCallType::Callcode => "callcode",
4538            RpcCallType::Delegatecall => "delegatecall",
4539            RpcCallType::Staticcall => "staticcall",
4540            RpcCallType::Create | RpcCallType::Create2 | RpcCallType::Selfdestruct => {
4541                anyhow::bail!("Verified call trace contains a forbidden state-changing operation")
4542            }
4543        };
4544        let permitted = manifest.call_edges.iter().any(|edge| {
4545            edge.purpose == purpose
4546                && edge.call_type.eq_ignore_ascii_case(call_type)
4547                && Address::from_str(&edge.caller).ok() == Some(call.from)
4548                && Address::from_str(&edge.target).ok() == Some(target)
4549        });
4550        anyhow::ensure!(
4551            permitted,
4552            "Verified call trace contains an unreviewed {call_type} edge {} -> {target} for {purpose}",
4553            call.from
4554        );
4555        let child_context = match call.call_type {
4556            RpcCallType::Call | RpcCallType::Staticcall => target,
4557            RpcCallType::Callcode | RpcCallType::Delegatecall => caller_context,
4558            RpcCallType::Create | RpcCallType::Create2 | RpcCallType::Selfdestruct => {
4559                unreachable!("forbidden operations return before child traversal")
4560            }
4561        };
4562        validate_internal_calls(&call.calls, child_context, purpose, manifest)?;
4563    }
4564    Ok(())
4565}
4566
4567async fn verify_wrap_balance_increase(
4568    executor: &TransactionExecutor,
4569    weth_address: &Address,
4570    amount_wei: U256,
4571    included: &IncludedTransaction,
4572) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
4573    let previous_block = included.block_number.checked_sub(1).ok_or_else(|| {
4574        anyhow::anyhow!(
4575            "Included wrap transaction {} has invalid block number 0",
4576            included.tx_hash
4577        )
4578    })?;
4579    let call = ERC20::balanceOfCall {
4580        account: executor.wallet_address,
4581    }
4582    .abi_encode();
4583    let balance_before = required_verification(
4584        executor
4585            .verification
4586            .verify_decoded_call(
4587                None,
4588                weth_address,
4589                U256::ZERO,
4590                &call,
4591                previous_block,
4592                |result| ERC20::balanceOfCall::abi_decode_returns(result).map_err(Into::into),
4593            )
4594            .await,
4595        "wrapped balance before finality",
4596    )
4597    .with_context(|| {
4598        format!(
4599            "failed to verify WETH balance before included transaction {} at block {previous_block}",
4600            included.tx_hash
4601        )
4602    })?;
4603    let balance_after = required_verification(
4604        executor
4605            .verification
4606            .verify_decoded_call(
4607                None,
4608                weth_address,
4609                U256::ZERO,
4610                &call,
4611                included.block_number,
4612                |result| ERC20::balanceOfCall::abi_decode_returns(result).map_err(Into::into),
4613            )
4614            .await,
4615        "wrapped balance after finality",
4616    )
4617    .with_context(|| {
4618        format!(
4619            "failed to verify WETH balance after included transaction {} at block {}",
4620            included.tx_hash, included.block_number
4621        )
4622    })?;
4623    let expected_balance = balance_before
4624        .value
4625        .checked_add(amount_wei)
4626        .ok_or_else(|| {
4627            anyhow::anyhow!(
4628                "WETH balance overflow for included transaction {} at block {}",
4629                included.tx_hash,
4630                included.block_number
4631            )
4632        })?;
4633    anyhow::ensure!(
4634        balance_after.value == expected_balance,
4635        "WETH balance after transaction {} did not increase by {amount_wei}: expected {expected_balance}, was {}",
4636        included.tx_hash,
4637        balance_after.value
4638    );
4639
4640    Ok(vec![
4641        verification_decision(&balance_before, Some(previous_block), Some(previous_block)),
4642        verification_decision(
4643            &balance_after,
4644            Some(included.block_number),
4645            Some(included.block_number),
4646        ),
4647    ])
4648}
4649
4650async fn verify_approve_allowance(
4651    executor: &TransactionExecutor,
4652    token: &Address,
4653    router: &Address,
4654    amount: U256,
4655    included: &IncludedTransaction,
4656) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
4657    let call = ERC20::allowanceCall {
4658        owner: executor.wallet_address,
4659        spender: *router,
4660    }
4661    .abi_encode();
4662    let allowance = required_verification(
4663        executor
4664            .verification
4665            .verify_decoded_call(
4666                None,
4667                token,
4668                U256::ZERO,
4669                &call,
4670                included.block_number,
4671                |result| ERC20::allowanceCall::abi_decode_returns(result).map_err(Into::into),
4672            )
4673            .await,
4674        "router allowance after finality",
4675    )
4676    .with_context(|| {
4677        format!(
4678            "failed to verify router allowance after included transaction {} at block {}",
4679            included.tx_hash, included.block_number
4680        )
4681    })?;
4682    anyhow::ensure!(
4683        allowance.value == amount,
4684        "Router allowance after transaction {} does not equal the requested amount {amount}: was {}",
4685        included.tx_hash,
4686        allowance.value
4687    );
4688
4689    Ok(vec![verification_decision(
4690        &allowance,
4691        Some(included.block_number),
4692        Some(included.block_number),
4693    )])
4694}
4695
4696async fn complete_finalized_swap(
4697    plan: &SwapPlan,
4698    intent_id: i64,
4699    tx_hash: B256,
4700    fill: Option<FinalizedSwapFill>,
4701    wallet: VerifiedWalletRefresh,
4702    executor: &TransactionExecutor,
4703    emitter: &ExecutionEventEmitter,
4704) -> anyhow::Result<()> {
4705    if let Some(fill) = fill {
4706        let filled = OrderFilled::new(
4707            emitter.trader_id(),
4708            plan.order.strategy_id(),
4709            plan.order.instrument_id(),
4710            plan.order.client_order_id(),
4711            fill.venue_order_id,
4712            emitter.account_id(),
4713            fill.trade_id,
4714            plan.order.order_side(),
4715            plan.order.order_type(),
4716            fill.last_qty,
4717            fill.last_px,
4718            plan.quote_currency,
4719            LiquiditySide::Taker,
4720            execution_event_id(tx_hash, b"fill"),
4721            fill.ts_event,
4722            fill.ts_event,
4723            false,
4724            None,
4725            Some(fill.commission),
4726            None,
4727        );
4728        emitter.try_send_order_event(OrderEventAny::Filled(filled))?;
4729
4730        if fill.last_qty < plan.order.quantity() {
4731            let canceled = OrderCanceled::new(
4732                emitter.trader_id(),
4733                plan.order.strategy_id(),
4734                plan.order.instrument_id(),
4735                plan.order.client_order_id(),
4736                execution_event_id(tx_hash, b"partial_cancel"),
4737                fill.ts_event,
4738                fill.ts_event,
4739                false,
4740                Some(fill.venue_order_id),
4741                Some(emitter.account_id()),
4742                None,
4743            );
4744            emitter.try_send_order_event(OrderEventAny::Canceled(canceled))?;
4745        }
4746    }
4747
4748    *executor.wallet_balance.lock() = wallet.wallet_balance;
4749    emitter.try_emit_account_state(
4750        wallet.balances,
4751        vec![],
4752        true,
4753        get_atomic_clock_realtime().get_time_ns(),
4754        None,
4755    )?;
4756    executor
4757        .database
4758        .mark_execution_event_emitted(intent_id, "fill")
4759        .await
4760}
4761
4762fn send_reverted_order(
4763    emitter: &ExecutionEventEmitter,
4764    order: &OrderAny,
4765    included: &IncludedTransaction,
4766) -> anyhow::Result<()> {
4767    let ts_event = finalized_inclusion_time(included)?;
4768    let rejected = OrderRejected::new(
4769        emitter.trader_id(),
4770        order.strategy_id(),
4771        order.instrument_id(),
4772        order.client_order_id(),
4773        emitter.account_id(),
4774        format!("Transaction {} reverted on-chain", included.tx_hash).into(),
4775        execution_event_id(included.tx_hash, b"reverted"),
4776        ts_event,
4777        ts_event,
4778        false,
4779        false,
4780    );
4781    emitter.try_send_order_event(OrderEventAny::Rejected(rejected))
4782}
4783
4784fn finalized_inclusion_time(included: &IncludedTransaction) -> anyhow::Result<UnixNanos> {
4785    let inclusion = &included.finality.inclusion_header;
4786    anyhow::ensure!(
4787        inclusion.number == included.block_number
4788            && inclusion.hash == included.receipt.block_hash.to_string(),
4789        "Verified inclusion header does not match the finalized receipt"
4790    );
4791    let timestamp = inclusion.timestamp;
4792    let nanos = timestamp
4793        .checked_mul(NANOSECONDS_IN_SECOND)
4794        .ok_or_else(|| anyhow::anyhow!("Verified inclusion timestamp exceeds nanoseconds"))?;
4795    Ok(UnixNanos::from(nanos))
4796}
4797
4798fn execution_event_id(tx_hash: B256, event: &[u8]) -> UUID4 {
4799    let mut identity = Vec::with_capacity(tx_hash.len() + event.len());
4800    identity.extend_from_slice(tx_hash.as_slice());
4801    identity.extend_from_slice(event);
4802    let digest = keccak256(identity);
4803    let mut bytes = [0u8; 16];
4804    bytes.copy_from_slice(&digest[..16]);
4805    UUID4::from_bytes(bytes)
4806}
4807
4808struct FinalizedSwapFill {
4809    venue_order_id: VenueOrderId,
4810    trade_id: TradeId,
4811    last_qty: Quantity,
4812    last_px: Price,
4813    commission: Money,
4814    ts_event: UnixNanos,
4815}
4816
4817struct VerifiedWalletRefresh {
4818    wallet_balance: WalletBalance,
4819    balances: Vec<AccountBalance>,
4820    decisions: Vec<ExecutionVerificationDecision>,
4821}
4822
4823fn validate_finalized_swap_fill(
4824    plan: &SwapPlan,
4825    included: &IncludedTransaction,
4826) -> anyhow::Result<Option<FinalizedSwapFill>> {
4827    let signature =
4828        keccak256("Swap(address,address,int256,int256,uint160,uint128,int24)").to_string();
4829    let swap_logs = included
4830        .receipt
4831        .logs
4832        .iter()
4833        .filter(|log| {
4834            !log.removed
4835                && log.topics.first().is_some_and(|topic| topic == &signature)
4836                && Address::from_str(&log.address).ok() == Some(plan.pool_address)
4837        })
4838        .collect::<Vec<_>>();
4839    anyhow::ensure!(
4840        swap_logs.len() == 1,
4841        "Finalized transaction {} emitted {} Swap logs from expected pool {}; expected exactly one",
4842        included.tx_hash,
4843        swap_logs.len(),
4844        plan.pool_address
4845    );
4846    let log = swap_logs[0];
4847    let log_transaction_hash = B256::from_str(&rpc_log::extract_transaction_hash(log)?)
4848        .with_context(|| "Invalid finalized Swap log transaction hash")?;
4849    let log_block_hash = log
4850        .block_hash
4851        .as_deref()
4852        .ok_or_else(|| anyhow::anyhow!("Finalized Swap log has no block hash"))?;
4853    anyhow::ensure!(
4854        log_transaction_hash == included.tx_hash
4855            && rpc_log::extract_block_number(log)? == included.block_number
4856            && u64::from(rpc_log::extract_transaction_index(log)?)
4857                == included.receipt.transaction_index
4858            && B256::from_str(log_block_hash)
4859                .with_context(|| "Invalid finalized Swap log block hash")?
4860                == included.receipt.block_hash,
4861        "Finalized Swap log position does not match transaction {}",
4862        included.tx_hash
4863    );
4864
4865    let dex = crate::exchanges::get_dex_extended(plan.pool.chain.name, &plan.pool.dex.name)
4866        .ok_or_else(|| {
4867            anyhow::anyhow!(
4868                "No RPC Swap decoder for {}:{}",
4869                plan.pool.chain.name,
4870                plan.pool.dex.name
4871            )
4872        })?;
4873    let event = dex.parse_swap_event_rpc(log)?;
4874    let (base_amount, quote_amount) =
4875        if plan.pool.get_base_token().address == plan.pool.token0.address {
4876            (event.amount0, event.amount1)
4877        } else {
4878            (event.amount1, event.amount0)
4879        };
4880    let last_qty = match plan.order.order_side() {
4881        OrderSide::Sell => {
4882            anyhow::ensure!(
4883                base_amount.is_positive() && base_amount.unsigned_abs() == plan.amount_in,
4884                "Finalized Swap input {base_amount} does not match the persisted amount {}",
4885                plan.amount_in
4886            );
4887            plan.order.quantity()
4888        }
4889        OrderSide::Buy => {
4890            anyhow::ensure!(
4891                quote_amount.is_positive() && quote_amount.unsigned_abs() == plan.amount_in,
4892                "Finalized Swap input {quote_amount} does not match the persisted amount {}",
4893                plan.amount_in
4894            );
4895            anyhow::ensure!(
4896                base_amount.is_negative(),
4897                "Finalized Swap base amount {base_amount} is not a BUY output"
4898            );
4899            raw_amount_to_quantity(
4900                base_amount.unsigned_abs(),
4901                plan.pool.get_base_token().decimals,
4902            )?
4903        }
4904    };
4905
4906    let block = &included.finality.inclusion_header;
4907    anyhow::ensure!(
4908        block.number == included.block_number
4909            && block.hash == included.receipt.block_hash.to_string(),
4910        "Verified inclusion header {} does not match receipt hash {}",
4911        included.block_number,
4912        included.receipt.block_hash
4913    );
4914    let timestamp_ns = block
4915        .timestamp
4916        .checked_mul(NANOSECONDS_IN_SECOND)
4917        .ok_or_else(|| anyhow::anyhow!("Finalized block timestamp overflows nanoseconds"))?;
4918    let mut swap = event.to_pool_swap(
4919        Arc::clone(&plan.pool.chain),
4920        plan.instrument_id,
4921        plan.pool.pool_identifier,
4922        UnixNanos::from(timestamp_ns),
4923    );
4924    swap.calculate_trade_info(&plan.pool.token0, &plan.pool.token1, None)?;
4925    let trade = swap
4926        .trade_info
4927        .as_ref()
4928        .ok_or_else(|| anyhow::anyhow!("Finalized Swap has no calculated trade information"))?;
4929    anyhow::ensure!(
4930        trade.order_side == plan.order.order_side(),
4931        "Finalized Swap side {} does not match {} order",
4932        trade.order_side,
4933        plan.order.order_side()
4934    );
4935    let gas_cost = included
4936        .receipt
4937        .effective_gas_price
4938        .checked_mul(U256::from(included.receipt.gas_used))
4939        .ok_or_else(|| anyhow::anyhow!("Finalized transaction gas commission overflow"))?;
4940    let commission = Money::from_u256(gas_cost, plan.pool.chain.native_currency())?;
4941    let trade_digest = keccak256(format!("{}:{}", included.tx_hash, swap.log_index));
4942    let trade_digest = trade_digest.to_string();
4943    let trade_id = TradeId::new_checked(&trade_digest[2..38])?;
4944
4945    if plan
4946        .order
4947        .trade_ids()
4948        .iter()
4949        .any(|existing| **existing == trade_id)
4950    {
4951        return Ok(None);
4952    }
4953
4954    let venue_order_id = VenueOrderId::new_checked(included.tx_hash.to_string())?;
4955    let ts_event = UnixNanos::from(timestamp_ns);
4956    let last_px = match plan.order.order_side() {
4957        OrderSide::Buy => fill_price_from_quote(last_qty, plan.amount_in, plan.quote_currency)?,
4958        _ => trade.execution_price,
4959    };
4960    Ok(Some(FinalizedSwapFill {
4961        venue_order_id,
4962        trade_id,
4963        last_qty,
4964        last_px,
4965        commission,
4966        ts_event,
4967    }))
4968}
4969
4970async fn load_verified_wallet_after_fill(
4971    plan: &SwapPlan,
4972    included: &IncludedTransaction,
4973    executor: &TransactionExecutor,
4974) -> anyhow::Result<VerifiedWalletRefresh> {
4975    let mut token_universe = executor.wallet_balance.lock().token_universe.clone();
4976    token_universe.insert(plan.pool.token0.address);
4977    token_universe.insert(plan.pool.token1.address);
4978
4979    let native_amount = required_verification(
4980        executor
4981            .verification
4982            .verify_balance(&executor.wallet_address, included.block_number)
4983            .await,
4984        "finalized native balance",
4985    )?;
4986    let native_balance = Money::from_u256(native_amount.value, plan.pool.chain.native_currency())?;
4987    let mut decisions = vec![verification_decision(
4988        &native_amount,
4989        Some(included.block_number),
4990        Some(included.block_number),
4991    )];
4992    let mut token_addresses = token_universe.iter().copied().collect::<Vec<_>>();
4993    token_addresses.sort_unstable();
4994    let mut token_balances = Vec::with_capacity(token_addresses.len());
4995    for address in token_addresses {
4996        let identities = executor
4997            .deployment_manifest
4998            .tokens
4999            .iter()
5000            .filter(|identity| Address::from_str(&identity.address).ok() == Some(address))
5001            .collect::<Vec<_>>();
5002        anyhow::ensure!(
5003            identities.len() == 1,
5004            "Wallet token {address} does not have exactly one deployment manifest identity"
5005        );
5006        let identity = identities[0];
5007        let token = Token::new(
5008            Arc::clone(&plan.pool.chain),
5009            address,
5010            identity.name.clone(),
5011            identity.symbol.clone(),
5012            identity.decimals,
5013        );
5014        let call = ERC20::balanceOfCall {
5015            account: executor.wallet_address,
5016        }
5017        .abi_encode();
5018        let amount = required_verification(
5019            executor
5020                .verification
5021                .verify_decoded_call(
5022                    None,
5023                    &address,
5024                    U256::ZERO,
5025                    &call,
5026                    included.block_number,
5027                    |result| ERC20::balanceOfCall::abi_decode_returns(result).map_err(Into::into),
5028                )
5029                .await,
5030            "finalized token balance",
5031        )?;
5032        decisions.push(verification_decision(
5033            &amount,
5034            Some(included.block_number),
5035            Some(included.block_number),
5036        ));
5037        token_balances.push(TokenBalance::new(amount.value, token));
5038    }
5039
5040    let mut wallet_balance = WalletBalance::new(token_universe);
5041    let balances = wallet_balance.replace_balances(native_balance, token_balances)?;
5042    Ok(VerifiedWalletRefresh {
5043        wallet_balance,
5044        balances,
5045        decisions,
5046    })
5047}
5048
5049async fn verify_connect_capabilities(
5050    verification: &VerificationCoordinator,
5051    manifest: &BlockchainDeploymentManifest,
5052    wallet: Address,
5053    weth: Address,
5054    block: u64,
5055) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
5056    let contract = manifest
5057        .contracts
5058        .first()
5059        .ok_or_else(|| anyhow::anyhow!("Deployment manifest has no capability probe target"))?;
5060    let contract_address = Address::from_str(&contract.address)
5061        .with_context(|| "Deployment manifest capability probe target is invalid")?;
5062    let storage = required_verification(
5063        verification
5064            .verify_storage(&contract_address, &B256::ZERO, block)
5065            .await,
5066        "Blockchain explicit-height storage capability",
5067    )?;
5068
5069    let balance_call = ERC20::balanceOfCall { account: wallet }.abi_encode();
5070    let gas = required_verification(
5071        verification
5072            .verify_gas_estimate(&wallet, &weth, U256::ZERO, &balance_call, block)
5073            .await,
5074        "Blockchain explicit-height gas capability",
5075    )?;
5076
5077    let mut decisions = vec![
5078        verification_decision(&storage, Some(block), Some(block)),
5079        verification_decision(&gas, Some(block), Some(block)),
5080    ];
5081
5082    for pool in &manifest.pools {
5083        let quote_contract = Address::from_str(&pool.quote_contract)
5084            .with_context(|| "Deployment manifest quote capability target is invalid")?;
5085        let token_in = Address::from_str(&pool.token0)
5086            .with_context(|| "Deployment manifest quote input token is invalid")?;
5087        let token_out = Address::from_str(&pool.token1)
5088            .with_context(|| "Deployment manifest quote output token is invalid")?;
5089        let fee = U24::try_from(pool.fee)
5090            .map_err(|_| anyhow::anyhow!("Deployment manifest pool fee is invalid"))?;
5091        let quote = required_verification(
5092            verification
5093                .verify_quote_exact_input_single(
5094                    &quote_contract,
5095                    token_in,
5096                    token_out,
5097                    U256::from(1u64),
5098                    fee,
5099                    block,
5100                )
5101                .await,
5102            "Blockchain explicit-height quote capability",
5103        )?;
5104        decisions.push(verification_decision(&quote, Some(block), Some(block)));
5105    }
5106
5107    let trace = required_verification(
5108        verification.verify_call_trace_capability().await,
5109        "Blockchain call trace capability",
5110    )?;
5111    decisions.push(verification_decision(&trace, None, None));
5112    Ok(decisions)
5113}
5114
5115/// Runs the read-only pre-trade checks for a swap: deployed bytecode at the pool, router,
5116/// and token addresses, and an operator-prepared router allowance and input-token balance
5117/// covering the amount. The shared signing pipeline checks the exact maximum native cost.
5118/// Never wraps or approves.
5119async fn check_swap_preconditions(
5120    plan: &SwapPlan,
5121    block: u64,
5122    executor: &TransactionExecutor,
5123) -> anyhow::Result<Vec<ExecutionVerificationDecision>> {
5124    let mut decisions = Vec::new();
5125    let factory_call = UniswapV3RouterState::factoryCall.abi_encode();
5126    let router_factory = required_verification(
5127        executor
5128            .verification
5129            .verify_decoded_call(
5130                None,
5131                &plan.router,
5132                U256::ZERO,
5133                &factory_call,
5134                block,
5135                |result| {
5136                    UniswapV3RouterState::factoryCall::abi_decode_returns(result)
5137                        .map_err(Into::into)
5138                },
5139            )
5140            .await,
5141        "swap router factory",
5142    )?;
5143    anyhow::ensure!(
5144        router_factory.value == plan.factory,
5145        "Router {} reports an unexpected factory",
5146        plan.router,
5147    );
5148    decisions.push(verification_decision(
5149        &router_factory,
5150        Some(block),
5151        Some(block),
5152    ));
5153
5154    let weth_call = UniswapV3RouterState::WETH9Call.abi_encode();
5155    let router_weth = required_verification(
5156        executor
5157            .verification
5158            .verify_decoded_call(
5159                None,
5160                &plan.router,
5161                U256::ZERO,
5162                &weth_call,
5163                block,
5164                |result| {
5165                    UniswapV3RouterState::WETH9Call::abi_decode_returns(result).map_err(Into::into)
5166                },
5167            )
5168            .await,
5169        "swap router wrapped native",
5170    )?;
5171    anyhow::ensure!(
5172        router_weth.value == plan.weth,
5173        "Router {} reports an unexpected wrapped native contract",
5174        plan.router,
5175    );
5176    decisions.push(verification_decision(
5177        &router_weth,
5178        Some(block),
5179        Some(block),
5180    ));
5181
5182    let pool_call = UniswapV3Factory::getPoolCall {
5183        tokenA: plan.token_in,
5184        tokenB: plan.token_out,
5185        fee: plan.fee,
5186    }
5187    .abi_encode();
5188    let registered_pool = required_verification(
5189        executor
5190            .verification
5191            .verify_decoded_call(
5192                None,
5193                &plan.factory,
5194                U256::ZERO,
5195                &pool_call,
5196                block,
5197                |result| {
5198                    UniswapV3Factory::getPoolCall::abi_decode_returns(result).map_err(Into::into)
5199                },
5200            )
5201            .await,
5202        "swap factory pool",
5203    )?;
5204    anyhow::ensure!(
5205        registered_pool.value == plan.pool_address,
5206        "Factory resolves an unexpected pool for the swap token pair and fee"
5207    );
5208    decisions.push(verification_decision(
5209        &registered_pool,
5210        Some(block),
5211        Some(block),
5212    ));
5213
5214    for token in [&plan.pool.token0, &plan.pool.token1] {
5215        let decimals_call = ERC20::decimalsCall.abi_encode();
5216        let decimals = required_verification(
5217            executor
5218                .verification
5219                .verify_decoded_call(
5220                    None,
5221                    &token.address,
5222                    U256::ZERO,
5223                    &decimals_call,
5224                    block,
5225                    |result| ERC20::decimalsCall::abi_decode_returns(result).map_err(Into::into),
5226                )
5227                .await,
5228            "swap token decimals",
5229        )?;
5230        anyhow::ensure!(
5231            decimals.value == token.decimals,
5232            "Token {} reports unexpected decimals",
5233            token.address,
5234        );
5235        decisions.push(verification_decision(&decimals, Some(block), Some(block)));
5236    }
5237
5238    let allowance_call = ERC20::allowanceCall {
5239        owner: executor.wallet_address,
5240        spender: plan.router,
5241    }
5242    .abi_encode();
5243    let allowance = required_verification(
5244        executor
5245            .verification
5246            .verify_decoded_call(
5247                None,
5248                &plan.token_in,
5249                U256::ZERO,
5250                &allowance_call,
5251                block,
5252                |result| ERC20::allowanceCall::abi_decode_returns(result).map_err(Into::into),
5253            )
5254            .await,
5255        "swap input allowance",
5256    )?;
5257
5258    if allowance.value < plan.amount_in {
5259        anyhow::bail!(
5260            "Router allowance {} is below the swap amount {} for input token {}; approve the router explicitly before submitting",
5261            allowance.value,
5262            plan.amount_in,
5263            plan.token_in
5264        );
5265    }
5266    decisions.push(verification_decision(&allowance, Some(block), Some(block)));
5267
5268    let balance_call = ERC20::balanceOfCall {
5269        account: executor.wallet_address,
5270    }
5271    .abi_encode();
5272    let balance = required_verification(
5273        executor
5274            .verification
5275            .verify_decoded_call(
5276                None,
5277                &plan.token_in,
5278                U256::ZERO,
5279                &balance_call,
5280                block,
5281                |result| ERC20::balanceOfCall::abi_decode_returns(result).map_err(Into::into),
5282            )
5283            .await,
5284        "swap input balance",
5285    )?;
5286
5287    if balance.value < plan.amount_in {
5288        anyhow::bail!(
5289            "Input token {} balance {} is below the swap amount {}",
5290            plan.token_in,
5291            balance.value,
5292            plan.amount_in
5293        );
5294    }
5295    decisions.push(verification_decision(&balance, Some(block), Some(block)));
5296
5297    Ok(decisions)
5298}
5299
5300/// Converts a base-denominated order quantity into raw token units with exact integer
5301/// scaling by the base token decimals.
5302///
5303/// `Quantity::raw` is scaled to the greater of its declared precision and `FIXED_PRECISION`;
5304/// token amounts are scaled to the token's decimals. Quantities not exactly representable in
5305/// token units are rejected rather than rounded.
5306fn quantity_to_raw_amount(quantity: Quantity, decimals: u8) -> anyhow::Result<U256> {
5307    if quantity.is_zero() {
5308        anyhow::bail!("Order quantity must be positive");
5309    }
5310
5311    let raw = U256::from(quantity.raw());
5312    let raw_precision = quantity.precision.max(FIXED_PRECISION);
5313    if decimals >= raw_precision {
5314        let scale = U256::from(10u64)
5315            .checked_pow(U256::from(decimals - raw_precision))
5316            .ok_or_else(|| anyhow::anyhow!("Order amount scaling overflow"))?;
5317        raw.checked_mul(scale).ok_or_else(|| {
5318            anyhow::anyhow!("Order amount overflow scaling quantity to raw token units")
5319        })
5320    } else {
5321        let divisor = U256::from(10u64)
5322            .checked_pow(U256::from(raw_precision - decimals))
5323            .ok_or_else(|| anyhow::anyhow!("Order amount scaling overflow"))?;
5324        if !(raw % divisor).is_zero() {
5325            anyhow::bail!(
5326                "Order quantity {quantity} is not exactly representable in {decimals} base token decimals"
5327            );
5328        }
5329        Ok(raw / divisor)
5330    }
5331}
5332
5333fn swap_token_pair(side: OrderSide, base: Address, quote: Address) -> (Address, Address) {
5334    match side {
5335        OrderSide::Sell => (base, quote),
5336        OrderSide::Buy => (quote, base),
5337    }
5338}
5339
5340fn fill_price_from_quote(
5341    last_qty: Quantity,
5342    quote_amount: U256,
5343    quote_currency: Currency,
5344) -> anyhow::Result<Price> {
5345    let quote = Money::from_u256(quote_amount, quote_currency)?;
5346    Price::from_decimal_dp(quote.as_decimal() / last_qty.as_decimal(), FIXED_PRECISION)
5347        .map_err(anyhow::Error::from)
5348}
5349
5350fn raw_amount_to_quantity(amount: U256, decimals: u8) -> anyhow::Result<Quantity> {
5351    if amount.is_zero() {
5352        anyhow::bail!("Executed amount must be positive");
5353    }
5354    let quantity = if decimals >= FIXED_PRECISION {
5355        let scale = U256::from(10u64)
5356            .checked_pow(U256::from(decimals - FIXED_PRECISION))
5357            .ok_or_else(|| anyhow::anyhow!("Executed amount scaling overflow"))?;
5358        Quantity::from_u256(amount / scale, FIXED_PRECISION).map_err(anyhow::Error::from)?
5359    } else {
5360        Quantity::from_u256(amount, decimals).map_err(anyhow::Error::from)?
5361    };
5362
5363    if quantity.is_zero() {
5364        anyhow::bail!(
5365            "Executed amount {amount} is below representable quantity precision {FIXED_PRECISION}"
5366        );
5367    }
5368    Ok(quantity)
5369}
5370
5371fn exact_output_amount(quote: &SwapQuote, zero_for_one: bool) -> anyhow::Result<U256> {
5372    let amount = if zero_for_one {
5373        quote.amount1
5374    } else {
5375        quote.amount0
5376    };
5377
5378    if !amount.is_negative() {
5379        anyhow::bail!("Swap quote output amount {amount} is not a positive output");
5380    }
5381    Ok(amount.unsigned_abs())
5382}
5383
5384/// Derives the minimum output accepted for the swap: the quoted output reduced by
5385/// `slippage_bps`, in exact integer arithmetic. Rejects a zero minimum, which would leave
5386/// the swap without slippage protection.
5387fn derive_min_amount_out(quoted_amount_out: U256, slippage_bps: u32) -> anyhow::Result<U256> {
5388    if slippage_bps >= BPS_DENOMINATOR {
5389        anyhow::bail!("Slippage {slippage_bps} bps must be below {BPS_DENOMINATOR}");
5390    }
5391    let min_amount_out = quoted_amount_out
5392        .checked_mul(U256::from(BPS_DENOMINATOR - slippage_bps))
5393        .and_then(|scaled| scaled.checked_div(U256::from(BPS_DENOMINATOR)))
5394        .ok_or_else(|| anyhow::anyhow!("Minimum output derivation overflow"))?;
5395    if min_amount_out.is_zero() {
5396        anyhow::bail!(
5397            "Derived minimum output is zero for quoted output {quoted_amount_out} at {slippage_bps} bps slippage"
5398        );
5399    }
5400    Ok(min_amount_out)
5401}
5402
5403impl BlockchainExecutionClient {
5404    #[allow(
5405        clippy::large_futures,
5406        reason = "keeps transaction verification futures inline without additional boxing"
5407    )]
5408    async fn build_execution_verification_migration(
5409        &self,
5410        snapshot: ExecutionVerificationMigrationSnapshot,
5411        finalized: VerifiedBlockHeader,
5412        finalized_headers: &[VerifiedBlockHeader],
5413        nonce_verification: &Verified<u64>,
5414    ) -> anyhow::Result<ExecutionVerificationMigration> {
5415        let next_canonical_nonce = nonce_verification.value;
5416        let mut hashes_by_intent: HashMap<i64, Vec<&ExecutionTransactionHashRow>> = HashMap::new();
5417        for hash in &snapshot.hashes {
5418            hashes_by_intent
5419                .entry(hash.intent_id)
5420                .or_default()
5421                .push(hash);
5422        }
5423        let active_count = snapshot
5424            .intents
5425            .iter()
5426            .filter(|intent| intent.active)
5427            .count();
5428        anyhow::ensure!(
5429            active_count <= 1,
5430            "Retained execution history has multiple active signer owners"
5431        );
5432
5433        let mut nonce_owners = HashMap::new();
5434        let mut records = Vec::with_capacity(snapshot.intents.len());
5435        let finalized_headers = finalized_headers
5436            .iter()
5437            .map(durable_verified_header)
5438            .collect::<Vec<_>>();
5439
5440        for intent in &snapshot.intents {
5441            anyhow::ensure!(
5442                intent.chain_id == self.chain.chain_id
5443                    && intent.wallet_address == self.config.wallet_address,
5444                "Retained execution intent belongs to another signer"
5445            );
5446            let purpose = TransactionPurpose::parse(&intent.purpose).ok_or_else(|| {
5447                anyhow::anyhow!("Retained execution intent has an unsupported purpose")
5448            })?;
5449            let hashes = hashes_by_intent
5450                .get(&intent.id)
5451                .map_or_default(Vec::as_slice);
5452            let current = hashes
5453                .iter()
5454                .copied()
5455                .filter(|hash| hash.current)
5456                .collect::<Vec<_>>();
5457            anyhow::ensure!(
5458                current.len() <= 1,
5459                "Retained execution intent {} has multiple current hashes",
5460                intent.id
5461            );
5462            let current = current.first().copied();
5463            let mut authenticated = HashMap::new();
5464
5465            for hash in hashes {
5466                if hash.payload_expected {
5467                    let raw = open_execution_payload(
5468                        self.payload_keys
5469                            .as_deref()
5470                            .expect("Postgres execution requires payload keys"),
5471                        self.payload_policy(),
5472                        intent,
5473                        hash,
5474                        "verification migration",
5475                    )?;
5476                    authenticated.insert(hash.id, raw);
5477                } else {
5478                    anyhow::ensure!(
5479                        hash.raw_transaction.is_none() && hash.sealed_transaction.is_none(),
5480                        "Unowned replacement hash retains signed bytes"
5481                    );
5482                }
5483            }
5484
5485            if let Some(nonce) = intent.nonce {
5486                anyhow::ensure!(
5487                    nonce_owners.insert(nonce, intent.id).is_none(),
5488                    "Retained execution history has duplicate signer nonce ownership"
5489                );
5490            }
5491
5492            let base_decision = verification_decision(
5493                nonce_verification,
5494                Some(finalized.number),
5495                Some(finalized.number),
5496            );
5497
5498            if !intent.active {
5499                if matches!(intent.status.as_str(), "finalized" | "reverted") {
5500                    let expected_marker =
5501                        if purpose == TransactionPurpose::Swap && intent.status == "finalized" {
5502                            intent.fill_emitted
5503                        } else {
5504                            intent.terminal_emitted
5505                        };
5506                    anyhow::ensure!(
5507                        expected_marker,
5508                        "Released terminal intent {} has no durable event marker",
5509                        intent.id
5510                    );
5511                } else {
5512                    anyhow::ensure!(
5513                        matches!(intent.status.as_str(), "dropped" | "recoverable")
5514                            && authenticated.is_empty(),
5515                        "Released nonterminal intent {} retains signed ownership",
5516                        intent.id
5517                    );
5518                    records.push(ExecutionVerificationMigrationRecord {
5519                        intent_id: intent.id,
5520                        nonce: intent.nonce,
5521                        transaction_hash: None,
5522                        terminal_status: None,
5523                        block_number: None,
5524                        block_hash: None,
5525                        receipt_success: None,
5526                        gas_used: None,
5527                        effective_gas_price: None,
5528                        recover_prepared: false,
5529                        decisions: vec![base_decision],
5530                    });
5531                    continue;
5532                }
5533            }
5534
5535            if intent.active && intent.nonce.is_none() {
5536                anyhow::ensure!(
5537                    intent.status == "prepared" && hashes.is_empty(),
5538                    "Unassigned active intent {} is not an unsigned preparation",
5539                    intent.id
5540                );
5541                records.push(ExecutionVerificationMigrationRecord {
5542                    intent_id: intent.id,
5543                    nonce: None,
5544                    transaction_hash: None,
5545                    terminal_status: None,
5546                    block_number: None,
5547                    block_hash: None,
5548                    receipt_success: None,
5549                    gas_used: None,
5550                    effective_gas_price: None,
5551                    recover_prepared: true,
5552                    decisions: vec![base_decision],
5553                });
5554                continue;
5555            }
5556
5557            let nonce = intent.nonce.ok_or_else(|| {
5558                anyhow::anyhow!("Retained signed intent {} has no nonce", intent.id)
5559            })?;
5560            let current = current.ok_or_else(|| {
5561                anyhow::anyhow!("Retained signed intent {} has no current hash", intent.id)
5562            })?;
5563            let raw_transaction = authenticated.get(&current.id).ok_or_else(|| {
5564                anyhow::anyhow!(
5565                    "Retained signed intent {} has no authenticated current payload",
5566                    intent.id
5567                )
5568            })?;
5569
5570            if intent.active && nonce == next_canonical_nonce {
5571                anyhow::ensure!(
5572                    !matches!(intent.status.as_str(), "finalized" | "reverted"),
5573                    "Active terminal intent conflicts with the canonical nonce ledger"
5574                );
5575                records.push(ExecutionVerificationMigrationRecord {
5576                    intent_id: intent.id,
5577                    nonce: Some(nonce),
5578                    transaction_hash: Some(current.transaction_hash.clone()),
5579                    terminal_status: None,
5580                    block_number: None,
5581                    block_hash: None,
5582                    receipt_success: None,
5583                    gas_used: None,
5584                    effective_gas_price: None,
5585                    recover_prepared: false,
5586                    decisions: vec![base_decision],
5587                });
5588                continue;
5589            }
5590            anyhow::ensure!(
5591                nonce < next_canonical_nonce,
5592                "Retained active nonce {nonce} is above canonical nonce {next_canonical_nonce}"
5593            );
5594
5595            let receipt_verification = required_verification(
5596                self.verification
5597                    .verify_receipt(&B256::from_str(&current.transaction_hash).with_context(
5598                        || {
5599                            format!(
5600                                "Retained transaction hash {} is invalid",
5601                                current.transaction_hash
5602                            )
5603                        },
5604                    )?)
5605                    .await,
5606                "migration receipt",
5607            )?;
5608            let receipt = receipt_verification.value.clone();
5609            anyhow::ensure!(
5610                receipt.block_number <= finalized.number,
5611                "Retained terminal receipt is above the verified finalized boundary"
5612            );
5613            let inclusion_verification = required_verification(
5614                self.verification.verify_block(receipt.block_number).await,
5615                "migration inclusion header",
5616            )?;
5617            anyhow::ensure!(
5618                inclusion_verification.value.hash == receipt.block_hash
5619                    && finalized_headers.iter().any(|header| {
5620                        header.number == receipt.block_number
5621                            && header.hash == receipt.block_hash.to_string()
5622                    }),
5623                "Retained terminal receipt is not on the verified finalized ancestry"
5624            );
5625            let tx_hash = B256::from_str(&current.transaction_hash)
5626                .context("Retained transaction hash is invalid")?;
5627            let included = IncludedTransaction {
5628                intent_id: intent.id,
5629                nonce,
5630                tx_hash,
5631                block_number: receipt.block_number,
5632                receipt: receipt.clone(),
5633                finality: StableFinality {
5634                    decisions: Vec::new(),
5635                    inclusion_header: durable_verified_header(&inclusion_verification.value),
5636                    finalized_headers: finalized_headers.clone(),
5637                },
5638            };
5639            let trace_purpose = match purpose {
5640                TransactionPurpose::Wrap => "wrap",
5641                TransactionPurpose::Approve => "approve",
5642                TransactionPurpose::Swap => {
5643                    match self.restore_swap_plan(intent)?.order.order_side() {
5644                        OrderSide::Sell => "swap_sell",
5645                        OrderSide::Buy => "swap_buy",
5646                    }
5647                }
5648            };
5649            let mut decisions = vec![
5650                verification_decision(
5651                    &receipt_verification,
5652                    Some(receipt.block_number),
5653                    Some(receipt.block_number),
5654                ),
5655                verification_decision(
5656                    &inclusion_verification,
5657                    Some(receipt.block_number),
5658                    Some(receipt.block_number),
5659                ),
5660            ];
5661            decisions.extend(
5662                verify_finalized_transaction_identity(
5663                    &included,
5664                    intent,
5665                    nonce,
5666                    raw_transaction,
5667                    &self.verification,
5668                    self.wallet_address,
5669                    self.chain.chain_id,
5670                    &self
5671                        .config
5672                        .verification
5673                        .as_ref()
5674                        .expect("verification config validated")
5675                        .deployment_manifest,
5676                    trace_purpose,
5677                )
5678                .await?,
5679            );
5680            let terminal_status = if receipt.status {
5681                TransactionStatus::Finalized
5682            } else {
5683                TransactionStatus::Reverted
5684            };
5685
5686            if !intent.active {
5687                anyhow::ensure!(
5688                    intent.status == terminal_status.as_str(),
5689                    "Released terminal intent status conflicts with its verified receipt"
5690                );
5691            }
5692            records.push(ExecutionVerificationMigrationRecord {
5693                intent_id: intent.id,
5694                nonce: Some(nonce),
5695                transaction_hash: Some(current.transaction_hash.clone()),
5696                terminal_status: Some(terminal_status),
5697                block_number: Some(receipt.block_number),
5698                block_hash: Some(receipt.block_hash.to_string()),
5699                receipt_success: Some(receipt.status),
5700                gas_used: Some(receipt.gas_used),
5701                effective_gas_price: Some(receipt.effective_gas_price.to_string()),
5702                recover_prepared: false,
5703                decisions,
5704            });
5705        }
5706
5707        Ok(ExecutionVerificationMigration { snapshot, records })
5708    }
5709}
5710
5711#[async_trait(?Send)]
5712impl ExecutionClient for BlockchainExecutionClient {
5713    fn is_connected(&self) -> bool {
5714        self.core.is_connected()
5715    }
5716
5717    fn client_id(&self) -> ClientId {
5718        self.core.client_id
5719    }
5720
5721    fn account_id(&self) -> AccountId {
5722        self.core.account_id
5723    }
5724
5725    fn venue(&self) -> Venue {
5726        self.core.venue
5727    }
5728
5729    fn handles_order_venue(&self, venue: Venue) -> bool {
5730        venue.parse_dex().is_ok_and(|(blockchain, dex_type)| {
5731            blockchain == self.chain.name && dex_type == DexType::UniswapV3
5732        })
5733    }
5734
5735    fn oms_type(&self) -> OmsType {
5736        self.core.oms_type
5737    }
5738
5739    fn get_account(&self) -> Option<AccountAny> {
5740        self.core.cache().account_owned(&self.core.account_id)
5741    }
5742
5743    fn generate_account_state(
5744        &self,
5745        balances: Vec<AccountBalance>,
5746        margins: Vec<MarginBalance>,
5747        reported: bool,
5748        ts_event: UnixNanos,
5749        info: Option<Params>,
5750    ) -> anyhow::Result<()> {
5751        self.emitter
5752            .try_emit_account_state(balances, margins, reported, ts_event, info)
5753    }
5754
5755    fn start(&mut self) -> anyhow::Result<()> {
5756        if self.core.is_started() {
5757            return Ok(());
5758        }
5759
5760        self.emitter.set_sender(get_exec_event_sender());
5761        self.core.set_started();
5762        log::info!(
5763            "Started: client_id={}, account_id={}",
5764            self.core.client_id,
5765            self.core.account_id
5766        );
5767        Ok(())
5768    }
5769
5770    fn stop(&mut self) -> anyhow::Result<()> {
5771        if self.core.is_stopped() {
5772            return Ok(());
5773        }
5774
5775        self.pending_tasks.begin_shutdown();
5776        self.signer = None;
5777        self.core.set_stopped();
5778        self.core.set_disconnected();
5779        log::info!("Stopped: client_id={}", self.core.client_id);
5780        Ok(())
5781    }
5782
5783    #[allow(
5784        clippy::large_futures,
5785        reason = "keeps transaction verification futures inline without additional boxing"
5786    )]
5787    fn submit_order(&self, cmd: SubmitOrder) -> anyhow::Result<()> {
5788        let order = self.core.cache().try_order_owned(&cmd.client_order_id)?;
5789
5790        if order.is_closed() {
5791            log::warn!("Cannot submit closed order {}", order.client_order_id());
5792            return Ok(());
5793        }
5794
5795        if let Err(reason) = validate_order(&order) {
5796            self.emitter.emit_order_denied(&order, &reason.to_string());
5797            return Ok(());
5798        }
5799
5800        if !self.pending_tasks.is_open() {
5801            self.emitter
5802                .emit_order_denied(&order, "Blockchain execution client is shutting down");
5803            return Ok(());
5804        }
5805
5806        let plan = match self.prepare_swap(&cmd, &order) {
5807            Ok(plan) => plan,
5808            Err(e) => {
5809                self.emitter.emit_order_denied(&order, &e.to_string());
5810                return Ok(());
5811            }
5812        };
5813
5814        let executor = match self.transaction_executor() {
5815            Ok(executor) => executor,
5816            Err(e) => {
5817                self.emitter.emit_order_denied(&order, &e.to_string());
5818                return Ok(());
5819            }
5820        };
5821
5822        let emitter = self.emitter.clone();
5823        let max_quote_age_blocks = self.transaction_limits.max_quote_age_blocks;
5824        let deadline_seconds = self.transaction_limits.deadline_seconds;
5825        let client_order_id = order.client_order_id();
5826
5827        let future = async move {
5828            if let Err(e) = execute_swap(
5829                plan,
5830                executor,
5831                emitter,
5832                max_quote_age_blocks,
5833                deadline_seconds,
5834            )
5835            .await
5836            {
5837                log::warn!("Swap execution for order {client_order_id} failed: {e:?}");
5838            }
5839        };
5840
5841        if let Err(e) = self.pending_tasks.spawn(future) {
5842            release_preparing_slot(&self.in_flight);
5843            log::warn!("Skipping blockchain swap after shutdown began: {e}");
5844        }
5845
5846        Ok(())
5847    }
5848
5849    fn submit_order_list(&self, cmd: SubmitOrderList) -> anyhow::Result<()> {
5850        let orders = self
5851            .core
5852            .cache()
5853            .orders_for_ids(&cmd.order_list.client_order_ids, &cmd);
5854
5855        for order in &orders {
5856            if order.is_closed() {
5857                log::warn!("Cannot submit closed order {}", order.client_order_id());
5858                continue;
5859            }
5860
5861            self.emitter
5862                .emit_order_denied(order, ORDER_LIST_UNSUPPORTED);
5863        }
5864
5865        Ok(())
5866    }
5867
5868    fn modify_order(&self, cmd: ModifyOrder) -> anyhow::Result<()> {
5869        let ts_event = get_atomic_clock_realtime().get_time_ns();
5870
5871        if let Ok(order) = self.core.get_order(&cmd.client_order_id) {
5872            self.emitter.emit_order_modify_denied(
5873                &order,
5874                ORDER_MODIFY_UNSUPPORTED,
5875                ts_event,
5876                Some(cmd.command_id),
5877            );
5878        } else {
5879            self.emitter.emit_order_modify_denied_event(
5880                cmd.strategy_id,
5881                cmd.instrument_id,
5882                cmd.client_order_id,
5883                cmd.venue_order_id,
5884                ORDER_MODIFY_UNSUPPORTED,
5885                ts_event,
5886                Some(cmd.command_id),
5887            );
5888        }
5889
5890        Ok(())
5891    }
5892
5893    fn cancel_order(&self, cmd: CancelOrder) -> anyhow::Result<()> {
5894        let ts_event = get_atomic_clock_realtime().get_time_ns();
5895
5896        if let Ok(order) = self.core.get_order(&cmd.client_order_id) {
5897            self.emitter.emit_order_cancel_denied(
5898                &order,
5899                ORDER_CANCEL_UNSUPPORTED,
5900                ts_event,
5901                Some(cmd.command_id),
5902            );
5903        } else {
5904            self.emitter.emit_order_cancel_denied_event(
5905                cmd.strategy_id,
5906                cmd.instrument_id,
5907                cmd.client_order_id,
5908                cmd.venue_order_id,
5909                ORDER_CANCEL_UNSUPPORTED,
5910                ts_event,
5911                Some(cmd.command_id),
5912            );
5913        }
5914
5915        Ok(())
5916    }
5917
5918    fn cancel_all_orders(&self, cmd: CancelAllOrders) -> anyhow::Result<()> {
5919        log::warn!(
5920            "Cancel-all for {} is not supported on the blockchain execution client",
5921            cmd.instrument_id
5922        );
5923        Ok(())
5924    }
5925
5926    fn batch_cancel_orders(&self, cmd: BatchCancelOrders) -> anyhow::Result<()> {
5927        for cancel in cmd.cancels {
5928            self.cancel_order(cancel)?;
5929        }
5930        Ok(())
5931    }
5932
5933    fn query_account(&self, cmd: QueryAccount) -> anyhow::Result<()> {
5934        anyhow::ensure!(
5935            cmd.account_id == self.core.account_id,
5936            "Query account ID {} does not match client account ID {}",
5937            cmd.account_id,
5938            self.core.account_id
5939        );
5940        anyhow::ensure!(self.core.is_started(), "Execution client is not started");
5941
5942        let balances = self.wallet_balance.lock().as_account_balances()?;
5943        self.generate_account_state(
5944            balances,
5945            vec![],
5946            true,
5947            get_atomic_clock_realtime().get_time_ns(),
5948            None,
5949        )
5950    }
5951
5952    fn query_order(&self, cmd: QueryOrder) -> anyhow::Result<()> {
5953        log::debug!(
5954            "Order queries are not supported on the blockchain execution client; cannot query {}",
5955            cmd.client_order_id
5956        );
5957        Ok(())
5958    }
5959
5960    fn retain_unresolved_submissions(&self) -> bool {
5961        true
5962    }
5963
5964    #[allow(
5965        clippy::large_futures,
5966        reason = "keeps transaction verification futures inline without additional boxing"
5967    )]
5968    async fn connect(&mut self) -> anyhow::Result<()> {
5969        if self.core.is_connected() {
5970            log::warn!("Blockchain execution client already connected");
5971            return Ok(());
5972        }
5973
5974        log::info!(
5975            "Connecting to blockchain execution client on chain {}",
5976            self.chain.name
5977        );
5978
5979        if !self.pending_tasks.is_open() || !self.pending_tasks.is_empty() {
5980            self.pending_tasks.begin_shutdown();
5981            self.pending_tasks
5982                .finish_shutdown(Duration::from_secs(5), Duration::from_secs(2))
5983                .await
5984                .map_err(|e| anyhow::anyhow!("Failed to terminate blockchain submissions: {e}"))?;
5985            self.signer = None;
5986            self.pending_tasks
5987                .start_generation()
5988                .map_err(|e| anyhow::anyhow!("Failed to start blockchain task generation: {e}"))?;
5989        }
5990        release_preparing_slot(&self.in_flight);
5991
5992        let setup_guard = TaskGroupGuard::new(&[&self.pending_tasks], || {});
5993
5994        let payload_keys = PayloadKeySet::load(
5995            self.config.payload_key_env.as_deref(),
5996            &self.config.payload_key_retired_env,
5997            self.config.payload_deployment_id.as_deref(),
5998        )?
5999        .map(Arc::new);
6000
6001        if self.cache.database.is_some() || self.config.postgres_cache_database_config.is_some() {
6002            let keys = payload_keys.as_deref().ok_or_else(|| {
6003                anyhow::anyhow!(
6004                    "Postgres execution requires an active payload key and deployment identity"
6005                )
6006            })?;
6007
6008            if self.cache.database.is_none() {
6009                let pg_options = self
6010                    .config
6011                    .postgres_cache_database_config
6012                    .as_ref()
6013                    .expect("Postgres configuration checked above");
6014                let database = crate::cache::database::BlockchainCacheDatabase::connect(
6015                    pg_options.clone().into(),
6016                )
6017                .await
6018                .map_err(|e| {
6019                    anyhow::anyhow!("Failed to connect to the Postgres cache database: {e}")
6020                })?;
6021                self.cache.database = Some(database);
6022            }
6023            self.cache
6024                .database
6025                .as_ref()
6026                .expect("database was attached")
6027                .require_execution_payload_storage_ready(keys)
6028                .await?;
6029            self.cache.initialize_chain().await;
6030            self.cache.ensure_execution_transaction_schema().await?;
6031            let check = self
6032                .cache
6033                .database
6034                .as_ref()
6035                .expect("database was attached")
6036                .check_execution_payload_storage(
6037                    Some(keys),
6038                    Some(PayloadPolicy {
6039                        chain_id: self.chain.chain_id,
6040                        signer: self.wallet_address,
6041                        gas_limit: self.config.gas_limit,
6042                        max_fee_per_gas: self.config.max_fee_per_gas_wei,
6043                    }),
6044                    100,
6045                )
6046                .await?;
6047            anyhow::ensure!(
6048                check.protected,
6049                "Postgres execution requires protected payload storage"
6050            );
6051        } else {
6052            log::warn!(
6053                "No Postgres cache database configured; transactions will be refused (no durable store)"
6054            );
6055        }
6056        self.payload_keys = payload_keys;
6057
6058        let verification = self
6059            .config
6060            .verification
6061            .as_ref()
6062            .expect("verification config validated at construction");
6063        let position = if let Some(database) = self.cache.database.as_ref() {
6064            database
6065                .load_execution_verification_position(
6066                    self.chain.chain_id,
6067                    &self.config.wallet_address,
6068                    &verification.manifest_version,
6069                    &verification.manifest_digest,
6070                )
6071                .await?
6072        } else {
6073            None
6074        };
6075        let migration_snapshot = if position.is_none() {
6076            if let Some(database) = self.cache.database.as_ref() {
6077                let snapshot = database
6078                    .load_execution_verification_migration_snapshot(
6079                        self.chain.chain_id,
6080                        &self.config.wallet_address,
6081                    )
6082                    .await?;
6083
6084                if snapshot.intents.is_empty() {
6085                    None
6086                } else {
6087                    Some(snapshot)
6088                }
6089            } else {
6090                None
6091            }
6092        } else {
6093            None
6094        };
6095
6096        let chain_id_verification = required_verification(
6097            self.verification.verify_chain_id().await,
6098            "Blockchain chain ID",
6099        )?;
6100        let checkpoint_verification = required_verification(
6101            self.verification.verify_checkpoint().await,
6102            "Blockchain checkpoint",
6103        )?;
6104        let checkpoint = checkpoint_verification.value;
6105        let finalized_verification = required_verification(
6106            self.verification.verify_finalized_header().await,
6107            "Blockchain finalized header",
6108        )?;
6109        let finalized = finalized_verification.value;
6110        let mut connect_decisions = vec![
6111            verification_decision(&chain_id_verification, None, None),
6112            verification_decision(
6113                &checkpoint_verification,
6114                Some(checkpoint.number),
6115                Some(checkpoint.number),
6116            ),
6117            verification_decision(
6118                &finalized_verification,
6119                Some(finalized.number),
6120                Some(finalized.number),
6121            ),
6122        ];
6123        let mut finalized_headers = if let Some(position) = position.as_ref() {
6124            let durable_tip = parse_verified_header(&position.finalized_tip)?;
6125            anyhow::ensure!(
6126                durable_tip.number >= checkpoint.number,
6127                "Durable finalized header tip precedes the trusted checkpoint"
6128            );
6129            let durable_tip_verification = required_verification(
6130                self.verification.verify_block(durable_tip.number).await,
6131                "Blockchain durable finalized tip",
6132            )?;
6133            anyhow::ensure!(
6134                durable_tip_verification.value == durable_tip,
6135                "Durable finalized header tip conflicts with independent sources"
6136            );
6137            connect_decisions.push(verification_decision(
6138                &durable_tip_verification,
6139                Some(durable_tip.number),
6140                Some(durable_tip.number),
6141            ));
6142            vec![durable_tip]
6143        } else {
6144            vec![checkpoint]
6145        };
6146        let mut ancestry_cursor = *finalized_headers
6147            .last()
6148            .expect("finalized header ledger is nonempty");
6149        anyhow::ensure!(
6150            finalized.number >= ancestry_cursor.number,
6151            "Verified finalized height regressed below the durable finalized header tip"
6152        );
6153
6154        while ancestry_cursor.number < finalized.number {
6155            let end = ancestry_cursor
6156                .number
6157                .saturating_add(4_096)
6158                .min(finalized.number);
6159            let start = ancestry_cursor.number.saturating_add(1);
6160            let headers_verification = required_verification(
6161                self.verification
6162                    .verify_header_window(ancestry_cursor, end)
6163                    .await,
6164                "Blockchain finalized ancestry",
6165            )?;
6166            let headers = &headers_verification.value;
6167            ancestry_cursor = *headers
6168                .last()
6169                .expect("nonempty ancestry window advances the cursor");
6170            finalized_headers.extend(headers.iter().copied());
6171            connect_decisions.push(verification_decision(
6172                &headers_verification,
6173                Some(start),
6174                Some(end),
6175            ));
6176        }
6177        anyhow::ensure!(
6178            ancestry_cursor == finalized,
6179            "Verified finalized header conflicts with its ancestry window"
6180        );
6181        let nonce_verification = required_verification(
6182            self.verification
6183                .verify_transaction_count(&self.wallet_address, finalized.number)
6184                .await,
6185            "Blockchain finalized transaction count",
6186        )?;
6187        let observed_canonical_nonce = nonce_verification.value;
6188        let next_canonical_nonce = position
6189            .as_ref()
6190            .map_or(observed_canonical_nonce, |position| {
6191                position.next_canonical_nonce
6192            });
6193
6194        if let Some(position) = position.as_ref() {
6195            log::debug!(
6196                "Resumed execution verification ledger at nonce revision {} with observed finalized nonce {}",
6197                position.revision,
6198                observed_canonical_nonce,
6199            );
6200        }
6201        connect_decisions.push(verification_decision(
6202            &nonce_verification,
6203            Some(finalized.number),
6204            Some(finalized.number),
6205        ));
6206        let deployment_verification = required_verification(
6207            self.verification
6208                .verify_deployment_manifest(&verification.deployment_manifest, finalized.number)
6209                .await,
6210            "Blockchain deployment manifest",
6211        )?;
6212        connect_decisions.push(verification_decision(
6213            &deployment_verification,
6214            Some(finalized.number),
6215            Some(finalized.number),
6216        ));
6217        connect_decisions.extend(
6218            verify_connect_capabilities(
6219                &self.verification,
6220                &verification.deployment_manifest,
6221                self.wallet_address,
6222                self.weth_address,
6223                finalized.number,
6224            )
6225            .await?,
6226        );
6227        let migration = if let Some(snapshot) = migration_snapshot {
6228            Some(
6229                self.build_execution_verification_migration(
6230                    snapshot,
6231                    finalized,
6232                    &finalized_headers,
6233                    &nonce_verification,
6234                )
6235                .await?,
6236            )
6237        } else {
6238            None
6239        };
6240
6241        if let Some(database) = self.cache.database.as_ref() {
6242            let identities = std::iter::once(&verification.authoritative)
6243                .chain(
6244                    verification
6245                        .verifiers
6246                        .iter()
6247                        .map(|provider| &provider.identity),
6248                )
6249                .collect::<Vec<_>>();
6250            let provider_ids = identities
6251                .iter()
6252                .map(|identity| identity.provider_id.clone())
6253                .collect::<Vec<_>>();
6254            let operator_ids = identities
6255                .iter()
6256                .map(|identity| identity.operator_id.clone())
6257                .collect::<Vec<_>>();
6258            let failure_domain_ids = identities
6259                .iter()
6260                .flat_map(|identity| identity.failure_domain_ids.iter().cloned())
6261                .collect::<Vec<_>>();
6262            let finalized_headers = finalized_headers
6263                .iter()
6264                .map(durable_verified_header)
6265                .collect::<Vec<_>>();
6266            database
6267                .ensure_execution_verification_schema(&ExecutionVerificationBootstrap {
6268                    chain_id: self.chain.chain_id,
6269                    wallet_address: &self.config.wallet_address,
6270                    manifest_version: &verification.manifest_version,
6271                    manifest_digest: &verification.manifest_digest,
6272                    checkpoint_number: checkpoint.number,
6273                    checkpoint_hash: &checkpoint.hash.to_string(),
6274                    checkpoint_parent_hash: &checkpoint.parent_hash.to_string(),
6275                    checkpoint_timestamp: checkpoint.timestamp,
6276                    checkpoint_base_fee_per_gas: checkpoint.base_fee_per_gas,
6277                    finalized_headers: &finalized_headers,
6278                    next_canonical_nonce,
6279                    observed_canonical_nonce,
6280                    provider_ids: &provider_ids,
6281                    operator_ids: &operator_ids,
6282                    failure_domain_ids: &failure_domain_ids,
6283                    decisions: &connect_decisions,
6284                    migration: migration.as_ref(),
6285                })
6286                .await?;
6287        }
6288
6289        let payload_connect_lease = if let (Some(database), Some(keys)) =
6290            (self.cache.database.as_ref(), self.payload_keys.as_deref())
6291        {
6292            Some(
6293                database
6294                    .require_execution_payload_storage(keys, self.payload_policy(), 100)
6295                    .await?,
6296            )
6297        } else {
6298            None
6299        };
6300
6301        // Load the signer key from the configured environment variable; the key is never
6302        // logged, serialized, or stored in configuration
6303        let private_key = Zeroizing::new(
6304            std::env::var(&self.config.signer_private_key_env).map_err(|_| {
6305                anyhow::anyhow!(
6306                    "Signer private key environment variable '{}' is not set",
6307                    self.config.signer_private_key_env
6308                )
6309            })?,
6310        );
6311        let encoded_key = private_key.trim();
6312        let encoded_key = encoded_key.strip_prefix("0x").unwrap_or(encoded_key);
6313        let key_bytes = Zeroizing::new(hex::decode_array::<32>(encoded_key).map_err(|_| {
6314            anyhow::anyhow!(
6315                "Signer private key in '{}' is not a valid hex private key",
6316                self.config.signer_private_key_env
6317            )
6318        })?);
6319        let signer = PrivateKeySigner::from_slice(&key_bytes[..]).map_err(|_| {
6320            anyhow::anyhow!(
6321                "Signer private key in '{}' is not a valid secp256k1 private key",
6322                self.config.signer_private_key_env
6323            )
6324        })?;
6325
6326        if signer.address() != self.wallet_address {
6327            anyhow::bail!(
6328                "Signer address {} derived from '{}' does not match configured wallet address {}",
6329                signer.address(),
6330                self.config.signer_private_key_env,
6331                self.wallet_address
6332            );
6333        }
6334
6335        self.signer = Some(Arc::new(signer));
6336        drop(payload_connect_lease);
6337
6338        if self.cache.has_database()
6339            && let Err(e) = self.reconcile_unresolved_execution().await
6340        {
6341            self.signer = None;
6342            return Err(e);
6343        }
6344
6345        if let Err(e) = self.refresh_wallet_balances().await {
6346            self.signer = None;
6347            return Err(e);
6348        }
6349
6350        self.register_migration_check();
6351        self.core.set_connected();
6352        setup_guard.disarm();
6353        log::info!(
6354            "Blockchain execution client connected on chain {}",
6355            self.chain.name
6356        );
6357        Ok(())
6358    }
6359
6360    async fn disconnect(&mut self) -> anyhow::Result<()> {
6361        self.pending_tasks.begin_shutdown();
6362        let tasks_result = self
6363            .pending_tasks
6364            .finish_shutdown(Duration::from_secs(5), Duration::from_secs(2))
6365            .await;
6366        self.signer = None;
6367        self.core.set_disconnected();
6368        tasks_result
6369            .map_err(|e| anyhow::anyhow!("Failed to terminate blockchain submissions: {e}"))?;
6370        Ok(())
6371    }
6372
6373    async fn generate_order_status_report(
6374        &self,
6375        _cmd: &GenerateOrderStatusReport,
6376    ) -> anyhow::Result<Option<OrderStatusReport>> {
6377        anyhow::bail!("{VENUE_EXECUTION_REPORTS_UNSUPPORTED}");
6378    }
6379
6380    async fn generate_order_status_reports(
6381        &self,
6382        _cmd: &GenerateOrderStatusReports,
6383    ) -> anyhow::Result<Vec<OrderStatusReport>> {
6384        anyhow::bail!("{VENUE_EXECUTION_REPORTS_UNSUPPORTED}");
6385    }
6386
6387    async fn generate_fill_reports(
6388        &self,
6389        _cmd: GenerateFillReports,
6390    ) -> anyhow::Result<Vec<FillReport>> {
6391        anyhow::bail!("{VENUE_EXECUTION_REPORTS_UNSUPPORTED}");
6392    }
6393
6394    async fn generate_position_status_reports(
6395        &self,
6396        _cmd: &GeneratePositionStatusReports,
6397    ) -> anyhow::Result<Vec<PositionStatusReport>> {
6398        anyhow::bail!("{VENUE_EXECUTION_REPORTS_UNSUPPORTED}");
6399    }
6400
6401    async fn generate_mass_status(
6402        &self,
6403        _lookback_mins: Option<u64>,
6404    ) -> anyhow::Result<Option<ExecutionMassStatus>> {
6405        // Venue mass status is unsupported; durable intent reconciliation at connect
6406        // covers restart recovery, and Ok(None) keeps LiveNode startup safe
6407        log::info!(
6408            "Mass status is not supported on the blockchain execution client; skipping venue reconciliation"
6409        );
6410        Ok(None)
6411    }
6412}
6413
6414fn validate_order(order: &impl Order) -> Result<(), OrderDeniedReason> {
6415    if order.is_reduce_only() {
6416        return Err(OrderDeniedReason::UnsupportedReduceOnly);
6417    }
6418
6419    Ok(())
6420}
6421
6422#[cfg(test)]
6423mod tests {
6424    #![allow(
6425        clippy::large_futures,
6426        reason = "exercises inline transaction futures without changing their allocation behavior"
6427    )]
6428
6429    use std::{
6430        cell::RefCell,
6431        rc::Rc,
6432        sync::atomic::{AtomicU64, Ordering},
6433    };
6434
6435    use alloy::{
6436        primitives::{address, aliases::I24},
6437        sol_types::SolValue,
6438    };
6439    use nautilus_common::{
6440        cache::Cache,
6441        clock::{Clock, VirtualClock},
6442        live::runner::replace_exec_event_sender,
6443        messages::{ExecutionEvent, execution::TradingCommand},
6444        testing::wait_until_async,
6445    };
6446    use nautilus_core::UUID4;
6447    use nautilus_infrastructure::sql::pg::{PostgresConnectOptions, get_postgres_connect_options};
6448    use nautilus_live::{
6449        execution::{
6450            config::ExecutionManagerConfig,
6451            submission::{SubmissionRecoveryExhausted, SubmissionRecoverySource},
6452        },
6453        manager::ExecutionManager,
6454    };
6455    use nautilus_model::{
6456        defi::{
6457            PoolProfiler,
6458            chain::chains,
6459            data::block::BlockPosition,
6460            pool_analysis::{
6461                position::PoolPosition,
6462                snapshot::{PoolAnalytics, PoolSnapshot, PoolState},
6463            },
6464            tick_map::{tick::PoolTick, tick_math::get_tick_at_sqrt_ratio},
6465        },
6466        enums::{AccountType, CurrencyType},
6467        events::{OrderEventAny, OrderPendingCancel, OrderPendingUpdate},
6468        identifiers::{OrderListId, StrategyId, TraderId},
6469        orders::{OrderList, OrderTestBuilder, stubs::TestOrderEventStubs},
6470        types::Price,
6471    };
6472    use rstest::rstest;
6473    use sqlx::postgres::{PgAdvisoryLock, PgAdvisoryLockKey, PgPoolOptions};
6474    use ustr::Ustr;
6475
6476    use super::*;
6477    use crate::{
6478        cache::database::tests::connect_test_database,
6479        config::{
6480            BlockchainCallEdgeManifest, BlockchainChainAnchorConfig, BlockchainContractManifest,
6481            BlockchainContractProbe, BlockchainContractRole, BlockchainDeploymentManifest,
6482            BlockchainPoolManifest, BlockchainProviderIdentity, BlockchainTokenManifest,
6483            BlockchainVerificationConfig, BlockchainVerificationProviderConfig, QuoteSpendLimit,
6484        },
6485        constants::BLOCKCHAIN_VENUE,
6486        exchanges::arbitrum::UNISWAP_V3,
6487        rpc::http::{
6488            EXECUTION_RPC_TIMEOUT_SECS,
6489            tests::mock::{MockRpcState, start_mock_rpc_server},
6490        },
6491    };
6492
6493    /// Polls for the receipt of a broadcast transaction until it exists or the poll bound
6494    /// is exhausted. A `null` receipt result is a legitimate pending response.
6495    async fn poll_for_receipt(
6496        http_rpc_client: &BlockchainHttpRpcClient,
6497        tx_hash: &B256,
6498        max_polls: u32,
6499        interval: Duration,
6500    ) -> anyhow::Result<Option<RpcTransactionReceipt>> {
6501        let mut last_error = None;
6502        let mut observed_pending = false;
6503
6504        for attempt in 0..max_polls {
6505            if attempt > 0 {
6506                tokio::time::sleep(interval).await;
6507            }
6508
6509            match http_rpc_client.get_transaction_receipt(tx_hash).await {
6510                Ok(Some(receipt)) => return Ok(Some(receipt)),
6511                Ok(None) => observed_pending = true,
6512                Err(e) => {
6513                    log::warn!(
6514                        "Receipt poll {}/{} for transaction {tx_hash} failed: {e}",
6515                        attempt + 1,
6516                        max_polls
6517                    );
6518                    last_error = Some(e);
6519                }
6520            }
6521        }
6522
6523        if !observed_pending && let Some(e) = last_error {
6524            return Err(e);
6525        }
6526
6527        Ok(None)
6528    }
6529
6530    const CHAIN_ID_ARBITRUM: &str =
6531        include_str!("../../test_data/execution/rpc_eth_chain_id_arbitrum.json");
6532    const CHAIN_ID_ETHEREUM: &str =
6533        include_str!("../../test_data/execution/rpc_eth_chain_id_ethereum.json");
6534    const GET_CODE_DEPLOYED: &str =
6535        include_str!("../../test_data/execution/rpc_eth_get_code_deployed.json");
6536    const GET_CODE_EMPTY: &str =
6537        include_str!("../../test_data/execution/rpc_eth_get_code_empty.json");
6538    const GET_BALANCE: &str = include_str!("../../test_data/execution/rpc_eth_get_balance.json");
6539    const GET_BALANCE_ZERO: &str =
6540        include_str!("../../test_data/execution/rpc_eth_get_balance_zero.json");
6541    const GET_BALANCE_INSUFFICIENT: &str =
6542        include_str!("../../test_data/execution/rpc_eth_get_balance_insufficient.json");
6543    const CALL_BALANCE: &str = include_str!("../../test_data/execution/rpc_eth_call_balance.json");
6544    const CALL_BALANCE_AFTER_WRAP: &str =
6545        include_str!("../../test_data/execution/rpc_eth_call_balance_after_wrap.json");
6546    const CALL_BALANCE_WETH: &str =
6547        include_str!("../../test_data/execution/rpc_eth_call_balance_weth.json");
6548    const CALL_BALANCE_USDC: &str =
6549        include_str!("../../test_data/execution/rpc_eth_call_balance_usdc.json");
6550    const CALL_BALANCE_WETH_UPDATED: &str =
6551        include_str!("../../test_data/execution/rpc_eth_call_balance_weth_updated.json");
6552    const CALL_BALANCE_USDC_UPDATED: &str =
6553        include_str!("../../test_data/execution/rpc_eth_call_balance_usdc_updated.json");
6554    const CALL_BOOL_TRUE: &str =
6555        include_str!("../../test_data/execution/rpc_eth_call_bool_true.json");
6556    const CALL_EMPTY: &str = include_str!("../../test_data/execution/rpc_eth_call_empty.json");
6557    const CALL_ZERO: &str = include_str!("../../test_data/execution/rpc_eth_call_zero.json");
6558    const CALL_ALLOWANCE: &str =
6559        include_str!("../../test_data/execution/rpc_eth_call_allowance.json");
6560    const CALL_ALLOWANCE_1000: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x00000000000000000000000000000000000000000000000000000000000003e8\"}";
6561    const CALL_ALLOWANCE_MAX: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"}";
6562    const CALL_FACTORY: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f984\"}";
6563    const CALL_WETH: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1\"}";
6564    const CALL_USDC: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x000000000000000000000000af88d065e77c8cc2239327c5edb3a432268e5831\"}";
6565    const CALL_FEE_500: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x00000000000000000000000000000000000000000000000000000000000001f4\"}";
6566    const CALL_POOL: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x000000000000000000000000c6962004f452be9203591991d15f6b388e09e8d0\"}";
6567    const CALL_REVERTED: &str =
6568        r#"{"jsonrpc":"2.0","id":1,"error":{"code":3,"message":"execution reverted"}}"#;
6569    const STORAGE_ZERO: &str = r#"{"jsonrpc":"2.0","id":1,"result":"0x0000000000000000000000000000000000000000000000000000000000000000"}"#;
6570    const TRACE_UNKNOWN_TRANSACTION: &str =
6571        r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"transaction not found"}}"#;
6572    const CALL_DECIMALS_18: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x0000000000000000000000000000000000000000000000000000000000000012\"}";
6573    const CALL_DECIMALS_6: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x0000000000000000000000000000000000000000000000000000000000000006\"}";
6574    const TRANSACTION_COUNT: &str =
6575        include_str!("../../test_data/execution/rpc_eth_get_transaction_count.json");
6576    const TRANSACTION_COUNT_NEXT: &str =
6577        include_str!("../../test_data/execution/rpc_eth_get_transaction_count_next.json");
6578    const ESTIMATE_GAS: &str = include_str!("../../test_data/execution/rpc_eth_estimate_gas.json");
6579    const MAX_PRIORITY_FEE: &str =
6580        include_str!("../../test_data/execution/rpc_eth_max_priority_fee_per_gas.json");
6581    const BLOCK_BY_NUMBER: &str =
6582        include_str!("../../test_data/execution/rpc_eth_get_block_by_number.json");
6583    const BLOCK_CANONICAL: &str =
6584        include_str!("../../test_data/execution/rpc_eth_get_block_canonical.json");
6585    const BLOCK_FINALIZED: &str =
6586        include_str!("../../test_data/execution/rpc_eth_get_block_finalized.json");
6587    const RECEIPT_SUCCESS: &str =
6588        include_str!("../../test_data/execution/rpc_eth_get_transaction_receipt_success.json");
6589    const RECEIPT_REVERTED: &str =
6590        include_str!("../../test_data/execution/rpc_eth_get_transaction_receipt_reverted.json");
6591    const RECEIPT_NULL: &str =
6592        include_str!("../../test_data/execution/rpc_eth_get_transaction_receipt_null.json");
6593    const SEND_RAW_TRANSACTION: &str =
6594        include_str!("../../test_data/execution/rpc_eth_send_raw_transaction.json");
6595    const SEND_RAW_TRANSACTION_REJECTED: &str =
6596        include_str!("../../test_data/execution/rpc_eth_send_raw_transaction_rejected.json");
6597    const SEND_RAW_TRANSACTION_NONCE_TOO_LOW: &str =
6598        include_str!("../../test_data/execution/rpc_eth_send_raw_transaction_nonce_too_low.json");
6599    const RPC_METHOD_NOT_FOUND: &str =
6600        include_str!("../../test_data/execution/rpc_error_method_not_found.json");
6601
6602    const WALLET: &str = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266";
6603    const ROUTER: &str = "0xE592427A0AEce92De3Edee1F18E0157C05861564";
6604    const WETH: &str = "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1";
6605    const USDC: &str = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831";
6606    const TEST_TIMEOUT: Duration = Duration::from_secs(10);
6607
6608    const WETH_ADDRESS: Address = address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1");
6609    const USDC_ADDRESS: Address = address!("af88d065e77c8cC2239327C5EDb3A432268e5831");
6610    const ROUTER_ADDRESS: Address = address!("E592427A0AEce92De3Edee1F18E0157C05861564");
6611
6612    // Anvil development key for WALLET (public, test-only)
6613    const TEST_PRIVATE_KEY: &str =
6614        "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
6615
6616    const BALANCE_OF_SELECTOR: &str = "0x70a08231";
6617    const ALLOWANCE_SELECTOR: &str = "0xdd62ed3e";
6618    const POOL_TOKEN0_SELECTOR: &str = "0x0dfe1681";
6619    const POOL_TOKEN1_SELECTOR: &str = "0xd21220a7";
6620    const POOL_FEE_SELECTOR: &str = "0xddca3f43";
6621    const DECIMALS_SELECTOR: &str = "0x313ce567";
6622    const FACTORY_SELECTOR: &str = "0xc45a0155";
6623    const WETH9_SELECTOR: &str = "0x4aa4a4fc";
6624    const GET_POOL_SELECTOR: &str = "0x1698ee82";
6625    const QUOTE_EXACT_INPUT_SELECTOR: &str = "0xc6a5026a";
6626    const QUOTE_EXACT_OUTPUT_SELECTOR: &str = "0xbd21704a";
6627
6628    fn test_pool() -> Pool {
6629        let chain = Arc::new(chains::ARBITRUM.clone());
6630        let dex = Arc::clone(&UNISWAP_V3.dex);
6631        let weth = Token::new(
6632            Arc::clone(&chain),
6633            address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
6634            "Wrapped Ether".to_string(),
6635            "WETH".to_string(),
6636            18,
6637        );
6638        let usdc = Token::new(
6639            Arc::clone(&chain),
6640            address!("af88d065e77c8cC2239327C5EDb3A432268e5831"),
6641            "USD Coin".to_string(),
6642            "USDC".to_string(),
6643            6,
6644        );
6645
6646        Pool::new(
6647            chain,
6648            dex,
6649            address!("C6962004f452bE9203591991D15f6b388e09E8D0"),
6650            PoolIdentifier::from_address(address!("C6962004f452bE9203591991D15f6b388e09E8D0")),
6651            55_000_000,
6652            weth,
6653            usdc,
6654            Some(500),
6655            Some(10),
6656            UnixNanos::default(),
6657        )
6658    }
6659
6660    fn test_config(http_rpc_url: String) -> BlockchainExecutionClientConfig {
6661        test_config_with_signer_env(http_rpc_url, "BLOCKCHAIN_TEST_PRIVATE_KEY")
6662    }
6663
6664    fn test_config_with_signer_env(
6665        http_rpc_url: String,
6666        signer_env: &str,
6667    ) -> BlockchainExecutionClientConfig {
6668        let verifier_separator = if http_rpc_url.contains('?') { '&' } else { '?' };
6669        let code_hash = keccak256(
6670            hex::decode("6080604052348015600e575f5ffd5b5060").expect("valid test bytecode"),
6671        )
6672        .to_string();
6673        let result = |response: &str| {
6674            serde_json::from_str::<serde_json::Value>(response).unwrap()["result"]
6675                .as_str()
6676                .unwrap()
6677                .to_string()
6678        };
6679        let probe = |call_data: &str, expected_output: String| BlockchainContractProbe {
6680            call_data: call_data.to_string(),
6681            expected_output,
6682        };
6683        let contract = |address: &str, role| {
6684            let probes = match role {
6685                BlockchainContractRole::Router => vec![
6686                    probe(FACTORY_SELECTOR, result(CALL_FACTORY)),
6687                    probe(WETH9_SELECTOR, result(CALL_WETH)),
6688                ],
6689                BlockchainContractRole::Factory => vec![probe(
6690                    &hex::encode_prefixed(
6691                        UniswapV3Factory::getPoolCall {
6692                            tokenA: WETH_ADDRESS,
6693                            tokenB: USDC_ADDRESS,
6694                            fee: U24::try_from(500u32).unwrap(),
6695                        }
6696                        .abi_encode(),
6697                    ),
6698                    result(CALL_POOL),
6699                )],
6700                BlockchainContractRole::WrappedNative => {
6701                    vec![probe(DECIMALS_SELECTOR, result(CALL_DECIMALS_18))]
6702                }
6703                BlockchainContractRole::Quote => {
6704                    vec![probe(FACTORY_SELECTOR, result(CALL_FACTORY))]
6705                }
6706                BlockchainContractRole::Token => {
6707                    vec![probe(DECIMALS_SELECTOR, result(CALL_DECIMALS_6))]
6708                }
6709                BlockchainContractRole::Pool => vec![
6710                    probe(POOL_TOKEN0_SELECTOR, result(CALL_WETH)),
6711                    probe(POOL_TOKEN1_SELECTOR, result(CALL_USDC)),
6712                    probe(POOL_FEE_SELECTOR, result(CALL_FEE_500)),
6713                ],
6714                BlockchainContractRole::Implementation => Vec::new(),
6715            };
6716            BlockchainContractManifest {
6717                address: address.to_string(),
6718                role,
6719                runtime_code_hash: code_hash.clone(),
6720                proxy: None,
6721                probes,
6722            }
6723        };
6724        let deployment_manifest = BlockchainDeploymentManifest {
6725            version: "test-v1".to_string(),
6726            chain_id: chains::ARBITRUM.chain_id,
6727            chain_name: chains::ARBITRUM.name.to_string(),
6728            contracts: vec![
6729                contract(ROUTER, BlockchainContractRole::Router),
6730                contract(
6731                    "0x1F98431c8aD98523631AE4a59f267346ea31F984",
6732                    BlockchainContractRole::Factory,
6733                ),
6734                contract(WETH, BlockchainContractRole::WrappedNative),
6735                contract(
6736                    "0x61fFE014bA17989E743c5F6cB21bF9697530B21e",
6737                    BlockchainContractRole::Quote,
6738                ),
6739                contract(USDC, BlockchainContractRole::Token),
6740                contract(
6741                    "0xC6962004f452bE9203591991D15f6b388e09E8D0",
6742                    BlockchainContractRole::Pool,
6743                ),
6744            ],
6745            tokens: vec![
6746                BlockchainTokenManifest {
6747                    address: WETH.to_string(),
6748                    name: "Wrapped Ether".to_string(),
6749                    symbol: "WETH".to_string(),
6750                    decimals: 18,
6751                    asset_role: "both".to_string(),
6752                },
6753                BlockchainTokenManifest {
6754                    address: USDC.to_string(),
6755                    name: "USD Coin".to_string(),
6756                    symbol: "USDC".to_string(),
6757                    decimals: 6,
6758                    asset_role: "both".to_string(),
6759                },
6760            ],
6761            pools: vec![BlockchainPoolManifest {
6762                address: "0xC6962004f452bE9203591991D15f6b388e09E8D0".to_string(),
6763                token0: WETH.to_string(),
6764                token1: USDC.to_string(),
6765                fee: 500,
6766                factory: "0x1F98431c8aD98523631AE4a59f267346ea31F984".to_string(),
6767                quote_contract: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e".to_string(),
6768            }],
6769            call_edges: ["swap_sell", "swap_buy"]
6770                .into_iter()
6771                .map(|purpose| BlockchainCallEdgeManifest {
6772                    purpose: purpose.to_string(),
6773                    caller: ROUTER.to_string(),
6774                    target: "0xC6962004f452bE9203591991D15f6b388e09E8D0".to_string(),
6775                    call_type: "call".to_string(),
6776                })
6777                .collect(),
6778        };
6779        let manifest_digest =
6780            keccak256(serde_json::to_vec(&deployment_manifest).unwrap()).to_string();
6781        let verification = BlockchainVerificationConfig {
6782            authoritative: BlockchainProviderIdentity {
6783                provider_id: "authoritative".to_string(),
6784                operator_id: "operator-a".to_string(),
6785                failure_domain_ids: vec!["domain-a".to_string()],
6786            },
6787            verifiers: vec![
6788                BlockchainVerificationProviderConfig {
6789                    identity: BlockchainProviderIdentity {
6790                        provider_id: "verifier-a".to_string(),
6791                        operator_id: "operator-b".to_string(),
6792                        failure_domain_ids: vec!["domain-b".to_string()],
6793                    },
6794                    http_rpc_url: format!("{http_rpc_url}{verifier_separator}source=verifier-a")
6795                        .into(),
6796                },
6797                BlockchainVerificationProviderConfig {
6798                    identity: BlockchainProviderIdentity {
6799                        provider_id: "verifier-b".to_string(),
6800                        operator_id: "operator-c".to_string(),
6801                        failure_domain_ids: vec!["domain-c".to_string()],
6802                    },
6803                    http_rpc_url: format!("{http_rpc_url}{verifier_separator}source=verifier-b")
6804                        .into(),
6805                },
6806            ],
6807            chain_anchor: BlockchainChainAnchorConfig {
6808                chain_id: chains::ARBITRUM.chain_id,
6809                chain_name: chains::ARBITRUM.name.to_string(),
6810                checkpoint_height: 30_346_560,
6811                checkpoint_hash:
6812                    "0x1111111111111111111111111111111111111111111111111111111111111111".to_string(),
6813                checkpoint_timestamp: 1_761_888_800,
6814                max_head_skew_blocks: 3,
6815                max_head_age_secs: u64::MAX,
6816                max_future_drift_secs: u64::MAX,
6817            },
6818            manifest_version: "test-v1".to_string(),
6819            manifest_digest,
6820            deployment_manifest,
6821        };
6822        BlockchainExecutionClientConfig::builder()
6823            .client_id(AccountId::from("BLOCKCHAIN-001"))
6824            .chain(chains::ARBITRUM.clone())
6825            .wallet_address(WALLET.to_string())
6826            .http_rpc_url(http_rpc_url.into())
6827            .verification(verification)
6828            .signer_private_key_env(signer_env.to_string())
6829            .router_addresses(vec![ROUTER.to_string()])
6830            .weth_address(WETH.to_string())
6831            .max_fee_per_gas_wei(1_000_000_000)
6832            .base_fee_buffer_bps(2_000)
6833            .gas_limit(1_000_000)
6834            .gas_buffer_bps(2_000)
6835            .allowed_token_pairs(vec![(WETH.to_string(), USDC.to_string())])
6836            .slippage_bps(50)
6837            .max_slippage_bps(200)
6838            .max_order_amount(1_000_000_000_000_000_000)
6839            .deadline_seconds(300)
6840            .max_quote_age_blocks(100)
6841            .receipt_timeout_secs(1)
6842            .build()
6843    }
6844
6845    fn buy_test_config(http_rpc_url: String) -> BlockchainExecutionClientConfig {
6846        let max_amount = expected_buy_amount_in().to_string();
6847        let mut config = test_config(http_rpc_url);
6848        config.allowed_token_pairs = Some(vec![
6849            (WETH.to_string(), USDC.to_string()),
6850            (USDC.to_string(), WETH.to_string()),
6851        ]);
6852        config.quote_spend_limits = Some(vec![quote_spend_limit(USDC, WETH, 6, &max_amount)]);
6853        config
6854    }
6855
6856    fn refresh_test_manifest_digest(config: &mut BlockchainExecutionClientConfig) {
6857        let verification = config.verification.as_mut().unwrap();
6858        verification.manifest_digest =
6859            keccak256(serde_json::to_vec(&verification.deployment_manifest).unwrap()).to_string();
6860    }
6861
6862    fn quote_spend_limit(
6863        token_in: &str,
6864        token_out: &str,
6865        spend_token_decimals: u8,
6866        max_amount: &str,
6867    ) -> QuoteSpendLimit {
6868        QuoteSpendLimit::builder()
6869            .token_in(token_in.to_string())
6870            .token_out(token_out.to_string())
6871            .spend_token(token_in.to_string())
6872            .spend_token_decimals(spend_token_decimals)
6873            .max_amount(max_amount.to_string())
6874            .build()
6875    }
6876
6877    fn test_client_from_config(
6878        config: BlockchainExecutionClientConfig,
6879        pool: Pool,
6880    ) -> BlockchainExecutionClient {
6881        test_client_result(config, pool).unwrap()
6882    }
6883
6884    fn test_client_result(
6885        config: BlockchainExecutionClientConfig,
6886        pool: Pool,
6887    ) -> anyhow::Result<BlockchainExecutionClient> {
6888        test_client_and_cache(config, pool).map(|(client, _)| client)
6889    }
6890
6891    fn test_client_and_cache(
6892        config: BlockchainExecutionClientConfig,
6893        pool: Pool,
6894    ) -> anyhow::Result<(BlockchainExecutionClient, Rc<RefCell<Cache>>)> {
6895        let cache = Rc::new(RefCell::new(Cache::default()));
6896        cache.borrow_mut().add_pool(pool).unwrap();
6897        let core = ExecutionClientCore::new(
6898            TraderId::from("TRADER-001"),
6899            ClientId::from("BLOCKCHAIN-001"),
6900            *BLOCKCHAIN_VENUE,
6901            OmsType::Netting,
6902            AccountId::from("BLOCKCHAIN-001"),
6903            AccountType::Wallet,
6904            None,
6905            Rc::clone(&cache),
6906        );
6907
6908        let client = BlockchainExecutionClient::new(core, config)?;
6909        Ok((client, cache))
6910    }
6911
6912    fn test_client(http_rpc_url: String) -> BlockchainExecutionClient {
6913        test_client_from_config(test_config(http_rpc_url), test_pool())
6914    }
6915
6916    async fn client_with_mock_rpc(
6917        state: MockRpcState,
6918    ) -> (BlockchainExecutionClient, MockRpcState) {
6919        let addr = start_mock_rpc_server(state.clone()).await;
6920        (test_client(format!("http://{addr}")), state)
6921    }
6922
6923    async fn client_with_token_mock_rpc(
6924        state: MockRpcState,
6925        signer_env: &str,
6926    ) -> (BlockchainExecutionClient, MockRpcState, Rc<RefCell<Cache>>) {
6927        let state = with_connect_capabilities(state);
6928        let addr = start_mock_rpc_server(state.clone()).await;
6929        let pool = test_pool();
6930        let tokens = [pool.token0.clone(), pool.token1.clone()];
6931        let mut config = test_config_with_signer_env(format!("http://{addr}"), signer_env);
6932        config.tokens = Some(vec![WETH.to_string(), USDC.to_string()]);
6933        let (mut client, cache) = test_client_and_cache(config, pool).unwrap();
6934        for token in tokens {
6935            client.cache.add_token(token).await.unwrap();
6936        }
6937        (client, state, cache)
6938    }
6939
6940    fn execution_rpc_state() -> MockRpcState {
6941        MockRpcState::default()
6942            .with_receipt_hash_from_request()
6943            .with_response("eth_chainId", CHAIN_ID_ARBITRUM)
6944            .with_response("eth_getCode", GET_CODE_DEPLOYED)
6945            .with_response("eth_getBalance", GET_BALANCE)
6946            .with_response("eth_getBlockByNumber", BLOCK_BY_NUMBER)
6947            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
6948            .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", BLOCK_CANONICAL)
6949            .with_parameter_response("eth_getBlockByNumber", "finalized", BLOCK_FINALIZED)
6950            .with_parameter_response("eth_getBlockByNumber", "0x1cf0d42", BLOCK_FINALIZED)
6951            .with_response("eth_maxPriorityFeePerGas", MAX_PRIORITY_FEE)
6952            .with_call_response(FACTORY_SELECTOR, CALL_FACTORY)
6953            .with_call_response(WETH9_SELECTOR, CALL_WETH)
6954            .with_call_response(GET_POOL_SELECTOR, CALL_POOL)
6955            .with_call_response(POOL_TOKEN0_SELECTOR, CALL_WETH)
6956            .with_call_response(POOL_TOKEN1_SELECTOR, CALL_USDC)
6957            .with_call_response(POOL_FEE_SELECTOR, CALL_FEE_500)
6958            .with_contract_call_response(WETH, DECIMALS_SELECTOR, CALL_DECIMALS_18)
6959            .with_contract_call_response(USDC, DECIMALS_SELECTOR, CALL_DECIMALS_6)
6960            .with_call_response(
6961                QUOTE_EXACT_INPUT_SELECTOR,
6962                &quote_response(expected_sell_quote_amount()),
6963            )
6964            .with_call_response(
6965                QUOTE_EXACT_OUTPUT_SELECTOR,
6966                &quote_response(expected_buy_amount_in()),
6967            )
6968    }
6969
6970    fn ready_rpc_state() -> MockRpcState {
6971        with_connect_capabilities(execution_rpc_state())
6972            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE)
6973            .with_call_response(ALLOWANCE_SELECTOR, CALL_ALLOWANCE)
6974    }
6975
6976    fn with_connect_capabilities(state: MockRpcState) -> MockRpcState {
6977        state
6978            .with_response("eth_getStorageAt", STORAGE_ZERO)
6979            .with_response("eth_estimateGas", ESTIMATE_GAS)
6980            .with_parameter_response(
6981                "debug_traceTransaction",
6982                &B256::ZERO.to_string(),
6983                TRACE_UNKNOWN_TRANSACTION,
6984            )
6985    }
6986
6987    fn signing_rpc_state() -> MockRpcState {
6988        ready_rpc_state()
6989            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
6990            .with_response("eth_estimateGas", ESTIMATE_GAS)
6991    }
6992
6993    fn broadcast_rpc_state() -> MockRpcState {
6994        execution_rpc_state()
6995            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
6996            .with_response("eth_estimateGas", ESTIMATE_GAS)
6997            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS)
6998            .with_send_raw_transaction_echo()
6999            .with_call_response_sequence(ALLOWANCE_SELECTOR, &[CALL_ZERO, CALL_ALLOWANCE_1000])
7000    }
7001
7002    async fn expected_wrap_tx_hash(value: U256) -> B256 {
7003        expected_tx_hash(
7004            WETH_ADDRESS,
7005            value,
7006            Bytes::from(nautilus_core::hex::decode("d0e30db0").unwrap()),
7007        )
7008        .await
7009    }
7010
7011    async fn expected_approve_tx_hash(amount: U256) -> B256 {
7012        let calldata = ERC20::approveCall {
7013            spender: ROUTER_ADDRESS,
7014            amount,
7015        }
7016        .abi_encode();
7017        expected_tx_hash(WETH_ADDRESS, U256::ZERO, Bytes::from(calldata)).await
7018    }
7019
7020    async fn expected_tx_hash(to: Address, value: U256, input: Bytes) -> B256 {
7021        // The orchestration's policy math is deterministic: nonce 7 from the fixture,
7022        // buffered gas 78000, buffered max fee 130000000, priority fee 10000000
7023        let expected_tx =
7024            build_eip1559_transaction(42161, 7, 78_000, 130_000_000, 10_000_000, to, value, input);
7025        let (expected_hash, _) = sign_eip1559_transaction(
7026            expected_tx,
7027            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7028        )
7029        .await
7030        .unwrap();
7031        expected_hash
7032    }
7033
7034    async fn await_recorded_requests(state: &MockRpcState, method: &str, expected: usize) {
7035        wait_until_async(
7036            || async {
7037                state
7038                    .recorded_requests()
7039                    .iter()
7040                    .filter(|request| request["method"] == method)
7041                    .count()
7042                    >= expected
7043            },
7044            TEST_TIMEOUT,
7045        )
7046        .await;
7047    }
7048
7049    /// The block number served by the `eth_getBlockByNumber` fixture; swap quotes pin their
7050    /// profiler state to it so the freshness check passes.
7051    const FIXTURE_BLOCK: u64 = 30_346_560;
7052    const FIXTURE_BLOCK_PARAM: &str = "0x1cf0d40";
7053    const FIXTURE_BLOCK_HASH: &str =
7054        "0x1111111111111111111111111111111111111111111111111111111111111111";
7055    /// The timestamp served by the `eth_getBlockByNumber` fixture.
7056    const FIXTURE_BLOCK_TIMESTAMP: u64 = 1_761_888_800;
7057    /// Synthetic full-range liquidity for the test pool profiler.
7058    const TEST_LIQUIDITY: u128 = 1_000_000_000_000_000_000_000;
7059
7060    fn test_profiler(pool: &Pool, block_number: u64) -> PoolProfiler {
7061        test_profiler_at_block(pool, block_number, FIXTURE_BLOCK_HASH)
7062    }
7063
7064    fn test_profiler_at_block(pool: &Pool, block_number: u64, block_hash: &str) -> PoolProfiler {
7065        test_profiler_with_range(
7066            pool,
7067            block_number,
7068            block_hash,
7069            U160::from(1u128 << 96),
7070            -887_220,
7071            887_220,
7072            TEST_LIQUIDITY,
7073        )
7074    }
7075
7076    fn test_profiler_with_state(
7077        pool: &Pool,
7078        block_number: u64,
7079        sqrt_price_x96: U160,
7080        liquidity: u128,
7081    ) -> PoolProfiler {
7082        test_profiler_with_range(
7083            pool,
7084            block_number,
7085            FIXTURE_BLOCK_HASH,
7086            sqrt_price_x96,
7087            -887_220,
7088            887_220,
7089            liquidity,
7090        )
7091    }
7092
7093    /// Builds a profiler from a synthetic snapshot with a single position over
7094    /// `[tick_lower, tick_upper]`: exact-input quotes within the range match the
7095    /// constant-product curve, and a tiny test swap never crosses a tick.
7096    fn test_profiler_with_range(
7097        pool: &Pool,
7098        block_number: u64,
7099        block_hash: &str,
7100        sqrt_price_x96: U160,
7101        tick_lower: i32,
7102        tick_upper: i32,
7103        liquidity: u128,
7104    ) -> PoolProfiler {
7105        let snapshot = PoolSnapshot::new(
7106            pool.instrument_id,
7107            PoolState {
7108                current_tick: get_tick_at_sqrt_ratio(sqrt_price_x96),
7109                price_sqrt_ratio_x96: sqrt_price_x96,
7110                liquidity,
7111                protocol_fees_token0: U256::ZERO,
7112                protocol_fees_token1: U256::ZERO,
7113                fee_protocol: 0,
7114                fee_protocol0_basis_points: None,
7115                fee_protocol1_basis_points: None,
7116                fee_growth_global_0: U256::ZERO,
7117                fee_growth_global_1: U256::ZERO,
7118            },
7119            vec![PoolPosition::new(
7120                address!("DeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF"),
7121                tick_lower,
7122                tick_upper,
7123                liquidity as i128,
7124            )],
7125            vec![
7126                PoolTick::new(
7127                    tick_lower,
7128                    liquidity,
7129                    liquidity as i128,
7130                    U256::ZERO,
7131                    U256::ZERO,
7132                    true,
7133                    0,
7134                ),
7135                PoolTick::new(
7136                    tick_upper,
7137                    liquidity,
7138                    -(liquidity as i128),
7139                    U256::ZERO,
7140                    U256::ZERO,
7141                    true,
7142                    0,
7143                ),
7144            ],
7145            PoolAnalytics::default(),
7146            BlockPosition::new(
7147                block_number,
7148                block_hash.to_string(),
7149                BLOCK_SCOPED_SNAPSHOT_INDEX,
7150                BLOCK_SCOPED_SNAPSHOT_INDEX,
7151            )
7152            .with_block_hash(Some(block_hash.to_string())),
7153            UnixNanos::default(),
7154            UnixNanos::default(),
7155        );
7156        let mut profiler = PoolProfiler::new(Arc::new(pool.clone()));
7157        profiler.restore_from_snapshot(snapshot).unwrap();
7158        profiler
7159    }
7160
7161    fn test_market_sell_order(instrument_id: InstrumentId) -> OrderAny {
7162        market_sell_order_with_id(instrument_id, "O-SWAP-001")
7163    }
7164
7165    fn test_market_buy_order(instrument_id: InstrumentId) -> OrderAny {
7166        market_buy_order_with_id(instrument_id, "O-SWAP-BUY-001")
7167    }
7168
7169    fn submit_order_cmd(order: &OrderAny) -> SubmitOrder {
7170        SubmitOrder::new(
7171            TraderId::from("TRADER-001"),
7172            Some(ClientId::from("BLOCKCHAIN-001")),
7173            order.strategy_id(),
7174            order.instrument_id(),
7175            order.client_order_id(),
7176            order.init_event().clone(),
7177            None,
7178            None,
7179            None,
7180            UUID4::new(),
7181            UnixNanos::default(),
7182            None,
7183        )
7184    }
7185
7186    /// Builds a client whose shared cache holds the test pool, a live profiler at
7187    /// `FIXTURE_BLOCK`, and a SELL market order, without a durable store.
7188    fn swap_client_with_cache(
7189        config: BlockchainExecutionClientConfig,
7190    ) -> (BlockchainExecutionClient, Rc<RefCell<Cache>>) {
7191        let cache = Rc::new(RefCell::new(Cache::default()));
7192        let pool = test_pool();
7193        cache.borrow_mut().add_pool(pool.clone()).unwrap();
7194        cache
7195            .borrow_mut()
7196            .add_order(
7197                test_market_sell_order(pool.instrument_id),
7198                None,
7199                None,
7200                false,
7201            )
7202            .unwrap();
7203        cache
7204            .borrow_mut()
7205            .add_pool_profiler(test_profiler_at_block(
7206                &pool,
7207                FIXTURE_BLOCK,
7208                FIXTURE_BLOCK_HASH,
7209            ))
7210            .unwrap();
7211        let core = ExecutionClientCore::new(
7212            TraderId::from("TRADER-001"),
7213            ClientId::from("BLOCKCHAIN-001"),
7214            *BLOCKCHAIN_VENUE,
7215            OmsType::Netting,
7216            AccountId::from("BLOCKCHAIN-001"),
7217            AccountType::Wallet,
7218            None,
7219            Rc::clone(&cache),
7220        );
7221
7222        let client = BlockchainExecutionClient::new(core, config).unwrap();
7223        (client, cache)
7224    }
7225
7226    /// Builds a connected, signer-equipped swap client backed by a fresh Postgres schema.
7227    async fn swap_client_with_database(
7228        test_name: &str,
7229        state: MockRpcState,
7230    ) -> Option<(
7231        sqlx::PgPool,
7232        String,
7233        BlockchainExecutionClient,
7234        MockRpcState,
7235        Rc<RefCell<Cache>>,
7236    )> {
7237        swap_client_with_database_config(test_name, state, test_config).await
7238    }
7239
7240    async fn swap_client_with_buy_database(
7241        test_name: &str,
7242        state: MockRpcState,
7243    ) -> Option<(
7244        sqlx::PgPool,
7245        String,
7246        BlockchainExecutionClient,
7247        MockRpcState,
7248        Rc<RefCell<Cache>>,
7249    )> {
7250        swap_client_with_database_config(test_name, state, buy_test_config).await
7251    }
7252
7253    async fn swap_client_with_database_config<F>(
7254        test_name: &str,
7255        state: MockRpcState,
7256        config: F,
7257    ) -> Option<(
7258        sqlx::PgPool,
7259        String,
7260        BlockchainExecutionClient,
7261        MockRpcState,
7262        Rc<RefCell<Cache>>,
7263    )>
7264    where
7265        F: FnOnce(String) -> BlockchainExecutionClientConfig,
7266    {
7267        let (admin_pool, pg_config) = connect_test_postgres(test_name).await?;
7268        let schema = format!("{test_name}_{}", std::process::id());
7269        setup_execution_schema(&admin_pool, &schema).await;
7270
7271        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
7272        let db_options = db_options.options([("search_path", schema.clone())]);
7273        let database = connect_test_database(db_options).await.unwrap();
7274        let addr = start_mock_rpc_server(state.clone()).await;
7275        let (mut client, cache) = swap_client_with_cache(config(format!("http://{addr}")));
7276        client.cache.database = Some(database);
7277        // Mirror the connect-time migration: tests create the pre-submission table shape
7278        client
7279            .cache
7280            .ensure_execution_transaction_schema()
7281            .await
7282            .unwrap();
7283        protect_test_storage(&mut client, &schema).await;
7284        initialize_test_verification_ledger(&client).await;
7285        client.signer = Some(Arc::new(
7286            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7287        ));
7288        client.core.set_connected();
7289
7290        Some((admin_pool, schema, client, state, cache))
7291    }
7292
7293    async fn initialize_test_verification_ledger(client: &BlockchainExecutionClient) {
7294        initialize_test_verification_ledger_with_headers(
7295            client,
7296            &[ExecutionVerifiedHeader {
7297                number: FIXTURE_BLOCK,
7298                hash: FIXTURE_BLOCK_HASH.to_string(),
7299                parent_hash: "0x0000000000000000000000000000000000000000000000000000000000000001"
7300                    .to_string(),
7301                timestamp: FIXTURE_BLOCK_TIMESTAMP,
7302                base_fee_per_gas: Some(100_000_000),
7303            }],
7304        )
7305        .await;
7306    }
7307
7308    async fn initialize_test_verification_ledger_with_headers(
7309        client: &BlockchainExecutionClient,
7310        finalized_headers: &[ExecutionVerifiedHeader],
7311    ) {
7312        ensure_test_verification_ledger(client, finalized_headers, 7, 7)
7313            .await
7314            .unwrap();
7315    }
7316
7317    async fn ensure_test_verification_ledger(
7318        client: &BlockchainExecutionClient,
7319        finalized_headers: &[ExecutionVerifiedHeader],
7320        next_canonical_nonce: u64,
7321        observed_canonical_nonce: u64,
7322    ) -> anyhow::Result<()> {
7323        let verification = client.config.verification.as_ref().unwrap();
7324        let provider_ids = vec![
7325            "authoritative".to_string(),
7326            "verifier-a".to_string(),
7327            "verifier-b".to_string(),
7328        ];
7329        let operator_ids = vec![
7330            "operator-a".to_string(),
7331            "operator-b".to_string(),
7332            "operator-c".to_string(),
7333        ];
7334        let failure_domain_ids = vec![
7335            "domain-a".to_string(),
7336            "domain-b".to_string(),
7337            "domain-c".to_string(),
7338        ];
7339        let decisions = [ExecutionVerificationDecision {
7340            read_class: "numbered_block",
7341            height_start: Some(FIXTURE_BLOCK),
7342            height_end: Some(FIXTURE_BLOCK),
7343            normalized_value_digest: B256::ZERO.to_string(),
7344        }];
7345        client
7346            .cache
7347            .database
7348            .as_ref()
7349            .unwrap()
7350            .ensure_execution_verification_schema(&ExecutionVerificationBootstrap {
7351                chain_id: 42_161,
7352                wallet_address: WALLET,
7353                manifest_version: &verification.manifest_version,
7354                manifest_digest: &verification.manifest_digest,
7355                checkpoint_number: FIXTURE_BLOCK,
7356                checkpoint_hash: FIXTURE_BLOCK_HASH,
7357                checkpoint_parent_hash:
7358                    "0x0000000000000000000000000000000000000000000000000000000000000001",
7359                checkpoint_timestamp: FIXTURE_BLOCK_TIMESTAMP,
7360                checkpoint_base_fee_per_gas: Some(100_000_000),
7361                finalized_headers,
7362                next_canonical_nonce,
7363                observed_canonical_nonce,
7364                provider_ids: &provider_ids,
7365                operator_ids: &operator_ids,
7366                failure_domain_ids: &failure_domain_ids,
7367                decisions: &decisions,
7368                migration: None,
7369            })
7370            .await
7371    }
7372
7373    async fn initialize_test_verification_migration(
7374        client: &BlockchainExecutionClient,
7375        finalized_headers: &[ExecutionVerifiedHeader],
7376        next_canonical_nonce: u64,
7377        decisions: &[ExecutionVerificationDecision],
7378        migration: &ExecutionVerificationMigration,
7379    ) {
7380        let verification = client.config.verification.as_ref().unwrap();
7381        let provider_ids = vec![
7382            "authoritative".to_string(),
7383            "verifier-a".to_string(),
7384            "verifier-b".to_string(),
7385        ];
7386        let operator_ids = vec![
7387            "operator-a".to_string(),
7388            "operator-b".to_string(),
7389            "operator-c".to_string(),
7390        ];
7391        let failure_domain_ids = vec![
7392            "domain-a".to_string(),
7393            "domain-b".to_string(),
7394            "domain-c".to_string(),
7395        ];
7396        client
7397            .cache
7398            .database
7399            .as_ref()
7400            .unwrap()
7401            .ensure_execution_verification_schema(&ExecutionVerificationBootstrap {
7402                chain_id: 42_161,
7403                wallet_address: WALLET,
7404                manifest_version: &verification.manifest_version,
7405                manifest_digest: &verification.manifest_digest,
7406                checkpoint_number: FIXTURE_BLOCK,
7407                checkpoint_hash: FIXTURE_BLOCK_HASH,
7408                checkpoint_parent_hash:
7409                    "0x0000000000000000000000000000000000000000000000000000000000000001",
7410                checkpoint_timestamp: FIXTURE_BLOCK_TIMESTAMP,
7411                checkpoint_base_fee_per_gas: Some(100_000_000),
7412                finalized_headers,
7413                next_canonical_nonce,
7414                observed_canonical_nonce: next_canonical_nonce,
7415                provider_ids: &provider_ids,
7416                operator_ids: &operator_ids,
7417                failure_domain_ids: &failure_domain_ids,
7418                decisions,
7419                migration: Some(migration),
7420            })
7421            .await
7422            .unwrap();
7423    }
7424
7425    async fn swap_rpc_state() -> MockRpcState {
7426        let min_amount_out = expected_min_amount_out(50);
7427        swap_rpc_state_with_min_amount_out(min_amount_out).await
7428    }
7429
7430    async fn swap_rpc_state_with_min_amount_out(min_amount_out: U256) -> MockRpcState {
7431        let (tx_hash, _) = expected_swap_tx(min_amount_out).await;
7432        finalized_swap_rpc_state(tx_hash, min_amount_out)
7433    }
7434
7435    async fn swap_rpc_state_for_mismatch() -> MockRpcState {
7436        swap_rpc_state()
7437            .await
7438            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION)
7439    }
7440
7441    fn awaiting_in_flight(client: &BlockchainExecutionClient) -> InFlightTransaction {
7442        let slot = *client.in_flight.lock();
7443        let Some(InFlightSlot::AwaitingFinality(in_flight)) = slot else {
7444            panic!("expected an awaiting-finality transaction, was {slot:?}");
7445        };
7446        in_flight
7447    }
7448
7449    fn recovering_in_flight(client: &BlockchainExecutionClient) -> RecoveryTransaction {
7450        let slot = *client.in_flight.lock();
7451        let Some(InFlightSlot::Recovering(recovery)) = slot else {
7452            panic!("expected a recovery transaction, was {slot:?}");
7453        };
7454        recovery
7455    }
7456
7457    async fn execution_intent_markers(
7458        admin_pool: &sqlx::PgPool,
7459        schema: &str,
7460    ) -> Vec<(String, String, bool, bool)> {
7461        sqlx::query_as(sqlx::AssertSqlSafe(format!(
7462            "SELECT purpose, status, terminal_emitted, active \
7463             FROM {schema}.execution_intent ORDER BY id"
7464        )))
7465        .fetch_all(admin_pool)
7466        .await
7467        .unwrap()
7468    }
7469
7470    #[allow(unsafe_code)] // env-var mutation in tests; unique names avoid cross-test races
7471    fn payload_test_keys(
7472        active: [u8; 32],
7473        retired: Vec<[u8; 32]>,
7474        deployment_id: &str,
7475    ) -> PayloadKeySet {
7476        static NEXT_ENV_ID: AtomicU64 = AtomicU64::new(0);
7477
7478        let env_id = NEXT_ENV_ID.fetch_add(1, Ordering::Relaxed);
7479        let active_env = format!("BLOCKCHAIN_TEST_PAYLOAD_KEY_{env_id}_ACTIVE");
7480        let retired_envs = retired
7481            .iter()
7482            .enumerate()
7483            .map(|(index, _)| format!("BLOCKCHAIN_TEST_PAYLOAD_KEY_{env_id}_RETIRED_{index}"))
7484            .collect::<Vec<_>>();
7485        // SAFETY: each invocation uses unique variable names and removes them before returning
7486        unsafe { std::env::set_var(&active_env, hex::encode(active)) };
7487
7488        for (env, key) in retired_envs.iter().zip(retired) {
7489            // SAFETY: the retired variable name is unique to this invocation
7490            unsafe { std::env::set_var(env, hex::encode(key)) };
7491        }
7492
7493        let keys = PayloadKeySet::load(Some(&active_env), &retired_envs, Some(deployment_id))
7494            .unwrap()
7495            .unwrap();
7496
7497        // SAFETY: no other test or thread uses these unique variable names
7498        unsafe { std::env::remove_var(active_env) };
7499        for env in retired_envs {
7500            // SAFETY: the retired variable name is unique to this invocation
7501            unsafe { std::env::remove_var(env) };
7502        }
7503        keys
7504    }
7505
7506    #[allow(unsafe_code)] // env-var mutation in tests; unique names avoid cross-test races
7507    fn set_test_payload_key(
7508        client: &mut BlockchainExecutionClient,
7509        key: [u8; 32],
7510        deployment_id: &str,
7511    ) -> PayloadKeySet {
7512        static NEXT_ENV_ID: AtomicU64 = AtomicU64::new(0);
7513
7514        let env_id = NEXT_ENV_ID.fetch_add(1, Ordering::Relaxed);
7515        let active_env = format!("BLOCKCHAIN_TEST_EXECUTION_KEY_{env_id}");
7516        // SAFETY: each invocation uses a unique variable name retained for reconnect tests
7517        unsafe { std::env::set_var(&active_env, hex::encode(key)) };
7518        client.config.payload_key_env = Some(active_env);
7519        client.config.payload_deployment_id = Some(deployment_id.to_string());
7520        client.load_payload_keys().unwrap().unwrap()
7521    }
7522
7523    async fn protect_test_storage(client: &mut BlockchainExecutionClient, deployment_id: &str) {
7524        let keys = set_test_payload_key(client, [0xa5; 32], deployment_id);
7525        client
7526            .cache
7527            .database
7528            .as_ref()
7529            .unwrap()
7530            .ensure_execution_payload_storage(&keys)
7531            .await
7532            .unwrap();
7533        client.payload_keys = Some(Arc::new(keys));
7534    }
7535
7536    async fn reserve_test_wrap_intent(database: &BlockchainCacheDatabase) -> ExecutionIntentRow {
7537        reserve_test_wrap_intent_for_wallet(database, WALLET).await
7538    }
7539
7540    async fn reserve_test_wrap_intent_for_wallet(
7541        database: &BlockchainCacheDatabase,
7542        wallet: &str,
7543    ) -> ExecutionIntentRow {
7544        database
7545            .reserve_execution_intent(&ExecutionIntentInsert {
7546                chain_id: 42161,
7547                wallet_address: wallet.to_string(),
7548                purpose: "wrap".to_string(),
7549                client_order_id: None,
7550                trader_id: None,
7551                strategy_id: None,
7552                account_id: None,
7553                instrument_id: None,
7554                pool_address: None,
7555                transaction_to: WETH_ADDRESS.to_string(),
7556                transaction_input: "0xd0e30db0".to_string(),
7557                transaction_value: "1".to_string(),
7558                amount_in: None,
7559                created_block: FIXTURE_BLOCK,
7560            })
7561            .await
7562            .unwrap()
7563    }
7564
7565    async fn persist_test_wrap_broadcast(
7566        database: &BlockchainCacheDatabase,
7567        keys: Option<&PayloadKeySet>,
7568    ) -> (ExecutionIntentRow, B256, Vec<u8>) {
7569        let intent = reserve_test_wrap_intent(database).await;
7570        database
7571            .assign_execution_intent_nonce(intent.id, 7)
7572            .await
7573            .unwrap();
7574        let intent = database.get_execution_intent(intent.id).await.unwrap();
7575        let transaction = build_eip1559_transaction(
7576            42161,
7577            7,
7578            78_000,
7579            130_000_000,
7580            10_000_000,
7581            WETH_ADDRESS,
7582            U256::from(1u64),
7583            Bytes::from(nautilus_core::hex::decode("d0e30db0").unwrap()),
7584        );
7585        let (tx_hash, raw_tx) = sign_eip1559_transaction(
7586            transaction,
7587            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7588        )
7589        .await
7590        .unwrap();
7591        persist_test_payload(database, keys, &intent, tx_hash, &raw_tx).await;
7592        database
7593            .record_execution_status(
7594                intent.id,
7595                &tx_hash.to_string(),
7596                TransactionStatus::Broadcast,
7597                None,
7598                None,
7599                None,
7600                None,
7601                None,
7602            )
7603            .await
7604            .unwrap();
7605        (intent, tx_hash, raw_tx)
7606    }
7607
7608    #[tokio::test]
7609    async fn migration_check_reads_authoritative_swap_intents() {
7610        let (admin, config) = connect_test_postgres("migration_check")
7611            .await
7612            .expect("Postgres required");
7613        let schema = format!("migration_check_{}", UUID4::new()).replace('-', "_");
7614        setup_execution_schema(&admin, &schema).await;
7615        let options: sqlx::postgres::PgConnectOptions = config.into();
7616        let database = connect_test_database(options.options([("search_path", schema.clone())]))
7617            .await
7618            .unwrap();
7619        database
7620            .ensure_execution_transaction_schema()
7621            .await
7622            .unwrap();
7623        let id = test_pool().instrument_id;
7624        database.check_instrument_migration(id).await.unwrap();
7625        let intent = reserve_test_swap_intent(&database).await;
7626
7627        let active = database.check_instrument_migration(id).await.unwrap_err();
7628        let unrelated = database
7629            .check_instrument_migration(InstrumentId::from("UNRELATED.DEFI"))
7630            .await;
7631        sqlx::query(sqlx::AssertSqlSafe(format!(
7632            "UPDATE {schema}.execution_intent SET active = FALSE WHERE id = $1"
7633        )))
7634        .bind(intent.id)
7635        .execute(&admin)
7636        .await
7637        .unwrap();
7638        let inactive = database.check_instrument_migration(id).await;
7639        drop_execution_schema(&admin, &schema).await;
7640        let unavailable = database.check_instrument_migration(id).await.unwrap_err();
7641
7642        assert_eq!(
7643            active.to_string(),
7644            format!("Instrument {id} has active swap intents")
7645        );
7646        unrelated.unwrap();
7647        inactive.unwrap();
7648        assert_eq!(
7649            unavailable.to_string(),
7650            "failed to check active swap intents before instrument replacement"
7651        );
7652    }
7653
7654    async fn reserve_test_swap_intent(database: &BlockchainCacheDatabase) -> ExecutionIntentRow {
7655        let pool = test_pool();
7656        let order = test_market_sell_order(pool.instrument_id);
7657        let calldata = expected_swap_calldata(expected_min_amount_out(50));
7658
7659        database
7660            .reserve_execution_intent(&ExecutionIntentInsert {
7661                chain_id: 42161,
7662                wallet_address: WALLET.to_string(),
7663                purpose: "swap".to_string(),
7664                client_order_id: Some(order.client_order_id().to_string()),
7665                trader_id: Some(order.trader_id().to_string()),
7666                strategy_id: Some(order.strategy_id().to_string()),
7667                account_id: Some("BLOCKCHAIN-001".to_string()),
7668                instrument_id: Some(pool.instrument_id.to_string()),
7669                pool_address: Some(pool.address.to_string()),
7670                transaction_to: ROUTER_ADDRESS.to_string(),
7671                transaction_input: hex::encode_prefixed(&calldata),
7672                transaction_value: U256::ZERO.to_string(),
7673                amount_in: Some("1000000000000000".to_string()),
7674                created_block: FIXTURE_BLOCK,
7675            })
7676            .await
7677            .unwrap()
7678    }
7679
7680    async fn persist_invalid_test_swap(
7681        database: &BlockchainCacheDatabase,
7682        keys: Option<&PayloadKeySet>,
7683    ) -> (ExecutionIntentRow, B256) {
7684        let intent = reserve_test_swap_intent(database).await;
7685        database
7686            .assign_execution_intent_nonce(intent.id, 7)
7687            .await
7688            .unwrap();
7689        let intent = database.get_execution_intent(intent.id).await.unwrap();
7690        let (tx_hash, raw_transaction) = expected_swap_tx(expected_min_amount_out(50)).await;
7691        let mut raw_transaction = hex::decode(raw_transaction.strip_prefix("0x").unwrap()).unwrap();
7692        raw_transaction.push(0xff);
7693        persist_test_payload(database, keys, &intent, tx_hash, &raw_transaction).await;
7694        database
7695            .record_execution_status(
7696                intent.id,
7697                &tx_hash.to_string(),
7698                TransactionStatus::Broadcast,
7699                None,
7700                None,
7701                None,
7702                None,
7703                None,
7704            )
7705            .await
7706            .unwrap();
7707
7708        (intent, tx_hash)
7709    }
7710
7711    async fn persist_test_swap_broadcast(
7712        database: &BlockchainCacheDatabase,
7713        keys: Option<&PayloadKeySet>,
7714    ) -> (ExecutionIntentRow, B256, Vec<u8>) {
7715        let intent = reserve_test_swap_intent(database).await;
7716        database
7717            .assign_execution_intent_nonce(intent.id, 7)
7718            .await
7719            .unwrap();
7720        let intent = database.get_execution_intent(intent.id).await.unwrap();
7721        let (tx_hash, raw_transaction) = expected_swap_tx(expected_min_amount_out(50)).await;
7722        let raw_transaction = hex::decode(raw_transaction.strip_prefix("0x").unwrap()).unwrap();
7723        persist_test_payload(database, keys, &intent, tx_hash, &raw_transaction).await;
7724        database
7725            .record_execution_status(
7726                intent.id,
7727                &tx_hash.to_string(),
7728                TransactionStatus::Broadcast,
7729                None,
7730                None,
7731                None,
7732                None,
7733                None,
7734            )
7735            .await
7736            .unwrap();
7737        (intent, tx_hash, raw_transaction)
7738    }
7739
7740    async fn persist_test_payload(
7741        database: &BlockchainCacheDatabase,
7742        keys: Option<&PayloadKeySet>,
7743        intent: &ExecutionIntentRow,
7744        tx_hash: B256,
7745        raw_transaction: &[u8],
7746    ) {
7747        if let Some(keys) = keys {
7748            database.reserve_execution_payload_seal(keys).await.unwrap();
7749            let transaction_hash = tx_hash.to_string();
7750            let context =
7751                payload_context_identity(intent, &transaction_hash, 42_161, keys.deployment_id())
7752                    .unwrap();
7753            let envelope = keys.seal(raw_transaction, &context).unwrap();
7754            database
7755                .add_execution_transaction_envelope(intent.id, 42_161, &transaction_hash, &envelope)
7756                .await
7757                .unwrap();
7758        } else {
7759            database
7760                .add_execution_transaction_hash(
7761                    intent.id,
7762                    42_161,
7763                    &tx_hash.to_string(),
7764                    raw_transaction,
7765                )
7766                .await
7767                .unwrap();
7768        }
7769    }
7770
7771    async fn later_reconnect(
7772        previous: BlockchainExecutionClient,
7773        http_rpc_url: String,
7774    ) -> anyhow::Error {
7775        let database = previous.cache.database.as_ref().unwrap().clone();
7776        let payload_keys = previous.payload_keys.clone();
7777        drop(previous);
7778        let mut next = test_client(http_rpc_url);
7779        next.cache.database = Some(database);
7780        next.payload_keys = payload_keys;
7781        next.signer = Some(Arc::new(
7782            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7783        ));
7784        next.reconcile_unresolved_execution().await.unwrap_err()
7785    }
7786
7787    fn start_with_events(
7788        client: &mut BlockchainExecutionClient,
7789    ) -> tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent> {
7790        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
7791        replace_exec_event_sender(sender);
7792        client.start().unwrap();
7793        receiver
7794    }
7795
7796    async fn await_pending_tasks(client: &BlockchainExecutionClient) {
7797        tokio::time::timeout(TEST_TIMEOUT, async {
7798            while !client.pending_tasks.all_finished() {
7799                tokio::time::sleep(Duration::from_millis(1)).await;
7800            }
7801        })
7802        .await
7803        .unwrap();
7804    }
7805
7806    fn collect_order_events(
7807        receiver: &mut tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
7808    ) -> Vec<OrderEventAny> {
7809        let mut events = Vec::new();
7810
7811        while let Ok(event) = receiver.try_recv() {
7812            if let ExecutionEvent::Order(order_event) = event {
7813                events.push(order_event);
7814            }
7815        }
7816        events
7817    }
7818
7819    fn assert_swap_quarantined_without_terminal_event(events: &[OrderEventAny]) {
7820        assert_eq!(events.len(), 1, "was: {events:?}");
7821        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
7822    }
7823
7824    fn assert_swap_submitted_and_filled(events: &[OrderEventAny]) {
7825        assert_eq!(events.len(), 2, "was: {events:?}");
7826        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
7827        assert!(matches!(&events[1], OrderEventAny::Filled(_)));
7828    }
7829
7830    fn expected_swap_calldata(min_amount_out: U256) -> Vec<u8> {
7831        UniswapV3SwapRouter::exactInputSingleCall {
7832            params: UniswapV3SwapRouter::ExactInputSingleParams {
7833                tokenIn: WETH_ADDRESS,
7834                tokenOut: address!("af88d065e77c8cC2239327C5EDb3A432268e5831"),
7835                fee: U24::try_from(500u32).unwrap(),
7836                recipient: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"),
7837                deadline: U256::from(FIXTURE_BLOCK_TIMESTAMP + 300),
7838                amountIn: U256::from(1_000_000_000_000_000u64),
7839                amountOutMinimum: min_amount_out,
7840                sqrtPriceLimitX96: U160::ZERO,
7841            },
7842        }
7843        .abi_encode()
7844    }
7845
7846    fn expected_min_amount_out(slippage_bps: u32) -> U256 {
7847        expected_min_amount_out_for(&test_pool(), true, slippage_bps)
7848    }
7849
7850    fn expected_min_amount_out_for(pool: &Pool, zero_for_one: bool, slippage_bps: u32) -> U256 {
7851        let profiler = test_profiler(pool, FIXTURE_BLOCK);
7852        let quote = profiler
7853            .swap_exact_in(U256::from(1_000_000_000_000_000u64), zero_for_one, None)
7854            .unwrap();
7855        let quoted = exact_output_amount(&quote, zero_for_one).unwrap();
7856        derive_min_amount_out(quoted, slippage_bps).unwrap()
7857    }
7858
7859    fn expected_sell_quote_amount() -> U256 {
7860        let profiler = test_profiler(&test_pool(), FIXTURE_BLOCK);
7861        let quote = profiler
7862            .swap_exact_in(U256::from(1_000_000_000_000_000u64), true, None)
7863            .unwrap();
7864        exact_output_amount(&quote, true).unwrap()
7865    }
7866
7867    fn quote_response(amount: U256) -> String {
7868        let result = (amount, U160::from(1u128 << 96), 0u32, U256::from(50_000u64)).abi_encode();
7869        serde_json::json!({
7870            "jsonrpc": "2.0",
7871            "id": 1,
7872            "result": hex::encode_prefixed(result),
7873        })
7874        .to_string()
7875    }
7876
7877    async fn expected_swap_tx(min_amount_out: U256) -> (B256, String) {
7878        // The orchestration's policy math is deterministic: nonce 7 from the fixture,
7879        // buffered gas 78000, buffered max fee 130000000, priority fee 10000000
7880        let expected_tx = build_eip1559_transaction(
7881            42161,
7882            7,
7883            78_000,
7884            130_000_000,
7885            10_000_000,
7886            ROUTER_ADDRESS,
7887            U256::ZERO,
7888            Bytes::from(expected_swap_calldata(min_amount_out)),
7889        );
7890        sign_eip1559_transaction(
7891            expected_tx,
7892            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7893        )
7894        .await
7895        .map(|(hash, raw)| (hash, nautilus_core::hex::encode_prefixed(&raw)))
7896        .unwrap()
7897    }
7898
7899    fn expected_buy_base_amount() -> U256 {
7900        U256::from(1_000_000_000_000_000u64)
7901    }
7902
7903    fn expected_buy_amount_in() -> U256 {
7904        let profiler = test_profiler(&test_pool(), FIXTURE_BLOCK);
7905        profiler
7906            .swap_exact_out(expected_buy_base_amount(), false, None)
7907            .unwrap()
7908            .get_input_amount()
7909    }
7910
7911    fn expected_buy_min_amount_out(slippage_bps: u32) -> U256 {
7912        derive_min_amount_out(expected_buy_base_amount(), slippage_bps).unwrap()
7913    }
7914
7915    fn expected_buy_swap_calldata(min_amount_out: U256, amount_in: U256) -> Vec<u8> {
7916        UniswapV3SwapRouter::exactInputSingleCall {
7917            params: UniswapV3SwapRouter::ExactInputSingleParams {
7918                tokenIn: USDC_ADDRESS,
7919                tokenOut: WETH_ADDRESS,
7920                fee: U24::try_from(500u32).unwrap(),
7921                recipient: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"),
7922                deadline: U256::from(FIXTURE_BLOCK_TIMESTAMP + 300),
7923                amountIn: amount_in,
7924                amountOutMinimum: min_amount_out,
7925                sqrtPriceLimitX96: U160::ZERO,
7926            },
7927        }
7928        .abi_encode()
7929    }
7930
7931    async fn expected_buy_swap_tx(min_amount_out: U256, amount_in: U256) -> (B256, String) {
7932        let expected_tx = build_eip1559_transaction(
7933            42161,
7934            7,
7935            78_000,
7936            130_000_000,
7937            10_000_000,
7938            ROUTER_ADDRESS,
7939            U256::ZERO,
7940            Bytes::from(expected_buy_swap_calldata(min_amount_out, amount_in)),
7941        );
7942        sign_eip1559_transaction(
7943            expected_tx,
7944            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7945        )
7946        .await
7947        .map(|(hash, raw)| (hash, nautilus_core::hex::encode_prefixed(&raw)))
7948        .unwrap()
7949    }
7950
7951    fn finalized_buy_swap_receipt(tx_hash: B256, amount_in: U256) -> String {
7952        finalized_buy_swap_receipt_with_base_out(tx_hash, amount_in, expected_buy_base_amount())
7953    }
7954
7955    fn finalized_buy_swap_receipt_with_base_out(
7956        tx_hash: B256,
7957        amount_in: U256,
7958        base_out: U256,
7959    ) -> String {
7960        let data = (
7961            -I256::try_from(u128::try_from(base_out).unwrap()).unwrap(),
7962            I256::try_from(u128::try_from(amount_in).unwrap()).unwrap(),
7963            U160::from(1_u128 << 96),
7964            TEST_LIQUIDITY,
7965            I24::try_from(0).unwrap(),
7966        )
7967            .abi_encode();
7968        serde_json::json!({
7969            "jsonrpc": "2.0",
7970            "id": 1,
7971            "result": {
7972                "transactionHash": tx_hash.to_string(),
7973                "blockHash": "0x2222222222222222222222222222222222222222222222222222222222222222",
7974                "blockNumber": "0x1cf0d41",
7975                "transactionIndex": "0x2",
7976                "gasUsed": "0xc3c0",
7977                "effectiveGasPrice": "0x5f5e100",
7978                "status": "0x1",
7979                "logs": [{
7980                    "removed": false,
7981                    "logIndex": "0x6",
7982                    "transactionIndex": "0x2",
7983                    "transactionHash": tx_hash.to_string(),
7984                    "blockHash": "0x2222222222222222222222222222222222222222222222222222222222222222",
7985                    "blockNumber": "0x1cf0d41",
7986                    "address": test_pool().address.to_string(),
7987                    "data": hex::encode_prefixed(data),
7988                    "topics": [
7989                        "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67",
7990                        "0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266",
7991                        "0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266"
7992                    ]
7993                }]
7994            }
7995        })
7996        .to_string()
7997    }
7998
7999    fn finalized_buy_swap_block(tx_hash: B256, min_amount_out: U256, amount_in: U256) -> String {
8000        serde_json::json!({
8001            "jsonrpc": "2.0",
8002            "id": 1,
8003            "result": {
8004                "number": "0x1cf0d41",
8005                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8006                "parentHash": FIXTURE_BLOCK_HASH,
8007                "timestamp": "0x69044a21",
8008                "baseFeePerGas": "0x5f5e100",
8009                "transactions": [{
8010                    "hash": tx_hash.to_string(),
8011                    "from": WALLET,
8012                    "nonce": "0x7",
8013                    "chainId": "0xa4b1",
8014                    "type": "0x2",
8015                    "to": ROUTER,
8016                    "input": hex::encode_prefixed(expected_buy_swap_calldata(min_amount_out, amount_in)),
8017                    "value": "0x0",
8018                    "gas": "0x130b0",
8019                    "maxFeePerGas": "0x7bfa480",
8020                    "maxPriorityFeePerGas": "0x989680"
8021                }]
8022            }
8023        })
8024        .to_string()
8025    }
8026
8027    fn finalized_buy_swap_rpc_state(
8028        tx_hash: B256,
8029        min_amount_out: U256,
8030        amount_in: U256,
8031    ) -> MockRpcState {
8032        let receipt = finalized_buy_swap_receipt(tx_hash, amount_in);
8033        let block = finalized_buy_swap_block(tx_hash, min_amount_out, amount_in);
8034        with_finalized_identity(
8035            signing_rpc_state()
8036                .with_response("eth_getTransactionReceipt", &receipt)
8037                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
8038                .with_send_raw_transaction_echo()
8039                .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE)
8040                .with_call_response(ALLOWANCE_SELECTOR, CALL_ALLOWANCE),
8041            &block,
8042            &receipt,
8043        )
8044    }
8045
8046    fn finalized_swap_receipt(tx_hash: B256) -> String {
8047        let data = (
8048            I256::try_from(1_000_000_000_000_000_i128).unwrap(),
8049            I256::try_from(-1_000_000_i128).unwrap(),
8050            U160::from(1_u128 << 96),
8051            TEST_LIQUIDITY,
8052            I24::try_from(0).unwrap(),
8053        )
8054            .abi_encode();
8055        serde_json::json!({
8056            "jsonrpc": "2.0",
8057            "id": 1,
8058            "result": {
8059                "transactionHash": tx_hash.to_string(),
8060                "blockHash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8061                "blockNumber": "0x1cf0d41",
8062                "transactionIndex": "0x2",
8063                "gasUsed": "0xc3c0",
8064                "effectiveGasPrice": "0x5f5e100",
8065                "status": "0x1",
8066                "logs": [{
8067                    "removed": false,
8068                    "logIndex": "0x6",
8069                    "transactionIndex": "0x2",
8070                    "transactionHash": tx_hash.to_string(),
8071                    "blockHash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8072                    "blockNumber": "0x1cf0d41",
8073                    "address": test_pool().address.to_string(),
8074                    "data": hex::encode_prefixed(data),
8075                    "topics": [
8076                        "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67",
8077                        "0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266",
8078                        "0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266"
8079                    ]
8080                }]
8081            }
8082        })
8083        .to_string()
8084    }
8085
8086    fn finalized_swap_receipt_with_unrelated_swap(tx_hash: B256) -> String {
8087        let mut receipt: serde_json::Value =
8088            serde_json::from_str(&finalized_swap_receipt(tx_hash)).unwrap();
8089        let logs = receipt["result"]["logs"].as_array_mut().unwrap();
8090        let mut unrelated = logs[0].clone();
8091        unrelated["address"] = serde_json::json!(ROUTER);
8092        unrelated["logIndex"] = serde_json::json!("0x7");
8093        logs.push(unrelated);
8094        receipt.to_string()
8095    }
8096
8097    fn finalized_swap_block(tx_hash: B256, min_amount_out: U256) -> String {
8098        serde_json::json!({
8099            "jsonrpc": "2.0",
8100            "id": 1,
8101            "result": {
8102                "number": "0x1cf0d41",
8103                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8104                "parentHash": FIXTURE_BLOCK_HASH,
8105                "timestamp": "0x69044a21",
8106                "baseFeePerGas": "0x5f5e100",
8107                "transactions": [{
8108                    "hash": tx_hash.to_string(),
8109                    "from": WALLET,
8110                    "nonce": "0x7",
8111                    "chainId": "0xa4b1",
8112                    "type": "0x2",
8113                    "to": ROUTER,
8114                    "input": hex::encode_prefixed(expected_swap_calldata(min_amount_out)),
8115                    "value": "0x0",
8116                    "gas": "0x130b0",
8117                    "maxFeePerGas": "0x7bfa480",
8118                    "maxPriorityFeePerGas": "0x989680"
8119                }]
8120            }
8121        })
8122        .to_string()
8123    }
8124
8125    fn finalized_swap_rpc_state(tx_hash: B256, min_amount_out: U256) -> MockRpcState {
8126        let receipt = finalized_swap_receipt(tx_hash);
8127        let block = finalized_swap_block(tx_hash, min_amount_out);
8128        with_finalized_identity(
8129            signing_rpc_state()
8130                .with_response("eth_getTransactionReceipt", &receipt)
8131                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
8132                .with_send_raw_transaction_echo()
8133                .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE)
8134                .with_call_response(ALLOWANCE_SELECTOR, CALL_ALLOWANCE),
8135            &block,
8136            &receipt,
8137        )
8138    }
8139
8140    fn with_finalized_identity(
8141        state: MockRpcState,
8142        block_response: &str,
8143        receipt_response: &str,
8144    ) -> MockRpcState {
8145        let block: serde_json::Value = serde_json::from_str(block_response).unwrap();
8146        let receipt: serde_json::Value = serde_json::from_str(receipt_response).unwrap();
8147        let transaction = block["result"]["transactions"][0].clone();
8148        let transaction_response = serde_json::json!({
8149            "jsonrpc": "2.0",
8150            "id": 1,
8151            "result": transaction,
8152        })
8153        .to_string();
8154        let success = receipt["result"]["status"] == "0x1";
8155        let mut trace = serde_json::json!({
8156            "type": "CALL",
8157            "from": transaction["from"],
8158            "to": transaction["to"],
8159            "value": transaction["value"],
8160            "gas": transaction["gas"],
8161            "gasUsed": receipt["result"]["gasUsed"],
8162            "input": transaction["input"],
8163            "output": "0x",
8164            "calls": [],
8165        });
8166
8167        if !success {
8168            trace["error"] = serde_json::json!("execution reverted");
8169        }
8170        let trace_response = serde_json::json!({
8171            "jsonrpc": "2.0",
8172            "id": 1,
8173            "result": trace,
8174        })
8175        .to_string();
8176        state
8177            .with_response("eth_getTransactionByHash", &transaction_response)
8178            .with_response("debug_traceTransaction", &trace_response)
8179    }
8180
8181    fn receipt_with_transaction_hash(receipt_response: &str, tx_hash: B256) -> String {
8182        let mut receipt: serde_json::Value = serde_json::from_str(receipt_response).unwrap();
8183        receipt["result"]["transactionHash"] = serde_json::json!(tx_hash.to_string());
8184        receipt.to_string()
8185    }
8186
8187    fn replacement_head_block(tx_hash: B256) -> String {
8188        serde_json::json!({
8189            "jsonrpc": "2.0",
8190            "id": 1,
8191            "result": {
8192                "number": "0x1cf0d40",
8193                "hash": "0x1111111111111111111111111111111111111111111111111111111111111111",
8194                "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000001",
8195                "timestamp": "0x69044a20",
8196                "baseFeePerGas": "0x5f5e100",
8197                "transactions": [{
8198                    "hash": "0x3333333333333333333333333333333333333333333333333333333333333333",
8199                    "from": "0x0000000000000000000000000000000000000001",
8200                    "nonce": "0x1",
8201                    "type": "0x0",
8202                    "to": WETH,
8203                    "input": "0x",
8204                    "value": "0x0",
8205                    "gas": "0x5208"
8206                }, {
8207                    "hash": tx_hash.to_string(),
8208                    "from": WALLET,
8209                    "nonce": "0x7",
8210                    "chainId": "0xa4b1",
8211                    "type": "0x2",
8212                    "to": WETH,
8213                    "input": "0xd0e30db0",
8214                    "value": "0x38d7ea4c68000",
8215                    "gas": "0x130b0",
8216                    "maxFeePerGas": "0x7bfa480",
8217                    "maxPriorityFeePerGas": "0x989680"
8218                }]
8219            }
8220        })
8221        .to_string()
8222    }
8223
8224    fn finalized_wrap_block(tx_hash: B256) -> String {
8225        serde_json::json!({
8226            "jsonrpc": "2.0",
8227            "id": 1,
8228            "result": {
8229                "number": "0x1cf0d41",
8230                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8231                "parentHash": FIXTURE_BLOCK_HASH,
8232                "timestamp": "0x69044a21",
8233                "baseFeePerGas": "0x5f5e100",
8234                "transactions": [{
8235                    "hash": tx_hash.to_string(),
8236                    "from": WALLET,
8237                    "nonce": "0x7",
8238                    "chainId": "0xa4b1",
8239                    "type": "0x2",
8240                    "to": WETH,
8241                    "input": "0xd0e30db0",
8242                    "value": "0x38d7ea4c68000",
8243                    "gas": "0x130b0",
8244                    "maxFeePerGas": "0x7bfa480",
8245                    "maxPriorityFeePerGas": "0x989680"
8246                }]
8247            }
8248        })
8249        .to_string()
8250    }
8251
8252    fn finalized_approve_block(tx_hash: B256, amount: U256) -> String {
8253        let calldata = ERC20::approveCall {
8254            spender: ROUTER_ADDRESS,
8255            amount,
8256        }
8257        .abi_encode();
8258        serde_json::json!({
8259            "jsonrpc": "2.0",
8260            "id": 1,
8261            "result": {
8262                "number": "0x1cf0d41",
8263                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8264                "parentHash": FIXTURE_BLOCK_HASH,
8265                "timestamp": "0x69044a21",
8266                "baseFeePerGas": "0x5f5e100",
8267                "transactions": [{
8268                    "hash": tx_hash.to_string(),
8269                    "from": WALLET,
8270                    "nonce": "0x7",
8271                    "chainId": "0xa4b1",
8272                    "type": "0x2",
8273                    "to": WETH,
8274                    "input": hex::encode_prefixed(calldata),
8275                    "value": "0x0",
8276                    "gas": "0x130b0",
8277                    "maxFeePerGas": "0x7bfa480",
8278                    "maxPriorityFeePerGas": "0x989680"
8279                }]
8280            }
8281        })
8282        .to_string()
8283    }
8284
8285    fn fixture_sell_plan() -> SwapPlan {
8286        let pool = test_pool();
8287        let order = test_market_sell_order(pool.instrument_id);
8288        let quote_token = pool.get_quote_token();
8289        SwapPlan {
8290            order,
8291            quote_currency: quote_token.currency().unwrap(),
8292            instrument_id: pool.instrument_id,
8293            pool_address: pool.address,
8294            router: ROUTER_ADDRESS,
8295            factory: UNISWAP_V3.dex.factory,
8296            weth: WETH_ADDRESS,
8297            token_in: WETH_ADDRESS,
8298            token_out: USDC_ADDRESS,
8299            fee: U24::try_from(500u32).unwrap(),
8300            amount_in: U256::from(1_000_000_000_000_000u64),
8301            min_amount_out: expected_min_amount_out(50),
8302            slippage_bps: 50,
8303            quote_spend_ceiling: None,
8304            profiler_position: Some(profiler_event_position()),
8305            pool,
8306        }
8307    }
8308
8309    fn fixture_block_response(number: u64, hash: B256) -> String {
8310        let parent_hash = if number == FIXTURE_BLOCK {
8311            B256::from_str("0x0000000000000000000000000000000000000000000000000000000000000001")
8312                .unwrap()
8313        } else {
8314            B256::from_str(FIXTURE_BLOCK_HASH).unwrap()
8315        };
8316        serde_json::json!({
8317            "jsonrpc": "2.0",
8318            "id": 1,
8319            "result": {
8320                "number": format!("0x{number:x}"),
8321                "hash": hash.to_string(),
8322                "parentHash": parent_hash.to_string(),
8323                "timestamp": format!("0x{:x}", FIXTURE_BLOCK_TIMESTAMP + number - FIXTURE_BLOCK),
8324                "baseFeePerGas": "0x5f5e100",
8325                "transactions": []
8326            }
8327        })
8328        .to_string()
8329    }
8330
8331    fn profiler_event_receipt(pool_address: Address) -> String {
8332        let transaction_hash = B256::from([0x33; 32]);
8333        serde_json::json!({
8334            "jsonrpc": "2.0",
8335            "id": 1,
8336            "result": {
8337                "transactionHash": transaction_hash.to_string(),
8338                "blockHash": FIXTURE_BLOCK_HASH,
8339                "blockNumber": "0x1cf0d40",
8340                "transactionIndex": "0x2",
8341                "gasUsed": "0xc3c0",
8342                "effectiveGasPrice": "0x5f5e100",
8343                "status": "0x1",
8344                "logs": [{
8345                    "removed": false,
8346                    "logIndex": "0x6",
8347                    "transactionIndex": "0x2",
8348                    "transactionHash": transaction_hash.to_string(),
8349                    "blockHash": FIXTURE_BLOCK_HASH,
8350                    "blockNumber": "0x1cf0d40",
8351                    "address": pool_address.to_string(),
8352                    "data": "0x",
8353                    "topics": [test_pool().dex.swap_created_event.as_ref()]
8354                }]
8355            }
8356        })
8357        .to_string()
8358    }
8359
8360    fn profiler_event_position() -> BlockPosition {
8361        BlockPosition::new(FIXTURE_BLOCK, B256::from([0x33; 32]).to_string(), 2, 6)
8362            .with_block_hash(Some(FIXTURE_BLOCK_HASH.to_string()))
8363    }
8364
8365    #[rstest]
8366    fn quantity_to_raw_amount_scales_by_token_decimals() {
8367        assert_eq!(
8368            quantity_to_raw_amount(Quantity::from("0.001"), 18).unwrap(),
8369            U256::from(1_000_000_000_000_000u64)
8370        );
8371        assert_eq!(
8372            quantity_to_raw_amount(Quantity::from("1.5"), 18).unwrap(),
8373            U256::from(1_500_000_000_000_000_000u128)
8374        );
8375        assert_eq!(
8376            quantity_to_raw_amount(Quantity::from("12.5"), 6).unwrap(),
8377            U256::from(12_500_000u64)
8378        );
8379    }
8380
8381    #[rstest]
8382    fn quantity_to_raw_amount_uses_defi_quantity_precision() {
8383        let amount = U256::from(10_000_000_000_000_000u64);
8384        let quantity = Quantity::from_u256(amount, 18).unwrap();
8385
8386        assert_eq!(quantity_to_raw_amount(quantity, 18).unwrap(), amount);
8387    }
8388
8389    #[rstest]
8390    fn quantity_to_raw_amount_rejects_zero() {
8391        let error = quantity_to_raw_amount(Quantity::from("0.0"), 18).unwrap_err();
8392
8393        assert_eq!(error.to_string(), "Order quantity must be positive");
8394    }
8395
8396    #[rstest]
8397    fn quantity_to_raw_amount_rejects_inexact_token_units() {
8398        let error = quantity_to_raw_amount(Quantity::from("0.0000001"), 6).unwrap_err();
8399
8400        assert!(
8401            error
8402                .to_string()
8403                .contains("is not exactly representable in 6 base token decimals"),
8404            "was: {error}"
8405        );
8406    }
8407
8408    #[rstest]
8409    fn raw_amount_to_quantity_inverts_base_quantity() {
8410        let quantity = Quantity::from("0.001");
8411        let amount = quantity_to_raw_amount(quantity, 18).unwrap();
8412
8413        assert_eq!(raw_amount_to_quantity(amount, 18).unwrap(), quantity);
8414    }
8415
8416    #[rstest]
8417    fn raw_amount_to_quantity_rejects_positive_amount_truncated_to_zero() {
8418        let error = raw_amount_to_quantity(U256::from(99u64), 18).unwrap_err();
8419
8420        assert!(
8421            error
8422                .to_string()
8423                .contains("is below representable quantity precision"),
8424            "was: {error}"
8425        );
8426    }
8427
8428    #[rstest]
8429    fn fill_price_from_quote_recovers_spent_quote_after_quantity_truncation() {
8430        let last_qty = raw_amount_to_quantity(U256::from(1_000_000_403_079_044u64), 18).unwrap();
8431        let quote_amount = U256::from(1_891_348u64);
8432        let quote = Currency::new_checked("USDC", 6, 0, "USD Coin", CurrencyType::Crypto).unwrap();
8433        let last_px = fill_price_from_quote(last_qty, quote_amount, quote).unwrap();
8434
8435        assert_eq!(
8436            Money::from_decimal(last_qty.as_decimal() * last_px.as_decimal(), quote).unwrap(),
8437            Money::from_u256(quote_amount, quote).unwrap()
8438        );
8439    }
8440
8441    #[rstest]
8442    fn swap_token_pair_is_directional() {
8443        assert_eq!(
8444            swap_token_pair(OrderSide::Sell, WETH_ADDRESS, USDC_ADDRESS),
8445            (WETH_ADDRESS, USDC_ADDRESS)
8446        );
8447        assert_eq!(
8448            swap_token_pair(OrderSide::Buy, WETH_ADDRESS, USDC_ADDRESS),
8449            (USDC_ADDRESS, WETH_ADDRESS)
8450        );
8451    }
8452
8453    #[rstest]
8454    fn restore_swap_plan_buy_uses_quote_input() {
8455        let (client, cache) =
8456            swap_client_with_cache(buy_test_config("http://127.0.0.1:1".to_string()));
8457        let order = test_market_buy_order(test_pool().instrument_id);
8458        cache
8459            .borrow_mut()
8460            .add_order(order.clone(), None, None, true)
8461            .unwrap();
8462        let amount_in = U256::from(2_345_678u64);
8463        let intent = ExecutionIntentRow {
8464            id: 7,
8465            schema_version: crate::execution::transaction::EXECUTION_SCHEMA_VERSION,
8466            chain_id: 42161,
8467            wallet_address: WALLET.to_string(),
8468            nonce: Some(7),
8469            purpose: "swap".to_string(),
8470            status: "finalized".to_string(),
8471            client_order_id: Some(order.client_order_id().to_string()),
8472            trader_id: Some(order.trader_id().to_string()),
8473            strategy_id: Some(order.strategy_id().to_string()),
8474            account_id: Some("BLOCKCHAIN-001".to_string()),
8475            instrument_id: Some(order.instrument_id().to_string()),
8476            pool_address: Some(test_pool().address.to_string()),
8477            transaction_to: ROUTER.to_string(),
8478            transaction_input: "0x".to_string(),
8479            transaction_value: "0".to_string(),
8480            amount_in: Some(amount_in.to_string()),
8481            created_block: FIXTURE_BLOCK,
8482            acknowledgement_emitted: true,
8483            fill_emitted: false,
8484            terminal_emitted: false,
8485            active: true,
8486        };
8487
8488        let plan = client.restore_swap_plan(&intent).unwrap();
8489
8490        assert_eq!(plan.token_in, USDC_ADDRESS);
8491        assert_eq!(plan.token_out, WETH_ADDRESS);
8492        assert_eq!(plan.amount_in, amount_in);
8493    }
8494
8495    #[rstest]
8496    #[case(1_000_000, 50, 995_000)]
8497    #[case(1_000_000, 0, 1_000_000)]
8498    #[case(1_000_000, 200, 980_000)]
8499    #[case(10_000, 9_999, 1)]
8500    fn derive_min_amount_out_applies_slippage(
8501        #[case] quoted: u64,
8502        #[case] slippage_bps: u32,
8503        #[case] expected: u64,
8504    ) {
8505        assert_eq!(
8506            derive_min_amount_out(U256::from(quoted), slippage_bps).unwrap(),
8507            U256::from(expected)
8508        );
8509    }
8510
8511    #[rstest]
8512    fn derive_min_amount_out_rejects_zero_result() {
8513        let error = derive_min_amount_out(U256::from(9_999u64), 9_999).unwrap_err();
8514
8515        assert!(
8516            error.to_string().contains("Derived minimum output is zero"),
8517            "was: {error}"
8518        );
8519    }
8520
8521    #[rstest]
8522    fn derive_min_amount_out_rejects_full_slippage() {
8523        let error = derive_min_amount_out(U256::from(1_000_000u64), 10_000).unwrap_err();
8524
8525        assert!(
8526            error.to_string().contains("must be below 10000"),
8527            "was: {error}"
8528        );
8529    }
8530
8531    #[rstest]
8532    fn replacement_scan_range_is_bounded_and_checked() {
8533        assert_eq!(
8534            replacement_scan_range(10, 10).unwrap(),
8535            RangeInclusive::new(10, 10)
8536        );
8537        assert_eq!(
8538            replacement_scan_range(10, 10 + MAX_REPLACEMENT_SCAN_BLOCKS).unwrap(),
8539            RangeInclusive::new(10, 10 + MAX_REPLACEMENT_SCAN_BLOCKS - 1)
8540        );
8541        assert!(
8542            replacement_scan_range(11, 10)
8543                .unwrap_err()
8544                .to_string()
8545                .contains("is behind execution creation block")
8546        );
8547        assert_eq!(
8548            replacement_scan_range(u64::MAX - 1, u64::MAX).unwrap(),
8549            RangeInclusive::new(u64::MAX - 1, u64::MAX)
8550        );
8551    }
8552
8553    #[rstest]
8554    fn terminal_execution_event_ids_are_stable_and_kind_specific() {
8555        let transaction_hash = B256::from([0x42; 32]);
8556
8557        let fill = execution_event_id(transaction_hash, b"fill");
8558        let fill_retry = execution_event_id(transaction_hash, b"fill");
8559        let reverted = execution_event_id(transaction_hash, b"reverted");
8560
8561        assert_eq!(fill, fill_retry);
8562        assert_ne!(fill, reverted);
8563    }
8564
8565    #[rstest]
8566    fn prepared_transaction_debug_redacts_raw_transaction() {
8567        let prepared = PreparedTransaction {
8568            intent_id: 1,
8569            created_block: 2,
8570            nonce: 3,
8571            tx_hash: B256::ZERO,
8572            raw_tx: vec![0xde, 0xad, 0xbe, 0xef],
8573            payload_lease: None,
8574        };
8575
8576        let debug = format!("{prepared:?}");
8577
8578        assert!(debug.contains("raw_tx: \"<redacted>\""));
8579        assert!(!debug.contains("[222, 173, 190, 239]"));
8580    }
8581
8582    #[rstest]
8583    fn call_trace_rejects_unreviewed_internal_edge() {
8584        let signed = crate::execution::transaction::DecodedSignedTransaction {
8585            hash: B256::from([1; 32]),
8586            signer: Address::from_str(WALLET).unwrap(),
8587            chain_id: 42_161,
8588            nonce: 7,
8589            to: ROUTER_ADDRESS,
8590            value: U256::ZERO,
8591            input: Bytes::from(expected_swap_calldata(expected_min_amount_out(50))),
8592            gas_limit: 78_000,
8593            max_fee_per_gas: 130_000_000,
8594            max_priority_fee_per_gas: 10_000_000,
8595        };
8596        let input_digest = keccak256(&signed.input);
8597        let trace = VerifiedCallTrace {
8598            call_type: RpcCallType::Call,
8599            from: signed.signer,
8600            to: Some(signed.to),
8601            value: signed.value,
8602            input_selector: signed
8603                .input
8604                .get(..4)
8605                .map(|selector| selector.try_into().unwrap()),
8606            input_digest,
8607            success: true,
8608            calls: vec![VerifiedCallTrace {
8609                call_type: RpcCallType::Call,
8610                from: ROUTER_ADDRESS,
8611                to: Some(WETH_ADDRESS),
8612                value: U256::ZERO,
8613                input_selector: None,
8614                input_digest: B256::ZERO,
8615                success: true,
8616                calls: Vec::new(),
8617            }],
8618        };
8619        let manifest = &test_config("http://127.0.0.1:1".to_string())
8620            .verification
8621            .unwrap()
8622            .deployment_manifest;
8623
8624        let error = validate_call_trace(&trace, &signed, true, "swap_sell", manifest).unwrap_err();
8625
8626        assert!(
8627            error.to_string().contains("unreviewed call edge"),
8628            "was: {error}"
8629        );
8630    }
8631
8632    #[rstest]
8633    fn call_trace_rejects_unlisted_precompile_target() {
8634        let manifest = test_config("http://127.0.0.1:1".to_string())
8635            .verification
8636            .unwrap()
8637            .deployment_manifest;
8638        let calls = [VerifiedCallTrace {
8639            call_type: RpcCallType::Call,
8640            from: ROUTER_ADDRESS,
8641            to: Some(address!("0000000000000000000000000000000000000007")),
8642            value: U256::ZERO,
8643            input_selector: None,
8644            input_digest: B256::ZERO,
8645            success: true,
8646            calls: Vec::new(),
8647        }];
8648
8649        let error =
8650            validate_internal_calls(&calls, ROUTER_ADDRESS, "swap_sell", &manifest).unwrap_err();
8651
8652        assert_eq!(
8653            error.to_string(),
8654            format!(
8655                "Verified call trace contains an unreviewed call edge {ROUTER_ADDRESS} -> {} for swap_sell",
8656                address!("0000000000000000000000000000000000000007")
8657            )
8658        );
8659    }
8660
8661    #[rstest]
8662    fn call_trace_requires_exact_call_type() {
8663        let manifest = test_config("http://127.0.0.1:1".to_string())
8664            .verification
8665            .unwrap()
8666            .deployment_manifest;
8667        let calls = [VerifiedCallTrace {
8668            call_type: RpcCallType::Staticcall,
8669            from: ROUTER_ADDRESS,
8670            to: Some(test_pool().address),
8671            value: U256::ZERO,
8672            input_selector: None,
8673            input_digest: B256::ZERO,
8674            success: true,
8675            calls: Vec::new(),
8676        }];
8677
8678        let error =
8679            validate_internal_calls(&calls, ROUTER_ADDRESS, "swap_sell", &manifest).unwrap_err();
8680
8681        assert!(
8682            error.to_string().contains("unreviewed staticcall edge"),
8683            "was: {error}"
8684        );
8685    }
8686
8687    #[rstest]
8688    fn call_trace_requires_exact_caller() {
8689        let manifest = test_config("http://127.0.0.1:1".to_string())
8690            .verification
8691            .unwrap()
8692            .deployment_manifest;
8693        let calls = [VerifiedCallTrace {
8694            call_type: RpcCallType::Call,
8695            from: WETH_ADDRESS,
8696            to: Some(test_pool().address),
8697            value: U256::ZERO,
8698            input_selector: None,
8699            input_digest: B256::ZERO,
8700            success: true,
8701            calls: Vec::new(),
8702        }];
8703
8704        let error =
8705            validate_internal_calls(&calls, ROUTER_ADDRESS, "swap_sell", &manifest).unwrap_err();
8706
8707        assert_eq!(
8708            error.to_string(),
8709            "Verified call trace child has an invalid caller context"
8710        );
8711    }
8712
8713    #[rstest]
8714    fn call_trace_rejects_contract_creation() {
8715        let signed = crate::execution::transaction::DecodedSignedTransaction {
8716            hash: B256::from([1; 32]),
8717            signer: Address::from_str(WALLET).unwrap(),
8718            chain_id: 42_161,
8719            nonce: 7,
8720            to: ROUTER_ADDRESS,
8721            value: U256::ZERO,
8722            input: Bytes::from(expected_swap_calldata(expected_min_amount_out(50))),
8723            gas_limit: 78_000,
8724            max_fee_per_gas: 130_000_000,
8725            max_priority_fee_per_gas: 10_000_000,
8726        };
8727        let trace = VerifiedCallTrace {
8728            call_type: RpcCallType::Call,
8729            from: signed.signer,
8730            to: Some(signed.to),
8731            value: signed.value,
8732            input_selector: signed
8733                .input
8734                .get(..4)
8735                .map(|selector| selector.try_into().unwrap()),
8736            input_digest: keccak256(&signed.input),
8737            success: true,
8738            calls: vec![VerifiedCallTrace {
8739                call_type: RpcCallType::Create,
8740                from: ROUTER_ADDRESS,
8741                to: Some(address!("0000000000000000000000000000000000000007")),
8742                value: U256::ZERO,
8743                input_selector: None,
8744                input_digest: B256::ZERO,
8745                success: true,
8746                calls: Vec::new(),
8747            }],
8748        };
8749        let manifest = &test_config("http://127.0.0.1:1".to_string())
8750            .verification
8751            .unwrap()
8752            .deployment_manifest;
8753
8754        let error = validate_call_trace(&trace, &signed, true, "swap_sell", manifest).unwrap_err();
8755
8756        assert!(
8757            error
8758                .to_string()
8759                .contains("forbidden state-changing operation"),
8760            "was: {error}"
8761        );
8762    }
8763
8764    #[tokio::test]
8765    async fn swap_quote_rejects_missing_ingestion_block_hash() {
8766        let (client, state) = client_with_mock_rpc(execution_rpc_state()).await;
8767        let plan = fixture_sell_plan();
8768        let position = BlockPosition::new(
8769            FIXTURE_BLOCK,
8770            FIXTURE_BLOCK_HASH.to_string(),
8771            BLOCK_SCOPED_SNAPSHOT_INDEX,
8772            BLOCK_SCOPED_SNAPSHOT_INDEX,
8773        );
8774
8775        let error = validate_swap_quote(
8776            &position,
8777            &plan,
8778            100,
8779            &client.verification,
8780            &client
8781                .config
8782                .verification
8783                .as_ref()
8784                .unwrap()
8785                .deployment_manifest,
8786        )
8787        .await
8788        .unwrap_err();
8789
8790        assert!(
8791            error.to_string().contains("no ingestion-time block hash"),
8792            "was: {error}"
8793        );
8794        assert!(state.recorded_requests().is_empty());
8795    }
8796
8797    #[tokio::test]
8798    async fn swap_quote_rejects_replaced_ingestion_block() {
8799        let changed = fixture_block_response(FIXTURE_BLOCK, B256::from([0x44; 32]));
8800        let state = execution_rpc_state().with_parameter_response(
8801            "eth_getBlockByNumber",
8802            "0x1cf0d40",
8803            &changed,
8804        );
8805        let (client, _) = client_with_mock_rpc(state).await;
8806        let plan = fixture_sell_plan();
8807        let position = BlockPosition::new(
8808            FIXTURE_BLOCK,
8809            FIXTURE_BLOCK_HASH.to_string(),
8810            BLOCK_SCOPED_SNAPSHOT_INDEX,
8811            BLOCK_SCOPED_SNAPSHOT_INDEX,
8812        )
8813        .with_block_hash(Some(FIXTURE_BLOCK_HASH.to_string()));
8814
8815        let error = validate_swap_quote(
8816            &position,
8817            &plan,
8818            100,
8819            &client.verification,
8820            &client
8821                .config
8822                .verification
8823                .as_ref()
8824                .unwrap()
8825                .deployment_manifest,
8826        )
8827        .await
8828        .unwrap_err();
8829
8830        assert!(error.to_string().contains("changed from"), "was: {error}");
8831    }
8832
8833    #[tokio::test]
8834    async fn swap_quote_accepts_exact_canonical_event_watermark() {
8835        let pool = test_pool();
8836        let receipt = profiler_event_receipt(pool.address);
8837        let state = execution_rpc_state().with_response("eth_getTransactionReceipt", &receipt);
8838        let (client, _) = client_with_mock_rpc(state).await;
8839        let plan = fixture_sell_plan();
8840
8841        let anchors = validate_swap_quote(
8842            &profiler_event_position(),
8843            &plan,
8844            100,
8845            &client.verification,
8846            &client
8847                .config
8848                .verification
8849                .as_ref()
8850                .unwrap()
8851                .deployment_manifest,
8852        )
8853        .await
8854        .unwrap();
8855
8856        assert_eq!(anchors.watermark.number, profiler_event_position().number);
8857        assert_eq!(anchors.state.number, FIXTURE_BLOCK);
8858        assert_eq!(anchors.state.hash, B256::from([0x11; 32]));
8859        assert_eq!(anchors.state.timestamp, FIXTURE_BLOCK_TIMESTAMP);
8860    }
8861
8862    #[tokio::test]
8863    async fn swap_quote_rejects_mismatched_receipt_position() {
8864        let pool = test_pool();
8865        let mut receipt: serde_json::Value =
8866            serde_json::from_str(&profiler_event_receipt(pool.address)).unwrap();
8867        receipt["result"]["transactionIndex"] = serde_json::json!("0x3");
8868        let state =
8869            execution_rpc_state().with_response("eth_getTransactionReceipt", &receipt.to_string());
8870        let (client, _) = client_with_mock_rpc(state).await;
8871        let plan = fixture_sell_plan();
8872
8873        let error = validate_swap_quote(
8874            &profiler_event_position(),
8875            &plan,
8876            100,
8877            &client.verification,
8878            &client
8879                .config
8880                .verification
8881                .as_ref()
8882                .unwrap()
8883                .deployment_manifest,
8884        )
8885        .await
8886        .unwrap_err();
8887
8888        assert_eq!(
8889            error.to_string(),
8890            "Profiler receipt position does not match its ingestion watermark"
8891        );
8892    }
8893
8894    #[tokio::test]
8895    async fn swap_quote_rejects_watermark_from_different_pool() {
8896        let receipt = profiler_event_receipt(ROUTER_ADDRESS);
8897        let state = execution_rpc_state().with_response("eth_getTransactionReceipt", &receipt);
8898        let (client, _) = client_with_mock_rpc(state).await;
8899        let plan = fixture_sell_plan();
8900
8901        let error = validate_swap_quote(
8902            &profiler_event_position(),
8903            &plan,
8904            100,
8905            &client.verification,
8906            &client
8907                .config
8908                .verification
8909                .as_ref()
8910                .unwrap()
8911                .deployment_manifest,
8912        )
8913        .await
8914        .unwrap_err();
8915
8916        assert!(
8917            error
8918                .to_string()
8919                .contains("did not come from expected pool"),
8920            "was: {error}"
8921        );
8922    }
8923
8924    #[rstest]
8925    fn verified_sell_quote_sets_signed_amounts() {
8926        let plan = fixture_sell_plan();
8927        let quote = UniswapV3Quote {
8928            amount: expected_sell_quote_amount(),
8929            sqrt_price_x96_after: U160::from(1u128 << 96),
8930            initialized_ticks_crossed: 0,
8931            gas_estimate: U256::from(50_000u64),
8932        };
8933
8934        let (amount_in, min_amount_out) = verified_swap_amounts(&plan, quote).unwrap();
8935
8936        assert_eq!(amount_in, U256::from(1_000_000_000_000_000u64));
8937        assert_eq!(min_amount_out, expected_min_amount_out(50));
8938    }
8939
8940    #[rstest]
8941    fn exact_output_amount_extracts_negative_leg() {
8942        let pool = test_pool();
8943        let profiler = test_profiler(&pool, FIXTURE_BLOCK);
8944        let quote = profiler
8945            .swap_exact_in(U256::from(1_000_000_000_000_000u64), true, None)
8946            .unwrap();
8947
8948        let amount = exact_output_amount(&quote, true).unwrap();
8949
8950        assert!(amount < U256::from(1_000_000_000_000_000u64));
8951        assert!(amount > U256::from(990_000_000_000_000u64));
8952
8953        let error = exact_output_amount(&quote, false).unwrap_err();
8954        assert!(
8955            error.to_string().contains("is not a positive output"),
8956            "was: {error}"
8957        );
8958    }
8959
8960    #[rstest]
8961    #[case("0xC6962004f452bE9203591991D15f6b388e09E8D0.Arbitrum:UniswapV3", true)]
8962    #[case("0xC6962004f452bE9203591991D15f6b388e09E8D0.Ethereum:UniswapV3", false)]
8963    #[case("0xC6962004f452bE9203591991D15f6b388e09E8D0.Arbitrum:UniswapV4", false)]
8964    #[case("ETHUSDT-PERP.BINANCE", false)]
8965    fn handles_order_venue_matches_chain_and_dex(#[case] instrument: &str, #[case] expected: bool) {
8966        let client = test_client("http://127.0.0.1:1".to_string());
8967        let instrument_id: InstrumentId = instrument.parse().unwrap();
8968
8969        assert_eq!(client.handles_order_venue(instrument_id.venue), expected);
8970    }
8971
8972    #[tokio::test]
8973    async fn submit_order_denies_buy_without_allowlisted_pair() {
8974        let (mut client, cache) =
8975            swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
8976        let pool = test_pool();
8977        let order = test_market_buy_order(pool.instrument_id);
8978        cache
8979            .borrow_mut()
8980            .add_order(order.clone(), None, None, true)
8981            .unwrap();
8982        let mut receiver = start_with_events(&mut client);
8983
8984        client.submit_order(submit_order_cmd(&order)).unwrap();
8985
8986        let events = collect_order_events(&mut receiver);
8987        assert_eq!(events.len(), 1);
8988        let OrderEventAny::Denied(denied) = &events[0] else {
8989            panic!("expected OrderDenied, was {:?}", events[0]);
8990        };
8991        assert!(
8992            denied
8993                .reason
8994                .contains("not in the `allowed_token_pairs` allowlist"),
8995            "was: {}",
8996            denied.reason
8997        );
8998        assert!(
8999            denied.reason.contains(&USDC_ADDRESS.to_string()),
9000            "was: {}",
9001            denied.reason
9002        );
9003    }
9004
9005    #[tokio::test]
9006    async fn submit_order_denies_buy_quote_denominated_quantity() {
9007        let (mut client, cache) =
9008            swap_client_with_cache(buy_test_config("http://127.0.0.1:1".to_string()));
9009        let pool = test_pool();
9010        let order = OrderTestBuilder::new(OrderType::Market)
9011            .trader_id(TraderId::from("TRADER-001"))
9012            .strategy_id(StrategyId::from("S-001"))
9013            .instrument_id(pool.instrument_id)
9014            .client_order_id(ClientOrderId::from("O-SWAP-BUY-001"))
9015            .side(OrderSide::Buy)
9016            .quantity(Quantity::from("0.001"))
9017            .quote_quantity(true)
9018            .build();
9019        cache
9020            .borrow_mut()
9021            .add_order(order.clone(), None, None, true)
9022            .unwrap();
9023        let mut receiver = start_with_events(&mut client);
9024
9025        client.submit_order(submit_order_cmd(&order)).unwrap();
9026
9027        let events = collect_order_events(&mut receiver);
9028        assert_eq!(events.len(), 1);
9029        let OrderEventAny::Denied(denied) = &events[0] else {
9030            panic!("expected OrderDenied, was {:?}", events[0]);
9031        };
9032
9033        assert_eq!(denied.reason.as_str(), "UNSUPPORTED_QUOTE_QUANTITY");
9034    }
9035
9036    #[tokio::test]
9037    async fn submit_order_denies_buy_amount_above_max_order_amount() {
9038        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9039        config.max_order_amount = Some(999_999_999_999_999);
9040        let (mut client, cache) = swap_client_with_cache(config);
9041        let order = test_market_buy_order(test_pool().instrument_id);
9042        cache
9043            .borrow_mut()
9044            .add_order(order.clone(), None, None, true)
9045            .unwrap();
9046        let mut receiver = start_with_events(&mut client);
9047
9048        client.submit_order(submit_order_cmd(&order)).unwrap();
9049
9050        let events = collect_order_events(&mut receiver);
9051        assert_eq!(events.len(), 1);
9052        let OrderEventAny::Denied(denied) = &events[0] else {
9053            panic!("expected OrderDenied, was {:?}", events[0]);
9054        };
9055        assert!(
9056            denied
9057                .reason
9058                .contains("exceeds the configured `max_order_amount`"),
9059            "was: {}",
9060            denied.reason
9061        );
9062    }
9063
9064    #[tokio::test]
9065    async fn submit_order_denies_buy_without_quote_spend_limit() {
9066        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9067        config.quote_spend_limits = None;
9068        let (mut client, cache) = swap_client_with_cache(config);
9069        let order = test_market_buy_order(test_pool().instrument_id);
9070        cache
9071            .borrow_mut()
9072            .add_order(order.clone(), None, None, true)
9073            .unwrap();
9074        let mut receiver = start_with_events(&mut client);
9075
9076        client.submit_order(submit_order_cmd(&order)).unwrap();
9077
9078        let events = collect_order_events(&mut receiver);
9079        assert_eq!(events.len(), 1);
9080        let OrderEventAny::Denied(denied) = &events[0] else {
9081            panic!("expected OrderDenied, was {:?}", events[0]);
9082        };
9083        assert!(
9084            denied
9085                .reason
9086                .contains("No `quote_spend_limits` entry for BUY token pair"),
9087            "was: {}",
9088            denied.reason
9089        );
9090    }
9091
9092    #[tokio::test]
9093    async fn submit_order_uses_pair_specific_quote_spend_limit() {
9094        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9095        config.quote_spend_limits = Some(vec![quote_spend_limit(
9096            WETH,
9097            USDC,
9098            18,
9099            "1000000000000000000",
9100        )]);
9101        let (mut client, cache) = swap_client_with_cache(config);
9102        let order = test_market_buy_order(test_pool().instrument_id);
9103        cache
9104            .borrow_mut()
9105            .add_order(order.clone(), None, None, true)
9106            .unwrap();
9107        let mut receiver = start_with_events(&mut client);
9108
9109        client.submit_order(submit_order_cmd(&order)).unwrap();
9110
9111        let events = collect_order_events(&mut receiver);
9112        assert_eq!(events.len(), 1);
9113        let OrderEventAny::Denied(denied) = &events[0] else {
9114            panic!("expected OrderDenied, was {:?}", events[0]);
9115        };
9116        assert!(
9117            denied
9118                .reason
9119                .contains("No `quote_spend_limits` entry for BUY token pair"),
9120            "was: {}",
9121            denied.reason
9122        );
9123    }
9124
9125    #[tokio::test]
9126    async fn submit_order_denies_buy_with_quote_spend_precision_mismatch() {
9127        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9128        config.quote_spend_limits.as_mut().unwrap()[0].spend_token_decimals = 18;
9129        let error = test_client_result(config, test_pool()).unwrap_err();
9130        assert!(
9131            error
9132                .to_string()
9133                .contains("Quote spend limit decimals do not match the deployment manifest"),
9134            "was: {error}"
9135        );
9136    }
9137
9138    #[tokio::test]
9139    async fn submit_order_denies_buy_with_zero_quote_spend_limit() {
9140        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9141        config.quote_spend_limits.as_mut().unwrap()[0].max_amount = "0".to_string();
9142        let (mut client, cache) = swap_client_with_cache(config);
9143        let order = test_market_buy_order(test_pool().instrument_id);
9144        cache
9145            .borrow_mut()
9146            .add_order(order.clone(), None, None, true)
9147            .unwrap();
9148        let mut receiver = start_with_events(&mut client);
9149
9150        client.submit_order(submit_order_cmd(&order)).unwrap();
9151
9152        let events = collect_order_events(&mut receiver);
9153        assert_eq!(events.len(), 1);
9154        let OrderEventAny::Denied(denied) = &events[0] else {
9155            panic!("expected OrderDenied, was {:?}", events[0]);
9156        };
9157        assert!(
9158            denied
9159                .reason
9160                .contains("exceeds the configured `quote_spend_limits` maximum 0"),
9161            "was: {}",
9162            denied.reason
9163        );
9164    }
9165
9166    #[tokio::test]
9167    async fn submit_order_denies_buy_one_raw_unit_above_quote_spend_limit_before_readiness() {
9168        let amount_in = expected_buy_amount_in();
9169        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9170        config.quote_spend_limits.as_mut().unwrap()[0].max_amount =
9171            (amount_in - U256::from(1u8)).to_string();
9172        let (mut client, cache) = swap_client_with_cache(config);
9173        let order = test_market_buy_order(test_pool().instrument_id);
9174        cache
9175            .borrow_mut()
9176            .add_order(order.clone(), None, None, true)
9177            .unwrap();
9178        let mut receiver = start_with_events(&mut client);
9179
9180        client.submit_order(submit_order_cmd(&order)).unwrap();
9181
9182        let events = collect_order_events(&mut receiver);
9183        assert_eq!(events.len(), 1);
9184        let OrderEventAny::Denied(denied) = &events[0] else {
9185            panic!("expected OrderDenied, was {:?}", events[0]);
9186        };
9187        assert!(
9188            denied.reason.contains(&format!(
9189                "BUY quote amount {amount_in} exceeds the configured `quote_spend_limits`"
9190            )),
9191            "was: {}",
9192            denied.reason
9193        );
9194        assert!(!client.core.is_connected());
9195        assert!(!client.cache.has_database());
9196        assert!(client.signer.is_none());
9197        assert!(client.pending_tasks.is_empty());
9198    }
9199
9200    #[tokio::test]
9201    async fn submit_order_denies_non_market_order_type() {
9202        let (mut client, cache) =
9203            swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9204        let pool = test_pool();
9205        let order = OrderTestBuilder::new(OrderType::Limit)
9206            .trader_id(TraderId::from("TRADER-001"))
9207            .strategy_id(StrategyId::from("S-001"))
9208            .instrument_id(pool.instrument_id)
9209            .client_order_id(ClientOrderId::from("O-SWAP-001"))
9210            .side(OrderSide::Sell)
9211            .quantity(Quantity::from("0.001"))
9212            .price(Price::from("2000"))
9213            .build();
9214        cache
9215            .borrow_mut()
9216            .add_order(order.clone(), None, None, true)
9217            .unwrap();
9218        let mut receiver = start_with_events(&mut client);
9219
9220        client.submit_order(submit_order_cmd(&order)).unwrap();
9221
9222        let events = collect_order_events(&mut receiver);
9223        assert_eq!(events.len(), 1);
9224        let OrderEventAny::Denied(denied) = &events[0] else {
9225            panic!("expected OrderDenied, was {:?}", events[0]);
9226        };
9227        assert!(
9228            denied.reason.contains("only Market is supported"),
9229            "was: {}",
9230            denied.reason
9231        );
9232    }
9233
9234    #[tokio::test]
9235    async fn submit_order_denies_quote_denominated_quantity() {
9236        let (mut client, cache) =
9237            swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9238        let pool = test_pool();
9239        let order = OrderTestBuilder::new(OrderType::Market)
9240            .trader_id(TraderId::from("TRADER-001"))
9241            .strategy_id(StrategyId::from("S-001"))
9242            .instrument_id(pool.instrument_id)
9243            .client_order_id(ClientOrderId::from("O-SWAP-001"))
9244            .side(OrderSide::Sell)
9245            .quantity(Quantity::from("0.001"))
9246            .quote_quantity(true)
9247            .build();
9248        cache
9249            .borrow_mut()
9250            .add_order(order.clone(), None, None, true)
9251            .unwrap();
9252        let mut receiver = start_with_events(&mut client);
9253
9254        client.submit_order(submit_order_cmd(&order)).unwrap();
9255
9256        let events = collect_order_events(&mut receiver);
9257        assert_eq!(events.len(), 1);
9258        let OrderEventAny::Denied(denied) = &events[0] else {
9259            panic!("expected OrderDenied, was {:?}", events[0]);
9260        };
9261
9262        assert_eq!(denied.reason.as_str(), "UNSUPPORTED_QUOTE_QUANTITY");
9263    }
9264
9265    #[tokio::test]
9266    async fn submit_order_denies_unknown_pool() {
9267        let (mut client, cache) =
9268            swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9269        let unknown: InstrumentId = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45.Arbitrum:UniswapV3"
9270            .parse()
9271            .unwrap();
9272        let order = OrderTestBuilder::new(OrderType::Market)
9273            .trader_id(TraderId::from("TRADER-001"))
9274            .strategy_id(StrategyId::from("S-001"))
9275            .instrument_id(unknown)
9276            .client_order_id(ClientOrderId::from("O-SWAP-001"))
9277            .side(OrderSide::Sell)
9278            .quantity(Quantity::from("0.001"))
9279            .build();
9280        cache
9281            .borrow_mut()
9282            .add_order(order.clone(), None, None, true)
9283            .unwrap();
9284        let mut receiver = start_with_events(&mut client);
9285
9286        client.submit_order(submit_order_cmd(&order)).unwrap();
9287
9288        let events = collect_order_events(&mut receiver);
9289        assert_eq!(events.len(), 1);
9290        let OrderEventAny::Denied(denied) = &events[0] else {
9291            panic!("expected OrderDenied, was {:?}", events[0]);
9292        };
9293        assert!(
9294            denied.reason.contains("Unknown pool"),
9295            "was: {}",
9296            denied.reason
9297        );
9298    }
9299
9300    #[tokio::test]
9301    async fn submit_order_denies_sell_when_only_buy_pair_allowlisted() {
9302        let mut config = test_config("http://127.0.0.1:1".to_string());
9303        config.allowed_token_pairs = Some(vec![(USDC.to_string(), WETH.to_string())]);
9304        let (mut client, _) = swap_client_with_cache(config);
9305        let order = test_market_sell_order(test_pool().instrument_id);
9306        let mut receiver = start_with_events(&mut client);
9307
9308        client.submit_order(submit_order_cmd(&order)).unwrap();
9309
9310        let events = collect_order_events(&mut receiver);
9311        assert_eq!(events.len(), 1);
9312        let OrderEventAny::Denied(denied) = &events[0] else {
9313            panic!("expected OrderDenied, was {:?}", events[0]);
9314        };
9315        assert!(
9316            denied
9317                .reason
9318                .contains("not in the `allowed_token_pairs` allowlist"),
9319            "was: {}",
9320            denied.reason
9321        );
9322        assert!(
9323            denied.reason.contains(&WETH_ADDRESS.to_string()),
9324            "was: {}",
9325            denied.reason
9326        );
9327    }
9328
9329    #[tokio::test]
9330    async fn submit_order_sell_ignores_quote_spend_limits() {
9331        let mut config = test_config("http://127.0.0.1:1".to_string());
9332        config.quote_spend_limits = Some(vec![quote_spend_limit(WETH, USDC, 18, "0")]);
9333        let (mut client, _) = swap_client_with_cache(config);
9334        let order = test_market_sell_order(test_pool().instrument_id);
9335        let mut receiver = start_with_events(&mut client);
9336
9337        client.submit_order(submit_order_cmd(&order)).unwrap();
9338
9339        let events = collect_order_events(&mut receiver);
9340        assert_eq!(events.len(), 1);
9341        let OrderEventAny::Denied(denied) = &events[0] else {
9342            panic!("expected OrderDenied, was {:?}", events[0]);
9343        };
9344        assert!(
9345            denied
9346                .reason
9347                .contains("Blockchain execution client is not connected"),
9348            "was: {}",
9349            denied.reason
9350        );
9351    }
9352
9353    #[tokio::test]
9354    async fn submit_order_denies_token_pair_outside_allowlist() {
9355        let mut config = test_config("http://127.0.0.1:1".to_string());
9356        config.allowed_token_pairs = Some(Vec::new());
9357        let (mut client, _) = swap_client_with_cache(config);
9358        let order = test_market_sell_order(test_pool().instrument_id);
9359        let mut receiver = start_with_events(&mut client);
9360
9361        client.submit_order(submit_order_cmd(&order)).unwrap();
9362
9363        let events = collect_order_events(&mut receiver);
9364        assert_eq!(events.len(), 1);
9365        let OrderEventAny::Denied(denied) = &events[0] else {
9366            panic!("expected OrderDenied, was {:?}", events[0]);
9367        };
9368        assert!(
9369            denied
9370                .reason
9371                .contains("not in the `allowed_token_pairs` allowlist"),
9372            "was: {}",
9373            denied.reason
9374        );
9375    }
9376
9377    #[tokio::test]
9378    async fn submit_order_denies_amount_above_max_order_amount() {
9379        let mut config = test_config("http://127.0.0.1:1".to_string());
9380        config.max_order_amount = Some(999_999_999_999_999); // 0.001 WETH in raw units minus one
9381        let (mut client, _) = swap_client_with_cache(config);
9382        let order = test_market_sell_order(test_pool().instrument_id);
9383        let mut receiver = start_with_events(&mut client);
9384
9385        client.submit_order(submit_order_cmd(&order)).unwrap();
9386
9387        let events = collect_order_events(&mut receiver);
9388        assert_eq!(events.len(), 1);
9389        let OrderEventAny::Denied(denied) = &events[0] else {
9390            panic!("expected OrderDenied, was {:?}", events[0]);
9391        };
9392        assert!(
9393            denied
9394                .reason
9395                .contains("exceeds the configured `max_order_amount`"),
9396            "was: {}",
9397            denied.reason
9398        );
9399    }
9400
9401    #[tokio::test]
9402    async fn submit_order_denies_slippage_param_above_ceiling() {
9403        let (mut client, _) = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9404        let order = test_market_sell_order(test_pool().instrument_id);
9405        let mut cmd = submit_order_cmd(&order);
9406        cmd.params = Some(serde_json::from_str(r#"{"slippage_bps": 201}"#).unwrap());
9407        let mut receiver = start_with_events(&mut client);
9408
9409        client.submit_order(cmd).unwrap();
9410
9411        let events = collect_order_events(&mut receiver);
9412        assert_eq!(events.len(), 1);
9413        let OrderEventAny::Denied(denied) = &events[0] else {
9414            panic!("expected OrderDenied, was {:?}", events[0]);
9415        };
9416        assert!(
9417            denied
9418                .reason
9419                .contains("exceeds the configured `max_slippage_bps`"),
9420            "was: {}",
9421            denied.reason
9422        );
9423    }
9424
9425    #[tokio::test]
9426    async fn submit_order_denies_pool_without_fee_tier() {
9427        let addr = start_mock_rpc_server(MockRpcState::default()).await;
9428        let mut pool = test_pool();
9429        pool.fee = None;
9430        let cache = Rc::new(RefCell::new(Cache::default()));
9431        cache.borrow_mut().add_pool(pool.clone()).unwrap();
9432        let order = test_market_sell_order(pool.instrument_id);
9433        cache
9434            .borrow_mut()
9435            .add_order(order.clone(), None, None, false)
9436            .unwrap();
9437        let core = ExecutionClientCore::new(
9438            TraderId::from("TRADER-001"),
9439            ClientId::from("BLOCKCHAIN-001"),
9440            *BLOCKCHAIN_VENUE,
9441            OmsType::Netting,
9442            AccountId::from("BLOCKCHAIN-001"),
9443            AccountType::Wallet,
9444            None,
9445            cache,
9446        );
9447        let mut client =
9448            BlockchainExecutionClient::new(core, test_config(format!("http://{addr}"))).unwrap();
9449        let mut receiver = start_with_events(&mut client);
9450
9451        client.submit_order(submit_order_cmd(&order)).unwrap();
9452
9453        let events = collect_order_events(&mut receiver);
9454        assert_eq!(events.len(), 1);
9455        let OrderEventAny::Denied(denied) = &events[0] else {
9456            panic!("expected OrderDenied, was {:?}", events[0]);
9457        };
9458        assert!(
9459            denied.reason.contains("no fee tier"),
9460            "was: {}",
9461            denied.reason
9462        );
9463    }
9464
9465    #[tokio::test]
9466    async fn submit_order_denies_without_live_profiler() {
9467        let addr = start_mock_rpc_server(MockRpcState::default()).await;
9468        let cache = Rc::new(RefCell::new(Cache::default()));
9469        let pool = test_pool();
9470        cache.borrow_mut().add_pool(pool.clone()).unwrap();
9471        let order = test_market_sell_order(pool.instrument_id);
9472        cache
9473            .borrow_mut()
9474            .add_order(order.clone(), None, None, false)
9475            .unwrap();
9476        let core = ExecutionClientCore::new(
9477            TraderId::from("TRADER-001"),
9478            ClientId::from("BLOCKCHAIN-001"),
9479            *BLOCKCHAIN_VENUE,
9480            OmsType::Netting,
9481            AccountId::from("BLOCKCHAIN-001"),
9482            AccountType::Wallet,
9483            None,
9484            cache,
9485        );
9486        let mut client =
9487            BlockchainExecutionClient::new(core, test_config(format!("http://{addr}"))).unwrap();
9488        let mut receiver = start_with_events(&mut client);
9489
9490        client.submit_order(submit_order_cmd(&order)).unwrap();
9491
9492        let events = collect_order_events(&mut receiver);
9493        assert_eq!(events.len(), 1);
9494        let OrderEventAny::Denied(denied) = &events[0] else {
9495            panic!("expected OrderDenied, was {:?}", events[0]);
9496        };
9497        assert!(
9498            denied.reason.contains("No pool profiler"),
9499            "was: {}",
9500            denied.reason
9501        );
9502    }
9503
9504    #[tokio::test]
9505    async fn submit_order_denies_when_not_connected() {
9506        let (mut client, _) = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9507        let order = test_market_sell_order(test_pool().instrument_id);
9508        let mut receiver = start_with_events(&mut client);
9509
9510        client.submit_order(submit_order_cmd(&order)).unwrap();
9511
9512        let events = collect_order_events(&mut receiver);
9513        assert_eq!(events.len(), 1);
9514        let OrderEventAny::Denied(denied) = &events[0] else {
9515            panic!("expected OrderDenied, was {:?}", events[0]);
9516        };
9517        assert!(
9518            denied.reason.contains("is not connected"),
9519            "was: {}",
9520            denied.reason
9521        );
9522    }
9523
9524    #[tokio::test]
9525    async fn submit_order_denies_without_durable_store() {
9526        let (mut client, _) = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9527        client.core.set_connected();
9528        let order = test_market_sell_order(test_pool().instrument_id);
9529        let mut receiver = start_with_events(&mut client);
9530
9531        client.submit_order(submit_order_cmd(&order)).unwrap();
9532
9533        let events = collect_order_events(&mut receiver);
9534        assert_eq!(events.len(), 1);
9535        let OrderEventAny::Denied(denied) = &events[0] else {
9536            panic!("expected OrderDenied, was {:?}", events[0]);
9537        };
9538        assert!(
9539            denied.reason.contains("No durable store configured"),
9540            "was: {}",
9541            denied.reason
9542        );
9543    }
9544
9545    #[tokio::test]
9546    async fn submit_order_denies_when_transaction_in_flight() {
9547        let (mut client, _) = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9548        client.core.set_connected();
9549        *client.in_flight.lock() = Some(InFlightSlot::AwaitingFinality(InFlightTransaction {
9550            intent_id: 1,
9551            nonce: 7,
9552            tx_hash: B256::ZERO,
9553            purpose: TransactionPurpose::Wrap,
9554        }));
9555        let order = test_market_sell_order(test_pool().instrument_id);
9556        let mut receiver = start_with_events(&mut client);
9557
9558        client.submit_order(submit_order_cmd(&order)).unwrap();
9559
9560        let events = collect_order_events(&mut receiver);
9561        assert_eq!(events.len(), 1);
9562        let OrderEventAny::Denied(denied) = &events[0] else {
9563            panic!("expected OrderDenied, was {:?}", events[0]);
9564        };
9565        assert!(
9566            denied.reason.contains("still awaiting finality"),
9567            "was: {}",
9568            denied.reason
9569        );
9570    }
9571
9572    #[tokio::test]
9573    async fn submit_order_denies_without_signer() {
9574        let Some((admin_pool, schema, mut client, _, _)) =
9575            swap_client_with_database("execution_submit_no_signer_test", swap_rpc_state().await)
9576                .await
9577        else {
9578            return;
9579        };
9580        client.signer = None;
9581        let order = test_market_sell_order(test_pool().instrument_id);
9582        let mut receiver = start_with_events(&mut client);
9583
9584        client.submit_order(submit_order_cmd(&order)).unwrap();
9585
9586        let events = collect_order_events(&mut receiver);
9587        assert_eq!(events.len(), 1);
9588        let OrderEventAny::Denied(denied) = &events[0] else {
9589            panic!("expected OrderDenied, was {:?}", events[0]);
9590        };
9591        assert!(
9592            denied.reason.contains("Signer not initialized"),
9593            "was: {}",
9594            denied.reason
9595        );
9596
9597        drop_execution_schema(&admin_pool, &schema).await;
9598    }
9599
9600    #[tokio::test]
9601    async fn submit_order_broadcasts_swap_and_records_client_order_id() {
9602        let Some((admin_pool, schema, mut client, state, _)) =
9603            swap_client_with_database("execution_submit_success_test", swap_rpc_state().await)
9604                .await
9605        else {
9606            return;
9607        };
9608        let order = test_market_sell_order(test_pool().instrument_id);
9609        let mut receiver = start_with_events(&mut client);
9610        let expected_min_out = expected_min_amount_out(50);
9611
9612        client.submit_order(submit_order_cmd(&order)).unwrap();
9613        await_pending_tasks(&client).await;
9614
9615        let events = collect_order_events(&mut receiver);
9616        assert_swap_submitted_and_filled(&events);
9617        let OrderEventAny::Submitted(submitted) = &events[0] else {
9618            panic!("expected OrderSubmitted, was {:?}", events[0]);
9619        };
9620        assert_eq!(submitted.client_order_id, order.client_order_id());
9621
9622        // The recorded broadcast matches the fully signed expected transaction
9623        let (expected_hash, expected_raw) = expected_swap_tx(expected_min_out).await;
9624        let broadcasts: Vec<_> = state
9625            .recorded_requests()
9626            .into_iter()
9627            .filter(|request| request["method"] == "eth_sendRawTransaction")
9628            .collect();
9629        assert_eq!(broadcasts.len(), 1);
9630        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
9631
9632        let record = client
9633            .cache
9634            .get_execution_transaction(42161, &expected_hash.to_string())
9635            .await
9636            .unwrap()
9637            .unwrap();
9638        assert_eq!(record.nonce, 7);
9639        assert_eq!(record.purpose, "swap");
9640        assert_eq!(record.status, "finalized");
9641        assert_eq!(
9642            record.client_order_id.as_deref(),
9643            Some(order.client_order_id().as_str())
9644        );
9645        assert!(client.in_flight.lock().is_none());
9646        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
9647            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
9648        )))
9649        .fetch_one(&admin_pool)
9650        .await
9651        .unwrap();
9652        let decision_count = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
9653            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
9654             WHERE outcome = 'verified'"
9655        )))
9656        .fetch_one(&admin_pool)
9657        .await
9658        .unwrap();
9659        let connect_decision_count = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
9660            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
9661                 WHERE decision_class = 'connect' AND outcome = 'verified'"
9662        )))
9663        .fetch_one(&admin_pool)
9664        .await
9665        .unwrap();
9666        assert_eq!(nonce_state, (8, 1));
9667        assert_eq!(decision_count, 35);
9668        assert_eq!(connect_decision_count, 1);
9669
9670        drop_execution_schema(&admin_pool, &schema).await;
9671    }
9672
9673    #[tokio::test]
9674    async fn submit_order_pins_every_pre_sign_state_read_to_swap_anchor() {
9675        let Some((admin_pool, schema, mut client, state, _)) =
9676            swap_client_with_database("execution_submit_anchor_reads_test", swap_rpc_state().await)
9677                .await
9678        else {
9679            return;
9680        };
9681        let order = test_market_sell_order(test_pool().instrument_id);
9682        let mut receiver = start_with_events(&mut client);
9683
9684        client.submit_order(submit_order_cmd(&order)).unwrap();
9685        await_pending_tasks(&client).await;
9686
9687        let events = collect_order_events(&mut receiver);
9688        assert_swap_submitted_and_filled(&events);
9689        let requests = state.recorded_requests();
9690        let broadcast_index = requests
9691            .iter()
9692            .position(|request| request["method"] == "eth_sendRawTransaction")
9693            .unwrap();
9694        let pre_broadcast = &requests[..broadcast_index];
9695        let latest_reads: Vec<_> = pre_broadcast
9696            .iter()
9697            .filter(|request| {
9698                request["method"] == "eth_getBlockByNumber" && request["params"][0] == "latest"
9699            })
9700            .collect();
9701        assert_eq!(latest_reads.len(), 3);
9702        assert!(
9703            latest_reads
9704                .iter()
9705                .all(|request| request["params"] == serde_json::json!(["latest", false]))
9706        );
9707
9708        for method in [
9709            "eth_getCode",
9710            "eth_call",
9711            "eth_estimateGas",
9712            "eth_getBalance",
9713        ] {
9714            let pinned: Vec<_> = pre_broadcast
9715                .iter()
9716                .filter(|request| request["method"] == method)
9717                .collect();
9718            assert!(!pinned.is_empty(), "method {method}");
9719            assert_eq!(pinned.len() % 3, 0, "method {method}: {pinned:?}");
9720            assert!(
9721                pinned
9722                    .iter()
9723                    .all(|request| request["params"][1] == FIXTURE_BLOCK_PARAM),
9724                "method {method}: {pinned:?}"
9725            );
9726        }
9727
9728        let numbered_blocks: Vec<_> = pre_broadcast
9729            .iter()
9730            .filter(|request| {
9731                request["method"] == "eth_getBlockByNumber"
9732                    && request["params"][0] == FIXTURE_BLOCK_PARAM
9733            })
9734            .collect();
9735        assert!(!numbered_blocks.is_empty());
9736        assert_eq!(numbered_blocks.len() % 3, 0);
9737        assert!(
9738            numbered_blocks
9739                .iter()
9740                .all(|request| request["params"][1] == false)
9741        );
9742
9743        let chain_ids: Vec<_> = pre_broadcast
9744            .iter()
9745            .filter(|request| request["method"] == "eth_chainId")
9746            .collect();
9747        assert_eq!(chain_ids.len(), 3);
9748        assert!(
9749            chain_ids
9750                .iter()
9751                .all(|request| request["params"] == serde_json::json!([]))
9752        );
9753        let nonces: Vec<_> = pre_broadcast
9754            .iter()
9755            .filter(|request| request["method"] == "eth_getTransactionCount")
9756            .collect();
9757        assert_eq!(nonces.len(), 6);
9758        assert_eq!(
9759            nonces
9760                .iter()
9761                .filter(|request| {
9762                    request["params"] == serde_json::json!([WALLET.to_ascii_lowercase(), "pending"])
9763                })
9764                .count(),
9765            3
9766        );
9767        assert_eq!(
9768            nonces
9769                .iter()
9770                .filter(|request| {
9771                    request["params"]
9772                        == serde_json::json!([WALLET.to_ascii_lowercase(), FIXTURE_BLOCK_PARAM])
9773                })
9774                .count(),
9775            3
9776        );
9777        let priority_fees: Vec<_> = pre_broadcast
9778            .iter()
9779            .filter(|request| request["method"] == "eth_maxPriorityFeePerGas")
9780            .collect();
9781        assert_eq!(priority_fees.len(), 3);
9782        assert!(
9783            priority_fees
9784                .iter()
9785                .all(|request| request["params"] == serde_json::json!([]))
9786        );
9787
9788        let (_, expected_raw) = expected_swap_tx(expected_min_amount_out(50)).await;
9789        assert_eq!(
9790            requests[broadcast_index]["params"][0].as_str().unwrap(),
9791            expected_raw
9792        );
9793        let created_block: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
9794            "SELECT created_block FROM {schema}.execution_intent"
9795        )))
9796        .fetch_one(&admin_pool)
9797        .await
9798        .unwrap();
9799        assert_eq!(created_block, i64::try_from(FIXTURE_BLOCK).unwrap());
9800
9801        drop_execution_schema(&admin_pool, &schema).await;
9802    }
9803
9804    #[tokio::test]
9805    async fn submit_order_denies_changed_swap_anchor_before_signing() {
9806        let canonical = fixture_block_response(FIXTURE_BLOCK, B256::from([0x11; 32]));
9807        let changed = fixture_block_response(FIXTURE_BLOCK, B256::from([0x44; 32]));
9808        let state = swap_rpc_state().await.with_parameter_response_sequence(
9809            "eth_getBlockByNumber",
9810            FIXTURE_BLOCK_PARAM,
9811            &[
9812                &canonical, &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9813                &canonical, &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9814                &canonical, &changed, &changed, &changed,
9815            ],
9816        );
9817        let Some((admin_pool, schema, mut client, state, _)) =
9818            swap_client_with_database("execution_submit_anchor_change_test", state).await
9819        else {
9820            return;
9821        };
9822        let order = test_market_sell_order(test_pool().instrument_id);
9823        let mut receiver = start_with_events(&mut client);
9824
9825        client.submit_order(submit_order_cmd(&order)).unwrap();
9826        await_pending_tasks(&client).await;
9827
9828        let events = collect_order_events(&mut receiver);
9829        assert_eq!(events.len(), 1, "was: {events:?}");
9830        let OrderEventAny::Denied(denied) = &events[0] else {
9831            panic!("expected OrderDenied, was {:?}", events[0]);
9832        };
9833        assert!(
9834            denied
9835                .reason
9836                .contains("pre-sign checkpoint reread verification disagreed"),
9837            "was: {}",
9838            denied.reason
9839        );
9840        assert_eq!(
9841            execution_intent_markers(&admin_pool, &schema).await,
9842            vec![("swap".into(), "recoverable".into(), false, false)]
9843        );
9844        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
9845            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
9846        )))
9847        .fetch_one(&admin_pool)
9848        .await
9849        .unwrap();
9850        assert_eq!(signed_count, 0);
9851        assert!(
9852            state
9853                .recorded_requests()
9854                .iter()
9855                .all(|request| { request["method"] != "eth_sendRawTransaction" })
9856        );
9857        assert!(client.in_flight.lock().is_none());
9858
9859        drop_execution_schema(&admin_pool, &schema).await;
9860    }
9861
9862    #[tokio::test]
9863    async fn submit_order_keeps_verified_swap_anchor_when_latest_advances() {
9864        let canonical = fixture_block_response(FIXTURE_BLOCK, B256::from([0x11; 32]));
9865        let newer = fixture_block_response(FIXTURE_BLOCK + 1, B256::from([0x44; 32]));
9866        let state = swap_rpc_state().await.with_parameter_response_sequence(
9867            "eth_getBlockByNumber",
9868            "latest",
9869            &[&canonical, &canonical, &canonical, &newer, &newer, &newer],
9870        );
9871        let Some((admin_pool, schema, mut client, state, _)) =
9872            swap_client_with_database("execution_submit_advancing_head_test", state).await
9873        else {
9874            return;
9875        };
9876        let order = test_market_sell_order(test_pool().instrument_id);
9877        let mut receiver = start_with_events(&mut client);
9878
9879        client.submit_order(submit_order_cmd(&order)).unwrap();
9880        await_pending_tasks(&client).await;
9881
9882        let events = collect_order_events(&mut receiver);
9883        assert_swap_submitted_and_filled(&events);
9884        let latest_reads = state
9885            .recorded_requests()
9886            .iter()
9887            .filter(|request| {
9888                request["method"] == "eth_getBlockByNumber" && request["params"][0] == "latest"
9889            })
9890            .count();
9891        assert_eq!(latest_reads, 3);
9892
9893        drop_execution_schema(&admin_pool, &schema).await;
9894    }
9895
9896    #[tokio::test]
9897    async fn submit_order_denies_changed_quote_watermark_before_signing() {
9898        let watermark_number = FIXTURE_BLOCK;
9899        let watermark_hash = B256::from([0x11; 32]);
9900        let canonical = fixture_block_response(watermark_number, watermark_hash);
9901        let changed = fixture_block_response(watermark_number, B256::from([0x66; 32]));
9902        let watermark_param = format!("0x{watermark_number:x}");
9903        let min_amount_out = expected_min_amount_out(50);
9904        let (tx_hash, _) = expected_swap_tx(min_amount_out).await;
9905        let head = finalized_swap_block(tx_hash, min_amount_out);
9906        let state = swap_rpc_state()
9907            .await
9908            .with_response("eth_getBlockByNumber", &head)
9909            .with_parameter_response_sequence(
9910                "eth_getBlockByNumber",
9911                &watermark_param,
9912                &[
9913                    &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9914                    &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9915                    &changed, &changed, &changed,
9916                ],
9917            );
9918        let Some((admin_pool, schema, mut client, state, cache)) =
9919            swap_client_with_database("execution_submit_watermark_change_test", state).await
9920        else {
9921            return;
9922        };
9923        let pool = test_pool();
9924        cache
9925            .borrow_mut()
9926            .add_pool_profiler(test_profiler_at_block(
9927                &pool,
9928                watermark_number,
9929                &watermark_hash.to_string(),
9930            ))
9931            .unwrap();
9932        let order = test_market_sell_order(pool.instrument_id);
9933        let mut receiver = start_with_events(&mut client);
9934
9935        client.submit_order(submit_order_cmd(&order)).unwrap();
9936        await_pending_tasks(&client).await;
9937
9938        let events = collect_order_events(&mut receiver);
9939        assert_eq!(events.len(), 1, "was: {events:?}");
9940        let OrderEventAny::Denied(denied) = &events[0] else {
9941            panic!("expected OrderDenied, was {:?}", events[0]);
9942        };
9943        assert!(
9944            denied.reason.contains("changed before signing"),
9945            "was: {}",
9946            denied.reason
9947        );
9948        assert_eq!(
9949            execution_intent_markers(&admin_pool, &schema).await,
9950            vec![("swap".into(), "recoverable".into(), false, false)]
9951        );
9952        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
9953            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
9954        )))
9955        .fetch_one(&admin_pool)
9956        .await
9957        .unwrap();
9958        assert_eq!(signed_count, 0);
9959        assert!(
9960            state
9961                .recorded_requests()
9962                .iter()
9963                .all(|request| { request["method"] != "eth_sendRawTransaction" })
9964        );
9965        assert!(client.in_flight.lock().is_none());
9966
9967        drop_execution_schema(&admin_pool, &schema).await;
9968    }
9969
9970    #[tokio::test]
9971    async fn changed_swap_anchor_retains_ownership_when_recovery_commit_fails() {
9972        let canonical = fixture_block_response(FIXTURE_BLOCK, B256::from([0x11; 32]));
9973        let changed = fixture_block_response(FIXTURE_BLOCK, B256::from([0x44; 32]));
9974        let state = swap_rpc_state().await.with_parameter_response_sequence(
9975            "eth_getBlockByNumber",
9976            FIXTURE_BLOCK_PARAM,
9977            &[
9978                &canonical, &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9979                &canonical, &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9980                &canonical, &changed, &changed, &changed,
9981            ],
9982        );
9983        let Some((admin_pool, schema, mut client, state, _)) =
9984            swap_client_with_database("execution_submit_anchor_recovery_fail_test", state).await
9985        else {
9986            return;
9987        };
9988        install_recoverable_commit_rejection(&admin_pool, &schema).await;
9989        let order = test_market_sell_order(test_pool().instrument_id);
9990        let mut receiver = start_with_events(&mut client);
9991
9992        client.submit_order(submit_order_cmd(&order)).unwrap();
9993        await_pending_tasks(&client).await;
9994
9995        let events = collect_order_events(&mut receiver);
9996        assert_eq!(events.len(), 1, "was: {events:?}");
9997        let OrderEventAny::Denied(denied) = &events[0] else {
9998            panic!("expected OrderDenied, was {:?}", events[0]);
9999        };
10000        assert!(
10001            denied
10002                .reason
10003                .contains("pre-sign checkpoint reread verification disagreed"),
10004            "was: {}",
10005            denied.reason
10006        );
10007        assert_eq!(
10008            execution_intent_markers(&admin_pool, &schema).await,
10009            vec![("swap".into(), "prepared".into(), false, true)]
10010        );
10011        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
10012            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
10013        )))
10014        .fetch_one(&admin_pool)
10015        .await
10016        .unwrap();
10017        assert_eq!(signed_count, 0);
10018        assert!(
10019            state
10020                .recorded_requests()
10021                .iter()
10022                .all(|request| { request["method"] != "eth_sendRawTransaction" })
10023        );
10024        assert!(matches!(
10025            *client.in_flight.lock(),
10026            Some(InFlightSlot::Preparing(TransactionPurpose::Swap))
10027        ));
10028
10029        drop_execution_schema(&admin_pool, &schema).await;
10030    }
10031
10032    #[rstest]
10033    #[case::filled("execution_inflight_finality_fill_test", false)]
10034    #[case::reverted("execution_inflight_finality_revert_test", true)]
10035    #[tokio::test]
10036    async fn swap_awaiting_finality_survives_inflight_exhaustion(
10037        #[case] test_name: &str,
10038        #[case] reverted: bool,
10039    ) {
10040        let min_amount_out = expected_min_amount_out(50);
10041        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10042
10043        let state = if reverted {
10044            let block = finalized_swap_block(expected_hash, min_amount_out);
10045            let receipt = receipt_with_transaction_hash(RECEIPT_REVERTED, expected_hash);
10046            with_finalized_identity(
10047                swap_rpc_state()
10048                    .await
10049                    .with_response("eth_getTransactionReceipt", &receipt),
10050                &block,
10051                &receipt,
10052            )
10053        } else {
10054            finalized_swap_rpc_state(expected_hash, min_amount_out)
10055        };
10056
10057        let Some((admin_pool, schema, mut client, _state, cache)) =
10058            swap_client_with_database(test_name, state).await
10059        else {
10060            return;
10061        };
10062
10063        let order = test_market_sell_order(test_pool().instrument_id);
10064        let client_order_id = order.client_order_id();
10065        let mut receiver = start_with_events(&mut client);
10066
10067        let plan = client
10068            .prepare_swap(&submit_order_cmd(&order), &order)
10069            .unwrap();
10070        execute_swap(
10071            plan,
10072            client.transaction_executor().unwrap(),
10073            client.emitter.clone(),
10074            client.transaction_limits.max_quote_age_blocks,
10075            client.transaction_limits.deadline_seconds,
10076        )
10077        .await
10078        .unwrap();
10079        let swap_events = collect_order_events(&mut receiver);
10080        assert_eq!(swap_events.len(), 2, "was: {swap_events:?}");
10081        assert!(matches!(&swap_events[0], OrderEventAny::Submitted(_)));
10082
10083        let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
10084        let config = ExecutionManagerConfig::default();
10085        let max_retries = config.inflight_max_retries;
10086        let mut manager = ExecutionManager::new(clock, Rc::clone(&cache), config).unwrap();
10087
10088        // The open-order check registers the client's retention requirement, as LiveNode does
10089        assert!(manager.check_open_orders(&[&client]).await.is_empty());
10090        cache.borrow_mut().update_order(&swap_events[0]).unwrap();
10091        tokio::time::pause();
10092        manager.register_submission(order.init_event(), Some(client.client_id()));
10093
10094        // Hold the finality outcome until well past the default in-flight budget
10095        let mut inflight_events = Vec::new();
10096        let mut queries_sent = 0;
10097
10098        for _ in 0..60 {
10099            tokio::time::advance(Duration::from_secs(1)).await;
10100            let result = manager.check_inflight_orders();
10101            inflight_events.extend(result.events);
10102
10103            for query in result.queries {
10104                let TradingCommand::QueryOrder(query) = query else {
10105                    panic!("expected QueryOrder, was {query:?}");
10106                };
10107
10108                client.query_order(query).unwrap();
10109                queries_sent += 1;
10110            }
10111        }
10112
10113        let exhaustions = manager.take_submission_recovery_exhaustions();
10114        let status_before_finality = cache.borrow().order(&client_order_id).unwrap().status();
10115        cache.borrow_mut().update_order(&swap_events[1]).unwrap();
10116        tokio::time::resume();
10117        drop_execution_schema(&admin_pool, &schema).await;
10118
10119        assert!(inflight_events.is_empty(), "was: {inflight_events:?}");
10120        assert_eq!(queries_sent, max_retries - 1);
10121        assert!(collect_order_events(&mut receiver).is_empty());
10122        assert_eq!(
10123            exhaustions,
10124            vec![SubmissionRecoveryExhausted {
10125                trader_id: order.trader_id(),
10126                client_id: Some(client.client_id()),
10127                strategy_id: order.strategy_id(),
10128                instrument_id: order.instrument_id(),
10129                client_order_id,
10130                source: SubmissionRecoverySource::Inflight,
10131                retry_count: max_retries,
10132                ts_event: UnixNanos::default(),
10133            }]
10134        );
10135        assert_eq!(status_before_finality, OrderStatus::Submitted);
10136        let cache = cache.borrow();
10137        let resolved = cache.order(&client_order_id).unwrap();
10138
10139        if reverted {
10140            let OrderEventAny::Rejected(rejected) = &swap_events[1] else {
10141                panic!("expected OrderRejected, was {:?}", swap_events[1]);
10142            };
10143
10144            assert_eq!(
10145                rejected.reason.as_str(),
10146                format!("Transaction {expected_hash} reverted on-chain")
10147            );
10148            assert!(!rejected.reconciliation);
10149            assert_eq!(resolved.status(), OrderStatus::Rejected);
10150            assert_eq!(
10151                resolved.filled_qty(),
10152                Quantity::zero(order.quantity().precision)
10153            );
10154        } else {
10155            assert!(matches!(&swap_events[1], OrderEventAny::Filled(_)));
10156            assert_eq!(resolved.status(), OrderStatus::Filled);
10157            assert_eq!(resolved.filled_qty(), order.quantity());
10158        }
10159    }
10160
10161    #[tokio::test]
10162    async fn finalized_swap_emits_exact_fill_once_and_refreshes_wallet() {
10163        let min_amount_out = expected_min_amount_out(50);
10164        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10165        let state = finalized_swap_rpc_state(expected_hash, min_amount_out);
10166        let Some((admin_pool, schema, mut client, state, _)) =
10167            swap_client_with_database("execution_submit_fill_test", state).await
10168        else {
10169            return;
10170        };
10171        let order = test_market_sell_order(test_pool().instrument_id);
10172        let mut receiver = start_with_events(&mut client);
10173
10174        let plan = client
10175            .prepare_swap(&submit_order_cmd(&order), &order)
10176            .unwrap();
10177        execute_swap(
10178            plan,
10179            client.transaction_executor().unwrap(),
10180            client.emitter.clone(),
10181            client.transaction_limits.max_quote_age_blocks,
10182            client.transaction_limits.deadline_seconds,
10183        )
10184        .await
10185        .unwrap();
10186
10187        let (nonce, wallet_address, transaction_to, transaction_input, transaction_value): (
10188            i64,
10189            String,
10190            String,
10191            String,
10192            String,
10193        ) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10194            "SELECT nonce, wallet_address, transaction_to, transaction_input, transaction_value \
10195             FROM {schema}.execution_intent"
10196        )))
10197        .fetch_one(&admin_pool)
10198        .await
10199        .unwrap();
10200        let finalized_block = client
10201            .http_rpc_client
10202            .block_by_number(FIXTURE_BLOCK + 1, true)
10203            .await
10204            .unwrap();
10205        let finalized_transaction = finalized_block
10206            .transactions
10207            .iter()
10208            .find(|transaction| transaction.hash == expected_hash)
10209            .unwrap();
10210        assert_eq!(finalized_transaction.from.to_string(), wallet_address);
10211        assert_eq!(finalized_transaction.nonce, u64::try_from(nonce).unwrap());
10212        assert_eq!(
10213            finalized_transaction.to,
10214            Some(Address::from_str(&transaction_to).unwrap())
10215        );
10216        assert_eq!(
10217            finalized_transaction.input.as_ref(),
10218            hex::decode(transaction_input.strip_prefix("0x").unwrap()).unwrap()
10219        );
10220        assert_eq!(
10221            finalized_transaction.value,
10222            U256::from_str(&transaction_value).unwrap()
10223        );
10224
10225        let mut order_events = Vec::new();
10226        let mut account_states = Vec::new();
10227
10228        while let Ok(event) = receiver.try_recv() {
10229            match event {
10230                ExecutionEvent::Order(event) => order_events.push(event),
10231                ExecutionEvent::Account(state) => account_states.push(state),
10232                other => panic!("unexpected execution event: {other:?}"),
10233            }
10234        }
10235        assert_eq!(order_events.len(), 2, "was: {order_events:?}");
10236        assert!(matches!(&order_events[0], OrderEventAny::Submitted(_)));
10237        let OrderEventAny::Filled(fill) = &order_events[1] else {
10238            panic!("expected OrderFilled, was {:?}", order_events[1]);
10239        };
10240        let expected_commission = Money::from_u256(
10241            U256::from(50_112_u64) * U256::from(100_000_000_u64),
10242            test_pool().chain.native_currency(),
10243        )
10244        .unwrap();
10245        assert_eq!(fill.client_order_id, order.client_order_id());
10246        assert_eq!(fill.venue_order_id.as_str(), expected_hash.to_string());
10247        assert_eq!(fill.order_side, OrderSide::Sell);
10248        assert_eq!(fill.last_qty, Quantity::from("0.001"));
10249        assert_eq!(fill.last_px, Price::from("1000"));
10250        assert_eq!(fill.currency.code, "USDC@ARBITRUM");
10251        assert_eq!(fill.commission, Some(expected_commission));
10252        assert_eq!(fill.liquidity_side, LiquiditySide::Taker);
10253        assert_eq!(account_states.len(), 1);
10254        let account_state = &account_states[0];
10255        assert_eq!(account_state.account_id, AccountId::from("BLOCKCHAIN-001"));
10256        assert_eq!(account_state.account_type, AccountType::Wallet);
10257        assert_eq!(account_state.base_currency, None);
10258        assert_eq!(account_state.balances.len(), 3);
10259        assert!(account_state.margins.is_empty());
10260        assert!(account_state.is_reported);
10261        assert_eq!(
10262            account_state.balances,
10263            client.wallet_balance.lock().as_account_balances().unwrap()
10264        );
10265
10266        let (fill_emitted, active): (bool, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10267            "SELECT fill_emitted, active FROM {schema}.execution_intent"
10268        )))
10269        .fetch_one(&admin_pool)
10270        .await
10271        .unwrap();
10272        assert!(fill_emitted);
10273        assert!(!active);
10274
10275        let database = client.cache.database.as_ref().unwrap().clone();
10276        let payload_keys = client.payload_keys.clone();
10277        let restart_config = client.config.clone();
10278        drop(client);
10279        let (mut restarted, _) = swap_client_with_cache(restart_config);
10280        restarted.cache.database = Some(database);
10281        restarted.payload_keys = payload_keys;
10282        restarted.signer = Some(Arc::new(
10283            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
10284        ));
10285        let mut restart_receiver = start_with_events(&mut restarted);
10286        restarted.reconcile_unresolved_execution().await.unwrap();
10287        restarted.reconcile_unresolved_execution().await.unwrap();
10288        assert!(collect_order_events(&mut restart_receiver).is_empty());
10289        let requests = state.recorded_requests();
10290        assert_eq!(
10291            requests
10292                .iter()
10293                .filter(|request| request["method"] == "eth_sendRawTransaction")
10294                .count(),
10295            1
10296        );
10297        assert_eq!(
10298            requests
10299                .iter()
10300                .filter(|request| {
10301                    request["method"] == "eth_call"
10302                        && request["params"][0]["data"]
10303                            .as_str()
10304                            .is_some_and(|data| data.starts_with(BALANCE_OF_SELECTOR))
10305                })
10306                .count(),
10307            9
10308        );
10309        assert_eq!(
10310            requests
10311                .iter()
10312                .filter(|request| request["method"] == "eth_getBalance")
10313                .count(),
10314            6
10315        );
10316
10317        drop_execution_schema(&admin_pool, &schema).await;
10318    }
10319
10320    #[tokio::test]
10321    async fn restart_emits_committed_swap_from_verified_inclusion_header() {
10322        let min_amount_out = expected_min_amount_out(50);
10323        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10324        let state = finalized_swap_rpc_state(expected_hash, min_amount_out);
10325        let Some((admin_pool, schema, mut client, _, _)) =
10326            swap_client_with_database("execution_committed_fill_restart_test", state).await
10327        else {
10328            return;
10329        };
10330        let order = test_market_sell_order(test_pool().instrument_id);
10331        let mut receiver = start_with_events(&mut client);
10332        let plan = client
10333            .prepare_swap(&submit_order_cmd(&order), &order)
10334            .unwrap();
10335
10336        execute_swap(
10337            plan,
10338            client.transaction_executor().unwrap(),
10339            client.emitter.clone(),
10340            client.transaction_limits.max_quote_age_blocks,
10341            client.transaction_limits.deadline_seconds,
10342        )
10343        .await
10344        .unwrap();
10345        assert_swap_submitted_and_filled(&collect_order_events(&mut receiver));
10346        let ancestry_range: (i64, i64) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10347            "SELECT height_start, height_end FROM {schema}.execution_verification_decision \
10348             WHERE decision_class = 'finality' AND read_class = 'numbered_block' \
10349               AND height_end > height_start"
10350        )))
10351        .fetch_one(&admin_pool)
10352        .await
10353        .unwrap();
10354        assert_eq!(
10355            ancestry_range,
10356            ((FIXTURE_BLOCK + 1) as i64, (FIXTURE_BLOCK + 2) as i64)
10357        );
10358
10359        sqlx::query(sqlx::AssertSqlSafe(format!(
10360            "UPDATE {schema}.execution_intent SET fill_emitted = FALSE, active = TRUE"
10361        )))
10362        .execute(&admin_pool)
10363        .await
10364        .unwrap();
10365        let database = client.cache.database.as_ref().unwrap().clone();
10366        let payload_keys = client.payload_keys.clone();
10367        let restart_config = client.config.clone();
10368        drop(client);
10369        let (mut restarted, _) = swap_client_with_cache(restart_config);
10370        restarted.cache.database = Some(database);
10371        restarted.payload_keys = payload_keys;
10372        restarted.signer = Some(Arc::new(
10373            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
10374        ));
10375        let mut restart_receiver = start_with_events(&mut restarted);
10376
10377        restarted.reconcile_unresolved_execution().await.unwrap();
10378
10379        let events = collect_order_events(&mut restart_receiver);
10380        let (fill_emitted, active): (bool, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10381            "SELECT fill_emitted, active FROM {schema}.execution_intent"
10382        )))
10383        .fetch_one(&admin_pool)
10384        .await
10385        .unwrap();
10386        assert_eq!(events.len(), 1, "was: {events:?}");
10387        assert!(matches!(&events[0], OrderEventAny::Filled(_)));
10388        assert!(fill_emitted);
10389        assert!(!active);
10390
10391        drop_execution_schema(&admin_pool, &schema).await;
10392    }
10393
10394    #[tokio::test]
10395    async fn finalized_swap_ignores_unrelated_swap_logs() {
10396        let min_amount_out = expected_min_amount_out(50);
10397        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10398        let receipt = finalized_swap_receipt_with_unrelated_swap(expected_hash);
10399        let state = finalized_swap_rpc_state(expected_hash, min_amount_out)
10400            .with_response("eth_getTransactionReceipt", &receipt);
10401        let Some((admin_pool, schema, mut client, _, _)) =
10402            swap_client_with_database("execution_submit_unrelated_log_test", state).await
10403        else {
10404            return;
10405        };
10406        let order = test_market_sell_order(test_pool().instrument_id);
10407        let mut receiver = start_with_events(&mut client);
10408
10409        client.submit_order(submit_order_cmd(&order)).unwrap();
10410        await_pending_tasks(&client).await;
10411
10412        let events = collect_order_events(&mut receiver);
10413        assert_swap_submitted_and_filled(&events);
10414
10415        drop_execution_schema(&admin_pool, &schema).await;
10416    }
10417
10418    #[tokio::test]
10419    async fn prepare_swap_buy_accepts_quote_spend_exact_boundary() {
10420        let amount_in = expected_buy_amount_in();
10421        let min_amount_out = expected_buy_min_amount_out(50);
10422        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10423        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10424        let max_amount = amount_in.to_string();
10425        let Some((admin_pool, schema, client, _, cache)) = swap_client_with_database_config(
10426            "execution_prepare_buy_test",
10427            state,
10428            move |http_rpc_url| {
10429                let mut config = buy_test_config(http_rpc_url);
10430                config.quote_spend_limits.as_mut().unwrap()[0].max_amount = max_amount;
10431                config
10432            },
10433        )
10434        .await
10435        else {
10436            return;
10437        };
10438        let order = test_market_buy_order(test_pool().instrument_id);
10439        cache
10440            .borrow_mut()
10441            .add_order(order.clone(), None, None, true)
10442            .unwrap();
10443
10444        let plan = client
10445            .prepare_swap(&submit_order_cmd(&order), &order)
10446            .unwrap();
10447
10448        assert_eq!(plan.token_in, USDC_ADDRESS);
10449        assert_eq!(plan.token_out, WETH_ADDRESS);
10450        assert_eq!(plan.amount_in, amount_in);
10451        assert_eq!(plan.min_amount_out, min_amount_out);
10452        assert_ne!(plan.token_in, WETH_ADDRESS);
10453
10454        drop_execution_schema(&admin_pool, &schema).await;
10455    }
10456
10457    #[tokio::test]
10458    async fn submit_order_broadcasts_buy_swap() {
10459        let amount_in = expected_buy_amount_in();
10460        let min_amount_out = expected_buy_min_amount_out(50);
10461        let (expected_hash, expected_raw) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10462        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10463        let Some((admin_pool, schema, mut client, state, cache)) =
10464            swap_client_with_buy_database("execution_submit_buy_success_test", state).await
10465        else {
10466            return;
10467        };
10468        let order = test_market_buy_order(test_pool().instrument_id);
10469        cache
10470            .borrow_mut()
10471            .add_order(order.clone(), None, None, true)
10472            .unwrap();
10473        let mut receiver = start_with_events(&mut client);
10474
10475        client.submit_order(submit_order_cmd(&order)).unwrap();
10476        await_pending_tasks(&client).await;
10477
10478        let events = collect_order_events(&mut receiver);
10479        assert_swap_submitted_and_filled(&events);
10480        let broadcasts: Vec<_> = state
10481            .recorded_requests()
10482            .into_iter()
10483            .filter(|request| request["method"] == "eth_sendRawTransaction")
10484            .collect();
10485        assert_eq!(broadcasts.len(), 1);
10486        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
10487
10488        drop_execution_schema(&admin_pool, &schema).await;
10489    }
10490
10491    #[tokio::test]
10492    async fn finalized_buy_swap_emits_fill_from_output_leg() {
10493        let amount_in = expected_buy_amount_in();
10494        let min_amount_out = expected_buy_min_amount_out(50);
10495        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10496        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10497        let Some((admin_pool, schema, mut client, state, cache)) =
10498            swap_client_with_buy_database("execution_submit_buy_fill_test", state).await
10499        else {
10500            return;
10501        };
10502        let order = test_market_buy_order(test_pool().instrument_id);
10503        cache
10504            .borrow_mut()
10505            .add_order(order.clone(), None, None, true)
10506            .unwrap();
10507        let mut receiver = start_with_events(&mut client);
10508        let plan = client
10509            .prepare_swap(&submit_order_cmd(&order), &order)
10510            .unwrap();
10511
10512        execute_swap(
10513            plan,
10514            client.transaction_executor().unwrap(),
10515            client.emitter.clone(),
10516            client.transaction_limits.max_quote_age_blocks,
10517            client.transaction_limits.deadline_seconds,
10518        )
10519        .await
10520        .unwrap();
10521
10522        let mut order_events = Vec::new();
10523
10524        while let Ok(event) = receiver.try_recv() {
10525            if let ExecutionEvent::Order(event) = event {
10526                order_events.push(event);
10527            }
10528        }
10529        assert_eq!(order_events.len(), 2, "was: {order_events:?}");
10530        assert!(matches!(&order_events[0], OrderEventAny::Submitted(_)));
10531        let OrderEventAny::Filled(fill) = &order_events[1] else {
10532            panic!("expected OrderFilled, was {:?}", order_events[1]);
10533        };
10534        let expected_commission = Money::from_u256(
10535            U256::from(50_112_u64) * U256::from(100_000_000_u64),
10536            test_pool().chain.native_currency(),
10537        )
10538        .unwrap();
10539        assert_eq!(fill.client_order_id, order.client_order_id());
10540        assert_eq!(fill.venue_order_id.as_str(), expected_hash.to_string());
10541        assert_eq!(fill.order_side, OrderSide::Buy);
10542        assert_eq!(fill.last_qty, Quantity::from("0.001"));
10543        assert_eq!(fill.currency.code, "USDC@ARBITRUM");
10544        assert_eq!(fill.commission, Some(expected_commission));
10545        assert_eq!(fill.liquidity_side, LiquiditySide::Taker);
10546        assert_eq!(
10547            Money::from_decimal(
10548                fill.last_qty.as_decimal() * fill.last_px.as_decimal(),
10549                fill.currency,
10550            )
10551            .unwrap(),
10552            Money::from_u256(amount_in, fill.currency).unwrap()
10553        );
10554
10555        let (fill_emitted, active): (bool, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10556            "SELECT fill_emitted, active FROM {schema}.execution_intent"
10557        )))
10558        .fetch_one(&admin_pool)
10559        .await
10560        .unwrap();
10561        assert!(fill_emitted);
10562        assert!(!active);
10563
10564        let database = client.cache.database.as_ref().unwrap().clone();
10565        let payload_keys = client.payload_keys.clone();
10566        let restart_config = client.config.clone();
10567        drop(client);
10568        let (mut restarted, _) = swap_client_with_cache(restart_config);
10569        restarted.cache.database = Some(database);
10570        restarted.payload_keys = payload_keys;
10571        restarted.signer = Some(Arc::new(
10572            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
10573        ));
10574        let mut restart_receiver = start_with_events(&mut restarted);
10575        restarted.reconcile_unresolved_execution().await.unwrap();
10576        restarted.reconcile_unresolved_execution().await.unwrap();
10577        assert!(collect_order_events(&mut restart_receiver).is_empty());
10578        assert_eq!(
10579            state
10580                .recorded_requests()
10581                .iter()
10582                .filter(|request| request["method"] == "eth_sendRawTransaction")
10583                .count(),
10584            1
10585        );
10586
10587        drop_execution_schema(&admin_pool, &schema).await;
10588    }
10589
10590    #[tokio::test]
10591    async fn finalized_buy_swap_cancels_remainder_when_output_is_short() {
10592        let amount_in = expected_buy_amount_in();
10593        let min_amount_out = expected_buy_min_amount_out(50);
10594        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10595        let short_base_out = min_amount_out;
10596        let mut state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10597        state = state.with_response(
10598            "eth_getTransactionReceipt",
10599            &finalized_buy_swap_receipt_with_base_out(expected_hash, amount_in, short_base_out),
10600        );
10601        let Some((admin_pool, schema, mut client, _, cache)) =
10602            swap_client_with_buy_database("execution_submit_buy_short_fill_test", state).await
10603        else {
10604            return;
10605        };
10606        let order = test_market_buy_order(test_pool().instrument_id);
10607        cache
10608            .borrow_mut()
10609            .add_order(order.clone(), None, None, true)
10610            .unwrap();
10611        let mut receiver = start_with_events(&mut client);
10612        let plan = client
10613            .prepare_swap(&submit_order_cmd(&order), &order)
10614            .unwrap();
10615
10616        execute_swap(
10617            plan,
10618            client.transaction_executor().unwrap(),
10619            client.emitter.clone(),
10620            client.transaction_limits.max_quote_age_blocks,
10621            client.transaction_limits.deadline_seconds,
10622        )
10623        .await
10624        .unwrap();
10625
10626        let events = collect_order_events(&mut receiver);
10627        assert_eq!(events.len(), 3, "was: {events:?}");
10628        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
10629        let OrderEventAny::Filled(fill) = &events[1] else {
10630            panic!("expected OrderFilled, was {:?}", events[1]);
10631        };
10632        let expected_qty = raw_amount_to_quantity(short_base_out, 18).unwrap();
10633        assert_eq!(fill.order_side, OrderSide::Buy);
10634        assert_eq!(fill.last_qty, expected_qty);
10635        assert!(fill.last_qty < order.quantity());
10636        let OrderEventAny::Canceled(canceled) = &events[2] else {
10637            panic!("expected OrderCanceled, was {:?}", events[2]);
10638        };
10639        assert_eq!(canceled.client_order_id, order.client_order_id());
10640        assert_eq!(
10641            canceled.venue_order_id.as_ref().map(VenueOrderId::as_str),
10642            Some(expected_hash.to_string().as_str())
10643        );
10644
10645        drop_execution_schema(&admin_pool, &schema).await;
10646    }
10647
10648    #[tokio::test]
10649    async fn finalized_buy_swap_reports_full_output_when_above_order_quantity() {
10650        let amount_in = expected_buy_amount_in();
10651        let min_amount_out = expected_buy_min_amount_out(50);
10652        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10653        let overshoot_base_out = expected_buy_base_amount() * U256::from(2) + U256::from(44);
10654        let mut state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10655        state = state.with_response(
10656            "eth_getTransactionReceipt",
10657            &finalized_buy_swap_receipt_with_base_out(expected_hash, amount_in, overshoot_base_out),
10658        );
10659        let Some((admin_pool, schema, mut client, _, cache)) =
10660            swap_client_with_buy_database("execution_submit_buy_overshoot_fill_test", state).await
10661        else {
10662            return;
10663        };
10664        let order = test_market_buy_order(test_pool().instrument_id);
10665        cache
10666            .borrow_mut()
10667            .add_order(order.clone(), None, None, true)
10668            .unwrap();
10669        let mut receiver = start_with_events(&mut client);
10670        let plan = client
10671            .prepare_swap(&submit_order_cmd(&order), &order)
10672            .unwrap();
10673
10674        execute_swap(
10675            plan,
10676            client.transaction_executor().unwrap(),
10677            client.emitter.clone(),
10678            client.transaction_limits.max_quote_age_blocks,
10679            client.transaction_limits.deadline_seconds,
10680        )
10681        .await
10682        .unwrap();
10683
10684        let events = collect_order_events(&mut receiver);
10685        assert_eq!(events.len(), 2, "was: {events:?}");
10686        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
10687        let OrderEventAny::Filled(fill) = &events[1] else {
10688            panic!("expected OrderFilled, was {:?}", events[1]);
10689        };
10690        let expected_qty = raw_amount_to_quantity(overshoot_base_out, 18).unwrap();
10691        assert_eq!(fill.order_side, OrderSide::Buy);
10692        assert_eq!(fill.last_qty, expected_qty);
10693        assert!(fill.last_qty > order.quantity());
10694        assert_eq!(
10695            Money::from_decimal(
10696                fill.last_qty.as_decimal() * fill.last_px.as_decimal(),
10697                fill.currency,
10698            )
10699            .unwrap(),
10700            Money::from_u256(amount_in, fill.currency).unwrap()
10701        );
10702
10703        drop_execution_schema(&admin_pool, &schema).await;
10704    }
10705
10706    #[tokio::test]
10707    async fn finalized_buy_swap_quarantines_sell_oriented_log() {
10708        let amount_in = expected_buy_amount_in();
10709        let min_amount_out = expected_buy_min_amount_out(50);
10710        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10711        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in)
10712            .with_response(
10713                "eth_getTransactionReceipt",
10714                &finalized_swap_receipt(expected_hash),
10715            );
10716        let Some((admin_pool, schema, mut client, _, cache)) =
10717            swap_client_with_buy_database("execution_submit_buy_sell_log_test", state).await
10718        else {
10719            return;
10720        };
10721        let order = test_market_buy_order(test_pool().instrument_id);
10722        cache
10723            .borrow_mut()
10724            .add_order(order.clone(), None, None, true)
10725            .unwrap();
10726        let mut receiver = start_with_events(&mut client);
10727        let plan = client
10728            .prepare_swap(&submit_order_cmd(&order), &order)
10729            .unwrap();
10730
10731        let error = execute_swap(
10732            plan,
10733            client.transaction_executor().unwrap(),
10734            client.emitter.clone(),
10735            client.transaction_limits.max_quote_age_blocks,
10736            client.transaction_limits.deadline_seconds,
10737        )
10738        .await
10739        .unwrap_err();
10740
10741        let events = collect_order_events(&mut receiver);
10742        assert_swap_quarantined_without_terminal_event(&events);
10743        assert!(
10744            error
10745                .to_string()
10746                .contains("does not match the persisted amount")
10747                || error.to_string().contains("is not a BUY output"),
10748            "was: {error}"
10749        );
10750        assert!(client.in_flight.lock().is_some());
10751
10752        drop_execution_schema(&admin_pool, &schema).await;
10753    }
10754
10755    #[tokio::test]
10756    async fn submit_order_applies_buy_slippage_to_base_output() {
10757        let amount_in = expected_buy_amount_in();
10758        let min_amount_out = expected_buy_min_amount_out(200);
10759        let (expected_hash, expected_raw) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10760        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10761        let Some((admin_pool, schema, mut client, state, cache)) =
10762            swap_client_with_buy_database("execution_submit_buy_slippage_test", state).await
10763        else {
10764            return;
10765        };
10766        let order = test_market_buy_order(test_pool().instrument_id);
10767        cache
10768            .borrow_mut()
10769            .add_order(order.clone(), None, None, true)
10770            .unwrap();
10771        let mut cmd = submit_order_cmd(&order);
10772        cmd.params = Some(serde_json::from_str(r#"{"slippage_bps": 200}"#).unwrap());
10773        let mut receiver = start_with_events(&mut client);
10774
10775        client.submit_order(cmd).unwrap();
10776        await_pending_tasks(&client).await;
10777
10778        let events = collect_order_events(&mut receiver);
10779        assert_swap_submitted_and_filled(&events);
10780        let broadcasts: Vec<_> = state
10781            .recorded_requests()
10782            .into_iter()
10783            .filter(|request| request["method"] == "eth_sendRawTransaction")
10784            .collect();
10785        assert_eq!(broadcasts.len(), 1);
10786        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
10787
10788        drop_execution_schema(&admin_pool, &schema).await;
10789    }
10790
10791    #[tokio::test]
10792    async fn submit_order_denies_buy_on_insufficient_quote_balance() {
10793        let amount_in = expected_buy_amount_in();
10794        let min_amount_out = expected_buy_min_amount_out(50);
10795        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10796        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in)
10797            .with_call_response(BALANCE_OF_SELECTOR, CALL_ZERO);
10798        let Some((admin_pool, schema, mut client, _, cache)) =
10799            swap_client_with_buy_database("execution_submit_buy_balance_test", state).await
10800        else {
10801            return;
10802        };
10803        let order = test_market_buy_order(test_pool().instrument_id);
10804        cache
10805            .borrow_mut()
10806            .add_order(order.clone(), None, None, true)
10807            .unwrap();
10808        let mut receiver = start_with_events(&mut client);
10809
10810        client.submit_order(submit_order_cmd(&order)).unwrap();
10811        await_pending_tasks(&client).await;
10812
10813        let events = collect_order_events(&mut receiver);
10814        assert_eq!(events.len(), 1);
10815        let OrderEventAny::Denied(denied) = &events[0] else {
10816            panic!("expected OrderDenied, was {:?}", events[0]);
10817        };
10818        assert!(
10819            denied.reason.contains("is below the swap amount"),
10820            "was: {}",
10821            denied.reason
10822        );
10823
10824        drop_execution_schema(&admin_pool, &schema).await;
10825    }
10826
10827    #[tokio::test]
10828    async fn finalized_swap_without_log_stays_quarantined() {
10829        let state = swap_rpc_state()
10830            .await
10831            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS);
10832        let Some((admin_pool, schema, mut client, _, _)) =
10833            swap_client_with_database("execution_submit_missing_log_test", state).await
10834        else {
10835            return;
10836        };
10837        let order = test_market_sell_order(test_pool().instrument_id);
10838        let mut receiver = start_with_events(&mut client);
10839
10840        client.submit_order(submit_order_cmd(&order)).unwrap();
10841        await_pending_tasks(&client).await;
10842
10843        let events = collect_order_events(&mut receiver);
10844        let (status, terminal_emitted, active): (String, bool, bool) =
10845            sqlx::query_as(sqlx::AssertSqlSafe(format!(
10846                "SELECT status, terminal_emitted, active FROM {schema}.execution_intent"
10847            )))
10848            .fetch_one(&admin_pool)
10849            .await
10850            .unwrap();
10851
10852        assert_swap_quarantined_without_terminal_event(&events);
10853        assert_eq!(status, "broadcast");
10854        assert!(!terminal_emitted);
10855        assert!(active);
10856        assert!(client.in_flight.lock().is_some());
10857
10858        drop_execution_schema(&admin_pool, &schema).await;
10859    }
10860
10861    #[tokio::test]
10862    async fn finalized_swap_refresh_failure_stays_owned_for_reconciliation() {
10863        let min_amount_out = expected_min_amount_out(50);
10864        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10865        let state = finalized_swap_rpc_state(expected_hash, min_amount_out).with_response_sequence(
10866            "eth_getBalance",
10867            &[
10868                GET_BALANCE,
10869                GET_BALANCE,
10870                GET_BALANCE,
10871                RPC_METHOD_NOT_FOUND,
10872                RPC_METHOD_NOT_FOUND,
10873                RPC_METHOD_NOT_FOUND,
10874            ],
10875        );
10876        let Some((admin_pool, schema, mut client, _state, _)) =
10877            swap_client_with_database("execution_submit_refresh_fail_test", state).await
10878        else {
10879            return;
10880        };
10881        let order = test_market_sell_order(test_pool().instrument_id);
10882        let mut receiver = start_with_events(&mut client);
10883        let plan = client
10884            .prepare_swap(&submit_order_cmd(&order), &order)
10885            .unwrap();
10886
10887        let error = execute_swap(
10888            plan,
10889            client.transaction_executor().unwrap(),
10890            client.emitter.clone(),
10891            client.transaction_limits.max_quote_age_blocks,
10892            client.transaction_limits.deadline_seconds,
10893        )
10894        .await
10895        .unwrap_err();
10896        let events = collect_order_events(&mut receiver);
10897        let (status, fill_emitted, active): (String, bool, bool) =
10898            sqlx::query_as(sqlx::AssertSqlSafe(format!(
10899                "SELECT status, fill_emitted, active FROM {schema}.execution_intent"
10900            )))
10901            .fetch_one(&admin_pool)
10902            .await
10903            .unwrap();
10904
10905        assert!(
10906            error
10907                .to_string()
10908                .contains("finalized native balance verification is locally invalid"),
10909            "was: {error}"
10910        );
10911        assert_eq!(events.len(), 1, "was: {events:?}");
10912        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
10913        assert_eq!(status, "broadcast");
10914        assert!(!fill_emitted);
10915        assert!(active);
10916        assert!(client.in_flight.lock().is_some());
10917
10918        drop_execution_schema(&admin_pool, &schema).await;
10919    }
10920
10921    #[tokio::test]
10922    async fn submit_order_denies_router_factory_mismatch_before_signing() {
10923        let state = swap_rpc_state()
10924            .await
10925            .with_call_response(FACTORY_SELECTOR, CALL_ZERO);
10926        let Some((admin_pool, schema, mut client, state, _)) =
10927            swap_client_with_database("execution_submit_factory_test", state).await
10928        else {
10929            return;
10930        };
10931        let order = test_market_sell_order(test_pool().instrument_id);
10932        let mut receiver = start_with_events(&mut client);
10933
10934        client.submit_order(submit_order_cmd(&order)).unwrap();
10935        await_pending_tasks(&client).await;
10936
10937        let events = collect_order_events(&mut receiver);
10938        assert_eq!(events.len(), 1);
10939        let OrderEventAny::Denied(denied) = &events[0] else {
10940            panic!("expected OrderDenied, was {:?}", events[0]);
10941        };
10942        assert!(
10943            denied
10944                .reason
10945                .contains("swap deployment manifest verification disagreed"),
10946            "was: {}",
10947            denied.reason
10948        );
10949        let requests = state.recorded_requests();
10950        assert!(
10951            requests
10952                .iter()
10953                .all(|request| request["method"] != "eth_getTransactionCount")
10954        );
10955        assert!(
10956            requests
10957                .iter()
10958                .all(|request| request["method"] != "eth_sendRawTransaction")
10959        );
10960
10961        drop_execution_schema(&admin_pool, &schema).await;
10962    }
10963
10964    #[tokio::test]
10965    async fn submit_order_denies_router_weth_mismatch_before_signing() {
10966        let state = swap_rpc_state()
10967            .await
10968            .with_call_response(WETH9_SELECTOR, CALL_ZERO);
10969        let Some((admin_pool, schema, mut client, state, _)) =
10970            swap_client_with_database("execution_submit_weth_test", state).await
10971        else {
10972            return;
10973        };
10974        let order = test_market_sell_order(test_pool().instrument_id);
10975        let mut receiver = start_with_events(&mut client);
10976
10977        client.submit_order(submit_order_cmd(&order)).unwrap();
10978        await_pending_tasks(&client).await;
10979
10980        let events = collect_order_events(&mut receiver);
10981        assert_eq!(events.len(), 1);
10982        let OrderEventAny::Denied(denied) = &events[0] else {
10983            panic!("expected OrderDenied, was {:?}", events[0]);
10984        };
10985        assert!(
10986            denied
10987                .reason
10988                .contains("swap deployment manifest verification disagreed"),
10989            "was: {}",
10990            denied.reason
10991        );
10992        let requests = state.recorded_requests();
10993        assert!(
10994            requests
10995                .iter()
10996                .all(|request| request["method"] != "eth_getTransactionCount")
10997        );
10998        assert!(
10999            requests
11000                .iter()
11001                .all(|request| request["method"] != "eth_sendRawTransaction")
11002        );
11003
11004        drop_execution_schema(&admin_pool, &schema).await;
11005    }
11006
11007    #[tokio::test]
11008    async fn submit_order_denies_factory_pool_mismatch_before_signing() {
11009        let state = swap_rpc_state()
11010            .await
11011            .with_call_response(GET_POOL_SELECTOR, CALL_ZERO);
11012        let Some((admin_pool, schema, mut client, state, _)) =
11013            swap_client_with_database("execution_submit_pool_identity_test", state).await
11014        else {
11015            return;
11016        };
11017        let order = test_market_sell_order(test_pool().instrument_id);
11018        let mut receiver = start_with_events(&mut client);
11019
11020        client.submit_order(submit_order_cmd(&order)).unwrap();
11021        await_pending_tasks(&client).await;
11022
11023        let events = collect_order_events(&mut receiver);
11024        assert_eq!(events.len(), 1);
11025        let OrderEventAny::Denied(denied) = &events[0] else {
11026            panic!("expected OrderDenied, was {:?}", events[0]);
11027        };
11028        assert!(
11029            denied
11030                .reason
11031                .contains("swap deployment manifest verification disagreed"),
11032            "was: {}",
11033            denied.reason
11034        );
11035        let requests = state.recorded_requests();
11036        assert!(
11037            requests
11038                .iter()
11039                .all(|request| request["method"] != "eth_getTransactionCount")
11040        );
11041        assert!(
11042            requests
11043                .iter()
11044                .all(|request| request["method"] != "eth_sendRawTransaction")
11045        );
11046
11047        drop_execution_schema(&admin_pool, &schema).await;
11048    }
11049
11050    #[tokio::test]
11051    async fn submit_order_denies_cached_token_decimal_mismatch_before_signing() {
11052        let state = swap_rpc_state().await.with_contract_call_response(
11053            WETH,
11054            DECIMALS_SELECTOR,
11055            CALL_DECIMALS_6,
11056        );
11057        let Some((admin_pool, schema, mut client, state, _)) =
11058            swap_client_with_database("execution_submit_decimals_test", state).await
11059        else {
11060            return;
11061        };
11062        let order = test_market_sell_order(test_pool().instrument_id);
11063        let mut receiver = start_with_events(&mut client);
11064
11065        client.submit_order(submit_order_cmd(&order)).unwrap();
11066        await_pending_tasks(&client).await;
11067
11068        let events = collect_order_events(&mut receiver);
11069        assert_eq!(events.len(), 1);
11070        let OrderEventAny::Denied(denied) = &events[0] else {
11071            panic!("expected OrderDenied, was {:?}", events[0]);
11072        };
11073        assert!(
11074            denied
11075                .reason
11076                .contains("swap deployment manifest verification disagreed"),
11077            "was: {}",
11078            denied.reason
11079        );
11080        let requests = state.recorded_requests();
11081        assert!(
11082            requests
11083                .iter()
11084                .all(|request| request["method"] != "eth_getTransactionCount")
11085        );
11086        assert!(
11087            requests
11088                .iter()
11089                .all(|request| request["method"] != "eth_sendRawTransaction")
11090        );
11091
11092        drop_execution_schema(&admin_pool, &schema).await;
11093    }
11094
11095    #[tokio::test]
11096    async fn submit_order_denies_on_insufficient_router_allowance() {
11097        let state = swap_rpc_state()
11098            .await
11099            .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO);
11100        let Some((admin_pool, schema, mut client, state, _)) =
11101            swap_client_with_database("execution_submit_allowance_test", state).await
11102        else {
11103            return;
11104        };
11105        let order = test_market_sell_order(test_pool().instrument_id);
11106        let mut receiver = start_with_events(&mut client);
11107
11108        client.submit_order(submit_order_cmd(&order)).unwrap();
11109        await_pending_tasks(&client).await;
11110
11111        let events = collect_order_events(&mut receiver);
11112        assert_eq!(events.len(), 1);
11113        let OrderEventAny::Denied(denied) = &events[0] else {
11114            panic!("expected OrderDenied, was {:?}", events[0]);
11115        };
11116        assert!(
11117            denied.reason.contains("below the swap amount"),
11118            "was: {}",
11119            denied.reason
11120        );
11121        let requests = state.recorded_requests();
11122        assert!(
11123            requests
11124                .iter()
11125                .all(|request| request["method"] != "eth_sendRawTransaction"),
11126            "no broadcast may follow a pre-trade denial"
11127        );
11128        let row_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11129            "SELECT COUNT(*) FROM {schema}.execution_intent"
11130        )))
11131        .fetch_one(&admin_pool)
11132        .await
11133        .unwrap();
11134        assert_eq!(row_count, 0);
11135        assert!(client.in_flight.lock().is_none());
11136
11137        drop_execution_schema(&admin_pool, &schema).await;
11138    }
11139
11140    #[tokio::test]
11141    async fn submit_order_denies_on_insufficient_input_balance() {
11142        let state = swap_rpc_state()
11143            .await
11144            .with_call_response(BALANCE_OF_SELECTOR, CALL_ZERO);
11145        let Some((admin_pool, schema, mut client, _, _)) =
11146            swap_client_with_database("execution_submit_balance_test", state).await
11147        else {
11148            return;
11149        };
11150        let order = test_market_sell_order(test_pool().instrument_id);
11151        let mut receiver = start_with_events(&mut client);
11152
11153        client.submit_order(submit_order_cmd(&order)).unwrap();
11154        await_pending_tasks(&client).await;
11155
11156        let events = collect_order_events(&mut receiver);
11157        assert_eq!(events.len(), 1);
11158        let OrderEventAny::Denied(denied) = &events[0] else {
11159            panic!("expected OrderDenied, was {:?}", events[0]);
11160        };
11161        assert!(
11162            denied.reason.contains("is below the swap amount"),
11163            "was: {}",
11164            denied.reason
11165        );
11166
11167        drop_execution_schema(&admin_pool, &schema).await;
11168    }
11169
11170    #[tokio::test]
11171    async fn submit_order_denies_on_insufficient_native_balance() {
11172        let state = swap_rpc_state()
11173            .await
11174            .with_response("eth_getBalance", GET_BALANCE_INSUFFICIENT);
11175        let Some((admin_pool, schema, mut client, state, _)) =
11176            swap_client_with_database("execution_submit_native_balance_test", state).await
11177        else {
11178            return;
11179        };
11180        let order = test_market_sell_order(test_pool().instrument_id);
11181        let mut receiver = start_with_events(&mut client);
11182
11183        client.submit_order(submit_order_cmd(&order)).unwrap();
11184        await_pending_tasks(&client).await;
11185
11186        let events = collect_order_events(&mut receiver);
11187        assert_eq!(events.len(), 1);
11188        let OrderEventAny::Denied(denied) = &events[0] else {
11189            panic!("expected OrderDenied, was {:?}", events[0]);
11190        };
11191        assert!(
11192            denied.reason.contains("below maximum transaction cost"),
11193            "was: {}",
11194            denied.reason
11195        );
11196        assert!(
11197            state
11198                .recorded_requests()
11199                .iter()
11200                .all(|request| request["method"] != "eth_sendRawTransaction"),
11201            "no broadcast may follow an insufficient native balance"
11202        );
11203        let (row_count, status): (i64, Option<String>) = sqlx::query_as(sqlx::AssertSqlSafe(
11204            format!("SELECT COUNT(*), MAX(status) FROM {schema}.execution_intent"),
11205        ))
11206        .fetch_one(&admin_pool)
11207        .await
11208        .unwrap();
11209        assert_eq!(row_count, 1);
11210        assert_eq!(status.as_deref(), Some("recoverable"));
11211        assert!(client.in_flight.lock().is_none());
11212
11213        drop_execution_schema(&admin_pool, &schema).await;
11214    }
11215
11216    #[tokio::test]
11217    async fn submit_order_denies_on_stale_quote() {
11218        let Some((admin_pool, schema, mut client, state, cache)) =
11219            swap_client_with_database("execution_submit_stale_quote_test", swap_rpc_state().await)
11220                .await
11221        else {
11222            return;
11223        };
11224        let pool = test_pool();
11225        cache
11226            .borrow_mut()
11227            .add_pool_profiler(test_profiler(&pool, FIXTURE_BLOCK - 101))
11228            .unwrap();
11229        let order = test_market_sell_order(pool.instrument_id);
11230        let mut receiver = start_with_events(&mut client);
11231
11232        client.submit_order(submit_order_cmd(&order)).unwrap();
11233        await_pending_tasks(&client).await;
11234
11235        let events = collect_order_events(&mut receiver);
11236        assert_eq!(events.len(), 1);
11237        let OrderEventAny::Denied(denied) = &events[0] else {
11238            panic!("expected OrderDenied, was {:?}", events[0]);
11239        };
11240        assert!(
11241            denied.reason.contains("Stale quote"),
11242            "was: {}",
11243            denied.reason
11244        );
11245        let requests = state.recorded_requests();
11246        assert!(
11247            requests
11248                .iter()
11249                .all(|request| request["method"] != "eth_sendRawTransaction"),
11250            "no broadcast may follow a pre-trade denial"
11251        );
11252
11253        drop_execution_schema(&admin_pool, &schema).await;
11254    }
11255
11256    #[tokio::test]
11257    async fn submit_order_denies_quote_ahead_of_chain_head() {
11258        let Some((admin_pool, schema, mut client, state, cache)) =
11259            swap_client_with_database("execution_submit_ahead_quote_test", swap_rpc_state().await)
11260                .await
11261        else {
11262            return;
11263        };
11264        let pool = test_pool();
11265        cache
11266            .borrow_mut()
11267            .add_pool_profiler(test_profiler(&pool, FIXTURE_BLOCK + 1))
11268            .unwrap();
11269        let order = test_market_sell_order(pool.instrument_id);
11270        let mut receiver = start_with_events(&mut client);
11271
11272        client.submit_order(submit_order_cmd(&order)).unwrap();
11273        await_pending_tasks(&client).await;
11274
11275        let events = collect_order_events(&mut receiver);
11276        assert_eq!(events.len(), 1);
11277        let OrderEventAny::Denied(denied) = &events[0] else {
11278            panic!("expected OrderDenied, was {:?}", events[0]);
11279        };
11280        assert!(
11281            denied.reason.contains("is ahead of the latest block"),
11282            "was: {}",
11283            denied.reason
11284        );
11285        let requests = state.recorded_requests();
11286        assert!(
11287            requests
11288                .iter()
11289                .all(|request| request["method"] != "eth_sendRawTransaction"),
11290            "no broadcast may follow a pre-trade denial"
11291        );
11292
11293        drop_execution_schema(&admin_pool, &schema).await;
11294    }
11295
11296    #[tokio::test]
11297    async fn submit_order_denies_on_deadline_overflow() {
11298        let Some((admin_pool, schema, mut client, state, _)) = swap_client_with_database(
11299            "execution_submit_deadline_overflow_test",
11300            swap_rpc_state().await,
11301        )
11302        .await
11303        else {
11304            return;
11305        };
11306        client.transaction_limits.deadline_seconds = u64::MAX;
11307        let order = test_market_sell_order(test_pool().instrument_id);
11308        let mut receiver = start_with_events(&mut client);
11309
11310        client.submit_order(submit_order_cmd(&order)).unwrap();
11311        await_pending_tasks(&client).await;
11312
11313        let events = collect_order_events(&mut receiver);
11314        assert_eq!(events.len(), 1);
11315        let OrderEventAny::Denied(denied) = &events[0] else {
11316            panic!("expected OrderDenied, was {:?}", events[0]);
11317        };
11318        assert!(
11319            denied.reason.contains("deadline overflow"),
11320            "was: {}",
11321            denied.reason
11322        );
11323        let requests = state.recorded_requests();
11324        assert!(
11325            requests
11326                .iter()
11327                .all(|request| request["method"] != "eth_sendRawTransaction"),
11328            "no broadcast may follow a pre-trade denial"
11329        );
11330        assert!(client.in_flight.lock().is_none());
11331
11332        drop_execution_schema(&admin_pool, &schema).await;
11333    }
11334
11335    #[tokio::test]
11336    async fn submit_order_reconciles_node_rejection_to_finalized_receipt() {
11337        let state = swap_rpc_state()
11338            .await
11339            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION_REJECTED);
11340        let Some((admin_pool, schema, mut client, _state, _)) =
11341            swap_client_with_database("execution_submit_node_rejected_test", state).await
11342        else {
11343            return;
11344        };
11345        let order = test_market_sell_order(test_pool().instrument_id);
11346        let mut receiver = start_with_events(&mut client);
11347
11348        client.submit_order(submit_order_cmd(&order)).unwrap();
11349        await_pending_tasks(&client).await;
11350
11351        let events = collect_order_events(&mut receiver);
11352        assert_swap_submitted_and_filled(&events);
11353        let (purpose, status, client_order_id): (String, String, Option<String>) =
11354            sqlx::query_as(sqlx::AssertSqlSafe(format!(
11355                "SELECT purpose, status, client_order_id FROM {schema}.execution_intent"
11356            )))
11357            .fetch_one(&admin_pool)
11358            .await
11359            .unwrap();
11360        assert_eq!(purpose, "swap");
11361        assert_eq!(status, "finalized");
11362        assert_eq!(
11363            client_order_id.as_deref(),
11364            Some(order.client_order_id().as_str())
11365        );
11366        assert!(client.in_flight.lock().is_none());
11367
11368        drop_execution_schema(&admin_pool, &schema).await;
11369    }
11370
11371    #[tokio::test]
11372    async fn submit_order_acknowledges_uncertain_nonce_too_low() {
11373        let state = swap_rpc_state()
11374            .await
11375            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION_NONCE_TOO_LOW);
11376        let Some((admin_pool, schema, mut client, _state, _)) =
11377            swap_client_with_database("execution_submit_nonce_too_low_test", state).await
11378        else {
11379            return;
11380        };
11381        let order = test_market_sell_order(test_pool().instrument_id);
11382        let mut receiver = start_with_events(&mut client);
11383
11384        client.submit_order(submit_order_cmd(&order)).unwrap();
11385        await_pending_tasks(&client).await;
11386
11387        let events = collect_order_events(&mut receiver);
11388        assert_swap_submitted_and_filled(&events);
11389        let (purpose, status, client_order_id): (String, String, Option<String>) =
11390            sqlx::query_as(sqlx::AssertSqlSafe(format!(
11391                "SELECT purpose, status, client_order_id FROM {schema}.execution_intent"
11392            )))
11393            .fetch_one(&admin_pool)
11394            .await
11395            .unwrap();
11396        assert_eq!(purpose, "swap");
11397        assert_eq!(status, "finalized");
11398        assert_eq!(
11399            client_order_id.as_deref(),
11400            Some(order.client_order_id().as_str())
11401        );
11402        assert!(client.in_flight.lock().is_none());
11403
11404        drop_execution_schema(&admin_pool, &schema).await;
11405    }
11406
11407    #[tokio::test]
11408    async fn submit_order_rejected_on_reverted_receipt() {
11409        let expected_min_out = expected_min_amount_out(50);
11410        let (expected_hash, _) = expected_swap_tx(expected_min_out).await;
11411        let block = finalized_swap_block(expected_hash, expected_min_out);
11412        let receipt = receipt_with_transaction_hash(RECEIPT_REVERTED, expected_hash);
11413        let state = with_finalized_identity(
11414            swap_rpc_state()
11415                .await
11416                .with_response("eth_getTransactionReceipt", &receipt),
11417            &block,
11418            &receipt,
11419        );
11420        let Some((admin_pool, schema, mut client, _state, _)) =
11421            swap_client_with_database("execution_submit_reverted_test", state).await
11422        else {
11423            return;
11424        };
11425        let order = test_market_sell_order(test_pool().instrument_id);
11426        let mut receiver = start_with_events(&mut client);
11427        client.submit_order(submit_order_cmd(&order)).unwrap();
11428        await_pending_tasks(&client).await;
11429
11430        let events = collect_order_events(&mut receiver);
11431        assert_eq!(events.len(), 2);
11432        assert!(
11433            matches!(&events[0], OrderEventAny::Submitted(_)),
11434            "was: {:?}",
11435            events[0]
11436        );
11437        let OrderEventAny::Rejected(rejected) = &events[1] else {
11438            panic!("expected OrderRejected, was {:?}", events[1]);
11439        };
11440        assert!(
11441            rejected.reason.contains("reverted on-chain"),
11442            "was: {}",
11443            rejected.reason
11444        );
11445
11446        let record = client
11447            .cache
11448            .get_execution_transaction(42161, &expected_hash.to_string())
11449            .await
11450            .unwrap()
11451            .unwrap();
11452        assert_eq!(record.purpose, "swap");
11453        assert_eq!(record.status, "reverted");
11454        assert_eq!(
11455            record.client_order_id.as_deref(),
11456            Some(order.client_order_id().as_str())
11457        );
11458        assert!(client.in_flight.lock().is_none());
11459
11460        drop_execution_schema(&admin_pool, &schema).await;
11461    }
11462
11463    #[tokio::test]
11464    async fn submit_order_acknowledges_ambiguous_broadcast() {
11465        // A response the client cannot parse classifies as an ambiguous broadcast failure:
11466        // the transaction may be live, so the durable intent remains submitted and occupied
11467        let state = swap_rpc_state()
11468            .await
11469            .with_response("eth_sendRawTransaction", "not json");
11470        let Some((admin_pool, schema, mut client, _state, _)) =
11471            swap_client_with_database("execution_submit_ambiguous_test", state).await
11472        else {
11473            return;
11474        };
11475        let order = test_market_sell_order(test_pool().instrument_id);
11476        let mut receiver = start_with_events(&mut client);
11477
11478        client.submit_order(submit_order_cmd(&order)).unwrap();
11479        await_pending_tasks(&client).await;
11480
11481        let events = collect_order_events(&mut receiver);
11482        assert_swap_submitted_and_filled(&events);
11483
11484        let record = client
11485            .cache
11486            .get_execution_transaction(
11487                42161,
11488                &expected_swap_tx(expected_min_amount_out(50))
11489                    .await
11490                    .0
11491                    .to_string(),
11492            )
11493            .await
11494            .unwrap()
11495            .unwrap();
11496        assert_eq!(record.purpose, "swap");
11497        assert_eq!(record.status, "finalized");
11498        assert!(client.in_flight.lock().is_none());
11499
11500        drop_execution_schema(&admin_pool, &schema).await;
11501    }
11502
11503    #[tokio::test]
11504    async fn submit_order_acknowledges_broadcast_hash_mismatch() {
11505        // The static fixture's hash differs from the locally signed hash, so acceptance of the
11506        // signed transaction is unverified until the independent receipt reaches finality
11507        let state = swap_rpc_state_for_mismatch().await;
11508        let Some((admin_pool, schema, mut client, _state, _)) =
11509            swap_client_with_database("execution_submit_hash_mismatch_test", state).await
11510        else {
11511            return;
11512        };
11513        let order = test_market_sell_order(test_pool().instrument_id);
11514        let mut receiver = start_with_events(&mut client);
11515
11516        client.submit_order(submit_order_cmd(&order)).unwrap();
11517        await_pending_tasks(&client).await;
11518
11519        let events = collect_order_events(&mut receiver);
11520        assert_swap_submitted_and_filled(&events);
11521
11522        let record = client
11523            .cache
11524            .get_execution_transaction(
11525                42161,
11526                &expected_swap_tx(expected_min_amount_out(50))
11527                    .await
11528                    .0
11529                    .to_string(),
11530            )
11531            .await
11532            .unwrap()
11533            .unwrap();
11534        assert_eq!(record.purpose, "swap");
11535        assert_eq!(record.status, "finalized");
11536        assert!(client.in_flight.lock().is_none());
11537
11538        drop_execution_schema(&admin_pool, &schema).await;
11539    }
11540
11541    #[tokio::test]
11542    async fn submit_order_persists_authenticated_envelope_before_broadcast() {
11543        let state = swap_rpc_state().await;
11544        let Some((admin_pool, schema, mut client, state, _)) =
11545            swap_client_with_database("protected_submit_test", state).await
11546        else {
11547            return;
11548        };
11549        let order = test_market_sell_order(test_pool().instrument_id);
11550        let mut receiver = start_with_events(&mut client);
11551
11552        client.submit_order(submit_order_cmd(&order)).unwrap();
11553        await_pending_tasks(&client).await;
11554
11555        let events = collect_order_events(&mut receiver);
11556        assert_swap_submitted_and_filled(&events);
11557        let representations: Vec<(bool, bool)> = sqlx::query_as(sqlx::AssertSqlSafe(format!(
11558            "SELECT raw_transaction IS NULL, sealed_transaction IS NOT NULL \
11559             FROM {schema}.execution_transaction_hash WHERE payload_expected"
11560        )))
11561        .fetch_all(&admin_pool)
11562        .await
11563        .unwrap();
11564        let broadcasts = state
11565            .recorded_requests()
11566            .into_iter()
11567            .filter(|request| request["method"] == "eth_sendRawTransaction")
11568            .count();
11569        assert_eq!(representations, vec![(true, true)]);
11570        assert_eq!(broadcasts, 1);
11571
11572        drop_execution_schema(&admin_pool, &schema).await;
11573    }
11574
11575    #[tokio::test]
11576    async fn protected_persistence_failure_prevents_broadcast_and_acknowledgment() {
11577        let state = swap_rpc_state().await;
11578        let Some((admin_pool, schema, mut client, state, _)) =
11579            swap_client_with_database("protected_persist_failure_test", state).await
11580        else {
11581            return;
11582        };
11583
11584        for statement in [
11585            format!(
11586                "CREATE FUNCTION {schema}.reject_protected_payload() RETURNS trigger \
11587                 LANGUAGE plpgsql AS 'BEGIN RAISE EXCEPTION ''test payload rejection''; END'"
11588            ),
11589            format!(
11590                "CREATE TRIGGER reject_protected_payload BEFORE INSERT ON \
11591                 {schema}.execution_transaction_hash FOR EACH ROW \
11592                 EXECUTE FUNCTION {schema}.reject_protected_payload()"
11593            ),
11594        ] {
11595            sqlx::query(sqlx::AssertSqlSafe(statement))
11596                .execute(&admin_pool)
11597                .await
11598                .unwrap();
11599        }
11600        let order = test_market_sell_order(test_pool().instrument_id);
11601        let mut receiver = start_with_events(&mut client);
11602
11603        client.submit_order(submit_order_cmd(&order)).unwrap();
11604        await_pending_tasks(&client).await;
11605
11606        let events = collect_order_events(&mut receiver);
11607        assert!(
11608            events
11609                .iter()
11610                .all(|event| !matches!(event, OrderEventAny::Submitted(_)))
11611        );
11612        let broadcasts = state
11613            .recorded_requests()
11614            .into_iter()
11615            .filter(|request| request["method"] == "eth_sendRawTransaction")
11616            .count();
11617        let payload_rows: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11618            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
11619        )))
11620        .fetch_one(&admin_pool)
11621        .await
11622        .unwrap();
11623        assert_eq!(broadcasts, 0);
11624        assert_eq!(payload_rows, 0);
11625
11626        drop_execution_schema(&admin_pool, &schema).await;
11627    }
11628
11629    #[tokio::test]
11630    async fn submit_order_reservation_failure_denies_without_broadcast_and_releases_slot() {
11631        let Some((admin_pool, schema, mut client, state, cache)) =
11632            swap_client_with_database("execution_submit_persist_fail_test", swap_rpc_state().await)
11633                .await
11634        else {
11635            return;
11636        };
11637        sqlx::query(sqlx::AssertSqlSafe(format!(
11638            "DROP TABLE {schema}.execution_intent CASCADE"
11639        )))
11640        .execute(&admin_pool)
11641        .await
11642        .unwrap();
11643        let pool = test_pool();
11644        let first = test_market_sell_order(pool.instrument_id);
11645        let second = market_sell_order_with_id(pool.instrument_id, "O-SWAP-002");
11646        cache
11647            .borrow_mut()
11648            .add_order(second.clone(), None, None, false)
11649            .unwrap();
11650        let mut receiver = start_with_events(&mut client);
11651
11652        client.submit_order(submit_order_cmd(&first)).unwrap();
11653        await_pending_tasks(&client).await;
11654
11655        let events = collect_order_events(&mut receiver);
11656        assert_eq!(events.len(), 1);
11657        let OrderEventAny::Denied(denied) = &events[0] else {
11658            panic!("expected OrderDenied, was {:?}", events[0]);
11659        };
11660        assert!(
11661            denied
11662                .reason
11663                .contains("Execution intent reservation failed before commit"),
11664            "was: {}",
11665            denied.reason
11666        );
11667        client.submit_order(submit_order_cmd(&second)).unwrap();
11668        await_pending_tasks(&client).await;
11669        let retry_events = collect_order_events(&mut receiver);
11670        assert_eq!(retry_events.len(), 1);
11671        let OrderEventAny::Denied(retry_denied) = &retry_events[0] else {
11672            panic!("expected OrderDenied, was {:?}", retry_events[0]);
11673        };
11674        assert_eq!(
11675            retry_denied.reason,
11676            "Execution intent reservation failed before commit"
11677        );
11678        let broadcasts = state
11679            .recorded_requests()
11680            .into_iter()
11681            .filter(|request| request["method"] == "eth_sendRawTransaction")
11682            .count();
11683        assert_eq!(broadcasts, 0);
11684        assert!(client.in_flight.lock().is_none());
11685
11686        drop_execution_schema(&admin_pool, &schema).await;
11687    }
11688
11689    #[tokio::test]
11690    async fn submit_order_reservation_commit_failure_keeps_preparing_slot() {
11691        let Some((admin_pool, schema, mut client, state, cache)) = swap_client_with_database(
11692            "execution_submit_reservation_commit_fail_test",
11693            swap_rpc_state().await,
11694        )
11695        .await
11696        else {
11697            return;
11698        };
11699        install_reservation_commit_rejection(&admin_pool, &schema).await;
11700        let pool = test_pool();
11701        let first = test_market_sell_order(pool.instrument_id);
11702        let second = market_sell_order_with_id(pool.instrument_id, "O-SWAP-002");
11703        cache
11704            .borrow_mut()
11705            .add_order(second.clone(), None, None, false)
11706            .unwrap();
11707        let mut receiver = start_with_events(&mut client);
11708
11709        client.submit_order(submit_order_cmd(&first)).unwrap();
11710        await_pending_tasks(&client).await;
11711        client.submit_order(submit_order_cmd(&second)).unwrap();
11712        await_pending_tasks(&client).await;
11713
11714        let events = collect_order_events(&mut receiver);
11715        let submitted = events
11716            .iter()
11717            .filter(|event| matches!(event, OrderEventAny::Submitted(_)))
11718            .count();
11719        let denied_commit = events
11720            .iter()
11721            .filter(|event| {
11722                matches!(event, OrderEventAny::Denied(denied) if denied.reason == "Execution intent reservation commit outcome is unknown; reconciliation is required")
11723            })
11724            .count();
11725        let denied_in_flight = events
11726            .iter()
11727            .filter(|event| {
11728                matches!(event, OrderEventAny::Denied(denied) if denied.reason.contains("at most one transaction can be in flight"))
11729            })
11730            .count();
11731        let requests = state.recorded_requests();
11732        let intent_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11733            "SELECT COUNT(*) FROM {schema}.execution_intent"
11734        )))
11735        .fetch_one(&admin_pool)
11736        .await
11737        .unwrap();
11738        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11739            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
11740        )))
11741        .fetch_one(&admin_pool)
11742        .await
11743        .unwrap();
11744
11745        assert_eq!(submitted, 0, "was: {events:?}");
11746        assert_eq!(denied_commit, 1, "was: {events:?}");
11747        assert_eq!(denied_in_flight, 1, "was: {events:?}");
11748        assert!(matches!(
11749            *client.in_flight.lock(),
11750            Some(InFlightSlot::Preparing(TransactionPurpose::Swap))
11751        ));
11752        assert_eq!(intent_count, 0);
11753        assert_eq!(signed_count, 0);
11754        assert!(
11755            requests
11756                .iter()
11757                .all(|request| request["method"] != "eth_getTransactionCount")
11758        );
11759        assert!(
11760            requests
11761                .iter()
11762                .all(|request| request["method"] != "eth_sendRawTransaction")
11763        );
11764
11765        drop_execution_schema(&admin_pool, &schema).await;
11766    }
11767
11768    #[tokio::test]
11769    async fn protected_payload_migration_failure_keeps_plaintext_and_blocks_ready() {
11770        let Some((admin_pool, schema, client, _)) = execution_client_with_unprotected_database(
11771            "protected_payload_migration_failure",
11772            execution_rpc_state(),
11773        )
11774        .await
11775        else {
11776            return;
11777        };
11778        let database = client.cache.database.as_ref().unwrap();
11779        let (intent, _) = persist_invalid_test_swap(database, None).await;
11780        let keys = payload_test_keys([0x31; 32], vec![], "migration-failure");
11781        let error = database
11782            .ensure_execution_payload_storage(&keys)
11783            .await
11784            .unwrap_err();
11785
11786        assert!(
11787            error
11788                .to_string()
11789                .contains("failed to authenticate execution payload")
11790        );
11791        let row = database
11792            .get_execution_transaction_hashes(intent.id)
11793            .await
11794            .unwrap()
11795            .pop()
11796            .unwrap();
11797        let operation: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11798            "SELECT operation FROM {schema}.execution_payload_state"
11799        )))
11800        .fetch_one(&admin_pool)
11801        .await
11802        .unwrap();
11803        assert_eq!(operation, "migrate");
11804        assert!(row.raw_transaction.is_some());
11805        assert!(row.sealed_transaction.is_none());
11806
11807        drop_execution_schema(&admin_pool, &schema).await;
11808    }
11809
11810    #[tokio::test]
11811    async fn protected_payload_migration_restart_restore_rewrap_and_rollback() {
11812        let Some((admin_pool, pg_config)) =
11813            connect_test_postgres("protected payload lifecycle").await
11814        else {
11815            return;
11816        };
11817        let schema = format!("protected_payload_lifecycle_{}", std::process::id());
11818        setup_execution_schema(&admin_pool, &schema).await;
11819        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
11820        let options = options.options([("search_path", schema.clone())]);
11821        let database = connect_test_database(options.clone()).await.unwrap();
11822        database
11823            .ensure_execution_transaction_schema()
11824            .await
11825            .unwrap();
11826        let intent = reserve_test_wrap_intent(&database).await;
11827        database
11828            .assign_execution_intent_nonce(intent.id, 7)
11829            .await
11830            .unwrap();
11831        let transaction = build_eip1559_transaction(
11832            42161,
11833            7,
11834            78_000,
11835            130_000_000,
11836            10_000_000,
11837            WETH_ADDRESS,
11838            U256::from(1_u64),
11839            Bytes::from(hex::decode("d0e30db0").unwrap()),
11840        );
11841        let (transaction_hash, raw_transaction) = sign_eip1559_transaction(
11842            transaction,
11843            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
11844        )
11845        .await
11846        .unwrap();
11847        database
11848            .add_execution_transaction_hash(
11849                intent.id,
11850                42161,
11851                &transaction_hash.to_string(),
11852                &raw_transaction,
11853            )
11854            .await
11855            .unwrap();
11856        let keys = payload_test_keys([0x41; 32], vec![], "restore-a");
11857
11858        database
11859            .ensure_execution_payload_storage(&keys)
11860            .await
11861            .unwrap();
11862        let operation: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11863            "SELECT operation FROM {schema}.execution_payload_state"
11864        )))
11865        .fetch_one(&admin_pool)
11866        .await
11867        .unwrap();
11868        assert_eq!(operation, "ready");
11869        drop(database);
11870
11871        let restarted = connect_test_database(options).await.unwrap();
11872        restarted
11873            .ensure_execution_payload_storage(&keys)
11874            .await
11875            .unwrap();
11876        let row = restarted
11877            .get_execution_transaction_hashes(intent.id)
11878            .await
11879            .unwrap()
11880            .pop()
11881            .unwrap();
11882        assert!(row.raw_transaction.is_none());
11883        let sealed_transaction = row.sealed_transaction.clone().unwrap();
11884        let stored_intent = restarted.get_execution_intent(intent.id).await.unwrap();
11885        let context = payload_context(&stored_intent, &row, keys.deployment_id()).unwrap();
11886        let alternate_envelope = keys.seal(&raw_transaction, &context).unwrap();
11887        assert_ne!(alternate_envelope, sealed_transaction);
11888        let repeated = restarted
11889            .add_execution_transaction_envelope(
11890                intent.id,
11891                42161,
11892                &transaction_hash.to_string(),
11893                &alternate_envelope,
11894            )
11895            .await
11896            .unwrap();
11897        let check = restarted
11898            .check_execution_payload_storage(Some(&keys), None, 1)
11899            .await
11900            .unwrap();
11901        assert_eq!(
11902            repeated.sealed_transaction,
11903            Some(sealed_transaction.clone())
11904        );
11905        assert_eq!(check.plaintext_rows, 0);
11906        assert_eq!(check.original_rows, 1);
11907        assert_eq!(check.replacement_rows, 0);
11908        assert_eq!(check.authenticated_rows, 1);
11909        assert!(!check.read_roles.is_empty());
11910
11911        sqlx::query(sqlx::AssertSqlSafe(format!(
11912            "UPDATE {schema}.execution_payload_key_state SET seals = 4294967295"
11913        )))
11914        .execute(&admin_pool)
11915        .await
11916        .unwrap();
11917        let exhausted = restarted
11918            .reserve_execution_payload_seal(&keys)
11919            .await
11920            .unwrap_err();
11921        assert!(exhausted.to_string().contains("seal limit"));
11922        let seals: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11923            "SELECT seals FROM {schema}.execution_payload_key_state"
11924        )))
11925        .fetch_one(&admin_pool)
11926        .await
11927        .unwrap();
11928        assert_eq!(seals, 4_294_967_295);
11929        sqlx::query(sqlx::AssertSqlSafe(format!(
11930            "UPDATE {schema}.execution_payload_key_state SET seals = 1"
11931        )))
11932        .execute(&admin_pool)
11933        .await
11934        .unwrap();
11935
11936        let missing_key = restarted
11937            .check_execution_payload_storage(None, None, 1)
11938            .await
11939            .unwrap_err();
11940        assert!(
11941            missing_key
11942                .to_string()
11943                .contains("no payload key is configured")
11944        );
11945        let restored_elsewhere = payload_test_keys([0x41; 32], vec![], "restore-b");
11946        let wrong_context = restarted
11947            .ensure_execution_payload_storage(&restored_elsewhere)
11948            .await
11949            .unwrap_err();
11950        assert!(wrong_context.to_string().contains("deployment ID"));
11951
11952        sqlx::query(sqlx::AssertSqlSafe(format!(
11953            "UPDATE {schema}.execution_transaction_hash \
11954             SET sealed_transaction = set_byte(sealed_transaction, octet_length(sealed_transaction) - 1, \
11955                 get_byte(sealed_transaction, octet_length(sealed_transaction) - 1) # 1)"
11956        )))
11957        .execute(&admin_pool)
11958        .await
11959        .unwrap();
11960        assert!(
11961            restarted
11962                .check_execution_payload_storage(Some(&keys), None, 1)
11963                .await
11964                .is_err()
11965        );
11966        sqlx::query(sqlx::AssertSqlSafe(format!(
11967            "UPDATE {schema}.execution_transaction_hash SET sealed_transaction = $1"
11968        )))
11969        .bind(&sealed_transaction)
11970        .execute(&admin_pool)
11971        .await
11972        .unwrap();
11973
11974        for statement in [
11975            format!(
11976                "ALTER TABLE {schema}.execution_transaction_hash \
11977                 DROP CONSTRAINT execution_transaction_payload_protected_check"
11978            ),
11979            format!("UPDATE {schema}.execution_transaction_hash SET sealed_transaction = NULL"),
11980        ] {
11981            sqlx::query(sqlx::AssertSqlSafe(statement))
11982                .execute(&admin_pool)
11983                .await
11984                .unwrap();
11985        }
11986        assert!(
11987            restarted
11988                .check_execution_payload_storage(Some(&keys), None, 1)
11989                .await
11990                .is_err()
11991        );
11992        sqlx::query(sqlx::AssertSqlSafe(format!(
11993            "UPDATE {schema}.execution_transaction_hash SET sealed_transaction = $1"
11994        )))
11995        .bind(&sealed_transaction)
11996        .execute(&admin_pool)
11997        .await
11998        .unwrap();
11999        sqlx::query(sqlx::AssertSqlSafe(format!(
12000            "ALTER TABLE {schema}.execution_transaction_hash \
12001             ADD CONSTRAINT execution_transaction_payload_protected_check CHECK ( \
12002                 (payload_expected AND raw_transaction IS NULL AND sealed_transaction IS NOT NULL) \
12003                 OR (NOT payload_expected AND raw_transaction IS NULL AND sealed_transaction IS NULL) \
12004             )"
12005        )))
12006        .execute(&admin_pool)
12007        .await
12008        .unwrap();
12009
12010        let rotated = payload_test_keys([0x52; 32], vec![[0x41; 32]], "restore-a");
12011        restarted
12012            .rewrap_execution_payload_storage(&rotated, 1)
12013            .await
12014            .unwrap();
12015        let rotated_check = restarted
12016            .check_execution_payload_storage(Some(&rotated), None, 1)
12017            .await
12018            .unwrap();
12019        assert_eq!(rotated_check.authenticated_rows, 1);
12020        assert_eq!(rotated_check.key_ids.len(), 1);
12021
12022        restarted
12023            .rollback_execution_payload_storage(&rotated, 1)
12024            .await
12025            .unwrap();
12026        let rolled_back = restarted
12027            .get_execution_transaction_hashes(intent.id)
12028            .await
12029            .unwrap()
12030            .pop()
12031            .unwrap();
12032        assert_eq!(
12033            rolled_back.raw_transaction.as_deref(),
12034            Some(raw_transaction.as_slice())
12035        );
12036        assert!(rolled_back.sealed_transaction.is_none());
12037        let legacy_check = restarted
12038            .check_execution_payload_storage(None, None, 1)
12039            .await
12040            .unwrap();
12041        assert!(!legacy_check.protected);
12042        assert_eq!(legacy_check.plaintext_rows, 1);
12043        assert_eq!(legacy_check.authenticated_rows, 1);
12044
12045        drop_execution_schema(&admin_pool, &schema).await;
12046    }
12047
12048    #[tokio::test]
12049    async fn protected_payload_storage_authenticates_multiple_execution_identities() {
12050        let Some((admin_pool, pg_config)) =
12051            connect_test_postgres("protected payload multiple identities").await
12052        else {
12053            return;
12054        };
12055        let schema = format!("protected_payload_identities_{}", std::process::id());
12056        setup_execution_schema(&admin_pool, &schema).await;
12057        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
12058        let database = connect_test_database(options.options([("search_path", schema.clone())]))
12059            .await
12060            .unwrap();
12061        database
12062            .ensure_execution_transaction_schema()
12063            .await
12064            .unwrap();
12065
12066        let private_keys = [
12067            TEST_PRIVATE_KEY,
12068            "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d",
12069        ];
12070
12071        for (index, private_key) in private_keys.into_iter().enumerate() {
12072            let signer = PrivateKeySigner::from_str(private_key).unwrap();
12073            let nonce = 7 + u64::try_from(index).unwrap();
12074            let intent =
12075                reserve_test_wrap_intent_for_wallet(&database, &signer.address().to_string()).await;
12076            database
12077                .assign_execution_intent_nonce(intent.id, nonce)
12078                .await
12079                .unwrap();
12080            let transaction = build_eip1559_transaction(
12081                42161,
12082                nonce,
12083                78_000,
12084                130_000_000,
12085                10_000_000,
12086                WETH_ADDRESS,
12087                U256::from(1_u64),
12088                Bytes::from(hex::decode("d0e30db0").unwrap()),
12089            );
12090            let (transaction_hash, raw_transaction) =
12091                sign_eip1559_transaction(transaction, &signer)
12092                    .await
12093                    .unwrap();
12094            database
12095                .add_execution_transaction_hash(
12096                    intent.id,
12097                    42161,
12098                    &transaction_hash.to_string(),
12099                    &raw_transaction,
12100                )
12101                .await
12102                .unwrap();
12103        }
12104
12105        let keys = payload_test_keys([0x61; 32], vec![], "multiple-identities");
12106        database
12107            .ensure_execution_payload_storage(&keys)
12108            .await
12109            .unwrap();
12110        let lease = database
12111            .require_execution_payload_storage(
12112                &keys,
12113                PayloadPolicy {
12114                    chain_id: 42161,
12115                    signer: Address::from_str(WALLET).unwrap(),
12116                    gas_limit: 1_000_000,
12117                    max_fee_per_gas: 1_000_000_000,
12118                },
12119                1,
12120            )
12121            .await
12122            .unwrap();
12123        drop(lease);
12124        let check = database
12125            .check_execution_payload_storage(Some(&keys), None, 1)
12126            .await
12127            .unwrap();
12128
12129        assert!(check.protected);
12130        assert_eq!(check.plaintext_rows, 0);
12131        assert_eq!(check.original_rows, 2);
12132        assert_eq!(check.replacement_rows, 0);
12133        assert_eq!(check.authenticated_rows, 2);
12134        assert_eq!(check.key_ids.len(), 1);
12135
12136        drop_execution_schema(&admin_pool, &schema).await;
12137    }
12138
12139    #[rstest]
12140    #[case::finalized(TransactionStatus::Finalized)]
12141    #[case::reverted(TransactionStatus::Reverted)]
12142    #[tokio::test]
12143    async fn protected_payload_storage_ignores_current_policy_for_released_terminal_history(
12144        #[case] status: TransactionStatus,
12145    ) {
12146        let Some((admin_pool, pg_config)) =
12147            connect_test_postgres("protected payload terminal history").await
12148        else {
12149            return;
12150        };
12151        let schema = format!(
12152            "protected_payload_terminal_{}_{}",
12153            status.as_str(),
12154            std::process::id()
12155        );
12156        setup_execution_schema(&admin_pool, &schema).await;
12157        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
12158        let database = connect_test_database(options.options([("search_path", schema.clone())]))
12159            .await
12160            .unwrap();
12161        database
12162            .ensure_execution_transaction_schema()
12163            .await
12164            .unwrap();
12165        let (intent, transaction_hash, _) = persist_test_wrap_broadcast(&database, None).await;
12166        database
12167            .record_execution_status(
12168                intent.id,
12169                &transaction_hash.to_string(),
12170                status,
12171                None,
12172                None,
12173                None,
12174                None,
12175                None,
12176            )
12177            .await
12178            .unwrap();
12179        database
12180            .mark_execution_event_emitted(intent.id, "terminal")
12181            .await
12182            .unwrap();
12183        let keys = payload_test_keys([0x62; 32], vec![], "terminal-history");
12184        database
12185            .ensure_execution_payload_storage(&keys)
12186            .await
12187            .unwrap();
12188
12189        let lease = database
12190            .require_execution_payload_storage(
12191                &keys,
12192                PayloadPolicy {
12193                    chain_id: 42161,
12194                    signer: Address::from_str(WALLET).unwrap(),
12195                    gas_limit: 1,
12196                    max_fee_per_gas: 1,
12197                },
12198                1,
12199            )
12200            .await
12201            .unwrap();
12202        drop(lease);
12203        let check = database
12204            .check_execution_payload_storage(Some(&keys), None, 1)
12205            .await
12206            .unwrap();
12207        let active_intent = reserve_test_wrap_intent(&database).await;
12208        database
12209            .assign_execution_intent_nonce(active_intent.id, 8)
12210            .await
12211            .unwrap();
12212        let active_intent = database
12213            .get_execution_intent(active_intent.id)
12214            .await
12215            .unwrap();
12216        let active_transaction = build_eip1559_transaction(
12217            42161,
12218            8,
12219            78_000,
12220            130_000_000,
12221            10_000_000,
12222            WETH_ADDRESS,
12223            U256::from(1_u64),
12224            Bytes::from(hex::decode("d0e30db0").unwrap()),
12225        );
12226        let (active_hash, active_raw_transaction) = sign_eip1559_transaction(
12227            active_transaction,
12228            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
12229        )
12230        .await
12231        .unwrap();
12232        persist_test_payload(
12233            &database,
12234            Some(&keys),
12235            &active_intent,
12236            active_hash,
12237            &active_raw_transaction,
12238        )
12239        .await;
12240        let active_error = match database
12241            .require_execution_payload_storage(
12242                &keys,
12243                PayloadPolicy {
12244                    chain_id: 42161,
12245                    signer: Address::from_str(WALLET).unwrap(),
12246                    gas_limit: 1,
12247                    max_fee_per_gas: 1,
12248                },
12249                1,
12250            )
12251            .await
12252        {
12253            Ok(_) => panic!("active execution payload unexpectedly passed current policy"),
12254            Err(e) => e,
12255        };
12256        let active_error = format!("{active_error:#}");
12257
12258        assert!(check.protected);
12259        assert_eq!(check.authenticated_rows, 1);
12260        assert!(
12261            active_error.contains(&format!(
12262                "execution intent {} transaction {active_hash} violates current execution policy",
12263                active_intent.id
12264            )),
12265            "was: {active_error}"
12266        );
12267        assert!(
12268            active_error.contains("gas limit 78000 exceeds configured ceiling 1"),
12269            "was: {active_error}"
12270        );
12271
12272        drop_execution_schema(&admin_pool, &schema).await;
12273    }
12274
12275    #[allow(unsafe_code)] // env-var mutation uses the test client's dedicated signer variable
12276    #[tokio::test]
12277    async fn rollback_blocks_execution_until_protection_and_full_check_succeed() {
12278        let state = ready_rpc_state();
12279        let Some((admin_pool, schema, mut client, state)) =
12280            execution_client_with_database("payload_rollback_reactivation", state).await
12281        else {
12282            return;
12283        };
12284        // SAFETY: this test binary owns the dedicated test signer variable
12285        unsafe { std::env::set_var("BLOCKCHAIN_TEST_PRIVATE_KEY", TEST_PRIVATE_KEY) };
12286        client.disconnect().await.unwrap();
12287        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
12288        replace_exec_event_sender(sender);
12289        client.start().unwrap();
12290
12291        client.rollback_payload_storage(1).await.unwrap();
12292        let unprotected = client.check_payload_storage(1).await.unwrap();
12293        let error = client.connect().await.unwrap_err();
12294
12295        assert!(!unprotected.protected);
12296        assert_eq!(unprotected.plaintext_rows, 0);
12297        assert_eq!(unprotected.authenticated_rows, 0);
12298        assert!(
12299            error
12300                .to_string()
12301                .contains("Postgres execution requires protected payload storage"),
12302            "was: {error}"
12303        );
12304        assert!(client.signer.is_none());
12305        assert!(state.recorded_requests().is_empty());
12306
12307        client.protect_payload_storage().await.unwrap();
12308        let protected = client.check_payload_storage(1).await.unwrap();
12309        assert!(protected.protected);
12310        assert_eq!(protected.plaintext_rows, 0);
12311        assert_eq!(protected.authenticated_rows, 0);
12312
12313        client.connect().await.unwrap();
12314
12315        assert!(client.is_connected());
12316        assert!(client.transaction_executor().is_ok());
12317        assert!(!state.recorded_requests().is_empty());
12318
12319        drop(client);
12320        drop_execution_schema(&admin_pool, &schema).await;
12321    }
12322
12323    #[rstest]
12324    #[case::active_key(true)]
12325    #[case::deployment_identity(false)]
12326    #[tokio::test]
12327    async fn postgres_connect_rejects_missing_payload_identity_before_rpc(
12328        #[case] remove_active_key: bool,
12329    ) {
12330        let test_name = if remove_active_key {
12331            "payload_connect_missing_active_key"
12332        } else {
12333            "payload_connect_missing_deployment"
12334        };
12335        let Some((admin_pool, schema, mut client, state)) =
12336            execution_client_with_database(test_name, ready_rpc_state()).await
12337        else {
12338            return;
12339        };
12340        client.disconnect().await.unwrap();
12341        client.payload_keys = None;
12342        if remove_active_key {
12343            client.config.payload_key_env = None;
12344            client.config.payload_deployment_id = None;
12345        } else {
12346            client.config.payload_deployment_id = None;
12347        }
12348
12349        let error = client.connect().await.unwrap_err();
12350
12351        assert!(
12352            error.to_string().contains(if remove_active_key {
12353                "Postgres execution requires an active payload key and deployment identity"
12354            } else {
12355                "Payload deployment ID is required"
12356            }),
12357            "was: {error}"
12358        );
12359        assert!(client.signer.is_none());
12360        assert!(client.payload_keys.is_none());
12361        assert!(state.recorded_requests().is_empty());
12362
12363        drop(client);
12364        drop_execution_schema(&admin_pool, &schema).await;
12365    }
12366
12367    #[tokio::test]
12368    async fn postgres_connect_rejects_missing_envelope_key_before_rpc() {
12369        let Some((admin_pool, schema, mut client, state)) = execution_client_with_database(
12370            "payload_connect_missing_envelope_key",
12371            ready_rpc_state(),
12372        )
12373        .await
12374        else {
12375            return;
12376        };
12377        let database = client.cache.database.as_ref().unwrap().clone();
12378        persist_test_wrap_broadcast(&database, client.payload_keys.as_deref()).await;
12379        client.disconnect().await.unwrap();
12380        client.payload_keys = None;
12381        let keys = set_test_payload_key(&mut client, [0xb6; 32], &schema);
12382        sqlx::query(sqlx::AssertSqlSafe(format!(
12383            "UPDATE {schema}.execution_payload_state SET active_key_id = $1 \
12384             WHERE component = 'signed_transactions'"
12385        )))
12386        .bind(keys.active_key_id().as_slice())
12387        .execute(&admin_pool)
12388        .await
12389        .unwrap();
12390
12391        let error = client.connect().await.unwrap_err();
12392
12393        assert!(
12394            error
12395                .to_string()
12396                .contains("Stored execution payload requires unavailable key"),
12397            "was: {error}"
12398        );
12399        assert!(client.signer.is_none());
12400        assert!(client.payload_keys.is_none());
12401        assert!(state.recorded_requests().is_empty());
12402
12403        drop(client);
12404        drop_execution_schema(&admin_pool, &schema).await;
12405    }
12406
12407    #[tokio::test]
12408    async fn payload_action_lease_blocks_rewrap_transition_until_release() {
12409        let Some((admin_pool, schema, client, _)) = execution_client_with_unprotected_database(
12410            "payload_action_lease",
12411            execution_rpc_state(),
12412        )
12413        .await
12414        else {
12415            return;
12416        };
12417        let database = client.cache.database.as_ref().unwrap();
12418        let keys = payload_test_keys([0x71; 32], vec![], "action-lease");
12419        database
12420            .ensure_execution_payload_storage(&keys)
12421            .await
12422            .unwrap();
12423        let lease = database
12424            .acquire_execution_payload_lease(&keys)
12425            .await
12426            .unwrap();
12427        let rotated = payload_test_keys([0x72; 32], vec![[0x71; 32]], "action-lease");
12428        let mut operation = Box::pin(database.rewrap_execution_payload_storage(&rotated, 1));
12429
12430        assert!(
12431            tokio::time::timeout(Duration::from_millis(50), &mut operation)
12432                .await
12433                .is_err()
12434        );
12435        let state: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
12436            "SELECT operation FROM {schema}.execution_payload_state"
12437        )))
12438        .fetch_one(&admin_pool)
12439        .await
12440        .unwrap();
12441        assert_eq!(state, "ready");
12442
12443        drop(lease);
12444        tokio::time::timeout(Duration::from_secs(2), operation)
12445            .await
12446            .unwrap()
12447            .unwrap();
12448        let state: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
12449            "SELECT operation FROM {schema}.execution_payload_state"
12450        )))
12451        .fetch_one(&admin_pool)
12452        .await
12453        .unwrap();
12454        assert_eq!(state, "ready");
12455
12456        drop_execution_schema(&admin_pool, &schema).await;
12457    }
12458
12459    #[tokio::test]
12460    async fn payload_infrastructure_checks_are_scoped_to_the_execution_schema() {
12461        let Some((admin_pool, pg_config)) = connect_test_postgres("payload schema isolation").await
12462        else {
12463            return;
12464        };
12465        let schema_a = format!("payload_schema_a_{}", std::process::id());
12466        let schema_b = format!("payload_schema_b_{}", std::process::id());
12467        setup_execution_schema(&admin_pool, &schema_a).await;
12468        setup_execution_schema(&admin_pool, &schema_b).await;
12469        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
12470        let database_a =
12471            connect_test_database(options.clone().options([("search_path", schema_a.clone())]))
12472                .await
12473                .unwrap();
12474        let database_b =
12475            connect_test_database(options.options([("search_path", schema_b.clone())]))
12476                .await
12477                .unwrap();
12478        database_a
12479            .ensure_execution_transaction_schema()
12480            .await
12481            .unwrap();
12482        database_b
12483            .ensure_execution_transaction_schema()
12484            .await
12485            .unwrap();
12486        let keys_a = payload_test_keys([0x91; 32], vec![], "schema-a");
12487        let keys_b = payload_test_keys([0x92; 32], vec![], "schema-b");
12488
12489        database_a
12490            .ensure_execution_payload_storage(&keys_a)
12491            .await
12492            .unwrap();
12493        database_b
12494            .ensure_execution_payload_storage(&keys_b)
12495            .await
12496            .unwrap();
12497
12498        for statement in [
12499            format!(
12500                "DROP TRIGGER execution_transaction_payload_fence ON \
12501                 {schema_a}.execution_transaction_hash"
12502            ),
12503            format!(
12504                "ALTER TABLE {schema_a}.execution_transaction_hash \
12505                 DROP CONSTRAINT execution_transaction_payload_protected_check"
12506            ),
12507        ] {
12508            sqlx::query(sqlx::AssertSqlSafe(statement))
12509                .execute(&admin_pool)
12510                .await
12511                .unwrap();
12512        }
12513
12514        let error = database_a
12515            .ensure_execution_payload_storage(&keys_a)
12516            .await
12517            .unwrap_err();
12518
12519        assert!(
12520            error
12521                .to_string()
12522                .contains("without its write fence or constraint"),
12523            "was: {error}"
12524        );
12525
12526        drop_execution_schema(&admin_pool, &schema_a).await;
12527        drop_execution_schema(&admin_pool, &schema_b).await;
12528    }
12529
12530    #[tokio::test]
12531    async fn execution_fresh_schema_preserves_nullable_wallet_address() {
12532        let Some((admin_pool, _)) = connect_test_postgres("fresh execution schema").await else {
12533            return;
12534        };
12535        let schema = format!("execution_fresh_test_{}", std::process::id());
12536        let mut transaction = admin_pool.begin().await.unwrap();
12537        sqlx::query(sqlx::AssertSqlSafe(format!("CREATE SCHEMA {schema}")))
12538            .execute(&mut *transaction)
12539            .await
12540            .unwrap();
12541        sqlx::query(sqlx::AssertSqlSafe(format!(
12542            "SET LOCAL search_path TO {schema}"
12543        )))
12544        .execute(&mut *transaction)
12545        .await
12546        .unwrap();
12547        sqlx::query("CREATE TABLE chain (chain_id INTEGER PRIMARY KEY)")
12548            .execute(&mut *transaction)
12549            .await
12550            .unwrap();
12551        sqlx::query("INSERT INTO chain (chain_id) VALUES (42161)")
12552            .execute(&mut *transaction)
12553            .await
12554            .unwrap();
12555        sqlx::query(sqlx::AssertSqlSafe(execution_transaction_create_sql()))
12556            .execute(&mut *transaction)
12557            .await
12558            .unwrap();
12559        sqlx::query(
12560            "INSERT INTO execution_transaction \
12561             (chain_id, nonce, transaction_hash, purpose, status) \
12562             VALUES (42161, 7, '0xfresh-legacy', 'wrap', 'rejected')",
12563        )
12564        .execute(&mut *transaction)
12565        .await
12566        .unwrap();
12567
12568        let is_nullable: String = sqlx::query_scalar(
12569            "SELECT is_nullable FROM information_schema.columns \
12570             WHERE table_schema = $1 AND table_name = 'execution_transaction' \
12571             AND column_name = 'wallet_address'",
12572        )
12573        .bind(&schema)
12574        .fetch_one(&mut *transaction)
12575        .await
12576        .unwrap();
12577        let wallet_address: Option<String> = sqlx::query_scalar(
12578            "SELECT wallet_address FROM execution_transaction \
12579             WHERE transaction_hash = '0xfresh-legacy'",
12580        )
12581        .fetch_one(&mut *transaction)
12582        .await
12583        .unwrap();
12584
12585        assert_eq!(is_nullable, "YES");
12586        assert_eq!(wallet_address, None);
12587        transaction.rollback().await.unwrap();
12588    }
12589
12590    #[tokio::test]
12591    async fn execution_schema_migration_preserves_existing_rows() {
12592        let Some((admin_pool, pg_config)) =
12593            connect_test_postgres("execution schema migration").await
12594        else {
12595            return;
12596        };
12597        let schema = format!("execution_migration_test_{}", std::process::id());
12598        setup_execution_schema(&admin_pool, &schema).await;
12599        sqlx::query(sqlx::AssertSqlSafe(format!(
12600            "INSERT INTO {schema}.execution_transaction \
12601             (chain_id, nonce, transaction_hash, purpose, status) \
12602             VALUES (42161, 7, '0xlegacy', 'wrap', 'rejected')"
12603        )))
12604        .execute(&admin_pool)
12605        .await
12606        .unwrap();
12607
12608        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
12609        let db_options = db_options.options([("search_path", schema.clone())]);
12610        let database = connect_test_database(db_options).await.unwrap();
12611        database
12612            .ensure_execution_transaction_schema()
12613            .await
12614            .unwrap();
12615        let legacy = database
12616            .get_execution_transaction(42161, "0xlegacy")
12617            .await
12618            .unwrap()
12619            .unwrap();
12620        assert_eq!(legacy.purpose, "wrap");
12621        assert_eq!(legacy.status, "rejected");
12622        assert_eq!(legacy.client_order_id, None);
12623        assert_eq!(legacy.wallet_address, None);
12624        let is_nullable: String = sqlx::query_scalar(
12625            "SELECT is_nullable FROM information_schema.columns \
12626             WHERE table_schema = $1 AND table_name = 'execution_transaction' \
12627             AND column_name = 'wallet_address'",
12628        )
12629        .bind(&schema)
12630        .fetch_one(&admin_pool)
12631        .await
12632        .unwrap();
12633        let fence_error = database
12634            .add_execution_transaction(
12635                42161,
12636                WALLET,
12637                8,
12638                "0xswap",
12639                "swap",
12640                "pending",
12641                Some("O-SWAP-001"),
12642            )
12643            .await
12644            .err()
12645            .unwrap();
12646        assert!(
12647            fence_error
12648                .to_string()
12649                .contains("Legacy execution writer refused"),
12650            "was: {fence_error}"
12651        );
12652        assert_eq!(is_nullable, "YES");
12653
12654        drop_execution_schema(&admin_pool, &schema).await;
12655    }
12656
12657    #[tokio::test]
12658    async fn execution_schema_migration_drops_legacy_wallet_not_null() {
12659        let Some((admin_pool, pg_config)) =
12660            connect_test_postgres("legacy wallet address schema migration").await
12661        else {
12662            return;
12663        };
12664        let schema = format!("execution_wallet_migration_test_{}", std::process::id());
12665        setup_execution_schema(&admin_pool, &schema).await;
12666        sqlx::query(sqlx::AssertSqlSafe(format!(
12667            "ALTER TABLE {schema}.execution_transaction \
12668             ADD COLUMN wallet_address TEXT NOT NULL"
12669        )))
12670        .execute(&admin_pool)
12671        .await
12672        .unwrap();
12673        sqlx::query(sqlx::AssertSqlSafe(format!(
12674            "INSERT INTO {schema}.execution_transaction \
12675             (chain_id, wallet_address, nonce, transaction_hash, purpose, status) \
12676             VALUES (42161, '{WALLET}', 7, '0xlegacy-wallet', 'wrap', 'rejected')"
12677        )))
12678        .execute(&admin_pool)
12679        .await
12680        .unwrap();
12681
12682        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
12683        let db_options = db_options.options([("search_path", schema.clone())]);
12684        let database = connect_test_database(db_options).await.unwrap();
12685        database
12686            .ensure_execution_transaction_schema()
12687            .await
12688            .unwrap();
12689        let legacy = database
12690            .get_execution_transaction(42161, "0xlegacy-wallet")
12691            .await
12692            .unwrap()
12693            .unwrap();
12694        let is_nullable: String = sqlx::query_scalar(
12695            "SELECT is_nullable FROM information_schema.columns \
12696             WHERE table_schema = $1 AND table_name = 'execution_transaction' \
12697             AND column_name = 'wallet_address'",
12698        )
12699        .bind(&schema)
12700        .fetch_one(&admin_pool)
12701        .await
12702        .unwrap();
12703
12704        assert_eq!(legacy.wallet_address.as_deref(), Some(WALLET));
12705        assert_eq!(is_nullable, "YES");
12706        drop_execution_schema(&admin_pool, &schema).await;
12707    }
12708
12709    #[tokio::test]
12710    async fn execution_schema_migration_refuses_unresolved_legacy_rows() {
12711        let Some((admin_pool, pg_config)) =
12712            connect_test_postgres("unsafe execution schema migration").await
12713        else {
12714            return;
12715        };
12716        let schema = format!("execution_unsafe_migration_test_{}", std::process::id());
12717        setup_execution_schema(&admin_pool, &schema).await;
12718        sqlx::query(sqlx::AssertSqlSafe(format!(
12719            "INSERT INTO {schema}.execution_transaction \
12720             (chain_id, nonce, transaction_hash, purpose, status) \
12721             VALUES (42161, 7, '0xunresolved', 'wrap', 'pending')"
12722        )))
12723        .execute(&admin_pool)
12724        .await
12725        .unwrap();
12726        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
12727        let db_options = db_options.options([("search_path", schema.clone())]);
12728        let database = connect_test_database(db_options).await.unwrap();
12729
12730        let error = database
12731            .ensure_execution_transaction_schema()
12732            .await
12733            .unwrap_err();
12734        let legacy_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
12735            "SELECT COUNT(*) FROM {schema}.execution_transaction \
12736             WHERE transaction_hash = '0xunresolved' AND status = 'pending'"
12737        )))
12738        .fetch_one(&admin_pool)
12739        .await
12740        .unwrap();
12741        let v2_table: Option<String> = sqlx::query_scalar("SELECT to_regclass($1)::TEXT")
12742            .bind(format!("{schema}.execution_intent"))
12743            .fetch_one(&admin_pool)
12744            .await
12745            .unwrap();
12746
12747        assert!(
12748            error
12749                .to_string()
12750                .contains("Cannot safely migrate 1 unresolved execution schema version 1"),
12751            "was: {error}"
12752        );
12753        assert_eq!(legacy_count, 1);
12754        assert_eq!(v2_table, None);
12755
12756        drop_execution_schema(&admin_pool, &schema).await;
12757    }
12758
12759    #[rstest]
12760    fn receipt_max_polls_derives_from_timeout() {
12761        assert_eq!(receipt_max_polls(0), 1);
12762        assert_eq!(receipt_max_polls(1), 1);
12763        assert_eq!(receipt_max_polls(60), 60);
12764        assert_eq!(receipt_max_polls(u64::MAX), u32::MAX);
12765        assert_eq!(receipt_timeout(0), Duration::from_secs(1));
12766        assert_eq!(receipt_timeout(60), Duration::from_secs(60));
12767        assert_eq!(
12768            receipt_timeout(u64::MAX),
12769            Duration::from_secs(u64::from(u32::MAX))
12770        );
12771    }
12772
12773    #[rstest]
12774    fn submit_order_errors_when_order_not_cached() {
12775        let client = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string())).0;
12776        let mut cmd = submit_order_cmd(&test_market_sell_order(test_pool().instrument_id));
12777        cmd.client_order_id = ClientOrderId::from("O-UNKNOWN");
12778
12779        let error = client.submit_order(cmd).unwrap_err();
12780
12781        assert!(!error.to_string().is_empty());
12782    }
12783
12784    #[tokio::test]
12785    async fn submit_order_denies_pool_fee_above_uint24() {
12786        let cache = Rc::new(RefCell::new(Cache::default()));
12787        let mut pool = test_pool();
12788        pool.fee = Some(16_777_216); // 2^24, above the uint24 calldata range
12789        cache.borrow_mut().add_pool(pool.clone()).unwrap();
12790        let order = test_market_sell_order(pool.instrument_id);
12791        cache
12792            .borrow_mut()
12793            .add_order(order.clone(), None, None, false)
12794            .unwrap();
12795        let core = ExecutionClientCore::new(
12796            TraderId::from("TRADER-001"),
12797            ClientId::from("BLOCKCHAIN-001"),
12798            *BLOCKCHAIN_VENUE,
12799            OmsType::Netting,
12800            AccountId::from("BLOCKCHAIN-001"),
12801            AccountType::Wallet,
12802            None,
12803            cache,
12804        );
12805        let mut client =
12806            BlockchainExecutionClient::new(core, test_config("http://127.0.0.1:1".to_string()))
12807                .unwrap();
12808        let mut receiver = start_with_events(&mut client);
12809
12810        client.submit_order(submit_order_cmd(&order)).unwrap();
12811
12812        let events = collect_order_events(&mut receiver);
12813        assert_eq!(events.len(), 1);
12814        let OrderEventAny::Denied(denied) = &events[0] else {
12815            panic!("expected OrderDenied, was {:?}", events[0]);
12816        };
12817        assert!(
12818            denied.reason.contains("exceeds uint24"),
12819            "was: {}",
12820            denied.reason
12821        );
12822    }
12823
12824    #[tokio::test]
12825    async fn submit_order_denies_uninitialized_profiler() {
12826        let cache = Rc::new(RefCell::new(Cache::default()));
12827        let pool = test_pool();
12828        cache.borrow_mut().add_pool(pool.clone()).unwrap();
12829        let order = test_market_sell_order(pool.instrument_id);
12830        cache
12831            .borrow_mut()
12832            .add_order(order.clone(), None, None, false)
12833            .unwrap();
12834        cache
12835            .borrow_mut()
12836            .add_pool_profiler(PoolProfiler::new(Arc::new(pool)))
12837            .unwrap();
12838        let core = ExecutionClientCore::new(
12839            TraderId::from("TRADER-001"),
12840            ClientId::from("BLOCKCHAIN-001"),
12841            *BLOCKCHAIN_VENUE,
12842            OmsType::Netting,
12843            AccountId::from("BLOCKCHAIN-001"),
12844            AccountType::Wallet,
12845            None,
12846            cache,
12847        );
12848        let mut client =
12849            BlockchainExecutionClient::new(core, test_config("http://127.0.0.1:1".to_string()))
12850                .unwrap();
12851        let mut receiver = start_with_events(&mut client);
12852
12853        client.submit_order(submit_order_cmd(&order)).unwrap();
12854
12855        let events = collect_order_events(&mut receiver);
12856        assert_eq!(events.len(), 1);
12857        let OrderEventAny::Denied(denied) = &events[0] else {
12858            panic!("expected OrderDenied, was {:?}", events[0]);
12859        };
12860        assert!(
12861            denied.reason.contains("is not initialized"),
12862            "was: {}",
12863            denied.reason
12864        );
12865    }
12866
12867    #[tokio::test]
12868    async fn submit_order_denies_when_quote_cannot_fill_order() {
12869        let cache = Rc::new(RefCell::new(Cache::default()));
12870        let pool = test_pool();
12871        cache.borrow_mut().add_pool(pool.clone()).unwrap();
12872        let order = test_market_sell_order(pool.instrument_id);
12873        cache
12874            .borrow_mut()
12875            .add_order(order.clone(), None, None, false)
12876            .unwrap();
12877        // A narrow one-unit-of-liquidity position cannot fill the order
12878        cache
12879            .borrow_mut()
12880            .add_pool_profiler(test_profiler_with_range(
12881                &pool,
12882                FIXTURE_BLOCK,
12883                FIXTURE_BLOCK_HASH,
12884                U160::from(1u128 << 96),
12885                -10,
12886                10,
12887                1,
12888            ))
12889            .unwrap();
12890        let core = ExecutionClientCore::new(
12891            TraderId::from("TRADER-001"),
12892            ClientId::from("BLOCKCHAIN-001"),
12893            *BLOCKCHAIN_VENUE,
12894            OmsType::Netting,
12895            AccountId::from("BLOCKCHAIN-001"),
12896            AccountType::Wallet,
12897            None,
12898            cache,
12899        );
12900        let mut client =
12901            BlockchainExecutionClient::new(core, test_config("http://127.0.0.1:1".to_string()))
12902                .unwrap();
12903        let mut receiver = start_with_events(&mut client);
12904
12905        client.submit_order(submit_order_cmd(&order)).unwrap();
12906
12907        let events = collect_order_events(&mut receiver);
12908        assert_eq!(events.len(), 1);
12909        let OrderEventAny::Denied(denied) = &events[0] else {
12910            panic!("expected OrderDenied, was {:?}", events[0]);
12911        };
12912        assert!(
12913            denied.reason.contains("cannot fill the order"),
12914            "was: {}",
12915            denied.reason
12916        );
12917    }
12918
12919    #[tokio::test]
12920    async fn submit_order_applies_slippage_param_override_at_ceiling() {
12921        let Some((admin_pool, schema, mut client, state, _)) = swap_client_with_database(
12922            "execution_submit_slippage_override_test",
12923            swap_rpc_state_with_min_amount_out(expected_min_amount_out(200)).await,
12924        )
12925        .await
12926        else {
12927            return;
12928        };
12929        let order = test_market_sell_order(test_pool().instrument_id);
12930        let mut cmd = submit_order_cmd(&order);
12931        // Exactly at the configured ceiling (200 bps): accepted, not denied
12932        cmd.params = Some(serde_json::from_str(r#"{"slippage_bps": 200}"#).unwrap());
12933        let mut receiver = start_with_events(&mut client);
12934        let expected_min_out = expected_min_amount_out(200);
12935
12936        client.submit_order(cmd).unwrap();
12937        await_pending_tasks(&client).await;
12938
12939        let events = collect_order_events(&mut receiver);
12940        assert_swap_submitted_and_filled(&events);
12941
12942        let (_, expected_raw) = expected_swap_tx(expected_min_out).await;
12943        let broadcasts: Vec<_> = state
12944            .recorded_requests()
12945            .into_iter()
12946            .filter(|request| request["method"] == "eth_sendRawTransaction")
12947            .collect();
12948        assert_eq!(broadcasts.len(), 1);
12949        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
12950
12951        drop_execution_schema(&admin_pool, &schema).await;
12952    }
12953
12954    #[tokio::test]
12955    async fn submit_order_accepts_quote_fresh_at_max_age_boundary() {
12956        let min_amount_out = expected_min_amount_out(50);
12957        let (tx_hash, _) = expected_swap_tx(min_amount_out).await;
12958        let head = finalized_swap_block(tx_hash, min_amount_out);
12959        let state = swap_rpc_state()
12960            .await
12961            .with_response("eth_getBlockByNumber", &head)
12962            .with_parameter_response("eth_getBlockByNumber", FIXTURE_BLOCK_PARAM, BLOCK_BY_NUMBER);
12963        let Some((admin_pool, schema, mut client, state, cache)) =
12964            swap_client_with_database_config(
12965                "execution_submit_fresh_boundary_test",
12966                state,
12967                |http_rpc_url| {
12968                    let mut config = test_config(http_rpc_url);
12969                    config.max_quote_age_blocks = Some(1);
12970                    config
12971                },
12972            )
12973            .await
12974        else {
12975            return;
12976        };
12977        let pool = test_pool();
12978        cache
12979            .borrow_mut()
12980            .add_pool_profiler(test_profiler_at_block(
12981                &pool,
12982                FIXTURE_BLOCK,
12983                FIXTURE_BLOCK_HASH,
12984            ))
12985            .unwrap();
12986        let order = test_market_sell_order(pool.instrument_id);
12987        let mut receiver = start_with_events(&mut client);
12988
12989        client.submit_order(submit_order_cmd(&order)).unwrap();
12990        await_pending_tasks(&client).await;
12991
12992        let events = collect_order_events(&mut receiver);
12993        assert_eq!(events.len(), 1, "was: {events:?}");
12994        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
12995        assert_eq!(
12996            state
12997                .recorded_requests()
12998                .iter()
12999                .filter(|request| request["method"] == "eth_sendRawTransaction")
13000                .count(),
13001            1
13002        );
13003
13004        drop_execution_schema(&admin_pool, &schema).await;
13005    }
13006
13007    #[tokio::test]
13008    async fn submit_order_sells_base_token_from_token1_position() {
13009        // A pool with the token order reversed relative to the convention: USDC is token0
13010        // and WETH is token1, so the base token (WETH, by token priority) sits in the
13011        // token1 position and the swap quotes zero_for_one = false
13012        let chain = Arc::new(chains::ARBITRUM.clone());
13013        let dex = Arc::clone(&UNISWAP_V3.dex);
13014        let usdc = Token::new(
13015            Arc::clone(&chain),
13016            address!("af88d065e77c8cC2239327C5EDb3A432268e5831"),
13017            "USD Coin".to_string(),
13018            "USDC".to_string(),
13019            6,
13020        );
13021        let weth = Token::new(
13022            Arc::clone(&chain),
13023            address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
13024            "Wrapped Ether".to_string(),
13025            "WETH".to_string(),
13026            18,
13027        );
13028        let pool = Pool::new(
13029            chain,
13030            dex,
13031            address!("C6962004f452bE9203591991D15f6b388e09E8D0"),
13032            PoolIdentifier::from_address(address!("C6962004f452bE9203591991D15f6b388e09E8D0")),
13033            55_000_000,
13034            usdc,
13035            weth,
13036            Some(500),
13037            Some(10),
13038            UnixNanos::default(),
13039        );
13040
13041        let cache = Rc::new(RefCell::new(Cache::default()));
13042        cache.borrow_mut().add_pool(pool.clone()).unwrap();
13043        let order = test_market_sell_order(pool.instrument_id);
13044        cache
13045            .borrow_mut()
13046            .add_order(order.clone(), None, None, false)
13047            .unwrap();
13048        // Asymmetric price so the zero_for_one direction changes the quote
13049        cache
13050            .borrow_mut()
13051            .add_pool_profiler(test_profiler_with_state(
13052                &pool,
13053                FIXTURE_BLOCK,
13054                U160::from(2u128 << 96),
13055                TEST_LIQUIDITY,
13056            ))
13057            .unwrap();
13058
13059        let (admin_pool, pg_config) = match connect_test_postgres("orientation").await {
13060            Some(setup) => setup,
13061            None => return,
13062        };
13063        let schema = format!("execution_submit_orientation_test_{}", std::process::id());
13064        setup_execution_schema(&admin_pool, &schema).await;
13065        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
13066        let db_options = db_options.options([("search_path", schema.clone())]);
13067        let database = connect_test_database(db_options).await.unwrap();
13068
13069        let state = swap_rpc_state()
13070            .await
13071            .with_call_response(POOL_TOKEN0_SELECTOR, CALL_USDC)
13072            .with_call_response(POOL_TOKEN1_SELECTOR, CALL_WETH)
13073            .with_response("eth_getTransactionReceipt", RECEIPT_NULL);
13074        let addr = start_mock_rpc_server(state.clone()).await;
13075        let core = ExecutionClientCore::new(
13076            TraderId::from("TRADER-001"),
13077            ClientId::from("BLOCKCHAIN-001"),
13078            *BLOCKCHAIN_VENUE,
13079            OmsType::Netting,
13080            AccountId::from("BLOCKCHAIN-001"),
13081            AccountType::Wallet,
13082            None,
13083            cache,
13084        );
13085        let mut config = test_config(format!("http://{addr}"));
13086        let result = |response: &str| {
13087            serde_json::from_str::<serde_json::Value>(response).unwrap()["result"]
13088                .as_str()
13089                .unwrap()
13090                .to_string()
13091        };
13092        {
13093            let verification = config.verification.as_mut().unwrap();
13094            let pool_identity = &mut verification.deployment_manifest.pools[0];
13095            pool_identity.token0 = USDC.to_string();
13096            pool_identity.token1 = WETH.to_string();
13097            let pool_contract = verification
13098                .deployment_manifest
13099                .contracts
13100                .iter_mut()
13101                .find(|contract| contract.role == BlockchainContractRole::Pool)
13102                .unwrap();
13103
13104            for probe in &mut pool_contract.probes {
13105                if probe.call_data.starts_with(POOL_TOKEN0_SELECTOR) {
13106                    probe.expected_output = result(CALL_USDC);
13107                } else if probe.call_data.starts_with(POOL_TOKEN1_SELECTOR) {
13108                    probe.expected_output = result(CALL_WETH);
13109                }
13110            }
13111        }
13112        refresh_test_manifest_digest(&mut config);
13113        let mut client = BlockchainExecutionClient::new(core, config).unwrap();
13114        client.cache.database = Some(database);
13115        client
13116            .cache
13117            .ensure_execution_transaction_schema()
13118            .await
13119            .unwrap();
13120        protect_test_storage(&mut client, &schema).await;
13121        initialize_test_verification_ledger(&client).await;
13122        client.signer = Some(Arc::new(
13123            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
13124        ));
13125        client.core.set_connected();
13126        let mut receiver = start_with_events(&mut client);
13127
13128        let profiler = test_profiler_with_state(
13129            &pool,
13130            FIXTURE_BLOCK,
13131            U160::from(2u128 << 96),
13132            TEST_LIQUIDITY,
13133        );
13134        let quote = profiler
13135            .swap_exact_in(U256::from(1_000_000_000_000_000u64), false, None)
13136            .unwrap();
13137        let quoted = exact_output_amount(&quote, false).unwrap();
13138        let expected_min_out = derive_min_amount_out(quoted, 50).unwrap();
13139        let wrong_direction_quote = profiler
13140            .swap_exact_in(U256::from(1_000_000_000_000_000u64), true, None)
13141            .unwrap();
13142        let wrong_direction_out = exact_output_amount(&wrong_direction_quote, true).unwrap();
13143        assert_ne!(
13144            quoted, wrong_direction_out,
13145            "the asymmetric price must make the quote direction observable"
13146        );
13147        assert_ne!(
13148            expected_min_out,
13149            expected_min_amount_out(50),
13150            "the profiler quote must remain distinct from the independent quote fixture"
13151        );
13152
13153        client.submit_order(submit_order_cmd(&order)).unwrap();
13154        await_pending_tasks(&client).await;
13155
13156        let events = collect_order_events(&mut receiver);
13157        assert_eq!(events.len(), 1);
13158        assert!(
13159            matches!(&events[0], OrderEventAny::Submitted(_)),
13160            "was: {:?}",
13161            events[0]
13162        );
13163
13164        let (_, expected_raw) = expected_swap_tx(expected_min_amount_out(50)).await;
13165        let broadcasts: Vec<_> = state
13166            .recorded_requests()
13167            .into_iter()
13168            .filter(|request| request["method"] == "eth_sendRawTransaction")
13169            .collect();
13170        assert_eq!(broadcasts.len(), 1);
13171        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
13172
13173        drop_execution_schema(&admin_pool, &schema).await;
13174    }
13175
13176    #[tokio::test]
13177    async fn submit_order_denies_on_chain_mismatch() {
13178        let state = swap_rpc_state()
13179            .await
13180            .with_response("eth_chainId", CHAIN_ID_ETHEREUM);
13181        let Some((admin_pool, schema, mut client, state, _)) =
13182            swap_client_with_database("execution_submit_chain_mismatch_test", state).await
13183        else {
13184            return;
13185        };
13186        let order = test_market_sell_order(test_pool().instrument_id);
13187        let mut receiver = start_with_events(&mut client);
13188
13189        client.submit_order(submit_order_cmd(&order)).unwrap();
13190        await_pending_tasks(&client).await;
13191
13192        let events = collect_order_events(&mut receiver);
13193        assert_eq!(events.len(), 1);
13194        let OrderEventAny::Denied(denied) = &events[0] else {
13195            panic!("expected OrderDenied, was {:?}", events[0]);
13196        };
13197        assert!(
13198            denied
13199                .reason
13200                .contains("pre-sign chain ID verification disagreed"),
13201            "was: {}",
13202            denied.reason
13203        );
13204        let requests = state.recorded_requests();
13205        assert!(
13206            requests
13207                .iter()
13208                .all(|request| request["method"] != "eth_sendRawTransaction"),
13209            "no broadcast may follow a chain mismatch"
13210        );
13211        assert!(client.in_flight.lock().is_none());
13212
13213        drop_execution_schema(&admin_pool, &schema).await;
13214    }
13215
13216    #[tokio::test]
13217    async fn submit_order_finality_timeout_marks_dropped_and_keeps_ownership() {
13218        let receipt_release = Arc::new(tokio::sync::Semaphore::new(0));
13219        let state = swap_rpc_state()
13220            .await
13221            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
13222            .with_response_release("eth_getTransactionReceipt", Arc::clone(&receipt_release));
13223        let Some((admin_pool, schema, mut client, state, _)) =
13224            swap_client_with_database("execution_submit_inclusion_timeout_test", state).await
13225        else {
13226            return;
13227        };
13228        client.transaction_limits.receipt_timeout_secs = 1;
13229        let order = test_market_sell_order(test_pool().instrument_id);
13230        let mut receiver = start_with_events(&mut client);
13231
13232        client.submit_order(submit_order_cmd(&order)).unwrap();
13233        await_recorded_requests(&state, "eth_getTransactionReceipt", 3).await;
13234        tokio::time::timeout(Duration::from_secs(3), await_pending_tasks(&client))
13235            .await
13236            .unwrap();
13237        receipt_release.add_permits(3);
13238
13239        // Broadcast acceptance was observed, so the order is submitted; the unobserved
13240        // inclusion justifies no further event
13241        let events = collect_order_events(&mut receiver);
13242        assert_eq!(events.len(), 1);
13243        assert!(
13244            matches!(&events[0], OrderEventAny::Submitted(_)),
13245            "was: {:?}",
13246            events[0]
13247        );
13248
13249        let record = client
13250            .cache
13251            .get_execution_transaction(
13252                42161,
13253                &expected_swap_tx(expected_min_amount_out(50))
13254                    .await
13255                    .0
13256                    .to_string(),
13257            )
13258            .await
13259            .unwrap()
13260            .unwrap();
13261        assert_eq!(record.status, "dropped");
13262        assert!(client.in_flight.lock().is_some());
13263
13264        drop_execution_schema(&admin_pool, &schema).await;
13265    }
13266
13267    #[tokio::test]
13268    async fn included_receipt_finality_timeout_marks_dropped_and_keeps_ownership() {
13269        let state = execution_rpc_state()
13270            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
13271            .with_response("eth_estimateGas", ESTIMATE_GAS)
13272            .with_response("eth_call", CALL_BALANCE)
13273            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS)
13274            .with_parameter_response("eth_getBlockByNumber", "finalized", BLOCK_BY_NUMBER)
13275            .with_send_raw_transaction_echo();
13276        let Some((admin_pool, schema, mut client, _)) =
13277            execution_client_with_database("execution_included_timeout_test", state).await
13278        else {
13279            return;
13280        };
13281        client.transaction_limits.receipt_timeout_secs = 1;
13282
13283        let error = client
13284            .wrap(U256::from(1_000_000_000_000_000_u64))
13285            .await
13286            .unwrap_err();
13287        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
13288            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
13289        )))
13290        .fetch_all(&admin_pool)
13291        .await
13292        .unwrap();
13293
13294        assert!(
13295            error.to_string().contains("Timed out awaiting finality"),
13296            "was: {error}"
13297        );
13298        assert_eq!(transitions, ["prepared", "signed", "broadcast", "dropped"]);
13299        assert!(client.in_flight.lock().is_some());
13300
13301        drop_execution_schema(&admin_pool, &schema).await;
13302    }
13303
13304    #[tokio::test]
13305    async fn submit_order_single_in_flight_rejects_concurrent_swap() {
13306        let broadcast_release = Arc::new(tokio::sync::Semaphore::new(0));
13307        let state = swap_rpc_state()
13308            .await
13309            .with_response_release("eth_sendRawTransaction", Arc::clone(&broadcast_release));
13310        let Some((admin_pool, schema, mut client, state, cache)) =
13311            swap_client_with_database("execution_submit_concurrent_test", state).await
13312        else {
13313            return;
13314        };
13315        let pool = test_pool();
13316        let first = test_market_sell_order(pool.instrument_id);
13317        let second = OrderTestBuilder::new(OrderType::Market)
13318            .trader_id(TraderId::from("TRADER-001"))
13319            .strategy_id(StrategyId::from("S-001"))
13320            .instrument_id(pool.instrument_id)
13321            .client_order_id(ClientOrderId::from("O-SWAP-002"))
13322            .side(OrderSide::Sell)
13323            .quantity(Quantity::from("0.001"))
13324            .build();
13325        cache
13326            .borrow_mut()
13327            .add_order(second.clone(), None, None, false)
13328            .unwrap();
13329        let mut receiver = start_with_events(&mut client);
13330
13331        client.submit_order(submit_order_cmd(&first)).unwrap();
13332        await_recorded_requests(&state, "eth_sendRawTransaction", 1).await;
13333        client.submit_order(submit_order_cmd(&second)).unwrap();
13334        let event = tokio::time::timeout(TEST_TIMEOUT, receiver.recv())
13335            .await
13336            .unwrap()
13337            .unwrap();
13338        let ExecutionEvent::Order(OrderEventAny::Denied(denied)) = event else {
13339            panic!("expected OrderDenied, was {event:?}");
13340        };
13341        assert_eq!(denied.client_order_id, second.client_order_id());
13342        assert!(
13343            denied
13344                .reason
13345                .contains("at most one transaction can be in flight"),
13346            "was: {}",
13347            denied.reason
13348        );
13349        broadcast_release.add_permits(1);
13350        await_pending_tasks(&client).await;
13351
13352        let events = collect_order_events(&mut receiver);
13353        assert_swap_submitted_and_filled(&events);
13354
13355        let broadcasts = state
13356            .recorded_requests()
13357            .into_iter()
13358            .filter(|request| request["method"] == "eth_sendRawTransaction")
13359            .count();
13360        assert_eq!(broadcasts, 1);
13361        let row_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
13362            "SELECT COUNT(*) FROM {schema}.execution_intent"
13363        )))
13364        .fetch_one(&admin_pool)
13365        .await
13366        .unwrap();
13367        assert_eq!(row_count, 1);
13368        assert!(client.in_flight.lock().is_none());
13369
13370        drop_execution_schema(&admin_pool, &schema).await;
13371    }
13372
13373    #[tokio::test]
13374    async fn preflight_ready_when_all_checks_pass() {
13375        let (client, state) = client_with_mock_rpc(ready_rpc_state()).await;
13376        let pool = test_pool();
13377
13378        let report = client.preflight(&pool.instrument_id).await.unwrap();
13379
13380        assert!(report.ready, "issues: {:?}", report.issues);
13381        assert!(report.issues.is_empty());
13382        assert_eq!(report.expected_chain_id, 42161);
13383        assert_eq!(report.actual_chain_id, 42161);
13384        assert!(report.chain_id_matches);
13385        assert_eq!(
13386            report.pool.address,
13387            address!("C6962004f452bE9203591991D15f6b388e09E8D0")
13388        );
13389        assert!(report.pool.has_deployed_code);
13390        assert_eq!(report.pool.fee, Some(500));
13391        assert_eq!(
13392            report.pool.base_token,
13393            address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1")
13394        );
13395        assert_eq!(
13396            report.pool.quote_token,
13397            address!("af88d065e77c8cC2239327C5EDb3A432268e5831")
13398        );
13399        assert_eq!(report.routers.len(), 1);
13400        assert!(report.routers[0].has_deployed_code);
13401        assert_eq!(report.tokens.len(), 2);
13402        assert_eq!(
13403            report.tokens[0].wallet_balance,
13404            U256::from(500_000_000_000_000_000u64)
13405        );
13406        assert_eq!(
13407            report.tokens[0].router_allowances,
13408            vec![(
13409                address!("E592427A0AEce92De3Edee1F18E0157C05861564"),
13410                U256::from(1_000_000_000_000_000_000u64)
13411            )]
13412        );
13413        assert_eq!(
13414            report.native_balance_wei,
13415            U256::from(1_000_000_000_000_000_000u64)
13416        );
13417        assert_eq!(report.base_fee_per_gas_wei, 100_000_000);
13418        assert_eq!(report.max_priority_fee_per_gas_wei, 10_000_000);
13419        assert_eq!(report.derived_max_fee_per_gas_wei, 130_000_000);
13420        assert!(report.fee_within_ceiling);
13421
13422        let requests = state.recorded_requests();
13423        for method in ["eth_getCode", "eth_call", "eth_getBalance"] {
13424            let matching: Vec<_> = requests
13425                .iter()
13426                .filter(|request| request["method"] == method)
13427                .collect();
13428            assert!(!matching.is_empty(), "method {method}");
13429            assert!(
13430                matching
13431                    .iter()
13432                    .all(|request| request["params"][1] == "latest"),
13433                "method {method}: {matching:?}"
13434            );
13435        }
13436    }
13437
13438    #[tokio::test]
13439    async fn preflight_not_ready_without_pool_fee() {
13440        let addr = start_mock_rpc_server(ready_rpc_state()).await;
13441        let mut pool = test_pool();
13442        pool.fee = None;
13443        let client = test_client_from_config(test_config(format!("http://{addr}")), pool.clone());
13444
13445        let report = client.preflight(&pool.instrument_id).await.unwrap();
13446
13447        assert!(!report.ready);
13448        assert_eq!(report.pool.fee, None);
13449        assert_eq!(report.issues, vec!["Pool fee tier is missing"]);
13450    }
13451
13452    #[tokio::test]
13453    async fn preflight_not_ready_on_wrong_chain() {
13454        let state = ready_rpc_state().with_response("eth_chainId", CHAIN_ID_ETHEREUM);
13455        let (client, _) = client_with_mock_rpc(state).await;
13456        let pool = test_pool();
13457
13458        let report = client.preflight(&pool.instrument_id).await.unwrap();
13459
13460        assert!(!report.ready);
13461        assert!(!report.chain_id_matches);
13462        assert!(
13463            report
13464                .issues
13465                .iter()
13466                .any(|issue| issue.contains("Chain ID mismatch"))
13467        );
13468    }
13469
13470    #[tokio::test]
13471    async fn preflight_not_ready_without_deployed_code() {
13472        let state = ready_rpc_state().with_response("eth_getCode", GET_CODE_EMPTY);
13473        let (client, _) = client_with_mock_rpc(state).await;
13474        let pool = test_pool();
13475
13476        let report = client.preflight(&pool.instrument_id).await.unwrap();
13477
13478        assert!(!report.ready);
13479        assert!(!report.pool.has_deployed_code);
13480        assert!(!report.routers[0].has_deployed_code);
13481        assert!(report.tokens.iter().all(|t| !t.has_deployed_code));
13482        assert!(
13483            report
13484                .issues
13485                .iter()
13486                .any(|issue| issue.contains("No deployed bytecode at router address"))
13487        );
13488    }
13489
13490    #[tokio::test]
13491    async fn preflight_not_ready_with_zero_balances_and_allowance() {
13492        let state = ready_rpc_state()
13493            .with_response("eth_getBalance", GET_BALANCE_ZERO)
13494            .with_call_response(BALANCE_OF_SELECTOR, CALL_ZERO)
13495            .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO);
13496        let (client, _) = client_with_mock_rpc(state).await;
13497        let pool = test_pool();
13498
13499        let report = client.preflight(&pool.instrument_id).await.unwrap();
13500
13501        assert!(!report.ready);
13502        assert!(
13503            report
13504                .issues
13505                .iter()
13506                .any(|issue| issue.contains("Native currency balance is zero"))
13507        );
13508        assert!(
13509            report
13510                .issues
13511                .iter()
13512                .any(|issue| issue.contains("balance is zero"))
13513        );
13514        assert!(
13515            report
13516                .issues
13517                .iter()
13518                .any(|issue| issue.contains("No router allowance"))
13519        );
13520    }
13521
13522    #[tokio::test]
13523    async fn preflight_not_ready_when_fees_exceed_ceiling() {
13524        let addr = start_mock_rpc_server(ready_rpc_state()).await;
13525        let mut config = test_config(format!("http://{addr}"));
13526        config.max_fee_per_gas_wei = 1;
13527        let pool = test_pool();
13528        let client = test_client_from_config(config, pool.clone());
13529
13530        let report = client.preflight(&pool.instrument_id).await.unwrap();
13531
13532        assert!(!report.ready);
13533        assert!(!report.fee_within_ceiling);
13534        assert_eq!(report.derived_max_fee_per_gas_wei, 130_000_000);
13535        assert!(
13536            report
13537                .issues
13538                .iter()
13539                .any(|issue| issue.contains("exceeds ceiling"))
13540        );
13541    }
13542
13543    #[rstest]
13544    fn resolve_pool_rejects_unknown_pool() {
13545        let client = test_client("http://127.0.0.1:1".to_string());
13546        let unknown: InstrumentId = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45.Arbitrum:UniswapV3"
13547            .parse()
13548            .unwrap();
13549
13550        let error = client.resolve_pool(&unknown).unwrap_err();
13551
13552        assert!(error.to_string().contains("Unknown pool"), "was: {error}");
13553    }
13554
13555    #[rstest]
13556    fn resolve_pool_rejects_mismatched_chain() {
13557        let client = test_client("http://127.0.0.1:1".to_string());
13558        let ethereum_pool: InstrumentId =
13559            "0xC6962004f452bE9203591991D15f6b388e09E8D0.Ethereum:UniswapV3"
13560                .parse()
13561                .unwrap();
13562
13563        let error = client.resolve_pool(&ethereum_pool).unwrap_err();
13564
13565        assert!(
13566            error
13567                .to_string()
13568                .contains("does not match the client chain"),
13569            "was: {error}"
13570        );
13571    }
13572
13573    #[rstest]
13574    fn resolve_pool_rejects_unsupported_dex() {
13575        let client = test_client("http://127.0.0.1:1".to_string());
13576        let v4_pool: InstrumentId = "0xC6962004f452bE9203591991D15f6b388e09E8D0.Arbitrum:UniswapV4"
13577            .parse()
13578            .unwrap();
13579
13580        let error = client.resolve_pool(&v4_pool).unwrap_err();
13581
13582        assert!(
13583            error.to_string().contains("only UniswapV3 is supported"),
13584            "was: {error}"
13585        );
13586    }
13587
13588    #[rstest]
13589    fn resolve_pool_rejects_pool_id_identifier() {
13590        let client = test_client("http://127.0.0.1:1".to_string());
13591        let pool_id: InstrumentId =
13592            "0x0000000000000000000000000000000000000000000000000000000000000000.Arbitrum:UniswapV3"
13593                .parse()
13594                .unwrap();
13595
13596        let error = client.resolve_pool(&pool_id).unwrap_err();
13597
13598        assert!(
13599            error
13600                .to_string()
13601                .contains("only address identifiers are supported"),
13602            "was: {error}"
13603        );
13604    }
13605
13606    #[rstest]
13607    fn resolve_pool_rejects_ambiguous_token_priority() {
13608        let chain = Arc::new(chains::ARBITRUM.clone());
13609        let dex = Arc::clone(&UNISWAP_V3.dex);
13610        let token_a = Token::new(
13611            Arc::clone(&chain),
13612            address!("1111111111111111111111111111111111111111"),
13613            "Token A".to_string(),
13614            "TOKA".to_string(),
13615            18,
13616        );
13617        let token_b = Token::new(
13618            Arc::clone(&chain),
13619            address!("2222222222222222222222222222222222222222"),
13620            "Token B".to_string(),
13621            "TOKB".to_string(),
13622            18,
13623        );
13624        let pool = Pool::new(
13625            chain,
13626            dex,
13627            address!("3333333333333333333333333333333333333333"),
13628            PoolIdentifier::from_address(address!("3333333333333333333333333333333333333333")),
13629            55_000_000,
13630            token_a,
13631            token_b,
13632            Some(500),
13633            Some(10),
13634            UnixNanos::default(),
13635        );
13636        let client =
13637            test_client_from_config(test_config("http://127.0.0.1:1".to_string()), pool.clone());
13638
13639        let error = client.resolve_pool(&pool.instrument_id).unwrap_err();
13640
13641        assert!(error.to_string().contains("ambiguous"), "was: {error}");
13642    }
13643
13644    #[rstest]
13645    fn new_parses_pair_specific_quote_spend_limits_with_distinct_precisions() {
13646        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13647        config.quote_spend_limits = Some(vec![
13648            quote_spend_limit(WETH, USDC, 18, &U256::MAX.to_string()),
13649            quote_spend_limit(USDC, WETH, 6, "1000000000"),
13650        ]);
13651
13652        let client = test_client_from_config(config, test_pool());
13653        let sell_ceiling = client
13654            .transaction_limits
13655            .quote_spend_limits
13656            .get(&(WETH_ADDRESS, USDC_ADDRESS))
13657            .unwrap();
13658        let buy_ceiling = client
13659            .transaction_limits
13660            .quote_spend_limits
13661            .get(&(USDC_ADDRESS, WETH_ADDRESS))
13662            .unwrap();
13663
13664        assert_eq!(sell_ceiling.spend_token, WETH_ADDRESS);
13665        assert_eq!(sell_ceiling.spend_token_decimals, 18);
13666        assert_eq!(sell_ceiling.max_amount, U256::MAX);
13667        assert_eq!(buy_ceiling.spend_token, USDC_ADDRESS);
13668        assert_eq!(buy_ceiling.spend_token_decimals, 6);
13669        assert_eq!(buy_ceiling.max_amount, U256::from(1_000_000_000u64));
13670    }
13671
13672    #[rstest]
13673    fn new_rejects_quote_spend_limit_token_pair_mismatch() {
13674        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13675        config.quote_spend_limits.as_mut().unwrap()[0].spend_token = WETH.to_string();
13676
13677        let error = test_client_result(config, test_pool()).unwrap_err();
13678
13679        assert!(
13680            error
13681                .to_string()
13682                .contains("`spend_token` must match `token_in`"),
13683            "was: {error}"
13684        );
13685    }
13686
13687    #[rstest]
13688    fn new_rejects_quote_spend_limit_pair_outside_allowlist() {
13689        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13690        config.quote_spend_limits = Some(vec![quote_spend_limit(
13691            USDC,
13692            "0x1111111111111111111111111111111111111111",
13693            6,
13694            "1000000000",
13695        )]);
13696
13697        let error = test_client_result(config, test_pool()).unwrap_err();
13698
13699        assert!(
13700            error
13701                .to_string()
13702                .contains("is not in the `allowed_token_pairs` allowlist"),
13703            "was: {error}"
13704        );
13705    }
13706
13707    #[rstest]
13708    fn new_rejects_duplicate_quote_spend_pairs() {
13709        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13710        config.quote_spend_limits = Some(vec![
13711            quote_spend_limit(USDC, WETH, 6, "1000000000"),
13712            quote_spend_limit(USDC, WETH, 6, "2000000000"),
13713        ]);
13714
13715        let error = test_client_result(config, test_pool()).unwrap_err();
13716
13717        assert!(
13718            error
13719                .to_string()
13720                .contains("Duplicate quote spend limit for token pair"),
13721            "was: {error}"
13722        );
13723    }
13724
13725    #[rstest]
13726    #[case::empty("")]
13727    #[case::signed("-1")]
13728    #[case::fractional("1.5")]
13729    #[case::hexadecimal("0x10")]
13730    #[case::overflow(
13731        "115792089237316195423570985008687907853269984665640564039457584007913129639936"
13732    )]
13733    fn new_rejects_invalid_quote_spend_max_amount(#[case] max_amount: &str) {
13734        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13735        config.quote_spend_limits.as_mut().unwrap()[0].max_amount = max_amount.to_string();
13736
13737        let error = test_client_result(config, test_pool()).unwrap_err();
13738
13739        assert!(
13740            error.to_string().contains("Quote spend limit `max_amount`"),
13741            "was: {error}"
13742        );
13743    }
13744
13745    #[rstest]
13746    #[case::allowed_token_pairs("allowed_token_pairs")]
13747    #[case::slippage_bps("slippage_bps")]
13748    #[case::max_slippage_bps("max_slippage_bps")]
13749    #[case::max_order_amount("max_order_amount")]
13750    #[case::deadline_seconds("deadline_seconds")]
13751    #[case::max_quote_age_blocks("max_quote_age_blocks")]
13752    #[case::receipt_timeout_secs("receipt_timeout_secs")]
13753    fn new_rejects_each_missing_transaction_limit(#[case] missing: &str) {
13754        let mut config = test_config("http://127.0.0.1:1".to_string());
13755        match missing {
13756            "allowed_token_pairs" => config.allowed_token_pairs = None,
13757            "slippage_bps" => config.slippage_bps = None,
13758            "max_slippage_bps" => config.max_slippage_bps = None,
13759            "max_order_amount" => config.max_order_amount = None,
13760            "deadline_seconds" => config.deadline_seconds = None,
13761            "max_quote_age_blocks" => config.max_quote_age_blocks = None,
13762            "receipt_timeout_secs" => config.receipt_timeout_secs = None,
13763            _ => unreachable!(),
13764        }
13765
13766        let error = test_client_result(config, test_pool()).unwrap_err();
13767
13768        assert_eq!(
13769            error.to_string(),
13770            "Blockchain execution transaction limits are required: allowed_token_pairs, slippage_bps, max_slippage_bps, max_order_amount, deadline_seconds, max_quote_age_blocks, receipt_timeout_secs"
13771        );
13772    }
13773
13774    #[rstest]
13775    fn new_rejects_empty_router_allowlist() {
13776        let mut config = test_config("http://127.0.0.1:1".to_string());
13777        config.router_addresses = Vec::new();
13778
13779        let error = test_client_result(config, test_pool()).unwrap_err();
13780
13781        assert!(
13782            error.to_string().contains("at least one router address"),
13783            "was: {error}"
13784        );
13785    }
13786
13787    #[tokio::test]
13788    async fn wrap_refuses_without_durable_store() {
13789        let (mut client, _) = client_with_mock_rpc(ready_rpc_state()).await;
13790        client.core.set_connected();
13791
13792        let error = client.wrap(U256::from(1_000u64)).await.unwrap_err();
13793
13794        assert!(
13795            error.to_string().contains("No durable store configured"),
13796            "was: {error}"
13797        );
13798    }
13799
13800    #[tokio::test]
13801    async fn approve_rejects_router_outside_allowlist() {
13802        let (mut client, state) = client_with_mock_rpc(ready_rpc_state()).await;
13803
13804        let error = client
13805            .approve(
13806                WETH_ADDRESS,
13807                U256::from(1_000u64),
13808                address!("68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"),
13809            )
13810            .await
13811            .err()
13812            .unwrap();
13813
13814        assert!(
13815            error
13816                .to_string()
13817                .contains("not in the configured `router_addresses` allowlist"),
13818            "was: {error}"
13819        );
13820        assert!(state.recorded_requests().is_empty());
13821    }
13822
13823    #[tokio::test]
13824    async fn approve_rejects_token_outside_input_allowlist() {
13825        let (mut client, state) = client_with_mock_rpc(ready_rpc_state()).await;
13826
13827        let error = client
13828            .approve(USDC_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
13829            .await
13830            .unwrap_err();
13831
13832        assert!(
13833            error
13834                .to_string()
13835                .contains("is not an input token in the configured `allowed_token_pairs`"),
13836            "was: {error}"
13837        );
13838        assert!(state.recorded_requests().is_empty());
13839    }
13840
13841    #[tokio::test]
13842    async fn in_flight_guard_rejects_second_transaction() {
13843        let (mut client, _) = client_with_mock_rpc(ready_rpc_state()).await;
13844        client.core.set_connected();
13845        *client.in_flight.lock() = Some(InFlightSlot::AwaitingFinality(InFlightTransaction {
13846            intent_id: 1,
13847            nonce: 7,
13848            tx_hash: B256::ZERO,
13849            purpose: TransactionPurpose::Wrap,
13850        }));
13851
13852        let error = client.wrap(U256::from(1_000u64)).await.unwrap_err();
13853
13854        assert!(
13855            error.to_string().contains("still awaiting finality"),
13856            "was: {error}"
13857        );
13858    }
13859
13860    #[tokio::test]
13861    async fn wrap_rejects_zero_amount() {
13862        let (mut client, _) = client_with_mock_rpc(ready_rpc_state()).await;
13863
13864        let error = client.wrap(U256::ZERO).await.unwrap_err();
13865
13866        assert!(
13867            error.to_string().contains("Wrap amount must be positive"),
13868            "was: {error}"
13869        );
13870    }
13871
13872    #[tokio::test]
13873    async fn wrap_rejects_code_free_target_before_broadcast() {
13874        let state = execution_rpc_state().with_response("eth_getCode", GET_CODE_EMPTY);
13875        let Some((admin_pool, schema, mut client, state)) =
13876            execution_client_with_database("execution_wrap_code_free_test", state).await
13877        else {
13878            return;
13879        };
13880
13881        let error = client
13882            .wrap(U256::from(1_000_000_000_000_000u64))
13883            .await
13884            .unwrap_err();
13885
13886        assert!(
13887            error
13888                .to_string()
13889                .contains("pre-sign deployment manifest verification disagreed"),
13890            "was: {error}"
13891        );
13892        assert!(client.in_flight.lock().is_none());
13893        let requests = state.recorded_requests();
13894        assert_eq!(
13895            requests
13896                .iter()
13897                .filter(|request| request["method"] == "eth_getCode")
13898                .count(),
13899            3
13900        );
13901        assert!(
13902            requests
13903                .iter()
13904                .all(|request| request["method"] != "eth_sendRawTransaction")
13905        );
13906
13907        drop_execution_schema(&admin_pool, &schema).await;
13908    }
13909
13910    #[tokio::test]
13911    async fn wrap_rejects_unrelated_target_before_broadcast() {
13912        let state = execution_rpc_state().with_response("eth_call", CALL_EMPTY);
13913        let Some((admin_pool, schema, mut client, state)) =
13914            execution_client_with_database("execution_wrap_unrelated_test", state).await
13915        else {
13916            return;
13917        };
13918
13919        let error = client
13920            .wrap(U256::from(1_000_000_000_000_000u64))
13921            .await
13922            .unwrap_err();
13923
13924        assert!(
13925            error
13926                .to_string()
13927                .contains("pre-sign wrapped token probe verification is unavailable"),
13928            "was: {error}"
13929        );
13930        assert!(client.in_flight.lock().is_none());
13931        let requests = state.recorded_requests();
13932        assert!(
13933            requests
13934                .iter()
13935                .all(|request| request["method"] != "eth_sendRawTransaction")
13936        );
13937
13938        drop_execution_schema(&admin_pool, &schema).await;
13939    }
13940
13941    #[tokio::test]
13942    async fn wrap_rejects_included_transaction_without_balance_delta() {
13943        let state = broadcast_rpc_state().with_response_sequence("eth_call", &[CALL_BALANCE; 9]);
13944        let Some((admin_pool, schema, mut client, state)) =
13945            execution_client_with_database("execution_wrap_no_delta_test", state).await
13946        else {
13947            return;
13948        };
13949
13950        let error = client
13951            .wrap(U256::from(1_000_000_000_000_000u64))
13952            .await
13953            .unwrap_err();
13954
13955        assert!(
13956            error.to_string().contains("did not increase"),
13957            "was: {error}"
13958        );
13959        let in_flight = awaiting_in_flight(&client);
13960        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
13961        assert_eq!(
13962            execution_intent_markers(&admin_pool, &schema).await,
13963            vec![("wrap".into(), "broadcast".into(), false, true)]
13964        );
13965        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
13966            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
13967        )))
13968        .fetch_one(&admin_pool)
13969        .await
13970        .unwrap();
13971        assert_eq!(nonce_state, (7, 0));
13972        let broadcasts = state
13973            .recorded_requests()
13974            .into_iter()
13975            .filter(|request| request["method"] == "eth_sendRawTransaction")
13976            .count();
13977        assert_eq!(broadcasts, 1);
13978
13979        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000u64)).await;
13980        let block = finalized_wrap_block(expected_hash);
13981        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
13982        let restart_state = with_finalized_identity(
13983            execution_rpc_state()
13984                .with_response("eth_getTransactionReceipt", &receipt)
13985                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
13986                .with_response_sequence("eth_call", &[CALL_BALANCE; 6]),
13987            &block,
13988            &receipt,
13989        );
13990        let addr = start_mock_rpc_server(restart_state).await;
13991        let error = later_reconnect(client, format!("http://{addr}")).await;
13992        assert!(
13993            error.to_string().contains("did not increase"),
13994            "was: {error}"
13995        );
13996        assert_eq!(
13997            execution_intent_markers(&admin_pool, &schema).await,
13998            vec![("wrap".into(), "broadcast".into(), false, true)]
13999        );
14000        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
14001            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
14002        )))
14003        .fetch_one(&admin_pool)
14004        .await
14005        .unwrap();
14006        assert_eq!(nonce_state, (7, 0));
14007
14008        drop_execution_schema(&admin_pool, &schema).await;
14009    }
14010
14011    #[tokio::test]
14012    async fn wrap_reports_inclusion_when_postcondition_read_fails() {
14013        let state = broadcast_rpc_state().with_response_sequence(
14014            "eth_call",
14015            &[
14016                CALL_BALANCE,
14017                CALL_BALANCE,
14018                CALL_BALANCE,
14019                CALL_BALANCE,
14020                CALL_BALANCE,
14021                CALL_BALANCE,
14022                RPC_METHOD_NOT_FOUND,
14023                RPC_METHOD_NOT_FOUND,
14024                RPC_METHOD_NOT_FOUND,
14025            ],
14026        );
14027        let Some((admin_pool, schema, mut client, _)) =
14028            execution_client_with_database("execution_wrap_postcondition_rpc_test", state).await
14029        else {
14030            return;
14031        };
14032
14033        let error = client
14034            .wrap(U256::from(1_000_000_000_000_000u64))
14035            .await
14036            .unwrap_err();
14037
14038        let message = error.to_string();
14039        assert!(
14040            message.contains("failed to verify WETH balance after included transaction 0x"),
14041            "was: {message}"
14042        );
14043        assert!(message.contains("at block 30346561"), "was: {message}");
14044        let in_flight = awaiting_in_flight(&client);
14045        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
14046        assert_eq!(
14047            execution_intent_markers(&admin_pool, &schema).await,
14048            vec![("wrap".into(), "broadcast".into(), false, true)]
14049        );
14050
14051        drop_execution_schema(&admin_pool, &schema).await;
14052    }
14053
14054    #[tokio::test]
14055    async fn approve_rejects_false_return_before_broadcast() {
14056        let state = execution_rpc_state().with_response("eth_call", CALL_ZERO);
14057        let Some((admin_pool, schema, mut client, state)) =
14058            execution_client_with_database("execution_approve_false_test", state).await
14059        else {
14060            return;
14061        };
14062
14063        let error = client
14064            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14065            .await
14066            .unwrap_err();
14067
14068        assert!(error.to_string().contains("returned false"), "was: {error}");
14069        assert!(client.in_flight.lock().is_none());
14070        let requests = state.recorded_requests();
14071        let approval_calls = requests
14072            .iter()
14073            .filter(|request| {
14074                request["method"] == "eth_call"
14075                    && request["params"][0]["data"]
14076                        .as_str()
14077                        .is_some_and(|data| data.starts_with("0x095ea7b3"))
14078            })
14079            .collect::<Vec<_>>();
14080        assert_eq!(approval_calls.len(), 3);
14081        for request in approval_calls {
14082            assert_eq!(
14083                request["params"][0]["from"]
14084                    .as_str()
14085                    .unwrap()
14086                    .parse::<Address>()
14087                    .unwrap(),
14088                WALLET.parse::<Address>().unwrap()
14089            );
14090            assert_eq!(request["params"][1], FIXTURE_BLOCK_PARAM);
14091        }
14092        assert!(
14093            requests
14094                .iter()
14095                .all(|request| request["method"] != "eth_getTransactionCount")
14096        );
14097        assert!(
14098            requests
14099                .iter()
14100                .all(|request| request["method"] != "eth_sendRawTransaction")
14101        );
14102
14103        drop_execution_schema(&admin_pool, &schema).await;
14104    }
14105
14106    #[tokio::test]
14107    async fn approve_rejects_router_with_wrong_factory_before_signing() {
14108        let state = ready_rpc_state().with_call_response(FACTORY_SELECTOR, CALL_ZERO);
14109        let Some((admin_pool, schema, mut client, state)) =
14110            execution_client_with_database("execution_approve_factory_test", state).await
14111        else {
14112            return;
14113        };
14114
14115        let error = client
14116            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14117            .await
14118            .unwrap_err();
14119
14120        assert!(
14121            error
14122                .to_string()
14123                .contains("pre-sign deployment manifest verification disagreed"),
14124            "was: {error}"
14125        );
14126        let requests = state.recorded_requests();
14127        assert!(
14128            requests
14129                .iter()
14130                .all(|request| request["method"] != "eth_getTransactionCount")
14131        );
14132        assert!(
14133            requests
14134                .iter()
14135                .all(|request| request["method"] != "eth_sendRawTransaction")
14136        );
14137
14138        drop_execution_schema(&admin_pool, &schema).await;
14139    }
14140
14141    #[tokio::test]
14142    async fn approve_rejects_router_with_wrong_weth_before_signing() {
14143        let state = ready_rpc_state().with_call_response(WETH9_SELECTOR, CALL_ZERO);
14144        let Some((admin_pool, schema, mut client, state)) =
14145            execution_client_with_database("execution_approve_weth_test", state).await
14146        else {
14147            return;
14148        };
14149
14150        let error = client
14151            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14152            .await
14153            .unwrap_err();
14154
14155        assert!(
14156            error
14157                .to_string()
14158                .contains("pre-sign deployment manifest verification disagreed"),
14159            "was: {error}"
14160        );
14161        let requests = state.recorded_requests();
14162        assert!(
14163            requests
14164                .iter()
14165                .all(|request| request["method"] != "eth_getTransactionCount")
14166        );
14167        assert!(
14168            requests
14169                .iter()
14170                .all(|request| request["method"] != "eth_sendRawTransaction")
14171        );
14172
14173        drop_execution_schema(&admin_pool, &schema).await;
14174    }
14175
14176    #[tokio::test]
14177    async fn approve_rejects_nonzero_to_nonzero_transition_before_signing() {
14178        let state = ready_rpc_state();
14179        let Some((admin_pool, schema, mut client, state)) =
14180            execution_client_with_database("execution_approve_nonzero_test", state).await
14181        else {
14182            return;
14183        };
14184
14185        let error = client
14186            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14187            .await
14188            .unwrap_err();
14189
14190        assert!(
14191            error.to_string().contains("approve zero before setting"),
14192            "was: {error}"
14193        );
14194        let requests = state.recorded_requests();
14195        assert!(
14196            requests
14197                .iter()
14198                .all(|request| request["method"] != "eth_getTransactionCount")
14199        );
14200        assert!(
14201            requests
14202                .iter()
14203                .all(|request| request["method"] != "eth_sendRawTransaction")
14204        );
14205
14206        drop_execution_schema(&admin_pool, &schema).await;
14207    }
14208
14209    #[tokio::test]
14210    async fn approve_zero_revokes_under_unlimited_policy() {
14211        let state = broadcast_rpc_state()
14212            .with_response("eth_call", CALL_BOOL_TRUE)
14213            .with_call_response_sequence(
14214                ALLOWANCE_SELECTOR,
14215                &[
14216                    CALL_ALLOWANCE,
14217                    CALL_ALLOWANCE,
14218                    CALL_ALLOWANCE,
14219                    CALL_ZERO,
14220                    CALL_ZERO,
14221                    CALL_ZERO,
14222                ],
14223            );
14224        let Some((admin_pool, schema, mut client, state)) =
14225            execution_client_with_database("execution_approve_revoke_test", state).await
14226        else {
14227            return;
14228        };
14229        client.config.unlimited_approval = true;
14230        client.transaction_limits.receipt_timeout_secs = TEST_TIMEOUT.as_secs();
14231
14232        let tx_hash = client
14233            .approve(WETH_ADDRESS, U256::ZERO, ROUTER_ADDRESS)
14234            .await
14235            .unwrap();
14236
14237        assert_eq!(tx_hash, expected_approve_tx_hash(U256::ZERO).await);
14238        let approve_data = state
14239            .recorded_requests()
14240            .into_iter()
14241            .find_map(|request| {
14242                (request["method"] == "eth_estimateGas")
14243                    .then(|| request["params"][0]["data"].as_str().map(str::to_owned))
14244                    .flatten()
14245            })
14246            .unwrap();
14247        assert!(approve_data.starts_with("0x095ea7b3"));
14248        assert!(approve_data.ends_with(&"0".repeat(64)));
14249        assert_eq!(
14250            state
14251                .recorded_requests()
14252                .iter()
14253                .filter(|request| {
14254                    request["method"] == "eth_call"
14255                        && request["params"][0]["data"]
14256                            .as_str()
14257                            .is_some_and(|data| data.starts_with(FACTORY_SELECTOR))
14258                })
14259                .count(),
14260            12
14261        );
14262        assert_eq!(
14263            execution_intent_markers(&admin_pool, &schema).await,
14264            vec![("approve".into(), "finalized".into(), true, false)]
14265        );
14266
14267        drop_execution_schema(&admin_pool, &schema).await;
14268    }
14269
14270    #[tokio::test]
14271    async fn approve_accepts_empty_return_with_sufficient_allowance() {
14272        let state = broadcast_rpc_state()
14273            .with_response("eth_call", CALL_EMPTY)
14274            .with_call_response_sequence(
14275                ALLOWANCE_SELECTOR,
14276                &[
14277                    CALL_ZERO,
14278                    CALL_ZERO,
14279                    CALL_ZERO,
14280                    CALL_ALLOWANCE_1000,
14281                    CALL_ALLOWANCE_1000,
14282                    CALL_ALLOWANCE_1000,
14283                ],
14284            );
14285        let Some((admin_pool, schema, mut client, _)) =
14286            execution_client_with_database("execution_approve_empty_test", state).await
14287        else {
14288            return;
14289        };
14290
14291        let tx_hash = client
14292            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14293            .await
14294            .unwrap();
14295
14296        let record = client
14297            .cache
14298            .get_execution_transaction(42161, &tx_hash.to_string())
14299            .await
14300            .unwrap()
14301            .unwrap();
14302        assert_eq!(record.purpose, "approve");
14303        assert_eq!(record.status, "finalized");
14304        assert!(client.in_flight.lock().is_none());
14305        assert_eq!(
14306            execution_intent_markers(&admin_pool, &schema).await,
14307            vec![("approve".into(), "finalized".into(), true, false)]
14308        );
14309
14310        drop_execution_schema(&admin_pool, &schema).await;
14311    }
14312
14313    #[tokio::test]
14314    async fn approve_rejects_empty_return_with_insufficient_allowance() {
14315        let state = broadcast_rpc_state()
14316            .with_response("eth_call", CALL_EMPTY)
14317            .with_call_response_sequence(ALLOWANCE_SELECTOR, &[CALL_ZERO; 6]);
14318        let Some((admin_pool, schema, mut client, _)) =
14319            execution_client_with_database("execution_approve_insufficient_test", state).await
14320        else {
14321            return;
14322        };
14323
14324        let error = client
14325            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14326            .await
14327            .unwrap_err();
14328
14329        assert!(
14330            error
14331                .to_string()
14332                .contains("does not equal the requested amount"),
14333            "was: {error}"
14334        );
14335        let in_flight = awaiting_in_flight(&client);
14336        assert_eq!(in_flight.purpose, TransactionPurpose::Approve);
14337        assert_eq!(
14338            execution_intent_markers(&admin_pool, &schema).await,
14339            vec![("approve".into(), "broadcast".into(), false, true)]
14340        );
14341        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
14342            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
14343        )))
14344        .fetch_one(&admin_pool)
14345        .await
14346        .unwrap();
14347        assert_eq!(nonce_state, (7, 0));
14348
14349        let expected_hash = expected_approve_tx_hash(U256::from(1_000u64)).await;
14350        let block = finalized_approve_block(expected_hash, U256::from(1_000u64));
14351        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
14352        let restart_state = with_finalized_identity(
14353            execution_rpc_state()
14354                .with_response("eth_getTransactionReceipt", &receipt)
14355                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
14356                .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO),
14357            &block,
14358            &receipt,
14359        );
14360        let addr = start_mock_rpc_server(restart_state).await;
14361        let error = later_reconnect(client, format!("http://{addr}")).await;
14362        assert!(
14363            error
14364                .to_string()
14365                .contains("does not equal the requested amount"),
14366            "was: {error}"
14367        );
14368        assert_eq!(
14369            execution_intent_markers(&admin_pool, &schema).await,
14370            vec![("approve".into(), "broadcast".into(), false, true)]
14371        );
14372        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
14373            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
14374        )))
14375        .fetch_one(&admin_pool)
14376        .await
14377        .unwrap();
14378        assert_eq!(nonce_state, (7, 0));
14379
14380        drop_execution_schema(&admin_pool, &schema).await;
14381    }
14382
14383    #[tokio::test]
14384    async fn approve_reports_inclusion_when_postcondition_read_fails() {
14385        let state = broadcast_rpc_state()
14386            .with_response("eth_call", CALL_BOOL_TRUE)
14387            .with_call_response_sequence(
14388                ALLOWANCE_SELECTOR,
14389                &[
14390                    CALL_ZERO,
14391                    CALL_ZERO,
14392                    CALL_ZERO,
14393                    RPC_METHOD_NOT_FOUND,
14394                    RPC_METHOD_NOT_FOUND,
14395                    RPC_METHOD_NOT_FOUND,
14396                ],
14397            );
14398        let Some((admin_pool, schema, mut client, _)) =
14399            execution_client_with_database("execution_approve_postcondition_rpc_test", state).await
14400        else {
14401            return;
14402        };
14403
14404        let error = client
14405            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14406            .await
14407            .unwrap_err();
14408
14409        let message = error.to_string();
14410        assert!(
14411            message.contains("failed to verify router allowance after included transaction 0x"),
14412            "was: {message}"
14413        );
14414        assert!(message.contains("at block 30346561"), "was: {message}");
14415        let in_flight = awaiting_in_flight(&client);
14416        assert_eq!(in_flight.purpose, TransactionPurpose::Approve);
14417        assert_eq!(
14418            execution_intent_markers(&admin_pool, &schema).await,
14419            vec![("approve".into(), "broadcast".into(), false, true)]
14420        );
14421
14422        drop_execution_schema(&admin_pool, &schema).await;
14423    }
14424
14425    #[tokio::test]
14426    async fn wallet_balance_refresh_replaces_complete_snapshot_with_exact_precision() {
14427        let state = execution_rpc_state()
14428            .with_response_sequence("eth_getBalance", &[GET_BALANCE, GET_BALANCE_ZERO])
14429            .with_response_sequence(
14430                "eth_call",
14431                &[
14432                    CALL_BALANCE_WETH,
14433                    CALL_BALANCE_USDC,
14434                    CALL_BALANCE_WETH_UPDATED,
14435                    CALL_BALANCE_USDC_UPDATED,
14436                ],
14437            );
14438        let (mut client, _, _) =
14439            client_with_token_mock_rpc(state, "BLOCKCHAIN_TEST_BALANCE_REPLACE").await;
14440        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14441        replace_exec_event_sender(sender);
14442        client.start().unwrap();
14443
14444        client.refresh_wallet_balances().await.unwrap();
14445        let balances = client.wallet_balance.lock().as_account_balances().unwrap();
14446
14447        assert_eq!(balances.len(), 3);
14448        assert_eq!(balances[0].currency.code, "ETH");
14449        assert_eq!(balances[0].currency.name, "Ethereum");
14450        assert_eq!(balances[0].currency.precision, 18);
14451        assert_eq!(balances[0].total.raw(), 1_000_000_000_000_000_000);
14452        assert_eq!(balances[0].free, balances[0].total);
14453        assert_eq!(balances[0].locked, Money::zero(balances[0].currency));
14454        assert_eq!(balances[1].currency.code, "WETH@ARBITRUM");
14455        assert_eq!(balances[1].currency.name, "Wrapped Ether");
14456        assert_eq!(balances[1].currency.precision, 18);
14457        assert_eq!(balances[1].total.raw(), 1_234_567_890_123_456_789);
14458        assert_eq!(balances[1].free, balances[1].total);
14459        assert_eq!(balances[1].locked, Money::zero(balances[1].currency));
14460        assert_eq!(balances[2].currency.code, "USDC@ARBITRUM");
14461        assert_eq!(balances[2].currency.name, "USD Coin");
14462        assert_eq!(balances[2].currency.precision, 6);
14463        assert_eq!(balances[2].total.raw(), 9_876_543_210_000_000_000);
14464        assert_eq!(balances[2].free, balances[2].total);
14465        assert_eq!(balances[2].locked, Money::zero(balances[2].currency));
14466
14467        client.refresh_wallet_balances().await.unwrap();
14468        let balances = client.wallet_balance.lock().as_account_balances().unwrap();
14469
14470        assert_eq!(balances.len(), 3);
14471        assert_eq!(client.wallet_balance.lock().token_balances.len(), 2);
14472        assert_eq!(balances[0].total.raw(), 0);
14473        assert_eq!(balances[1].total.raw(), 2_000_000_000_000_000_000);
14474        assert_eq!(balances[2].total.raw(), 12_345_670_000_000_000);
14475    }
14476
14477    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14478    #[tokio::test]
14479    async fn failed_connect_refresh_retains_snapshot_and_publishes_nothing() {
14480        let state = execution_rpc_state()
14481            .with_response_sequence("eth_getBalance", &[GET_BALANCE, GET_BALANCE_ZERO])
14482            .with_response_sequence(
14483                "eth_call",
14484                &[
14485                    CALL_BALANCE_WETH,
14486                    CALL_BALANCE_USDC,
14487                    CALL_BALANCE_WETH_UPDATED,
14488                    RPC_METHOD_NOT_FOUND,
14489                ],
14490            );
14491        let (mut client, _, _) =
14492            client_with_token_mock_rpc(state, "BLOCKCHAIN_TEST_BALANCE_ATOMIC").await;
14493        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
14494        replace_exec_event_sender(sender);
14495        client.start().unwrap();
14496        client.refresh_wallet_balances().await.unwrap();
14497        let retained = client.wallet_balance.lock().as_account_balances().unwrap();
14498        receiver.try_recv().unwrap();
14499        // SAFETY: this variable name is unique to this test across the test binary
14500        unsafe { std::env::set_var("BLOCKCHAIN_TEST_BALANCE_ATOMIC", TEST_PRIVATE_KEY) };
14501
14502        let error = client.connect().await.unwrap_err();
14503        let failed_address = Address::from_str(USDC).unwrap();
14504
14505        assert!(
14506            error.to_string().contains(&format!(
14507                "failed to fetch token balance for {failed_address}"
14508            )),
14509            "was: {error}"
14510        );
14511        assert!(!client.is_connected());
14512        assert!(client.signer.is_none());
14513        assert_eq!(
14514            client.wallet_balance.lock().as_account_balances().unwrap(),
14515            retained
14516        );
14517        assert!(matches!(
14518            receiver.try_recv(),
14519            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
14520        ));
14521    }
14522
14523    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14524    #[tokio::test]
14525    async fn failed_connect_publication_retains_snapshot() {
14526        let state = execution_rpc_state()
14527            .with_response_sequence("eth_getBalance", &[GET_BALANCE, GET_BALANCE_ZERO])
14528            .with_response_sequence(
14529                "eth_call",
14530                &[
14531                    CALL_BALANCE_WETH,
14532                    CALL_BALANCE_USDC,
14533                    CALL_BALANCE_WETH_UPDATED,
14534                    CALL_BALANCE_USDC_UPDATED,
14535                ],
14536            );
14537        let (mut client, _, _) =
14538            client_with_token_mock_rpc(state, "BLOCKCHAIN_TEST_BALANCE_PUBLICATION").await;
14539        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
14540        replace_exec_event_sender(sender);
14541        client.start().unwrap();
14542        client.refresh_wallet_balances().await.unwrap();
14543        let retained = client.wallet_balance.lock().as_account_balances().unwrap();
14544        receiver.try_recv().unwrap();
14545        drop(receiver);
14546        // SAFETY: this variable name is unique to this test across the test binary
14547        unsafe { std::env::set_var("BLOCKCHAIN_TEST_BALANCE_PUBLICATION", TEST_PRIVATE_KEY) };
14548
14549        let error = client.connect().await.unwrap_err();
14550
14551        assert!(
14552            error.to_string().contains("Failed to send account state"),
14553            "was: {error}"
14554        );
14555        assert!(!client.is_connected());
14556        assert!(client.signer.is_none());
14557        assert_eq!(
14558            client.wallet_balance.lock().as_account_balances().unwrap(),
14559            retained
14560        );
14561    }
14562
14563    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14564    #[tokio::test]
14565    async fn connect_and_repeated_query_publish_wallet_account_state() {
14566        let state = execution_rpc_state()
14567            .with_response_sequence("eth_call", &[CALL_BALANCE_WETH, CALL_BALANCE_USDC]);
14568        let (mut client, state, cache) =
14569            client_with_token_mock_rpc(state, "BLOCKCHAIN_TEST_ACCOUNT_STATE").await;
14570        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
14571        replace_exec_event_sender(sender);
14572        client.start().unwrap();
14573        // SAFETY: this variable name is unique to this test across the test binary
14574        unsafe { std::env::set_var("BLOCKCHAIN_TEST_ACCOUNT_STATE", TEST_PRIVATE_KEY) };
14575
14576        client.connect().await.unwrap();
14577
14578        let ExecutionEvent::Account(connected) = receiver.try_recv().unwrap() else {
14579            panic!("expected account state event")
14580        };
14581        assert_eq!(connected.account_id, AccountId::from("BLOCKCHAIN-001"));
14582        assert_eq!(connected.account_type, AccountType::Wallet);
14583        assert_eq!(connected.base_currency, None);
14584        assert_eq!(connected.balances.len(), 3);
14585        assert!(connected.margins.is_empty());
14586        assert!(connected.is_reported);
14587        cache.borrow_mut().update_account_state(&connected).unwrap();
14588
14589        let account = client.get_account().unwrap();
14590        assert!(matches!(account, AccountAny::Wallet(_)));
14591        assert_eq!(account.id(), AccountId::from("BLOCKCHAIN-001"));
14592        assert_eq!(account.last_event(), Some(connected.clone()));
14593
14594        let requests_before = state.recorded_requests().len();
14595        let query = || {
14596            QueryAccount::new(
14597                TraderId::from("TRADER-001"),
14598                Some(ClientId::from("BLOCKCHAIN-001")),
14599                AccountId::from("BLOCKCHAIN-001"),
14600                UUID4::new(),
14601                UnixNanos::default(),
14602                None,
14603                None,
14604            )
14605        };
14606        client.query_account(query()).unwrap();
14607        client.query_account(query()).unwrap();
14608
14609        let ExecutionEvent::Account(first_query) = receiver.try_recv().unwrap() else {
14610            panic!("expected first query account state event")
14611        };
14612        let ExecutionEvent::Account(second_query) = receiver.try_recv().unwrap() else {
14613            panic!("expected second query account state event")
14614        };
14615        assert!(connected.has_same_balances_and_margins(&first_query));
14616        assert!(first_query.has_same_balances_and_margins(&second_query));
14617        assert_eq!(first_query.account_id, connected.account_id);
14618        assert_eq!(first_query.account_type, connected.account_type);
14619        assert_eq!(first_query.base_currency, connected.base_currency);
14620        assert_eq!(first_query.is_reported, connected.is_reported);
14621        assert_ne!(first_query.event_id, second_query.event_id);
14622        assert_eq!(state.recorded_requests().len(), requests_before);
14623
14624        client.stop().unwrap();
14625        assert!(client.core.is_stopped());
14626        assert!(!client.is_connected());
14627        assert!(client.signer.is_none());
14628    }
14629
14630    #[tokio::test]
14631    async fn connect_rejects_on_chain_mismatch() {
14632        let state = ready_rpc_state().with_response("eth_chainId", CHAIN_ID_ETHEREUM);
14633        let (mut client, _) = client_with_mock_rpc(state).await;
14634
14635        let error = client.connect().await.unwrap_err();
14636
14637        assert!(
14638            error
14639                .to_string()
14640                .contains("Blockchain chain ID verification disagreed"),
14641            "was: {error}"
14642        );
14643    }
14644
14645    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14646    #[tokio::test]
14647    async fn connect_rejects_on_signer_wallet_mismatch() {
14648        let addr = start_mock_rpc_server(ready_rpc_state()).await;
14649        let config = test_config_with_signer_env(
14650            format!("http://{addr}"),
14651            "BLOCKCHAIN_TEST_PRIVATE_KEY_MISMATCH",
14652        );
14653        let mut client = test_client_from_config(config, test_pool());
14654        // Anvil development key #1 derives a different address than the configured wallet
14655        // SAFETY: this variable name is unique to this test across the test binary
14656        unsafe {
14657            std::env::set_var(
14658                "BLOCKCHAIN_TEST_PRIVATE_KEY_MISMATCH",
14659                "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d",
14660            );
14661        };
14662
14663        let error = client.connect().await.unwrap_err();
14664
14665        assert!(
14666            error
14667                .to_string()
14668                .contains("does not match configured wallet address"),
14669            "was: {error}"
14670        );
14671    }
14672
14673    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14674    #[tokio::test]
14675    async fn connect_rejects_missing_trace_capability_before_signer_load() {
14676        let state = ready_rpc_state().with_parameter_response(
14677            "debug_traceTransaction",
14678            &B256::ZERO.to_string(),
14679            RPC_METHOD_NOT_FOUND,
14680        );
14681        let addr = start_mock_rpc_server(state.clone()).await;
14682        let config = test_config_with_signer_env(
14683            format!("http://{addr}"),
14684            "BLOCKCHAIN_TEST_TRACE_CAPABILITY",
14685        );
14686        let mut client = test_client_from_config(config, test_pool());
14687        // SAFETY: this variable name is unique to this test across the test binary
14688        unsafe { std::env::set_var("BLOCKCHAIN_TEST_TRACE_CAPABILITY", TEST_PRIVATE_KEY) };
14689
14690        let error = client.connect().await.unwrap_err();
14691
14692        assert!(
14693            error
14694                .to_string()
14695                .contains("Blockchain call trace capability verification is locally invalid"),
14696            "was: {error}"
14697        );
14698        assert!(client.signer.is_none());
14699        assert!(
14700            state
14701                .recorded_requests()
14702                .iter()
14703                .all(|request| request["method"] != "eth_getBalance")
14704        );
14705    }
14706
14707    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14708    #[tokio::test]
14709    async fn connect_initializes_signer_from_env() {
14710        let addr = start_mock_rpc_server(ready_rpc_state()).await;
14711        let config =
14712            test_config_with_signer_env(format!("http://{addr}"), "BLOCKCHAIN_TEST_PRIVATE_KEY_OK");
14713        let mut client = test_client_from_config(config, test_pool());
14714        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14715        replace_exec_event_sender(sender);
14716        client.start().unwrap();
14717        // SAFETY: this variable name is unique to this test across the test binary
14718        unsafe { std::env::set_var("BLOCKCHAIN_TEST_PRIVATE_KEY_OK", TEST_PRIVATE_KEY) };
14719
14720        client.connect().await.unwrap();
14721
14722        let signer = client.signer.as_ref().unwrap();
14723        assert_eq!(
14724            signer.address(),
14725            address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266")
14726        );
14727    }
14728
14729    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14730    #[tokio::test]
14731    async fn reconnect_resumes_at_the_durable_finalized_tip() {
14732        let Some((admin_pool, pg_config)) =
14733            connect_test_postgres("verification ledger resume").await
14734        else {
14735            return;
14736        };
14737        let schema = format!("verification_ledger_resume_{}", std::process::id());
14738        setup_execution_schema(&admin_pool, &schema).await;
14739        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
14740        let options = options.options([("search_path", schema.clone())]);
14741        let database = connect_test_database(options).await.unwrap();
14742        database
14743            .ensure_execution_transaction_schema()
14744            .await
14745            .unwrap();
14746
14747        let state = ready_rpc_state();
14748        let addr = start_mock_rpc_server(state.clone()).await;
14749        let config = test_config_with_signer_env(
14750            format!("http://{addr}"),
14751            "BLOCKCHAIN_TEST_VERIFICATION_RESUME",
14752        );
14753        let mut client = test_client_from_config(config, test_pool());
14754        client.cache.database = Some(database);
14755        protect_test_storage(&mut client, &schema).await;
14756        let finalized_headers = [
14757            ExecutionVerifiedHeader {
14758                number: FIXTURE_BLOCK,
14759                hash: FIXTURE_BLOCK_HASH.to_string(),
14760                parent_hash: "0x0000000000000000000000000000000000000000000000000000000000000001"
14761                    .to_string(),
14762                timestamp: FIXTURE_BLOCK_TIMESTAMP,
14763                base_fee_per_gas: Some(100_000_000),
14764            },
14765            ExecutionVerifiedHeader {
14766                number: FIXTURE_BLOCK + 1,
14767                hash: B256::from([0x22; 32]).to_string(),
14768                parent_hash: FIXTURE_BLOCK_HASH.to_string(),
14769                timestamp: FIXTURE_BLOCK_TIMESTAMP + 1,
14770                base_fee_per_gas: Some(100_000_000),
14771            },
14772            ExecutionVerifiedHeader {
14773                number: FIXTURE_BLOCK + 2,
14774                hash: B256::from([0x33; 32]).to_string(),
14775                parent_hash: B256::from([0x22; 32]).to_string(),
14776                timestamp: FIXTURE_BLOCK_TIMESTAMP + 2,
14777                base_fee_per_gas: Some(100_000_000),
14778            },
14779        ];
14780        initialize_test_verification_ledger_with_headers(&client, &finalized_headers).await;
14781        let verification = client.config.verification.as_ref().unwrap();
14782        let position = client
14783            .cache
14784            .database
14785            .as_ref()
14786            .unwrap()
14787            .load_execution_verification_position(
14788                42_161,
14789                WALLET,
14790                &verification.manifest_version,
14791                &verification.manifest_digest,
14792            )
14793            .await
14794            .unwrap()
14795            .unwrap();
14796        let resume = client
14797            .cache
14798            .database
14799            .as_ref()
14800            .unwrap()
14801            .load_execution_verification_resume(
14802                42_161,
14803                WALLET,
14804                &verification.manifest_version,
14805                &verification.manifest_digest,
14806            )
14807            .await
14808            .unwrap()
14809            .unwrap();
14810        assert_eq!(position.next_canonical_nonce, 7);
14811        assert_eq!(position.revision, 0);
14812        assert_eq!(position.finalized_tip, finalized_headers[2]);
14813        assert_eq!(resume.next_canonical_nonce, 7);
14814        assert_eq!(resume.revision, 0);
14815        assert_eq!(resume.finalized_headers, finalized_headers);
14816
14817        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14818        replace_exec_event_sender(sender);
14819        client.start().unwrap();
14820        // SAFETY: this variable name is unique to this test across the test binary
14821        unsafe { std::env::set_var("BLOCKCHAIN_TEST_VERIFICATION_RESUME", TEST_PRIVATE_KEY) };
14822
14823        client.connect().await.unwrap();
14824
14825        let skipped_height = format!("0x{:x}", FIXTURE_BLOCK + 1);
14826        assert!(client.is_connected());
14827        assert!(state.recorded_requests().iter().all(|request| {
14828            request["method"] != "eth_getBlockByNumber"
14829                || request["params"][0].as_str() != Some(&skipped_height)
14830        }));
14831        let header_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
14832            "SELECT COUNT(*) FROM {schema}.execution_verified_finalized_header"
14833        )))
14834        .fetch_one(&admin_pool)
14835        .await
14836        .unwrap();
14837        assert_eq!(header_count, 3);
14838
14839        drop(client);
14840        drop_execution_schema(&admin_pool, &schema).await;
14841    }
14842
14843    #[tokio::test]
14844    async fn disconnect_revokes_signer_and_blocks_execution() {
14845        let (mut client, state) = client_with_mock_rpc(ready_rpc_state()).await;
14846        client.core.set_connected();
14847        client.signer = Some(Arc::new(
14848            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
14849        ));
14850
14851        client.disconnect().await.unwrap();
14852        let error = client.wrap(U256::from(1_000u64)).await.unwrap_err();
14853
14854        assert!(!client.is_connected());
14855        assert!(client.signer.is_none());
14856        assert!(
14857            error.to_string().contains("is not connected"),
14858            "was: {error}"
14859        );
14860        assert!(state.recorded_requests().is_empty());
14861    }
14862
14863    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14864    #[tokio::test]
14865    async fn connect_releases_stale_preparing_claim_after_tasks_finish() {
14866        let addr = start_mock_rpc_server(ready_rpc_state()).await;
14867        let config = test_config_with_signer_env(
14868            format!("http://{addr}"),
14869            "BLOCKCHAIN_TEST_RECONNECT_CLAIM",
14870        );
14871        let mut client = test_client_from_config(config, test_pool());
14872        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14873        replace_exec_event_sender(sender);
14874        client.start().unwrap();
14875        // SAFETY: this variable name is unique to this test across the test binary
14876        unsafe { std::env::set_var("BLOCKCHAIN_TEST_RECONNECT_CLAIM", TEST_PRIVATE_KEY) };
14877        *client.in_flight.lock() = Some(InFlightSlot::Preparing(TransactionPurpose::Swap));
14878        client
14879            .pending_tasks
14880            .spawn(async {})
14881            .expect("stale task spawn");
14882
14883        client.connect().await.unwrap();
14884
14885        assert!(client.in_flight.lock().is_none());
14886    }
14887
14888    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14889    #[tokio::test]
14890    async fn reconnect_after_aborted_submission_releases_preparing_claim() {
14891        // The swap task blocks in its first RPC; disconnect aborts it mid-preparation, and the
14892        // following connect awaits termination and releases the stale claim
14893        let state = ready_rpc_state().with_sleep("eth_getBlockByNumber", Duration::from_secs(30));
14894        let Some((admin_pool, schema, mut client, state, _)) =
14895            swap_client_with_database("execution_reconnect_claim_test", state).await
14896        else {
14897            return;
14898        };
14899        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14900        replace_exec_event_sender(sender);
14901        client.start().unwrap();
14902        // SAFETY: this variable name is unique to this test across the test binary
14903        unsafe { std::env::set_var("BLOCKCHAIN_TEST_PRIVATE_KEY", TEST_PRIVATE_KEY) };
14904
14905        let order = test_market_sell_order(test_pool().instrument_id);
14906        client.submit_order(submit_order_cmd(&order)).unwrap();
14907        await_recorded_requests(&state, "eth_getBlockByNumber", 1).await;
14908        assert!(client.in_flight.lock().is_some());
14909
14910        client.disconnect().await.unwrap();
14911        let ready_addr = start_mock_rpc_server(ready_rpc_state()).await;
14912        let ready = test_client(format!("http://{ready_addr}"));
14913        client.http_rpc_client = ready.http_rpc_client;
14914        client.verification = ready.verification;
14915        client.connect().await.unwrap();
14916
14917        assert!(client.in_flight.lock().is_none());
14918
14919        drop_execution_schema(&admin_pool, &schema).await;
14920    }
14921
14922    #[tokio::test]
14923    async fn poll_for_receipt_returns_none_after_exhaustion() {
14924        let state = ready_rpc_state().with_response("eth_getTransactionReceipt", RECEIPT_NULL);
14925        let (client, state) = client_with_mock_rpc(state).await;
14926
14927        let receipt = poll_for_receipt(&client.http_rpc_client, &B256::ZERO, 3, Duration::ZERO)
14928            .await
14929            .unwrap();
14930
14931        assert!(receipt.is_none());
14932        let requests = state.recorded_requests();
14933        assert_eq!(requests.len(), 3);
14934    }
14935
14936    #[tokio::test]
14937    async fn poll_for_receipt_returns_last_error_when_every_poll_fails() {
14938        let state =
14939            ready_rpc_state().with_response("eth_getTransactionReceipt", RPC_METHOD_NOT_FOUND);
14940        let (client, state) = client_with_mock_rpc(state).await;
14941
14942        let error = poll_for_receipt(&client.http_rpc_client, &B256::ZERO, 3, Duration::ZERO)
14943            .await
14944            .unwrap_err();
14945
14946        assert_eq!(
14947            error.to_string(),
14948            "eth_getTransactionReceipt RPC error -32601"
14949        );
14950        let requests = state.recorded_requests();
14951        assert_eq!(requests.len(), 3);
14952    }
14953
14954    #[tokio::test]
14955    async fn poll_for_receipt_returns_none_after_pending_then_errors() {
14956        let state = ready_rpc_state().with_response_sequence(
14957            "eth_getTransactionReceipt",
14958            &[RECEIPT_NULL, RPC_METHOD_NOT_FOUND, RPC_METHOD_NOT_FOUND],
14959        );
14960        let (client, state) = client_with_mock_rpc(state).await;
14961
14962        let receipt = poll_for_receipt(&client.http_rpc_client, &B256::ZERO, 3, Duration::ZERO)
14963            .await
14964            .unwrap();
14965
14966        assert!(receipt.is_none());
14967        let requests = state.recorded_requests();
14968        assert_eq!(requests.len(), 3);
14969    }
14970
14971    #[tokio::test]
14972    async fn cancellation_during_persistence_keeps_in_flight_slot() {
14973        let Some((admin_pool, pg_config)) = connect_test_postgres("persistence cancellation").await
14974        else {
14975            return;
14976        };
14977
14978        let schema = format!("execution_persist_cancel_test_{}", std::process::id());
14979        setup_execution_schema(&admin_pool, &schema).await;
14980
14981        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
14982        let db_options = db_options.options([("search_path", schema.clone())]);
14983        let database = connect_test_database(db_options).await.unwrap();
14984
14985        let state = signing_rpc_state();
14986        let addr = start_mock_rpc_server(state.clone()).await;
14987
14988        let mut client = test_client(format!("http://{addr}"));
14989        client.cache.database = Some(database);
14990        // Mirror the connect-time migration: tests create the pre-submission table shape
14991        client
14992            .cache
14993            .ensure_execution_transaction_schema()
14994            .await
14995            .unwrap();
14996        protect_test_storage(&mut client, &schema).await;
14997        initialize_test_verification_ledger(&client).await;
14998        client.signer = Some(Arc::new(
14999            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
15000        ));
15001        client.core.set_connected();
15002
15003        let advisory_lock = i64::from(std::process::id());
15004
15005        for statement in [
15006            format!(
15007                "CREATE FUNCTION {schema}.block_execution_hash_insert() RETURNS trigger \
15008                 LANGUAGE plpgsql AS 'BEGIN PERFORM pg_advisory_xact_lock({advisory_lock}); \
15009                 RETURN NEW; END'"
15010            ),
15011            format!(
15012                "CREATE TRIGGER block_execution_hash_insert BEFORE INSERT ON \
15013                 {schema}.execution_transaction_hash FOR EACH ROW EXECUTE FUNCTION \
15014                 {schema}.block_execution_hash_insert()"
15015            ),
15016        ] {
15017            sqlx::query(sqlx::AssertSqlSafe(statement))
15018                .execute(&admin_pool)
15019                .await
15020                .unwrap();
15021        }
15022        let mut lock_transaction = admin_pool.begin().await.unwrap();
15023        sqlx::query("SELECT pg_advisory_xact_lock($1)")
15024            .bind(advisory_lock)
15025            .execute(&mut *lock_transaction)
15026            .await
15027            .unwrap();
15028
15029        let value = U256::from(1_000_000_000_000_000u64);
15030        let in_flight = Arc::clone(&client.in_flight);
15031        let mut wrap = Box::pin(client.wrap(value));
15032        tokio::time::timeout(Duration::from_secs(2), async {
15033            loop {
15034                tokio::select! {
15035                    result = &mut wrap => {
15036                        panic!("persistence completed while the table was locked: {result:?}")
15037                    }
15038                    () = tokio::time::sleep(Duration::from_millis(1)) => {}
15039                }
15040
15041                if matches!(*in_flight.lock(), Some(InFlightSlot::AwaitingFinality(_))) {
15042                    break;
15043                }
15044            }
15045        })
15046        .await
15047        .unwrap();
15048        drop(wrap);
15049        lock_transaction.rollback().await.unwrap();
15050
15051        let slot = *client.in_flight.lock();
15052        let second_error = client
15053            .wrap(U256::from(2_000_000_000_000_000u64))
15054            .await
15055            .unwrap_err();
15056        let broadcasts = state
15057            .recorded_requests()
15058            .into_iter()
15059            .filter(|request| request["method"] == "eth_sendRawTransaction")
15060            .count();
15061        let status: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15062            "SELECT status FROM {schema}.execution_intent"
15063        )))
15064        .fetch_one(&admin_pool)
15065        .await
15066        .unwrap();
15067
15068        assert!(matches!(slot, Some(InFlightSlot::AwaitingFinality(_))));
15069        assert_eq!(status, "prepared");
15070        assert!(
15071            second_error.to_string().contains("awaiting finality"),
15072            "was: {second_error}"
15073        );
15074        assert_eq!(broadcasts, 0);
15075
15076        drop_execution_schema(&admin_pool, &schema).await;
15077    }
15078
15079    #[tokio::test]
15080    async fn clock_error_releases_preparing_slot_and_allows_retry() {
15081        let state = broadcast_rpc_state().with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
15082
15083        let Some((admin_pool, schema, client, state)) =
15084            execution_client_with_database("execution_clock_error_test", state).await
15085        else {
15086            return;
15087        };
15088
15089        let executor = client.transaction_executor().unwrap();
15090        let value = U256::from(1_000_000_000_000_000u64);
15091        let input = Bytes::from(WETH9::depositCall {}.abi_encode());
15092        let authorization = TransactionAuthorization::Wrap { weth: WETH_ADDRESS };
15093
15094        let error = executor
15095            .transact(
15096                UNIX_EPOCH - Duration::from_secs(1),
15097                WETH_ADDRESS,
15098                value,
15099                input.clone(),
15100                TransactionPurpose::Wrap,
15101                None,
15102                authorization,
15103            )
15104            .await
15105            .unwrap_err();
15106        let slot_after_error = *client.in_flight.lock();
15107        let requests_after_error = state.recorded_requests();
15108        let intent_count_after_error: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15109            "SELECT COUNT(*) FROM {schema}.execution_intent"
15110        )))
15111        .fetch_one(&admin_pool)
15112        .await
15113        .unwrap();
15114        let retry = executor
15115            .transact(
15116                SystemTime::now(),
15117                WETH_ADDRESS,
15118                value,
15119                input,
15120                TransactionPurpose::Wrap,
15121                None,
15122                authorization,
15123            )
15124            .await;
15125        let slot_after_retry = *client.in_flight.lock();
15126        let requests_after_retry = state.recorded_requests();
15127        let intent_count_after_retry: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15128            "SELECT COUNT(*) FROM {schema}.execution_intent"
15129        )))
15130        .fetch_one(&admin_pool)
15131        .await
15132        .unwrap();
15133        let expected_hash = expected_wrap_tx_hash(value).await;
15134
15135        drop_execution_schema(&admin_pool, &schema).await;
15136
15137        assert_eq!(
15138            error.to_string(),
15139            "Trusted host clock precedes the Unix epoch"
15140        );
15141        assert!(slot_after_error.is_none(), "was: {slot_after_error:?}");
15142        assert!(
15143            requests_after_error.is_empty(),
15144            "was: {requests_after_error:?}"
15145        );
15146        assert_eq!(intent_count_after_error, 0);
15147        let included = retry.unwrap();
15148        assert_eq!(included.nonce, 7);
15149        assert_eq!(included.tx_hash, expected_hash);
15150        assert!(matches!(
15151            slot_after_retry,
15152            Some(InFlightSlot::AwaitingFinality(_))
15153        ));
15154        assert_eq!(intent_count_after_retry, 1);
15155        assert_eq!(
15156            requests_after_retry
15157                .iter()
15158                .filter(|request| request["method"] == "eth_sendRawTransaction")
15159                .count(),
15160            1
15161        );
15162    }
15163
15164    #[tokio::test]
15165    async fn reservation_failure_releases_preparing_slot() {
15166        let state = signing_rpc_state();
15167        let Some((admin_pool, schema, mut client, state)) =
15168            execution_client_with_database("execution_reservation_fail_test", state).await
15169        else {
15170            return;
15171        };
15172        sqlx::query(sqlx::AssertSqlSafe(format!(
15173            "DROP TABLE {schema}.execution_intent CASCADE"
15174        )))
15175        .execute(&admin_pool)
15176        .await
15177        .unwrap();
15178
15179        let error = client
15180            .wrap(U256::from(1_000_000_000_000_000u64))
15181            .await
15182            .unwrap_err();
15183        let retry_error = client
15184            .wrap(U256::from(2_000_000_000_000_000u64))
15185            .await
15186            .unwrap_err();
15187        let broadcasts = state
15188            .recorded_requests()
15189            .into_iter()
15190            .filter(|request| request["method"] == "eth_sendRawTransaction")
15191            .count();
15192
15193        assert_eq!(
15194            error.to_string(),
15195            "Execution intent reservation failed before commit"
15196        );
15197        assert!(reservation_failure_proven_not_committed(&error));
15198        assert_eq!(
15199            retry_error.to_string(),
15200            "Execution intent reservation failed before commit"
15201        );
15202        assert_eq!(broadcasts, 0);
15203        assert!(client.in_flight.lock().is_none());
15204
15205        drop_execution_schema(&admin_pool, &schema).await;
15206    }
15207
15208    #[tokio::test]
15209    async fn reservation_commit_failure_keeps_preparing_slot() {
15210        let state = signing_rpc_state();
15211        let Some((admin_pool, schema, mut client, state)) =
15212            execution_client_with_database("execution_reservation_commit_fail_test", state).await
15213        else {
15214            return;
15215        };
15216        install_reservation_commit_rejection(&admin_pool, &schema).await;
15217
15218        let error = client
15219            .wrap(U256::from(1_000_000_000_000_000u64))
15220            .await
15221            .unwrap_err();
15222        let slot = *client.in_flight.lock();
15223        let second_error = client
15224            .wrap(U256::from(2_000_000_000_000_000u64))
15225            .await
15226            .unwrap_err();
15227        let requests = state.recorded_requests();
15228        let intent_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15229            "SELECT COUNT(*) FROM {schema}.execution_intent"
15230        )))
15231        .fetch_one(&admin_pool)
15232        .await
15233        .unwrap();
15234        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15235            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
15236        )))
15237        .fetch_one(&admin_pool)
15238        .await
15239        .unwrap();
15240
15241        assert_eq!(
15242            error.to_string(),
15243            "Execution intent reservation commit outcome is unknown; reconciliation is required"
15244        );
15245        assert!(!reservation_failure_proven_not_committed(&error));
15246        assert!(matches!(
15247            slot,
15248            Some(InFlightSlot::Preparing(TransactionPurpose::Wrap))
15249        ));
15250        assert!(
15251            second_error.to_string().contains("being prepared"),
15252            "was: {second_error}"
15253        );
15254        assert_eq!(intent_count, 0);
15255        assert_eq!(signed_count, 0);
15256        assert!(
15257            requests
15258                .iter()
15259                .all(|request| request["method"] != "eth_getTransactionCount")
15260        );
15261        assert!(
15262            requests
15263                .iter()
15264                .all(|request| request["method"] != "eth_sendRawTransaction")
15265        );
15266
15267        drop_execution_schema(&admin_pool, &schema).await;
15268    }
15269
15270    #[tokio::test]
15271    async fn persistence_failure_keeps_unbroadcast_slot() {
15272        let state = signing_rpc_state();
15273        let Some((admin_pool, schema, mut client, state)) =
15274            execution_client_with_database("execution_persist_fail_test", state).await
15275        else {
15276            return;
15277        };
15278        sqlx::query(sqlx::AssertSqlSafe(format!(
15279            "ALTER TABLE {schema}.execution_transaction_hash \
15280             ADD CONSTRAINT execution_hash_reject CHECK (FALSE)"
15281        )))
15282        .execute(&admin_pool)
15283        .await
15284        .unwrap();
15285
15286        let value = U256::from(1_000_000_000_000_000u64);
15287        let error = client.wrap(value).await.unwrap_err();
15288        let in_flight = awaiting_in_flight(&client);
15289        let second_error = client
15290            .wrap(U256::from(2_000_000_000_000_000u64))
15291            .await
15292            .unwrap_err();
15293        let broadcasts = state
15294            .recorded_requests()
15295            .into_iter()
15296            .filter(|request| request["method"] == "eth_sendRawTransaction")
15297            .count();
15298        let expected_hash = expected_wrap_tx_hash(value).await;
15299
15300        let error_message = error.to_string();
15301        assert!(error_message.starts_with(&format!(
15302            "Failed to persist transaction {expected_hash}: Failed to persist signed transaction"
15303        )), "was: {error_message}");
15304        assert!(
15305            error_message.ends_with("the in-flight slot stays occupied"),
15306            "was: {error_message}"
15307        );
15308        assert_eq!(in_flight.nonce, 7);
15309        assert_eq!(in_flight.tx_hash, expected_hash);
15310        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15311        assert!(
15312            second_error.to_string().contains("still awaiting finality"),
15313            "was: {second_error}"
15314        );
15315        assert_eq!(broadcasts, 0);
15316
15317        drop_execution_schema(&admin_pool, &schema).await;
15318    }
15319
15320    #[tokio::test]
15321    async fn cancellation_after_dispatch_keeps_record_and_in_flight_slot() {
15322        let state = signing_rpc_state().with_sleep(
15323            "eth_sendRawTransaction",
15324            Duration::from_secs(EXECUTION_RPC_TIMEOUT_SECS + 2),
15325        );
15326        let Some((admin_pool, schema, mut client, state)) =
15327            execution_client_with_database("execution_cancel_test", state).await
15328        else {
15329            return;
15330        };
15331
15332        let mut wrap = Box::pin(client.wrap(U256::from(1_000_000_000_000_000u64)));
15333        tokio::select! {
15334            result = &mut wrap => panic!("broadcast completed before cancellation: {result:?}"),
15335            () = await_recorded_requests(&state, "eth_sendRawTransaction", 1) => {}
15336        }
15337        drop(wrap);
15338
15339        let in_flight = awaiting_in_flight(&client);
15340        let error = client
15341            .wrap(U256::from(2_000_000_000_000_000u64))
15342            .await
15343            .unwrap_err();
15344        let record = client
15345            .cache
15346            .get_execution_transaction(42161, &in_flight.tx_hash.to_string())
15347            .await
15348            .unwrap()
15349            .unwrap();
15350        let broadcasts = state
15351            .recorded_requests()
15352            .into_iter()
15353            .filter(|request| request["method"] == "eth_sendRawTransaction")
15354            .count();
15355
15356        assert!(
15357            error.to_string().contains("still awaiting finality"),
15358            "was: {error}"
15359        );
15360        assert_eq!(record.nonce, 7);
15361        assert_eq!(record.purpose, "wrap");
15362        assert_eq!(record.status, "broadcast");
15363        assert_eq!(broadcasts, 1);
15364
15365        drop_execution_schema(&admin_pool, &schema).await;
15366    }
15367
15368    #[tokio::test]
15369    async fn cancellation_during_receipt_polling_keeps_record_and_in_flight_slot() {
15370        let state = signing_rpc_state()
15371            .with_send_raw_transaction_echo()
15372            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS)
15373            .with_sleep(
15374                "eth_getTransactionReceipt",
15375                Duration::from_secs(EXECUTION_RPC_TIMEOUT_SECS + 2),
15376            );
15377        let Some((admin_pool, schema, mut client, state)) =
15378            execution_client_with_database("execution_receipt_cancel_test", state).await
15379        else {
15380            return;
15381        };
15382
15383        let mut wrap = Box::pin(client.wrap(U256::from(1_000_000_000_000_000u64)));
15384        tokio::select! {
15385            result = &mut wrap => panic!("receipt polling completed before cancellation: {result:?}"),
15386            () = await_recorded_requests(&state, "eth_getTransactionReceipt", 3) => {}
15387        }
15388        drop(wrap);
15389
15390        let in_flight = awaiting_in_flight(&client);
15391        let second_error = client
15392            .wrap(U256::from(2_000_000_000_000_000u64))
15393            .await
15394            .unwrap_err();
15395        let record = client
15396            .cache
15397            .get_execution_transaction(42161, &in_flight.tx_hash.to_string())
15398            .await
15399            .unwrap()
15400            .unwrap();
15401        let requests = state.recorded_requests();
15402
15403        assert_eq!(in_flight.nonce, 7);
15404        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15405        assert!(
15406            second_error.to_string().contains("still awaiting finality"),
15407            "was: {second_error}"
15408        );
15409        assert_eq!(record.nonce, 7);
15410        assert_eq!(record.transaction_hash, in_flight.tx_hash.to_string());
15411        assert_eq!(record.purpose, "wrap");
15412        assert_eq!(record.status, "broadcast");
15413        assert_eq!(
15414            requests
15415                .iter()
15416                .filter(|request| request["method"] == "eth_sendRawTransaction")
15417                .count(),
15418            1
15419        );
15420        assert_eq!(
15421            requests
15422                .iter()
15423                .filter(|request| request["method"] == "eth_getTransactionReceipt")
15424                .count(),
15425            3
15426        );
15427
15428        drop_execution_schema(&admin_pool, &schema).await;
15429    }
15430
15431    #[tokio::test]
15432    async fn rejected_broadcast_stays_dropped_and_occupied() {
15433        let state = signing_rpc_state()
15434            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION_REJECTED)
15435            .with_response("eth_getTransactionReceipt", RECEIPT_NULL);
15436        let Some((admin_pool, schema, mut client, state)) =
15437            execution_client_with_database("execution_rejected_test", state).await
15438        else {
15439            return;
15440        };
15441
15442        let error = client
15443            .wrap(U256::from(1_000_000_000_000_000u64))
15444            .await
15445            .unwrap_err();
15446        let (purpose, status): (String, String) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
15447            "SELECT purpose, status FROM {schema}.execution_intent"
15448        )))
15449        .fetch_one(&admin_pool)
15450        .await
15451        .unwrap();
15452        let broadcasts = state
15453            .recorded_requests()
15454            .into_iter()
15455            .filter(|request| request["method"] == "eth_sendRawTransaction")
15456            .count();
15457
15458        assert!(
15459            error.to_string().contains("Timed out awaiting finality"),
15460            "was: {error}"
15461        );
15462        assert!(client.in_flight.lock().is_some());
15463        assert_eq!(purpose, "wrap");
15464        assert_eq!(status, "dropped");
15465        assert_eq!(broadcasts, 1);
15466
15467        drop_execution_schema(&admin_pool, &schema).await;
15468    }
15469
15470    #[tokio::test]
15471    async fn legacy_table_loss_does_not_release_rejected_broadcast() {
15472        let state = signing_rpc_state()
15473            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION_REJECTED)
15474            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
15475            .with_sleep("eth_sendRawTransaction", Duration::from_secs(1));
15476        let Some((admin_pool, schema, mut client, state)) =
15477            execution_client_with_database("execution_rejected_update_test", state).await
15478        else {
15479            return;
15480        };
15481
15482        let mut wrap = Box::pin(client.wrap(U256::from(1_000_000_000_000_000u64)));
15483        tokio::select! {
15484            result = &mut wrap => panic!("broadcast completed before database failure: {result:?}"),
15485            () = await_recorded_requests(&state, "eth_sendRawTransaction", 1) => {}
15486        }
15487        sqlx::query(sqlx::AssertSqlSafe(format!(
15488            "DROP TABLE {schema}.execution_transaction"
15489        )))
15490        .execute(&admin_pool)
15491        .await
15492        .unwrap();
15493
15494        let error = wrap.await.unwrap_err();
15495
15496        assert!(
15497            error.to_string().contains("Timed out awaiting finality"),
15498            "was: {error}"
15499        );
15500        let in_flight = awaiting_in_flight(&client);
15501        assert_eq!(in_flight.nonce, 7);
15502        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15503
15504        drop_execution_schema(&admin_pool, &schema).await;
15505    }
15506
15507    #[tokio::test]
15508    async fn finalized_receipt_keeps_slot_when_status_update_fails() {
15509        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000u64)).await;
15510        let block = finalized_wrap_block(expected_hash);
15511        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
15512        let state = with_finalized_identity(
15513            signing_rpc_state()
15514                .with_send_raw_transaction_echo()
15515                .with_response("eth_getTransactionReceipt", &receipt)
15516                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
15517                .with_call_response_sequence(
15518                    BALANCE_OF_SELECTOR,
15519                    &[
15520                        CALL_BALANCE,
15521                        CALL_BALANCE,
15522                        CALL_BALANCE,
15523                        CALL_BALANCE,
15524                        CALL_BALANCE,
15525                        CALL_BALANCE,
15526                        CALL_BALANCE_AFTER_WRAP,
15527                        CALL_BALANCE_AFTER_WRAP,
15528                        CALL_BALANCE_AFTER_WRAP,
15529                    ],
15530                ),
15531            &block,
15532            &receipt,
15533        );
15534        let Some((admin_pool, schema, mut client, state)) =
15535            execution_client_with_database("execution_finalized_update_test", state).await
15536        else {
15537            return;
15538        };
15539
15540        for statement in [
15541            format!(
15542                "CREATE FUNCTION {schema}.reject_finalized_status() RETURNS trigger \
15543                 LANGUAGE plpgsql AS 'BEGIN IF NEW.status = ''finalized'' THEN \
15544                 RAISE EXCEPTION ''test finalized status rejection''; END IF; \
15545                 RETURN NEW; END'"
15546            ),
15547            format!(
15548                "CREATE TRIGGER reject_finalized_status BEFORE UPDATE ON \
15549                 {schema}.execution_transaction_hash FOR EACH ROW \
15550                 EXECUTE FUNCTION {schema}.reject_finalized_status()"
15551            ),
15552        ] {
15553            sqlx::query(sqlx::AssertSqlSafe(statement))
15554                .execute(&admin_pool)
15555                .await
15556                .unwrap();
15557        }
15558
15559        let error = client
15560            .wrap(U256::from(1_000_000_000_000_000u64))
15561            .await
15562            .unwrap_err();
15563        let in_flight = awaiting_in_flight(&client);
15564        let requests = state.recorded_requests();
15565
15566        assert!(
15567            error
15568                .to_string()
15569                .contains("test finalized status rejection"),
15570            "was: {error}"
15571        );
15572        assert_eq!(in_flight.nonce, 7);
15573        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15574        assert_eq!(
15575            requests
15576                .iter()
15577                .filter(|request| request["method"] == "eth_sendRawTransaction")
15578                .count(),
15579            1
15580        );
15581        assert_eq!(
15582            requests
15583                .iter()
15584                .filter(|request| request["method"] == "eth_getTransactionReceipt")
15585                .count(),
15586            3
15587        );
15588
15589        drop_execution_schema(&admin_pool, &schema).await;
15590    }
15591
15592    #[tokio::test]
15593    async fn broadcast_timeout_marks_dropped_and_keeps_ownership() {
15594        let state = signing_rpc_state()
15595            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
15596            .with_sleep(
15597                "eth_sendRawTransaction",
15598                Duration::from_secs(EXECUTION_RPC_TIMEOUT_SECS + 2),
15599            );
15600        let Some((admin_pool, schema, mut client, _)) =
15601            execution_client_with_database("execution_timeout_test", state).await
15602        else {
15603            return;
15604        };
15605
15606        let error = client
15607            .wrap(U256::from(1_000_000_000_000_000u64))
15608            .await
15609            .unwrap_err();
15610
15611        assert!(
15612            error.to_string().contains("Timed out awaiting finality"),
15613            "was: {error}"
15614        );
15615        let in_flight = awaiting_in_flight(&client);
15616        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15617        assert_eq!(in_flight.nonce, 7);
15618
15619        // The persisted record stays active for reconciliation instead of rebroadcasting.
15620        let record = client
15621            .cache
15622            .get_execution_transaction(42161, &in_flight.tx_hash.to_string())
15623            .await
15624            .unwrap()
15625            .unwrap();
15626        assert_eq!(record.status, "dropped");
15627
15628        drop_execution_schema(&admin_pool, &schema).await;
15629    }
15630
15631    #[tokio::test]
15632    async fn restart_reconciles_dropped_transaction_without_rebroadcast() {
15633        let initial_state = broadcast_rpc_state()
15634            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
15635            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
15636        let Some((admin_pool, schema, mut first_client, _)) =
15637            execution_client_with_database("execution_restart_test", initial_state).await
15638        else {
15639            return;
15640        };
15641        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
15642        let error = first_client
15643            .wrap(U256::from(1_000_000_000_000_000_u64))
15644            .await
15645            .unwrap_err();
15646        assert!(
15647            error.to_string().contains("Timed out awaiting finality"),
15648            "was: {error}"
15649        );
15650        let database = first_client.cache.database.as_ref().unwrap().clone();
15651        let payload_keys = first_client.payload_keys.clone();
15652        drop(first_client);
15653
15654        let block = finalized_wrap_block(expected_hash);
15655        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
15656        let restart_state = with_finalized_identity(
15657            execution_rpc_state()
15658                .with_response("eth_getTransactionReceipt", &receipt)
15659                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
15660                .with_response_sequence(
15661                    "eth_call",
15662                    &[
15663                        CALL_BALANCE,
15664                        CALL_BALANCE,
15665                        CALL_BALANCE,
15666                        CALL_BALANCE_AFTER_WRAP,
15667                        CALL_BALANCE_AFTER_WRAP,
15668                        CALL_BALANCE_AFTER_WRAP,
15669                    ],
15670                ),
15671            &block,
15672            &receipt,
15673        );
15674        let addr = start_mock_rpc_server(restart_state.clone()).await;
15675        let mut restarted = test_client(format!("http://{addr}"));
15676        restarted.cache.database = Some(database);
15677        restarted.payload_keys = payload_keys;
15678        restarted.signer = Some(Arc::new(
15679            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
15680        ));
15681
15682        restarted.reconcile_unresolved_execution().await.unwrap();
15683        restarted.reconcile_unresolved_execution().await.unwrap();
15684
15685        let record = restarted
15686            .cache
15687            .get_execution_transaction(42161, &expected_hash.to_string())
15688            .await
15689            .unwrap()
15690            .unwrap();
15691        let requests = restart_state.recorded_requests();
15692        assert_eq!(record.status, "finalized");
15693        assert!(restarted.in_flight.lock().is_none());
15694        assert_eq!(
15695            requests
15696                .iter()
15697                .filter(|request| request["method"] == "eth_getTransactionReceipt")
15698                .count(),
15699            6
15700        );
15701        assert_eq!(
15702            requests
15703                .iter()
15704                .filter(|request| {
15705                    request["method"] == "eth_call"
15706                        && request["params"][0]["data"]
15707                            .as_str()
15708                            .is_some_and(|data| data.starts_with(BALANCE_OF_SELECTOR))
15709                })
15710                .count(),
15711            6
15712        );
15713        assert_eq!(
15714            requests
15715                .iter()
15716                .filter(|request| request["method"] == "eth_sendRawTransaction")
15717                .count(),
15718            0
15719        );
15720
15721        drop_execution_schema(&admin_pool, &schema).await;
15722    }
15723
15724    fn migration_test_intent(id: i64) -> ExecutionIntentRow {
15725        ExecutionIntentRow {
15726            id,
15727            schema_version: crate::execution::transaction::EXECUTION_SCHEMA_VERSION,
15728            chain_id: 42_161,
15729            wallet_address: WALLET.to_string(),
15730            nonce: None,
15731            purpose: "wrap".to_string(),
15732            status: "prepared".to_string(),
15733            client_order_id: None,
15734            trader_id: None,
15735            strategy_id: None,
15736            account_id: None,
15737            instrument_id: None,
15738            pool_address: None,
15739            transaction_to: WETH.to_string(),
15740            transaction_input: "0xd0e30db0".to_string(),
15741            transaction_value: "1".to_string(),
15742            amount_in: None,
15743            created_block: FIXTURE_BLOCK,
15744            acknowledgement_emitted: false,
15745            fill_emitted: false,
15746            terminal_emitted: false,
15747            active: true,
15748        }
15749    }
15750
15751    fn migration_nonce_verification() -> Verified<u64> {
15752        Verified {
15753            value: 7,
15754            read: crate::rpc::verification::VerificationRead::TransactionCount,
15755            provider_ids: [
15756                "authoritative".to_string(),
15757                "verifier-a".to_string(),
15758                "verifier-b".to_string(),
15759            ],
15760            normalized_value_digest: keccak256(7_u64.to_be_bytes()),
15761        }
15762    }
15763
15764    fn migration_finalized_header() -> VerifiedBlockHeader {
15765        VerifiedBlockHeader {
15766            number: FIXTURE_BLOCK,
15767            hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
15768            parent_hash: B256::from_str(
15769                "0x0000000000000000000000000000000000000000000000000000000000000001",
15770            )
15771            .unwrap(),
15772            timestamp: FIXTURE_BLOCK_TIMESTAMP,
15773            base_fee_per_gas: Some(100_000_000),
15774        }
15775    }
15776
15777    #[tokio::test]
15778    async fn verification_migration_recovers_prepared_unassigned_intent() {
15779        let client = test_client("http://127.0.0.1:1".to_string());
15780        let snapshot = ExecutionVerificationMigrationSnapshot {
15781            intents: vec![migration_test_intent(1)],
15782            hashes: Vec::new(),
15783        };
15784        let finalized = migration_finalized_header();
15785        let migration = client
15786            .build_execution_verification_migration(
15787                snapshot,
15788                finalized,
15789                &[finalized],
15790                &migration_nonce_verification(),
15791            )
15792            .await
15793            .unwrap();
15794
15795        assert_eq!(migration.records.len(), 1);
15796        let record = &migration.records[0];
15797        assert_eq!(record.intent_id, 1);
15798        assert_eq!(record.nonce, None);
15799        assert_eq!(record.transaction_hash, None);
15800        assert!(record.recover_prepared);
15801        assert_eq!(record.decisions.len(), 1);
15802    }
15803
15804    #[tokio::test]
15805    async fn verification_migration_rejects_inconsistent_released_history() {
15806        let client = test_client("http://127.0.0.1:1".to_string());
15807        let finalized = migration_finalized_header();
15808        let nonce_verification = migration_nonce_verification();
15809        let mut missing_marker = migration_test_intent(1);
15810        missing_marker.active = false;
15811        missing_marker.status = "finalized".to_string();
15812        missing_marker.nonce = Some(6);
15813        let error = client
15814            .build_execution_verification_migration(
15815                ExecutionVerificationMigrationSnapshot {
15816                    intents: vec![missing_marker],
15817                    hashes: Vec::new(),
15818                },
15819                finalized,
15820                &[finalized],
15821                &nonce_verification,
15822            )
15823            .await
15824            .err()
15825            .unwrap();
15826        assert!(
15827            error.to_string().contains("has no durable event marker"),
15828            "was: {error}"
15829        );
15830
15831        let mut first = migration_test_intent(1);
15832        first.active = false;
15833        first.status = "recoverable".to_string();
15834        first.nonce = Some(6);
15835        let mut second = first.clone();
15836        second.id = 2;
15837        let error = client
15838            .build_execution_verification_migration(
15839                ExecutionVerificationMigrationSnapshot {
15840                    intents: vec![first, second],
15841                    hashes: Vec::new(),
15842                },
15843                finalized,
15844                &[finalized],
15845                &nonce_verification,
15846            )
15847            .await
15848            .err()
15849            .unwrap();
15850        assert!(
15851            error
15852                .to_string()
15853                .contains("duplicate signer nonce ownership"),
15854            "was: {error}"
15855        );
15856    }
15857
15858    #[tokio::test]
15859    async fn verification_migration_reconstructs_consumed_active_intent() {
15860        let expected_hash = expected_wrap_tx_hash(U256::from(1u64)).await;
15861        let mut block_value: serde_json::Value =
15862            serde_json::from_str(&finalized_wrap_block(expected_hash)).unwrap();
15863        block_value["result"]["transactions"][0]["value"] = serde_json::json!("0x1");
15864        let block = block_value.to_string();
15865        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
15866        let state = with_finalized_identity(
15867            execution_rpc_state()
15868                .with_response("eth_getTransactionCount", TRANSACTION_COUNT_NEXT)
15869                .with_response("eth_getTransactionReceipt", &receipt)
15870                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block),
15871            &block,
15872            &receipt,
15873        );
15874        let Some((admin_pool, pg_config)) =
15875            connect_test_postgres("verification_migration_reconstructs_consumed_active_intent")
15876                .await
15877        else {
15878            return;
15879        };
15880        let schema = format!(
15881            "verification_migration_reconstructs_consumed_active_intent_{}",
15882            std::process::id()
15883        );
15884        setup_execution_schema(&admin_pool, &schema).await;
15885        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
15886        let database = connect_test_database(options.options([("search_path", schema.clone())]))
15887            .await
15888            .unwrap();
15889        let addr = start_mock_rpc_server(state).await;
15890        let (mut client, _) = swap_client_with_cache(test_config(format!("http://{addr}")));
15891        client.cache.database = Some(database.clone());
15892        client
15893            .cache
15894            .ensure_execution_transaction_schema()
15895            .await
15896            .unwrap();
15897        let (intent, persisted_hash, _) = persist_test_wrap_broadcast(&database, None).await;
15898        protect_test_storage(&mut client, &schema).await;
15899        assert_eq!(persisted_hash, expected_hash);
15900
15901        let snapshot = database
15902            .load_execution_verification_migration_snapshot(42_161, WALLET)
15903            .await
15904            .unwrap();
15905        let nonce_verification = required_verification(
15906            client
15907                .verification
15908                .verify_transaction_count(&Address::from_str(WALLET).unwrap(), FIXTURE_BLOCK + 1)
15909                .await,
15910            "test migration nonce",
15911        )
15912        .unwrap();
15913        let headers = [
15914            VerifiedBlockHeader {
15915                number: FIXTURE_BLOCK,
15916                hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
15917                parent_hash: B256::from_str(
15918                    "0x0000000000000000000000000000000000000000000000000000000000000001",
15919                )
15920                .unwrap(),
15921                timestamp: FIXTURE_BLOCK_TIMESTAMP,
15922                base_fee_per_gas: Some(100_000_000),
15923            },
15924            VerifiedBlockHeader {
15925                number: FIXTURE_BLOCK + 1,
15926                hash: B256::from([0x22; 32]),
15927                parent_hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
15928                timestamp: FIXTURE_BLOCK_TIMESTAMP + 1,
15929                base_fee_per_gas: Some(100_000_000),
15930            },
15931        ];
15932        let migration = client
15933            .build_execution_verification_migration(
15934                snapshot,
15935                headers[1],
15936                &headers,
15937                &nonce_verification,
15938            )
15939            .await
15940            .unwrap();
15941        let finalized_headers = headers
15942            .iter()
15943            .map(|header| ExecutionVerifiedHeader {
15944                number: header.number,
15945                hash: header.hash.to_string(),
15946                parent_hash: header.parent_hash.to_string(),
15947                timestamp: header.timestamp,
15948                base_fee_per_gas: header.base_fee_per_gas,
15949            })
15950            .collect::<Vec<_>>();
15951        let decisions = [verification_decision(
15952            &nonce_verification,
15953            Some(FIXTURE_BLOCK + 1),
15954            Some(FIXTURE_BLOCK + 1),
15955        )];
15956
15957        initialize_test_verification_migration(
15958            &client,
15959            &finalized_headers,
15960            8,
15961            &decisions,
15962            &migration,
15963        )
15964        .await;
15965
15966        let migrated = database.get_execution_intent(intent.id).await.unwrap();
15967        let resume = database
15968            .load_execution_verification_resume(
15969                42_161,
15970                WALLET,
15971                &client
15972                    .config
15973                    .verification
15974                    .as_ref()
15975                    .unwrap()
15976                    .manifest_version,
15977                &client.config.verification.as_ref().unwrap().manifest_digest,
15978            )
15979            .await
15980            .unwrap()
15981            .unwrap();
15982        let evidence: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15983            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
15984             WHERE intent_id = $1 AND decision_class = 'migration'"
15985        )))
15986        .bind(intent.id)
15987        .fetch_one(&admin_pool)
15988        .await
15989        .unwrap();
15990
15991        assert_eq!(migrated.status, "finalized");
15992        assert!(migrated.active);
15993        assert_eq!(resume.next_canonical_nonce, 8);
15994        assert!(evidence >= 5);
15995
15996        drop_execution_schema(&admin_pool, &schema).await;
15997    }
15998
15999    #[tokio::test]
16000    async fn verification_resume_accepts_one_consumed_owned_nonce() {
16001        let Some((admin_pool, schema, client, _)) = execution_client_with_database(
16002            "verification_resume_owned_nonce_test",
16003            ready_rpc_state(),
16004        )
16005        .await
16006        else {
16007            return;
16008        };
16009        let database = client.cache.database.as_ref().unwrap();
16010        persist_test_wrap_broadcast(database, client.payload_keys.as_deref()).await;
16011        let resume = database
16012            .load_execution_verification_resume(
16013                42_161,
16014                WALLET,
16015                &client
16016                    .config
16017                    .verification
16018                    .as_ref()
16019                    .unwrap()
16020                    .manifest_version,
16021                &client.config.verification.as_ref().unwrap().manifest_digest,
16022            )
16023            .await
16024            .unwrap()
16025            .unwrap();
16026
16027        ensure_test_verification_ledger(&client, &resume.finalized_headers, 7, 8)
16028            .await
16029            .unwrap();
16030
16031        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
16032            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
16033        )))
16034        .fetch_one(&admin_pool)
16035        .await
16036        .unwrap();
16037        assert_eq!(nonce_state, (7, 0));
16038
16039        drop_execution_schema(&admin_pool, &schema).await;
16040    }
16041
16042    #[tokio::test]
16043    async fn verification_resume_rejects_unowned_nonce_advance() {
16044        for (test_name, mutation, observed_canonical_nonce) in [
16045            ("verification_resume_no_active_test", "no_active", 8),
16046            ("verification_resume_excess_test", "unchanged", 9),
16047            ("verification_resume_signed_test", "signed", 8),
16048            ("verification_resume_prepared_test", "prepared", 8),
16049            (
16050                "verification_resume_missing_payload_test",
16051                "missing_payload",
16052                8,
16053            ),
16054        ] {
16055            let Some((admin_pool, schema, client, _)) =
16056                execution_client_with_database(test_name, ready_rpc_state()).await
16057            else {
16058                return;
16059            };
16060            let database = client.cache.database.as_ref().unwrap();
16061            let (intent, _, _) =
16062                persist_test_wrap_broadcast(database, client.payload_keys.as_deref()).await;
16063
16064            match mutation {
16065                "no_active" => {
16066                    sqlx::query(sqlx::AssertSqlSafe(format!(
16067                        "UPDATE {schema}.execution_intent SET active = FALSE WHERE id = $1"
16068                    )))
16069                    .bind(intent.id)
16070                    .execute(&admin_pool)
16071                    .await
16072                    .unwrap();
16073                }
16074                "signed" => {
16075                    sqlx::query(sqlx::AssertSqlSafe(format!(
16076                        "UPDATE {schema}.execution_intent SET status = 'signed' WHERE id = $1"
16077                    )))
16078                    .bind(intent.id)
16079                    .execute(&admin_pool)
16080                    .await
16081                    .unwrap();
16082                    sqlx::query(sqlx::AssertSqlSafe(format!(
16083                        "UPDATE {schema}.execution_transaction_hash SET status = 'signed' \
16084                         WHERE intent_id = $1"
16085                    )))
16086                    .bind(intent.id)
16087                    .execute(&admin_pool)
16088                    .await
16089                    .unwrap();
16090                }
16091                "prepared" => {
16092                    sqlx::query(sqlx::AssertSqlSafe(format!(
16093                        "UPDATE {schema}.execution_intent \
16094                         SET nonce = NULL, status = 'prepared' WHERE id = $1"
16095                    )))
16096                    .bind(intent.id)
16097                    .execute(&admin_pool)
16098                    .await
16099                    .unwrap();
16100                    sqlx::query(sqlx::AssertSqlSafe(format!(
16101                        "UPDATE {schema}.execution_transaction_hash SET current = FALSE \
16102                         WHERE intent_id = $1"
16103                    )))
16104                    .bind(intent.id)
16105                    .execute(&admin_pool)
16106                    .await
16107                    .unwrap();
16108                }
16109                "missing_payload" => {
16110                    sqlx::query(sqlx::AssertSqlSafe(format!(
16111                        "UPDATE {schema}.execution_transaction_hash \
16112                         SET payload_expected = FALSE, sealed_transaction = NULL \
16113                         WHERE intent_id = $1"
16114                    )))
16115                    .bind(intent.id)
16116                    .execute(&admin_pool)
16117                    .await
16118                    .unwrap();
16119                }
16120                "unchanged" => {}
16121                _ => unreachable!(),
16122            }
16123            let resume = database
16124                .load_execution_verification_resume(
16125                    42_161,
16126                    WALLET,
16127                    &client
16128                        .config
16129                        .verification
16130                        .as_ref()
16131                        .unwrap()
16132                        .manifest_version,
16133                    &client.config.verification.as_ref().unwrap().manifest_digest,
16134                )
16135                .await
16136                .unwrap()
16137                .unwrap();
16138
16139            let error = ensure_test_verification_ledger(
16140                &client,
16141                &resume.finalized_headers,
16142                7,
16143                observed_canonical_nonce,
16144            )
16145            .await
16146            .unwrap_err();
16147
16148            assert!(
16149                error
16150                    .to_string()
16151                    .contains(if observed_canonical_nonce == 9 {
16152                        "outside the owned recovery range"
16153                    } else {
16154                        "without"
16155                    }),
16156                "{mutation}: {error}"
16157            );
16158            let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
16159                "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
16160            )))
16161            .fetch_one(&admin_pool)
16162            .await
16163            .unwrap();
16164            assert_eq!(nonce_state, (7, 0), "{mutation}");
16165
16166            drop_execution_schema(&admin_pool, &schema).await;
16167        }
16168    }
16169
16170    #[tokio::test]
16171    async fn restart_marks_prepared_intent_recoverable_without_broadcast() {
16172        let Some((admin_pool, schema, client, state)) =
16173            execution_client_with_database("execution_prepared_restart_test", ready_rpc_state())
16174                .await
16175        else {
16176            return;
16177        };
16178        let database = client.cache.database.as_ref().unwrap();
16179        let intent = reserve_test_wrap_intent(database).await;
16180        *client.in_flight.lock() = Some(InFlightSlot::Preparing(TransactionPurpose::Wrap));
16181
16182        client.reconcile_unresolved_execution().await.unwrap();
16183
16184        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
16185            "SELECT status, active FROM {schema}.execution_intent WHERE id = {}",
16186            intent.id
16187        )))
16188        .fetch_one(&admin_pool)
16189        .await
16190        .unwrap();
16191        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16192            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
16193        )))
16194        .fetch_all(&admin_pool)
16195        .await
16196        .unwrap();
16197
16198        assert_eq!(status, "recoverable");
16199        assert!(!active);
16200        assert_eq!(transitions, ["prepared", "recoverable"]);
16201        assert!(client.in_flight.lock().is_none());
16202        assert!(
16203            state
16204                .recorded_requests()
16205                .iter()
16206                .all(|request| request["method"] != "eth_sendRawTransaction")
16207        );
16208
16209        drop_execution_schema(&admin_pool, &schema).await;
16210    }
16211
16212    #[tokio::test]
16213    async fn protected_restart_authenticates_envelope_before_recovery() {
16214        let initial_state = broadcast_rpc_state()
16215            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16216            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
16217        let Some((admin_pool, schema, mut first_client, _)) =
16218            execution_client_with_database("protected_restart_test", initial_state).await
16219        else {
16220            return;
16221        };
16222        let database = first_client.cache.database.as_ref().unwrap().clone();
16223        let value = U256::from(1_000_000_000_000_000_u64);
16224        let expected_hash = expected_wrap_tx_hash(value).await;
16225
16226        let error = first_client.wrap(value).await.unwrap_err();
16227
16228        assert!(error.to_string().contains("Timed out awaiting finality"));
16229        let intent = database
16230            .get_active_execution_intent(42161, WALLET)
16231            .await
16232            .unwrap()
16233            .unwrap();
16234        let payload = database
16235            .get_execution_transaction_hashes(intent.id)
16236            .await
16237            .unwrap()
16238            .pop()
16239            .unwrap();
16240        assert!(payload.raw_transaction.is_none());
16241        assert!(payload.sealed_transaction.is_some());
16242        let keys = first_client.payload_keys.take().unwrap();
16243        drop(first_client);
16244
16245        let block = finalized_wrap_block(expected_hash);
16246        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
16247        let restart_state = with_finalized_identity(
16248            execution_rpc_state()
16249                .with_response("eth_getTransactionReceipt", &receipt)
16250                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
16251                .with_response_sequence(
16252                    "eth_call",
16253                    &[
16254                        CALL_BALANCE,
16255                        CALL_BALANCE,
16256                        CALL_BALANCE,
16257                        CALL_BALANCE_AFTER_WRAP,
16258                        CALL_BALANCE_AFTER_WRAP,
16259                        CALL_BALANCE_AFTER_WRAP,
16260                    ],
16261                ),
16262            &block,
16263            &receipt,
16264        );
16265        let addr = start_mock_rpc_server(restart_state.clone()).await;
16266        let mut restarted = test_client(format!("http://{addr}"));
16267        restarted.cache.database = Some(database);
16268        restarted.payload_keys = Some(keys);
16269        restarted.signer = Some(Arc::new(
16270            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16271        ));
16272
16273        restarted.reconcile_unresolved_execution().await.unwrap();
16274
16275        let record = restarted
16276            .cache
16277            .get_execution_transaction(42161, &expected_hash.to_string())
16278            .await
16279            .unwrap()
16280            .unwrap();
16281        let requests = restart_state.recorded_requests();
16282        assert_eq!(record.status, "finalized");
16283        assert!(restarted.in_flight.lock().is_none());
16284        assert_eq!(
16285            requests
16286                .iter()
16287                .filter(|request| request["method"] == "eth_sendRawTransaction")
16288                .count(),
16289            0
16290        );
16291
16292        drop_execution_schema(&admin_pool, &schema).await;
16293    }
16294
16295    #[tokio::test]
16296    async fn active_intent_reconciliation_waits_for_reservation_fence() {
16297        let Some((admin_pool, schema, client, _)) = execution_client_with_database(
16298            "execution_active_intent_reservation_fence_test",
16299            ready_rpc_state(),
16300        )
16301        .await
16302        else {
16303            return;
16304        };
16305        let database = client.cache.database.as_ref().unwrap().clone();
16306        let lock = PgAdvisoryLock::new(format!(
16307            "nautilus:blockchain:execution:42161:{}",
16308            WALLET.to_ascii_lowercase()
16309        ));
16310        let PgAdvisoryLockKey::BigInt(lock_key) = lock.key() else {
16311            unreachable!("string advisory locks use the 64-bit key space");
16312        };
16313        let mut reservation = admin_pool.begin().await.unwrap();
16314        sqlx::query("SELECT pg_advisory_xact_lock($1)")
16315            .bind(*lock_key)
16316            .execute(&mut *reservation)
16317            .await
16318            .unwrap();
16319        sqlx::query(sqlx::AssertSqlSafe(format!(
16320            "INSERT INTO {schema}.execution_intent (\
16321                schema_version, chain_id, wallet_address, purpose, status, transaction_to, \
16322                transaction_input, transaction_value, created_block\
16323             ) VALUES (2, $1, $2, 'wrap', 'prepared', $3, '0xd0e30db0', '1', $4)"
16324        )))
16325        .bind(42161_i32)
16326        .bind(WALLET)
16327        .bind(WETH_ADDRESS.to_string())
16328        .bind(i64::try_from(FIXTURE_BLOCK).unwrap())
16329        .execute(&mut *reservation)
16330        .await
16331        .unwrap();
16332
16333        let mut reconciliation = Box::pin(database.get_active_execution_intent(42161, WALLET));
16334        assert!(
16335            tokio::time::timeout(Duration::from_millis(100), &mut reconciliation)
16336                .await
16337                .is_err(),
16338            "reconciliation did not wait for the reservation fence"
16339        );
16340
16341        reservation.commit().await.unwrap();
16342        let intent = tokio::time::timeout(Duration::from_secs(2), reconciliation)
16343            .await
16344            .unwrap()
16345            .unwrap()
16346            .unwrap();
16347
16348        assert_eq!(intent.chain_id, 42161);
16349        assert_eq!(intent.wallet_address, WALLET);
16350        assert_eq!(intent.purpose, "wrap");
16351        assert_eq!(intent.status, "prepared");
16352        assert!(intent.active);
16353
16354        drop_execution_schema(&admin_pool, &schema).await;
16355    }
16356
16357    #[tokio::test]
16358    async fn restart_keeps_unbroadcast_signed_intent_reserved() {
16359        let Some((admin_pool, schema, client, state)) =
16360            execution_client_with_database("execution_signed_restart_test", ready_rpc_state())
16361                .await
16362        else {
16363            return;
16364        };
16365        let database = client.cache.database.as_ref().unwrap();
16366        let intent = reserve_test_wrap_intent(database).await;
16367        let transaction = build_eip1559_transaction(
16368            42161,
16369            7,
16370            78_000,
16371            130_000_000,
16372            10_000_000,
16373            WETH_ADDRESS,
16374            U256::from(1u64),
16375            Bytes::from(nautilus_core::hex::decode("d0e30db0").unwrap()),
16376        );
16377        let (tx_hash, raw_transaction) = sign_eip1559_transaction(
16378            transaction,
16379            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16380        )
16381        .await
16382        .unwrap();
16383        database
16384            .assign_execution_intent_nonce(intent.id, 7)
16385            .await
16386            .unwrap();
16387        let intent = database.get_execution_intent(intent.id).await.unwrap();
16388        persist_test_payload(
16389            database,
16390            client.payload_keys.as_deref(),
16391            &intent,
16392            tx_hash,
16393            &raw_transaction,
16394        )
16395        .await;
16396
16397        let error = client.reconcile_unresolved_execution().await.unwrap_err();
16398
16399        assert!(
16400            error
16401                .to_string()
16402                .contains("was not authorized for broadcast"),
16403            "was: {error}"
16404        );
16405        let recovery = recovering_in_flight(&client);
16406        assert_eq!(recovery.intent_id, intent.id);
16407        assert_eq!(recovery.nonce, 7);
16408        assert_eq!(recovery.purpose, TransactionPurpose::Wrap);
16409        assert_eq!(
16410            execution_intent_markers(&admin_pool, &schema).await,
16411            vec![("wrap".into(), "signed".into(), false, true)]
16412        );
16413        assert!(
16414            state
16415                .recorded_requests()
16416                .iter()
16417                .all(|request| request["method"] != "eth_sendRawTransaction")
16418        );
16419
16420        drop_execution_schema(&admin_pool, &schema).await;
16421    }
16422
16423    #[tokio::test]
16424    async fn restart_quarantines_legacy_recoverable_signed_intent() {
16425        let Some((admin_pool, schema, client, state)) = execution_client_with_database(
16426            "execution_legacy_recoverable_restart_test",
16427            ready_rpc_state(),
16428        )
16429        .await
16430        else {
16431            return;
16432        };
16433        let database = client.cache.database.as_ref().unwrap();
16434        let intent = reserve_test_wrap_intent(database).await;
16435        let tx_hash = B256::from([0x55; 32]);
16436        database
16437            .assign_execution_intent_nonce(intent.id, 7)
16438            .await
16439            .unwrap();
16440        let intent = database.get_execution_intent(intent.id).await.unwrap();
16441        persist_test_payload(
16442            database,
16443            client.payload_keys.as_deref(),
16444            &intent,
16445            tx_hash,
16446            &[0x01, 0x02, 0x03],
16447        )
16448        .await;
16449        sqlx::query(sqlx::AssertSqlSafe(format!(
16450            "UPDATE {schema}.execution_intent SET status = 'recoverable', active = FALSE WHERE id = {}",
16451            intent.id
16452        )))
16453        .execute(&admin_pool)
16454        .await
16455        .unwrap();
16456
16457        let error = client.reconcile_unresolved_execution().await.unwrap_err();
16458
16459        assert!(
16460            error
16461                .to_string()
16462                .contains("retains signed transaction bytes"),
16463            "was: {error}"
16464        );
16465        assert!(client.in_flight.lock().is_none());
16466        assert!(
16467            state
16468                .recorded_requests()
16469                .iter()
16470                .all(|request| request["method"] != "eth_sendRawTransaction")
16471        );
16472
16473        drop_execution_schema(&admin_pool, &schema).await;
16474    }
16475
16476    #[rstest]
16477    #[case::current("execution_invalid_signed_restart_test", false, "broadcast")]
16478    #[case::historical("execution_invalid_historical_restart_test", true, "replaced")]
16479    #[tokio::test]
16480    async fn restart_rejects_invalid_signed_bytes_before_recovery_effects(
16481        #[case] test_name: &str,
16482        #[case] historical: bool,
16483        #[case] expected_status: &str,
16484    ) {
16485        let Some((admin_pool, schema, first_client, state, _)) =
16486            swap_client_with_database(test_name, ready_rpc_state()).await
16487        else {
16488            return;
16489        };
16490        let database = first_client.cache.database.as_ref().unwrap().clone();
16491        let (intent, _) =
16492            persist_invalid_test_swap(&database, first_client.payload_keys.as_deref()).await;
16493
16494        if historical {
16495            sqlx::query(sqlx::AssertSqlSafe(format!(
16496                "UPDATE {schema}.execution_transaction_hash \
16497                 SET current = FALSE, status = 'replaced' WHERE intent_id = $1"
16498            )))
16499            .bind(intent.id)
16500            .execute(&admin_pool)
16501            .await
16502            .unwrap();
16503            sqlx::query(sqlx::AssertSqlSafe(format!(
16504                "INSERT INTO {schema}.execution_transaction_hash (\
16505                     intent_id, chain_id, transaction_hash, payload_expected, status, current\
16506                 ) VALUES ($1, 42161, $2, FALSE, 'replaced', TRUE)"
16507            )))
16508            .bind(intent.id)
16509            .bind(B256::from([0x44; 32]).to_string())
16510            .execute(&admin_pool)
16511            .await
16512            .unwrap();
16513            sqlx::query(sqlx::AssertSqlSafe(format!(
16514                "UPDATE {schema}.execution_intent SET status = 'replaced' WHERE id = $1"
16515            )))
16516            .bind(intent.id)
16517            .execute(&admin_pool)
16518            .await
16519            .unwrap();
16520        }
16521        let transitions_before: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16522            "SELECT COUNT(*) FROM {schema}.execution_transaction_transition"
16523        )))
16524        .fetch_one(&admin_pool)
16525        .await
16526        .unwrap();
16527        let config = first_client.config.clone();
16528        let payload_keys = first_client.payload_keys.clone();
16529        drop(first_client);
16530
16531        let (mut restarted, _) = swap_client_with_cache(config);
16532        restarted.cache.database = Some(database);
16533        restarted.payload_keys = payload_keys;
16534        restarted.signer = Some(Arc::new(
16535            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16536        ));
16537        let mut receiver = start_with_events(&mut restarted);
16538
16539        let error = restarted
16540            .reconcile_unresolved_execution()
16541            .await
16542            .unwrap_err();
16543
16544        let recovery = recovering_in_flight(&restarted);
16545        let (status, acknowledgement_emitted, active): (String, bool, bool) =
16546            sqlx::query_as(sqlx::AssertSqlSafe(format!(
16547                "SELECT status, acknowledgement_emitted, active FROM {schema}.execution_intent"
16548            )))
16549            .fetch_one(&admin_pool)
16550            .await
16551            .unwrap();
16552        let transitions_after: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16553            "SELECT COUNT(*) FROM {schema}.execution_transaction_transition"
16554        )))
16555        .fetch_one(&admin_pool)
16556        .await
16557        .unwrap();
16558
16559        assert!(
16560            error
16561                .to_string()
16562                .contains("is not a complete EIP-2718 envelope"),
16563            "was: {error}"
16564        );
16565        assert_eq!(recovery.intent_id, intent.id);
16566        assert_eq!(recovery.nonce, 7);
16567        assert_eq!(recovery.purpose, TransactionPurpose::Swap);
16568        assert_eq!(status, expected_status);
16569        assert!(!acknowledgement_emitted);
16570        assert!(active);
16571        assert_eq!(transitions_after, transitions_before);
16572        assert!(collect_order_events(&mut receiver).is_empty());
16573        assert!(
16574            state
16575                .recorded_requests()
16576                .iter()
16577                .all(|request| request["method"] != "eth_sendRawTransaction")
16578        );
16579
16580        drop_execution_schema(&admin_pool, &schema).await;
16581    }
16582
16583    #[tokio::test]
16584    async fn restart_rebroadcasts_only_durably_authorized_bytes() {
16585        let Some((admin_pool, schema, first_client, _)) =
16586            execution_client_with_database("execution_broadcast_restart_test", ready_rpc_state())
16587                .await
16588        else {
16589            return;
16590        };
16591        let database = first_client.cache.database.as_ref().unwrap().clone();
16592        let (_, _, raw_tx) =
16593            persist_test_wrap_broadcast(&database, first_client.payload_keys.as_deref()).await;
16594        let payload_keys = first_client.payload_keys.clone();
16595        drop(first_client);
16596
16597        let restart_state = execution_rpc_state()
16598            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
16599            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16600            .with_response("eth_call", CALL_EMPTY)
16601            .with_send_raw_transaction_echo();
16602        let addr = start_mock_rpc_server(restart_state.clone()).await;
16603        let mut restarted = test_client(format!("http://{addr}"));
16604        restarted.cache.database = Some(database);
16605        restarted.payload_keys = payload_keys;
16606        restarted.signer = Some(Arc::new(
16607            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16608        ));
16609
16610        restarted.reconcile_unresolved_execution().await.unwrap();
16611
16612        let broadcasts = restart_state
16613            .recorded_requests()
16614            .into_iter()
16615            .filter(|request| request["method"] == "eth_sendRawTransaction")
16616            .collect::<Vec<_>>();
16617        assert_eq!(broadcasts.len(), 1);
16618        assert_eq!(broadcasts[0]["params"][0], hex::encode_prefixed(&raw_tx));
16619        assert_eq!(
16620            execution_intent_markers(&admin_pool, &schema).await,
16621            vec![("wrap".into(), "dropped".into(), false, true)]
16622        );
16623
16624        drop_execution_schema(&admin_pool, &schema).await;
16625    }
16626
16627    #[tokio::test]
16628    async fn restart_suppresses_rebroadcast_when_canonical_nonce_advanced() {
16629        let Some((admin_pool, schema, first_client, _)) = execution_client_with_database(
16630            "execution_rebroadcast_nonce_advanced_test",
16631            ready_rpc_state(),
16632        )
16633        .await
16634        else {
16635            return;
16636        };
16637        let database = first_client.cache.database.as_ref().unwrap().clone();
16638        let (intent, _, _) =
16639            persist_test_wrap_broadcast(&database, first_client.payload_keys.as_deref()).await;
16640        let payload_keys = first_client.payload_keys.clone();
16641        drop(first_client);
16642
16643        let mut empty_block: serde_json::Value =
16644            serde_json::from_str(&replacement_head_block(B256::from([0x44; 32]))).unwrap();
16645        empty_block["result"]["transactions"] = serde_json::json!([]);
16646        let empty_block = empty_block.to_string();
16647        let restart_state = execution_rpc_state()
16648            .with_response("eth_getTransactionCount", TRANSACTION_COUNT_NEXT)
16649            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16650            .with_response("eth_call", CALL_EMPTY)
16651            .with_parameter_response("eth_getBlockByNumber", "0x1cf0d40", &empty_block)
16652            .with_send_raw_transaction_echo();
16653        let addr = start_mock_rpc_server(restart_state.clone()).await;
16654        let mut restarted = test_client(format!("http://{addr}"));
16655        restarted.cache.database = Some(database);
16656        restarted.payload_keys = payload_keys;
16657        restarted.signer = Some(Arc::new(
16658            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16659        ));
16660
16661        let error = restarted
16662            .reconcile_unresolved_execution()
16663            .await
16664            .unwrap_err();
16665
16666        let requests = restart_state.recorded_requests();
16667        assert!(
16668            requests
16669                .iter()
16670                .all(|request| request["method"] != "eth_sendRawTransaction")
16671        );
16672        assert!(requests.iter().all(|request| {
16673            request["method"] != "eth_call" || request["params"][0]["data"] != "0xd0e30db0"
16674        }));
16675        let decision_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16676            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
16677             WHERE intent_id = $1 AND decision_class = 'rebroadcast'"
16678        )))
16679        .bind(intent.id)
16680        .fetch_one(&admin_pool)
16681        .await
16682        .unwrap();
16683        assert!(
16684            error
16685                .to_string()
16686                .contains("without an authenticated signer transaction"),
16687            "was: {error}"
16688        );
16689        assert_eq!(decision_count, 6);
16690        let replacement_decision_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16691            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
16692                 WHERE intent_id = $1 AND decision_class = 'replacement_scan'"
16693        )))
16694        .bind(intent.id)
16695        .fetch_one(&admin_pool)
16696        .await
16697        .unwrap();
16698        assert_eq!(replacement_decision_count, 2);
16699        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
16700            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
16701        )))
16702        .fetch_one(&admin_pool)
16703        .await
16704        .unwrap();
16705        assert_eq!(nonce_state, (7, 0));
16706
16707        drop_execution_schema(&admin_pool, &schema).await;
16708    }
16709
16710    #[tokio::test]
16711    async fn restart_suppresses_rebroadcast_when_receipt_exists() {
16712        let Some((admin_pool, schema, first_client, _)) = execution_client_with_database(
16713            "execution_rebroadcast_receipt_present_test",
16714            ready_rpc_state(),
16715        )
16716        .await
16717        else {
16718            return;
16719        };
16720        let database = first_client.cache.database.as_ref().unwrap().clone();
16721        let (intent, _, _) =
16722            persist_test_wrap_broadcast(&database, first_client.payload_keys.as_deref()).await;
16723        let payload_keys = first_client.payload_keys.clone();
16724        drop(first_client);
16725
16726        let restart_state = execution_rpc_state()
16727            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
16728            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS)
16729            .with_response("eth_call", CALL_EMPTY)
16730            .with_send_raw_transaction_echo();
16731        let addr = start_mock_rpc_server(restart_state.clone()).await;
16732        let mut restarted = test_client(format!("http://{addr}"));
16733        restarted.cache.database = Some(database);
16734        restarted.payload_keys = payload_keys;
16735        restarted.signer = Some(Arc::new(
16736            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16737        ));
16738
16739        let error = restarted
16740            .reconcile_unresolved_execution()
16741            .await
16742            .unwrap_err();
16743
16744        assert!(
16745            error
16746                .to_string()
16747                .contains("finalized transaction verification is locally invalid"),
16748            "was: {error}"
16749        );
16750        let requests = restart_state.recorded_requests();
16751        assert!(
16752            requests
16753                .iter()
16754                .all(|request| request["method"] != "eth_sendRawTransaction")
16755        );
16756        assert!(requests.iter().all(|request| {
16757            request["method"] != "eth_call" || request["params"][0]["data"] != "0xd0e30db0"
16758        }));
16759        let decision_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16760            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
16761             WHERE intent_id = $1 AND decision_class = 'rebroadcast'"
16762        )))
16763        .bind(intent.id)
16764        .fetch_one(&admin_pool)
16765        .await
16766        .unwrap();
16767        assert_eq!(decision_count, 6);
16768
16769        drop_execution_schema(&admin_pool, &schema).await;
16770    }
16771
16772    #[rstest]
16773    #[case("execution_rebroadcast_false_test", CALL_ZERO)]
16774    #[case("execution_rebroadcast_revert_test", CALL_REVERTED)]
16775    #[tokio::test]
16776    async fn restart_suppresses_rebroadcast_when_simulation_denies(
16777        #[case] test_name: &str,
16778        #[case] simulation_response: &str,
16779    ) {
16780        let Some((admin_pool, schema, first_client, _)) =
16781            execution_client_with_database(test_name, ready_rpc_state()).await
16782        else {
16783            return;
16784        };
16785        let database = first_client.cache.database.as_ref().unwrap().clone();
16786        let (intent, _, _) =
16787            persist_test_wrap_broadcast(&database, first_client.payload_keys.as_deref()).await;
16788        let payload_keys = first_client.payload_keys.clone();
16789        drop(first_client);
16790
16791        let restart_state = execution_rpc_state()
16792            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
16793            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16794            .with_response("eth_call", simulation_response)
16795            .with_send_raw_transaction_echo();
16796        let addr = start_mock_rpc_server(restart_state.clone()).await;
16797        let mut restarted = test_client(format!("http://{addr}"));
16798        restarted.cache.database = Some(database);
16799        restarted.payload_keys = payload_keys;
16800        restarted.signer = Some(Arc::new(
16801            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16802        ));
16803
16804        restarted.reconcile_unresolved_execution().await.unwrap();
16805
16806        let requests = restart_state.recorded_requests();
16807        assert!(
16808            requests
16809                .iter()
16810                .all(|request| request["method"] != "eth_sendRawTransaction")
16811        );
16812        let simulation_calls = requests
16813            .iter()
16814            .filter(|request| {
16815                request["method"] == "eth_call"
16816                    && request["params"][0]["data"] == "0xd0e30db0"
16817                    && request["params"][1] == FIXTURE_BLOCK_PARAM
16818            })
16819            .count();
16820        assert_eq!(simulation_calls, 3);
16821        let decision_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16822            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
16823             WHERE intent_id = $1 AND decision_class = 'rebroadcast'"
16824        )))
16825        .bind(intent.id)
16826        .fetch_one(&admin_pool)
16827        .await
16828        .unwrap();
16829        assert_eq!(decision_count, 7);
16830
16831        drop_execution_schema(&admin_pool, &schema).await;
16832    }
16833
16834    #[tokio::test]
16835    async fn restart_wrap_identity_mismatch_keeps_signer_ownership() {
16836        let initial_state = broadcast_rpc_state()
16837            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16838            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
16839        let Some((admin_pool, schema, mut first_client, _)) =
16840            execution_client_with_database("execution_restart_mismatch_test", initial_state).await
16841        else {
16842            return;
16843        };
16844        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
16845        let error = first_client
16846            .wrap(U256::from(1_000_000_000_000_000_u64))
16847            .await
16848            .unwrap_err();
16849        assert!(
16850            error.to_string().contains("Timed out awaiting finality"),
16851            "was: {error}"
16852        );
16853        let database = first_client.cache.database.as_ref().unwrap().clone();
16854        let payload_keys = first_client.payload_keys.clone();
16855        drop(first_client);
16856
16857        // The finalized transaction carries no value, so it cannot be the persisted wrap
16858        let mismatched_block = serde_json::json!({
16859            "jsonrpc": "2.0",
16860            "id": 1,
16861            "result": {
16862                "number": "0x1cf0d41",
16863                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
16864                "parentHash": FIXTURE_BLOCK_HASH,
16865                "timestamp": "0x69044a21",
16866                "baseFeePerGas": "0x5f5e100",
16867                "transactions": [{
16868                    "hash": expected_hash.to_string(),
16869                    "from": WALLET,
16870                    "nonce": "0x7",
16871                    "chainId": "0xa4b1",
16872                    "type": "0x2",
16873                    "to": WETH,
16874                    "input": "0xd0e30db0",
16875                    "value": "0x0",
16876                    "gas": "0x130b0",
16877                    "maxFeePerGas": "0x7bfa480",
16878                    "maxPriorityFeePerGas": "0x989680"
16879                }]
16880            }
16881        })
16882        .to_string();
16883        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
16884        let restart_state = with_finalized_identity(
16885            execution_rpc_state()
16886                .with_response("eth_getTransactionReceipt", &receipt)
16887                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &mismatched_block),
16888            &mismatched_block,
16889            &receipt,
16890        );
16891        let addr = start_mock_rpc_server(restart_state.clone()).await;
16892        let mut restarted = test_client(format!("http://{addr}"));
16893        restarted.cache.database = Some(database);
16894        restarted.payload_keys = payload_keys;
16895        restarted.signer = Some(Arc::new(
16896            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16897        ));
16898
16899        let error = restarted
16900            .reconcile_unresolved_execution()
16901            .await
16902            .unwrap_err();
16903
16904        assert!(
16905            error
16906                .to_string()
16907                .contains("finalized transaction identity mismatch"),
16908            "was: {error}"
16909        );
16910        let in_flight = awaiting_in_flight(&restarted);
16911        assert_eq!(in_flight.nonce, 7);
16912        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
16913        assert_eq!(in_flight.tx_hash, expected_hash);
16914        let requests = restart_state.recorded_requests();
16915        assert!(
16916            requests.iter().all(|request| {
16917                request["method"] != "eth_call"
16918                    || !request["params"][0]["data"]
16919                        .as_str()
16920                        .is_some_and(|data| data.starts_with(BALANCE_OF_SELECTOR))
16921            }),
16922            "the postcondition must not run when call identity is unproven"
16923        );
16924        assert!(
16925            requests
16926                .iter()
16927                .all(|request| request["method"] != "eth_sendRawTransaction")
16928        );
16929        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
16930            "SELECT status, active FROM {schema}.execution_intent"
16931        )))
16932        .fetch_one(&admin_pool)
16933        .await
16934        .unwrap();
16935        assert_eq!(status, "dropped");
16936        assert!(active);
16937
16938        let database = restarted.cache.database.as_ref().unwrap().clone();
16939        let payload_keys = restarted.payload_keys.clone();
16940        drop(restarted);
16941        let mut second = test_client(format!("http://{addr}"));
16942        second.cache.database = Some(database);
16943        second.payload_keys = payload_keys;
16944        second.signer = Some(Arc::new(
16945            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16946        ));
16947        let error = second.reconcile_unresolved_execution().await.unwrap_err();
16948        assert!(
16949            error
16950                .to_string()
16951                .contains("finalized transaction identity mismatch"),
16952            "was: {error}"
16953        );
16954        let active: bool = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16955            "SELECT active FROM {schema}.execution_intent"
16956        )))
16957        .fetch_one(&admin_pool)
16958        .await
16959        .unwrap();
16960        assert!(active);
16961
16962        drop_execution_schema(&admin_pool, &schema).await;
16963    }
16964
16965    #[tokio::test]
16966    async fn restart_wrap_postcondition_failure_keeps_signer_ownership() {
16967        let initial_state = broadcast_rpc_state()
16968            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16969            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
16970        let Some((admin_pool, schema, mut first_client, _)) =
16971            execution_client_with_database("execution_restart_postcondition_test", initial_state)
16972                .await
16973        else {
16974            return;
16975        };
16976        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
16977        let error = first_client
16978            .wrap(U256::from(1_000_000_000_000_000_u64))
16979            .await
16980            .unwrap_err();
16981        assert!(
16982            error.to_string().contains("Timed out awaiting finality"),
16983            "was: {error}"
16984        );
16985        let database = first_client.cache.database.as_ref().unwrap().clone();
16986        let payload_keys = first_client.payload_keys.clone();
16987        drop(first_client);
16988
16989        // Call identity matches, but the wrapped balance does not increase
16990        let failing_wrap_state = || {
16991            let block = finalized_wrap_block(expected_hash);
16992            let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
16993            with_finalized_identity(
16994                execution_rpc_state()
16995                    .with_response("eth_getTransactionReceipt", &receipt)
16996                    .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
16997                    .with_response_sequence("eth_call", &[CALL_BALANCE; 6]),
16998                &block,
16999                &receipt,
17000            )
17001        };
17002        let restart_state = failing_wrap_state();
17003        let addr = start_mock_rpc_server(restart_state.clone()).await;
17004        let mut restarted = test_client(format!("http://{addr}"));
17005        restarted.cache.database = Some(database);
17006        restarted.payload_keys = payload_keys;
17007        restarted.signer = Some(Arc::new(
17008            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17009        ));
17010
17011        let error = restarted
17012            .reconcile_unresolved_execution()
17013            .await
17014            .unwrap_err();
17015
17016        assert!(
17017            error.to_string().contains("did not increase by"),
17018            "was: {error}"
17019        );
17020        let in_flight = awaiting_in_flight(&restarted);
17021        assert_eq!(in_flight.nonce, 7);
17022        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
17023        assert!(
17024            restart_state
17025                .recorded_requests()
17026                .iter()
17027                .all(|request| request["method"] != "eth_sendRawTransaction")
17028        );
17029        assert_eq!(
17030            execution_intent_markers(&admin_pool, &schema).await,
17031            vec![("wrap".into(), "dropped".into(), false, true)]
17032        );
17033
17034        let addr = start_mock_rpc_server(failing_wrap_state()).await;
17035        let error = later_reconnect(restarted, format!("http://{addr}")).await;
17036        assert!(
17037            error.to_string().contains("did not increase by"),
17038            "was: {error}"
17039        );
17040        assert_eq!(
17041            execution_intent_markers(&admin_pool, &schema).await,
17042            vec![("wrap".into(), "dropped".into(), false, true)]
17043        );
17044
17045        drop_execution_schema(&admin_pool, &schema).await;
17046    }
17047
17048    #[tokio::test]
17049    async fn restart_wrap_revert_marks_terminal_and_releases() {
17050        let initial_state = broadcast_rpc_state()
17051            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
17052            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
17053        let Some((admin_pool, schema, mut first_client, _)) =
17054            execution_client_with_database("execution_restart_wrap_revert_test", initial_state)
17055                .await
17056        else {
17057            return;
17058        };
17059        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
17060        let error = first_client
17061            .wrap(U256::from(1_000_000_000_000_000_u64))
17062            .await
17063            .unwrap_err();
17064        assert!(
17065            error.to_string().contains("Timed out awaiting finality"),
17066            "was: {error}"
17067        );
17068        let database = first_client.cache.database.as_ref().unwrap().clone();
17069        let payload_keys = first_client.payload_keys.clone();
17070        drop(first_client);
17071
17072        let block = finalized_wrap_block(expected_hash);
17073        let receipt = receipt_with_transaction_hash(RECEIPT_REVERTED, expected_hash);
17074        let restart_state = with_finalized_identity(
17075            execution_rpc_state()
17076                .with_response("eth_getTransactionReceipt", &receipt)
17077                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block),
17078            &block,
17079            &receipt,
17080        );
17081        let addr = start_mock_rpc_server(restart_state.clone()).await;
17082        let mut restarted = test_client(format!("http://{addr}"));
17083        restarted.cache.database = Some(database);
17084        restarted.payload_keys = payload_keys;
17085        restarted.signer = Some(Arc::new(
17086            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17087        ));
17088
17089        restarted.reconcile_unresolved_execution().await.unwrap();
17090
17091        assert!(restarted.in_flight.lock().is_none());
17092        assert!(
17093            restart_state
17094                .recorded_requests()
17095                .iter()
17096                .all(|request| request["method"] != "eth_sendRawTransaction")
17097        );
17098        assert_eq!(
17099            execution_intent_markers(&admin_pool, &schema).await,
17100            vec![("wrap".into(), "reverted".into(), true, false)]
17101        );
17102
17103        drop_execution_schema(&admin_pool, &schema).await;
17104    }
17105
17106    #[tokio::test]
17107    async fn restart_quarantines_unretained_same_nonce_wrap_replacement() {
17108        let initial_state = broadcast_rpc_state()
17109            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
17110            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
17111        let Some((admin_pool, schema, mut first_client, _)) =
17112            execution_client_with_database("execution_restart_replacement_test", initial_state)
17113                .await
17114        else {
17115            return;
17116        };
17117        let original_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
17118        let error = first_client
17119            .wrap(U256::from(1_000_000_000_000_000_u64))
17120            .await
17121            .unwrap_err();
17122        assert!(
17123            error.to_string().contains("Timed out awaiting finality"),
17124            "was: {error}"
17125        );
17126        let database = first_client.cache.database.as_ref().unwrap().clone();
17127        let payload_keys = first_client.payload_keys.clone();
17128        drop(first_client);
17129
17130        // Matching call fields do not authenticate an unknown same-nonce payload.
17131        let replacement_hash = B256::from([0x44; 32]);
17132        let restart_state = execution_rpc_state()
17133            .with_response("eth_getTransactionCount", TRANSACTION_COUNT_NEXT)
17134            .with_response_sequence("eth_call", &[CALL_BALANCE, CALL_BALANCE_AFTER_WRAP])
17135            .with_response_sequence(
17136                "eth_getTransactionReceipt",
17137                &[RECEIPT_NULL, RECEIPT_NULL, RECEIPT_NULL],
17138            )
17139            .with_parameter_response(
17140                "eth_getBlockByNumber",
17141                "0x1cf0d40",
17142                &replacement_head_block(replacement_hash),
17143            )
17144            .with_parameter_response(
17145                "eth_getBlockByNumber",
17146                "0x1cf0d41",
17147                &finalized_wrap_block(replacement_hash),
17148            );
17149        let addr = start_mock_rpc_server(restart_state.clone()).await;
17150        let mut restarted = test_client(format!("http://{addr}"));
17151        restarted.cache.database = Some(database);
17152        restarted.payload_keys = payload_keys;
17153        restarted.signer = Some(Arc::new(
17154            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17155        ));
17156        restarted.transaction_limits.receipt_timeout_secs = 2;
17157
17158        let error = restarted
17159            .reconcile_unresolved_execution()
17160            .await
17161            .unwrap_err();
17162
17163        let hashes: Vec<(String, String, bool)> = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17164            "SELECT transaction_hash, status, current FROM \
17165                 {schema}.execution_transaction_hash ORDER BY id"
17166        )))
17167        .fetch_all(&admin_pool)
17168        .await
17169        .unwrap();
17170        let requests = restart_state.recorded_requests();
17171
17172        assert!(
17173            error
17174                .to_string()
17175                .contains("has no authenticated retained payload"),
17176            "was: {error}"
17177        );
17178        assert_eq!(
17179            hashes,
17180            [(original_hash.to_string(), "dropped".to_string(), true)]
17181        );
17182        assert!(restarted.in_flight.lock().is_some());
17183        assert_eq!(
17184            execution_intent_markers(&admin_pool, &schema).await,
17185            vec![("wrap".into(), "dropped".into(), false, true)]
17186        );
17187        assert_eq!(
17188            requests
17189                .iter()
17190                .filter(|request| request["method"] == "eth_getTransactionReceipt")
17191                .count(),
17192            3
17193        );
17194        assert!(requests.iter().all(|request| {
17195            request["method"] != "eth_call" || request["params"][0]["data"] != "0xd0e30db0"
17196        }));
17197        assert!(
17198            requests
17199                .iter()
17200                .all(|request| request["method"] != "eth_sendRawTransaction")
17201        );
17202
17203        drop_execution_schema(&admin_pool, &schema).await;
17204    }
17205
17206    #[tokio::test]
17207    async fn replacement_scan_accepts_only_an_authenticated_retained_payload() {
17208        let expected_hash = expected_wrap_tx_hash(U256::from(1_u64)).await;
17209        let mut replacement_block: serde_json::Value =
17210            serde_json::from_str(&replacement_head_block(expected_hash)).unwrap();
17211        replacement_block["result"]["transactions"][1]["value"] = serde_json::json!("0x1");
17212        let replacement_block = replacement_block.to_string();
17213        let state = execution_rpc_state().with_parameter_response(
17214            "eth_getBlockByNumber",
17215            "0x1cf0d40",
17216            &replacement_block,
17217        );
17218        let Some((admin_pool, schema, client, _)) =
17219            execution_client_with_database("replacement_scan_authenticated", state).await
17220        else {
17221            return;
17222        };
17223        let database = client.cache.database.as_ref().unwrap();
17224        let (intent, persisted_hash, persisted_raw) =
17225            persist_test_wrap_broadcast(database, client.payload_keys.as_deref()).await;
17226        assert_eq!(persisted_hash, expected_hash);
17227        let authenticated_payloads = HashMap::from([(expected_hash, persisted_raw.clone())]);
17228        let head = VerifiedBlockHeader {
17229            number: FIXTURE_BLOCK,
17230            hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
17231            parent_hash: B256::from_str(
17232                "0x0000000000000000000000000000000000000000000000000000000000000001",
17233            )
17234            .unwrap(),
17235            timestamp: FIXTURE_BLOCK_TIMESTAMP,
17236            base_fee_per_gas: Some(100_000_000),
17237        };
17238
17239        let matched = client
17240            .transaction_executor()
17241            .unwrap()
17242            .scan_canonical_replacement(&intent, 7, head, &authenticated_payloads)
17243            .await
17244            .unwrap()
17245            .unwrap();
17246
17247        assert_eq!(matched, (expected_hash, persisted_raw));
17248        let cursor: (i64, String) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17249            "SELECT finalized_cursor_number, finalized_cursor_hash \
17250             FROM {schema}.execution_replacement_scan WHERE intent_id = $1"
17251        )))
17252        .bind(intent.id)
17253        .fetch_one(&admin_pool)
17254        .await
17255        .unwrap();
17256        assert_eq!(
17257            cursor,
17258            (FIXTURE_BLOCK as i64, FIXTURE_BLOCK_HASH.to_string())
17259        );
17260        let evidence_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17261            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
17262             WHERE intent_id = $1 AND decision_class = 'replacement_scan'"
17263        )))
17264        .bind(intent.id)
17265        .fetch_one(&admin_pool)
17266        .await
17267        .unwrap();
17268        assert_eq!(evidence_count, 2);
17269
17270        drop_execution_schema(&admin_pool, &schema).await;
17271    }
17272
17273    #[tokio::test]
17274    async fn restart_reconciles_finalized_approve_after_validation() {
17275        let initial_state = broadcast_rpc_state()
17276            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
17277            .with_response("eth_call", CALL_BOOL_TRUE)
17278            .with_call_response_sequence(ALLOWANCE_SELECTOR, &[CALL_ZERO; 3])
17279            .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO);
17280        let Some((admin_pool, schema, mut first_client, _)) =
17281            execution_client_with_database("execution_restart_approve_test", initial_state).await
17282        else {
17283            return;
17284        };
17285        let expected_hash = expected_approve_tx_hash(U256::from(1_000u64)).await;
17286        let error = first_client
17287            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
17288            .await
17289            .unwrap_err();
17290        assert!(
17291            error.to_string().contains("Timed out awaiting finality"),
17292            "was: {error}"
17293        );
17294        let database = first_client.cache.database.as_ref().unwrap().clone();
17295        let payload_keys = first_client.payload_keys.clone();
17296        drop(first_client);
17297
17298        let block = finalized_approve_block(expected_hash, U256::from(1_000u64));
17299        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
17300        let restart_state = with_finalized_identity(
17301            execution_rpc_state()
17302                .with_response("eth_getTransactionReceipt", &receipt)
17303                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
17304                .with_call_response(ALLOWANCE_SELECTOR, CALL_ALLOWANCE_1000),
17305            &block,
17306            &receipt,
17307        );
17308        let addr = start_mock_rpc_server(restart_state.clone()).await;
17309        let mut restarted = test_client(format!("http://{addr}"));
17310        restarted.cache.database = Some(database);
17311        restarted.payload_keys = payload_keys;
17312        restarted.signer = Some(Arc::new(
17313            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17314        ));
17315
17316        restarted.reconcile_unresolved_execution().await.unwrap();
17317
17318        let record = restarted
17319            .cache
17320            .get_execution_transaction(42161, &expected_hash.to_string())
17321            .await
17322            .unwrap()
17323            .unwrap();
17324        let requests = restart_state.recorded_requests();
17325        assert_eq!(record.status, "finalized");
17326        assert_eq!(record.purpose, "approve");
17327        assert!(restarted.in_flight.lock().is_none());
17328        assert_eq!(
17329            execution_intent_markers(&admin_pool, &schema).await,
17330            vec![("approve".into(), "finalized".into(), true, false)]
17331        );
17332        assert_eq!(
17333            requests
17334                .iter()
17335                .filter(|request| {
17336                    request["method"] == "eth_call"
17337                        && request["params"][0]["data"]
17338                            .as_str()
17339                            .is_some_and(|data| data.starts_with(ALLOWANCE_SELECTOR))
17340                })
17341                .count(),
17342            3
17343        );
17344        assert_eq!(
17345            requests
17346                .iter()
17347                .filter(|request| request["method"] == "eth_sendRawTransaction")
17348                .count(),
17349            0
17350        );
17351
17352        drop_execution_schema(&admin_pool, &schema).await;
17353    }
17354
17355    #[tokio::test]
17356    async fn restart_approve_postcondition_failure_keeps_signer_ownership() {
17357        let initial_state = broadcast_rpc_state()
17358            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
17359            .with_response("eth_call", CALL_BOOL_TRUE)
17360            .with_call_response_sequence(ALLOWANCE_SELECTOR, &[CALL_ZERO; 3])
17361            .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO);
17362        let Some((admin_pool, schema, mut first_client, _)) =
17363            execution_client_with_database("execution_restart_approve_post_test", initial_state)
17364                .await
17365        else {
17366            return;
17367        };
17368        let expected_hash = expected_approve_tx_hash(U256::from(1_000u64)).await;
17369        let error = first_client
17370            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
17371            .await
17372            .unwrap_err();
17373        assert!(
17374            error.to_string().contains("Timed out awaiting finality"),
17375            "was: {error}"
17376        );
17377        let database = first_client.cache.database.as_ref().unwrap().clone();
17378        let payload_keys = first_client.payload_keys.clone();
17379        drop(first_client);
17380
17381        // Call identity matches, but the allowance does not equal the approved amount
17382        let block = finalized_approve_block(expected_hash, U256::from(1_000u64));
17383        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
17384        let restart_state = with_finalized_identity(
17385            execution_rpc_state()
17386                .with_response("eth_getTransactionReceipt", &receipt)
17387                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
17388                .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO),
17389            &block,
17390            &receipt,
17391        );
17392        let addr = start_mock_rpc_server(restart_state.clone()).await;
17393        let mut restarted = test_client(format!("http://{addr}"));
17394        restarted.cache.database = Some(database);
17395        restarted.payload_keys = payload_keys;
17396        restarted.signer = Some(Arc::new(
17397            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17398        ));
17399
17400        let error = restarted
17401            .reconcile_unresolved_execution()
17402            .await
17403            .unwrap_err();
17404
17405        assert!(
17406            error
17407                .to_string()
17408                .contains("does not equal the requested amount"),
17409            "was: {error}"
17410        );
17411        let in_flight = awaiting_in_flight(&restarted);
17412        assert_eq!(in_flight.nonce, 7);
17413        assert_eq!(in_flight.purpose, TransactionPurpose::Approve);
17414        assert!(
17415            restart_state
17416                .recorded_requests()
17417                .iter()
17418                .all(|request| request["method"] != "eth_sendRawTransaction")
17419        );
17420        assert_eq!(
17421            execution_intent_markers(&admin_pool, &schema).await,
17422            vec![("approve".into(), "dropped".into(), false, true)]
17423        );
17424
17425        let error = later_reconnect(restarted, format!("http://{addr}")).await;
17426        assert!(
17427            error
17428                .to_string()
17429                .contains("does not equal the requested amount"),
17430            "was: {error}"
17431        );
17432        assert_eq!(
17433            execution_intent_markers(&admin_pool, &schema).await,
17434            vec![("approve".into(), "dropped".into(), false, true)]
17435        );
17436
17437        drop_execution_schema(&admin_pool, &schema).await;
17438    }
17439
17440    #[tokio::test]
17441    async fn disappearing_unfinalized_receipt_drops_without_committing_inclusion() {
17442        let state = execution_rpc_state()
17443            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
17444            .with_response("eth_estimateGas", ESTIMATE_GAS)
17445            .with_response("eth_call", CALL_BALANCE)
17446            .with_response_sequence(
17447                "eth_getTransactionReceipt",
17448                &[
17449                    RECEIPT_SUCCESS,
17450                    RECEIPT_SUCCESS,
17451                    RECEIPT_SUCCESS,
17452                    RECEIPT_NULL,
17453                    RECEIPT_NULL,
17454                    RECEIPT_NULL,
17455                ],
17456            )
17457            .with_parameter_response("eth_getBlockByNumber", "finalized", BLOCK_BY_NUMBER)
17458            .with_send_raw_transaction_echo();
17459        let Some((admin_pool, schema, mut client, _)) =
17460            execution_client_with_database("execution_receipt_disappeared_test", state).await
17461        else {
17462            return;
17463        };
17464        client.transaction_limits.receipt_timeout_secs = 2;
17465
17466        let error = client
17467            .wrap(U256::from(1_000_000_000_000_000_u64))
17468            .await
17469            .unwrap_err();
17470        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17471            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
17472        )))
17473        .fetch_all(&admin_pool)
17474        .await
17475        .unwrap();
17476
17477        assert!(
17478            error.to_string().contains("Timed out awaiting finality"),
17479            "was: {error}"
17480        );
17481        assert_eq!(transitions, ["prepared", "signed", "broadcast", "dropped"]);
17482        assert!(client.in_flight.lock().is_some());
17483
17484        drop_execution_schema(&admin_pool, &schema).await;
17485    }
17486
17487    #[tokio::test]
17488    async fn changed_unfinalized_block_drops_without_committing_inclusion() {
17489        let changed_block = serde_json::json!({
17490            "jsonrpc": "2.0",
17491            "id": 1,
17492            "result": {
17493                "number": "0x1cf0d41",
17494                "hash": "0x4444444444444444444444444444444444444444444444444444444444444444",
17495                "parentHash": FIXTURE_BLOCK_HASH,
17496                "timestamp": "0x69044a21",
17497                "baseFeePerGas": "0x5f5e100",
17498                "transactions": []
17499            }
17500        })
17501        .to_string();
17502        let state = execution_rpc_state()
17503            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
17504            .with_response("eth_estimateGas", ESTIMATE_GAS)
17505            .with_response("eth_call", CALL_BALANCE)
17506            .with_response_sequence(
17507                "eth_getTransactionReceipt",
17508                &[
17509                    RECEIPT_SUCCESS,
17510                    RECEIPT_SUCCESS,
17511                    RECEIPT_SUCCESS,
17512                    RECEIPT_SUCCESS,
17513                    RECEIPT_SUCCESS,
17514                    RECEIPT_SUCCESS,
17515                ],
17516            )
17517            .with_parameter_response_sequence(
17518                "eth_getBlockByNumber",
17519                "0x1cf0d41",
17520                &[
17521                    BLOCK_CANONICAL,
17522                    BLOCK_CANONICAL,
17523                    BLOCK_CANONICAL,
17524                    &changed_block,
17525                    &changed_block,
17526                    &changed_block,
17527                ],
17528            )
17529            .with_parameter_response("eth_getBlockByNumber", "finalized", BLOCK_BY_NUMBER)
17530            .with_send_raw_transaction_echo();
17531        let Some((admin_pool, schema, mut client, _)) =
17532            execution_client_with_database("execution_reorg_test", state).await
17533        else {
17534            return;
17535        };
17536        client.transaction_limits.receipt_timeout_secs = 2;
17537
17538        let error = client
17539            .wrap(U256::from(1_000_000_000_000_000_u64))
17540            .await
17541            .unwrap_err();
17542        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17543            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
17544        )))
17545        .fetch_all(&admin_pool)
17546        .await
17547        .unwrap();
17548
17549        assert!(
17550            error.to_string().contains("Timed out awaiting finality"),
17551            "was: {error}"
17552        );
17553        assert_eq!(transitions, ["prepared", "signed", "broadcast", "dropped"]);
17554        assert!(client.in_flight.lock().is_some());
17555
17556        drop_execution_schema(&admin_pool, &schema).await;
17557    }
17558
17559    #[tokio::test]
17560    async fn pre_sign_pending_nonce_drift_blocks_wrap_before_signature() {
17561        let state = execution_rpc_state()
17562            .with_response_sequence(
17563                "eth_getTransactionCount",
17564                &[
17565                    TRANSACTION_COUNT,
17566                    TRANSACTION_COUNT,
17567                    TRANSACTION_COUNT,
17568                    TRANSACTION_COUNT_NEXT,
17569                    TRANSACTION_COUNT_NEXT,
17570                    TRANSACTION_COUNT_NEXT,
17571                ],
17572            )
17573            .with_response("eth_estimateGas", ESTIMATE_GAS)
17574            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE)
17575            .with_send_raw_transaction_echo();
17576        let Some((admin_pool, schema, mut client, state)) =
17577            execution_client_with_database("pre_sign_pending_nonce_drift", state).await
17578        else {
17579            return;
17580        };
17581
17582        let error = client
17583            .wrap(U256::from(1_000_000_000_000_000_u64))
17584            .await
17585            .unwrap_err();
17586        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17587            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
17588        )))
17589        .fetch_one(&admin_pool)
17590        .await
17591        .unwrap();
17592
17593        assert!(
17594            error
17595                .to_string()
17596                .contains("Pending nonce does not match the verified canonical nonce"),
17597            "was: {error}"
17598        );
17599        assert_eq!(signed_count, 0);
17600        assert!(
17601            state
17602                .recorded_requests()
17603                .iter()
17604                .all(|request| request["method"] != "eth_sendRawTransaction")
17605        );
17606        assert!(client.in_flight.lock().is_none());
17607
17608        drop_execution_schema(&admin_pool, &schema).await;
17609    }
17610
17611    #[tokio::test]
17612    async fn unknown_same_nonce_swap_replacement_emits_no_rejection() {
17613        let replacement_hash = B256::from([0x44; 32]);
17614        let replacement_block = replacement_head_block(replacement_hash);
17615        let state = execution_rpc_state()
17616            .with_parameter_response("eth_getBlockByNumber", "0x1cf0d40", &replacement_block)
17617            .with_send_raw_transaction_echo();
17618        let Some((admin_pool, schema, mut client, _, _)) =
17619            swap_client_with_database("unknown_same_nonce_swap_replacement", state).await
17620        else {
17621            return;
17622        };
17623        let mut receiver = start_with_events(&mut client);
17624        let database = client.cache.database.as_ref().unwrap();
17625        let (intent, original_hash, original_payload) =
17626            persist_test_swap_broadcast(database, client.payload_keys.as_deref()).await;
17627        let authenticated_payloads = HashMap::from([(original_hash, original_payload)]);
17628        let head = VerifiedBlockHeader {
17629            number: FIXTURE_BLOCK,
17630            hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
17631            parent_hash: B256::from_str(
17632                "0x0000000000000000000000000000000000000000000000000000000000000001",
17633            )
17634            .unwrap(),
17635            timestamp: FIXTURE_BLOCK_TIMESTAMP,
17636            base_fee_per_gas: Some(100_000_000),
17637        };
17638
17639        let error = client
17640            .transaction_executor()
17641            .unwrap()
17642            .scan_canonical_replacement(&intent, 7, head, &authenticated_payloads)
17643            .await
17644            .unwrap_err();
17645        let events = collect_order_events(&mut receiver);
17646        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17647            "SELECT status, active FROM {schema}.execution_intent"
17648        )))
17649        .fetch_one(&admin_pool)
17650        .await
17651        .unwrap();
17652
17653        assert!(
17654            error
17655                .to_string()
17656                .contains("has no authenticated retained payload"),
17657            "was: {error}"
17658        );
17659        assert!(events.is_empty(), "was: {events:?}");
17660        assert_eq!(status, "broadcast");
17661        assert!(active);
17662
17663        drop_execution_schema(&admin_pool, &schema).await;
17664    }
17665
17666    #[tokio::test]
17667    async fn replacement_scan_rejects_rpc_fields_that_conflict_with_the_payload() {
17668        let expected_hash = expected_wrap_tx_hash(U256::from(1_u64)).await;
17669        let mut replacement_block: serde_json::Value =
17670            serde_json::from_str(&replacement_head_block(expected_hash)).unwrap();
17671        replacement_block["result"]["transactions"][1]["value"] = serde_json::json!("0x2");
17672        let replacement_block = replacement_block.to_string();
17673        let state = execution_rpc_state().with_parameter_response(
17674            "eth_getBlockByNumber",
17675            "0x1cf0d40",
17676            &replacement_block,
17677        );
17678        let Some((admin_pool, schema, client, _)) =
17679            execution_client_with_database("replacement_scan_payload_mismatch", state).await
17680        else {
17681            return;
17682        };
17683        let database = client.cache.database.as_ref().unwrap();
17684        let (intent, persisted_hash, persisted_payload) =
17685            persist_test_wrap_broadcast(database, client.payload_keys.as_deref()).await;
17686        assert_eq!(persisted_hash, expected_hash);
17687        let authenticated_payloads = HashMap::from([(persisted_hash, persisted_payload)]);
17688        let head = VerifiedBlockHeader {
17689            number: FIXTURE_BLOCK,
17690            hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
17691            parent_hash: B256::from_str(
17692                "0x0000000000000000000000000000000000000000000000000000000000000001",
17693            )
17694            .unwrap(),
17695            timestamp: FIXTURE_BLOCK_TIMESTAMP,
17696            base_fee_per_gas: Some(100_000_000),
17697        };
17698
17699        let error = client
17700            .transaction_executor()
17701            .unwrap()
17702            .scan_canonical_replacement(&intent, 7, head, &authenticated_payloads)
17703            .await
17704            .unwrap_err();
17705        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17706            "SELECT status, active FROM {schema}.execution_intent"
17707        )))
17708        .fetch_one(&admin_pool)
17709        .await
17710        .unwrap();
17711
17712        assert!(
17713            error
17714                .to_string()
17715                .contains("failed authenticated payload validation"),
17716            "was: {error}"
17717        );
17718        assert_eq!(status, "broadcast");
17719        assert!(active);
17720
17721        drop_execution_schema(&admin_pool, &schema).await;
17722    }
17723
17724    #[tokio::test]
17725    async fn execution_transaction_constraints_reject_conflicting_identity() {
17726        const TRANSACTION_HASH: &str = "0xduplicate-transaction-hash";
17727        const OTHER_WALLET: &str = "0x0000000000000000000000000000000000000001";
17728        let Some((admin_pool, schema, client, _)) = execution_client_with_unprotected_database(
17729            "execution_duplicate_record_test",
17730            ready_rpc_state(),
17731        )
17732        .await
17733        else {
17734            return;
17735        };
17736        let database = client.cache.database.as_ref().unwrap();
17737        let operator = database
17738            .reserve_execution_intent(&ExecutionIntentInsert {
17739                chain_id: 42161,
17740                wallet_address: WALLET.to_string(),
17741                purpose: "wrap".to_string(),
17742                client_order_id: None,
17743                trader_id: None,
17744                strategy_id: None,
17745                account_id: None,
17746                instrument_id: None,
17747                pool_address: None,
17748                transaction_to: WETH_ADDRESS.to_string(),
17749                transaction_input: "0xd0e30db0".to_string(),
17750                transaction_value: "1".to_string(),
17751                amount_in: None,
17752                created_block: FIXTURE_BLOCK,
17753            })
17754            .await
17755            .unwrap();
17756        database
17757            .assign_execution_intent_nonce(operator.id, 7)
17758            .await
17759            .unwrap();
17760        database
17761            .add_execution_transaction_hash(operator.id, 42161, TRANSACTION_HASH, &[1, 2, 3])
17762            .await
17763            .unwrap();
17764        database
17765            .add_execution_transaction_hash(operator.id, 42161, TRANSACTION_HASH, &[1, 2, 3])
17766            .await
17767            .unwrap();
17768
17769        let signer_conflict = database
17770            .reserve_execution_intent(&ExecutionIntentInsert {
17771                chain_id: 42161,
17772                wallet_address: WALLET.to_string(),
17773                purpose: "approve".to_string(),
17774                client_order_id: None,
17775                trader_id: None,
17776                strategy_id: None,
17777                account_id: None,
17778                instrument_id: None,
17779                pool_address: None,
17780                transaction_to: ROUTER_ADDRESS.to_string(),
17781                transaction_input: "0x01".to_string(),
17782                transaction_value: "0".to_string(),
17783                amount_in: None,
17784                created_block: FIXTURE_BLOCK,
17785            })
17786            .await
17787            .unwrap_err();
17788        let other = database
17789            .reserve_execution_intent(&ExecutionIntentInsert {
17790                chain_id: 42161,
17791                wallet_address: OTHER_WALLET.to_string(),
17792                purpose: "approve".to_string(),
17793                client_order_id: None,
17794                trader_id: None,
17795                strategy_id: None,
17796                account_id: None,
17797                instrument_id: None,
17798                pool_address: None,
17799                transaction_to: ROUTER_ADDRESS.to_string(),
17800                transaction_input: "0x01".to_string(),
17801                transaction_value: "0".to_string(),
17802                amount_in: None,
17803                created_block: FIXTURE_BLOCK,
17804            })
17805            .await
17806            .unwrap();
17807        database
17808            .assign_execution_intent_nonce(other.id, 7)
17809            .await
17810            .unwrap();
17811        let hash_conflict = database
17812            .add_execution_transaction_hash(other.id, 42161, TRANSACTION_HASH, &[4, 5, 6])
17813            .await
17814            .unwrap_err();
17815
17816        let record = database
17817            .get_execution_transaction(42161, TRANSACTION_HASH)
17818            .await
17819            .unwrap()
17820            .unwrap();
17821        let count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17822            "SELECT COUNT(*) FROM {schema}.execution_intent"
17823        )))
17824        .fetch_one(&admin_pool)
17825        .await
17826        .unwrap();
17827
17828        assert_eq!(record.wallet_address.as_deref(), Some(WALLET));
17829        assert_eq!(record.nonce, 7);
17830        assert_eq!(record.transaction_hash, TRANSACTION_HASH);
17831        assert_eq!(record.purpose, "wrap");
17832        assert_eq!(record.status, "signed");
17833        assert_eq!(record.client_order_id, None);
17834        assert!(
17835            hash_conflict
17836                .to_string()
17837                .contains("conflicts with its persisted identity"),
17838            "was: {hash_conflict}"
17839        );
17840        assert_eq!(
17841            signer_conflict.to_string(),
17842            "Execution intent reservation failed before commit"
17843        );
17844        assert!(
17845            signer_conflict.chain().any(|cause| cause
17846                .to_string()
17847                .contains("execution_intent_active_signer_key")),
17848            "was: {signer_conflict:#}"
17849        );
17850        assert_eq!(count, 2);
17851
17852        drop_execution_schema(&admin_pool, &schema).await;
17853    }
17854
17855    #[tokio::test]
17856    async fn execution_status_transitions_are_idempotent() {
17857        const TRANSACTION_HASH: &str =
17858            "0x5555555555555555555555555555555555555555555555555555555555555555";
17859        let Some((admin_pool, schema, client, _)) = execution_client_with_unprotected_database(
17860            "execution_transition_test",
17861            ready_rpc_state(),
17862        )
17863        .await
17864        else {
17865            return;
17866        };
17867        let database = client.cache.database.as_ref().unwrap();
17868        let intent = database
17869            .reserve_execution_intent(&ExecutionIntentInsert {
17870                chain_id: 42161,
17871                wallet_address: WALLET.to_string(),
17872                purpose: "wrap".to_string(),
17873                client_order_id: None,
17874                trader_id: None,
17875                strategy_id: None,
17876                account_id: None,
17877                instrument_id: None,
17878                pool_address: None,
17879                transaction_to: WETH_ADDRESS.to_string(),
17880                transaction_input: "0xd0e30db0".to_string(),
17881                transaction_value: "1".to_string(),
17882                amount_in: None,
17883                created_block: FIXTURE_BLOCK,
17884            })
17885            .await
17886            .unwrap();
17887        database
17888            .assign_execution_intent_nonce(intent.id, 7)
17889            .await
17890            .unwrap();
17891        database
17892            .add_execution_transaction_hash(intent.id, 42161, TRANSACTION_HASH, &[1, 2, 3])
17893            .await
17894            .unwrap();
17895
17896        for _ in 0..2 {
17897            database
17898                .record_execution_status(
17899                    intent.id,
17900                    TRANSACTION_HASH,
17901                    TransactionStatus::Broadcast,
17902                    None,
17903                    None,
17904                    None,
17905                    None,
17906                    None,
17907                )
17908                .await
17909                .unwrap();
17910        }
17911
17912        for status in [TransactionStatus::Included, TransactionStatus::Included] {
17913            database
17914                .record_execution_status(
17915                    intent.id,
17916                    TRANSACTION_HASH,
17917                    status,
17918                    Some(FIXTURE_BLOCK + 1),
17919                    Some("0x2222222222222222222222222222222222222222222222222222222222222222"),
17920                    Some(true),
17921                    Some(50_112),
17922                    Some("100000000"),
17923                )
17924                .await
17925                .unwrap();
17926        }
17927
17928        for _ in 0..2 {
17929            database
17930                .record_execution_status(
17931                    intent.id,
17932                    TRANSACTION_HASH,
17933                    TransactionStatus::Finalized,
17934                    Some(FIXTURE_BLOCK + 1),
17935                    Some("0x2222222222222222222222222222222222222222222222222222222222222222"),
17936                    Some(true),
17937                    Some(50_112),
17938                    Some("100000000"),
17939                )
17940                .await
17941                .unwrap();
17942        }
17943
17944        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17945            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
17946        )))
17947        .fetch_all(&admin_pool)
17948        .await
17949        .unwrap();
17950        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17951            "SELECT status, active FROM {schema}.execution_intent"
17952        )))
17953        .fetch_one(&admin_pool)
17954        .await
17955        .unwrap();
17956        let append_only_error = sqlx::query(sqlx::AssertSqlSafe(format!(
17957            "DELETE FROM {schema}.execution_transaction_transition WHERE intent_id = {}",
17958            intent.id
17959        )))
17960        .execute(&admin_pool)
17961        .await
17962        .unwrap_err();
17963
17964        assert_eq!(
17965            transitions,
17966            ["prepared", "signed", "broadcast", "included", "finalized"]
17967        );
17968        assert_eq!(status, "finalized");
17969        assert!(active);
17970        assert!(
17971            append_only_error
17972                .to_string()
17973                .contains("Execution transitions are append-only"),
17974            "was: {append_only_error}"
17975        );
17976
17977        drop_execution_schema(&admin_pool, &schema).await;
17978    }
17979
17980    #[tokio::test]
17981    async fn wrap_then_approve_persists_records_and_clears_in_flight() {
17982        let state = execution_rpc_state()
17983            .with_parameter_response_sequence(
17984                "eth_getBlockByNumber",
17985                "latest",
17986                &[
17987                    BLOCK_BY_NUMBER,
17988                    BLOCK_BY_NUMBER,
17989                    BLOCK_BY_NUMBER,
17990                    BLOCK_FINALIZED,
17991                    BLOCK_FINALIZED,
17992                    BLOCK_FINALIZED,
17993                ],
17994            )
17995            .with_response_sequence(
17996                "eth_call",
17997                &[
17998                    CALL_BALANCE,
17999                    CALL_BALANCE,
18000                    CALL_BALANCE,
18001                    CALL_BALANCE,
18002                    CALL_BALANCE,
18003                    CALL_BALANCE,
18004                    CALL_BALANCE_AFTER_WRAP,
18005                    CALL_BALANCE_AFTER_WRAP,
18006                    CALL_BALANCE_AFTER_WRAP,
18007                    CALL_BOOL_TRUE,
18008                    CALL_BOOL_TRUE,
18009                    CALL_BOOL_TRUE,
18010                ],
18011            )
18012            .with_call_response_sequence(
18013                ALLOWANCE_SELECTOR,
18014                &[
18015                    CALL_ZERO,
18016                    CALL_ZERO,
18017                    CALL_ZERO,
18018                    CALL_ALLOWANCE_MAX,
18019                    CALL_ALLOWANCE_MAX,
18020                    CALL_ALLOWANCE_MAX,
18021                ],
18022            )
18023            .with_response_sequence(
18024                "eth_getTransactionCount",
18025                &[
18026                    TRANSACTION_COUNT,
18027                    TRANSACTION_COUNT,
18028                    TRANSACTION_COUNT,
18029                    TRANSACTION_COUNT,
18030                    TRANSACTION_COUNT,
18031                    TRANSACTION_COUNT,
18032                    TRANSACTION_COUNT_NEXT,
18033                    TRANSACTION_COUNT_NEXT,
18034                    TRANSACTION_COUNT_NEXT,
18035                    TRANSACTION_COUNT_NEXT,
18036                    TRANSACTION_COUNT_NEXT,
18037                    TRANSACTION_COUNT_NEXT,
18038                ],
18039            )
18040            .with_response("eth_estimateGas", ESTIMATE_GAS)
18041            .with_response_sequence(
18042                "eth_getTransactionReceipt",
18043                &[
18044                    RECEIPT_SUCCESS,
18045                    RECEIPT_SUCCESS,
18046                    RECEIPT_SUCCESS,
18047                    RECEIPT_SUCCESS,
18048                    RECEIPT_SUCCESS,
18049                    RECEIPT_SUCCESS,
18050                ],
18051            )
18052            .with_send_raw_transaction_echo();
18053        let Some((admin_pool, schema, mut client, state)) =
18054            execution_client_with_database("execution_client_test", state).await
18055        else {
18056            return;
18057        };
18058        client.config.unlimited_approval = true;
18059        client.transaction_limits.receipt_timeout_secs = 3;
18060
18061        let wrap_hash = client
18062            .wrap(U256::from(1_000_000_000_000_000u64))
18063            .await
18064            .unwrap();
18065
18066        let record = client
18067            .cache
18068            .get_execution_transaction(42161, &wrap_hash.to_string())
18069            .await
18070            .unwrap()
18071            .unwrap();
18072        assert_eq!(record.nonce, 7);
18073        assert_eq!(record.purpose, "wrap");
18074        assert_eq!(record.status, "finalized");
18075        assert_eq!(
18076            execution_intent_markers(&admin_pool, &schema).await,
18077            vec![("wrap".into(), "finalized".into(), true, false)]
18078        );
18079
18080        let approve_hash = client
18081            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
18082            .await
18083            .unwrap();
18084
18085        let record = client
18086            .cache
18087            .get_execution_transaction(42161, &approve_hash.to_string())
18088            .await
18089            .unwrap()
18090            .unwrap();
18091        assert_eq!(record.nonce, 8);
18092        assert_eq!(record.purpose, "approve");
18093        assert_eq!(record.status, "finalized");
18094        assert_eq!(
18095            execution_intent_markers(&admin_pool, &schema).await,
18096            vec![
18097                ("wrap".into(), "finalized".into(), true, false),
18098                ("approve".into(), "finalized".into(), true, false),
18099            ]
18100        );
18101
18102        let requests = state.recorded_requests();
18103        let broadcasts: Vec<_> = requests
18104            .iter()
18105            .filter(|request| request["method"] == "eth_sendRawTransaction")
18106            .collect();
18107        assert_eq!(broadcasts.len(), 2);
18108        for broadcast in &broadcasts {
18109            let payload = broadcast["params"][0].as_str().unwrap();
18110            assert!(payload.starts_with("0x02"), "was: {payload}");
18111        }
18112        let broadcast_indexes = requests
18113            .iter()
18114            .enumerate()
18115            .filter_map(|(index, request)| {
18116                (request["method"] == "eth_sendRawTransaction").then_some(index)
18117            })
18118            .collect::<Vec<_>>();
18119
18120        for (index, expected_block) in broadcast_indexes
18121            .into_iter()
18122            .zip([FIXTURE_BLOCK_PARAM, "0x1cf0d42"])
18123        {
18124            let nonce_fence = &requests[index - 6..index];
18125            assert!(nonce_fence[..3].iter().all(|request| {
18126                request["method"] == "eth_getTransactionCount"
18127                    && request["params"][1] == expected_block
18128            }));
18129            assert!(nonce_fence[3..].iter().all(|request| {
18130                request["method"] == "eth_getTransactionCount" && request["params"][1] == "pending"
18131            }));
18132        }
18133        let receipt_polls = requests
18134            .iter()
18135            .filter(|request| request["method"] == "eth_getTransactionReceipt")
18136            .count();
18137        assert_eq!(receipt_polls, 6);
18138        let allowance_calls: Vec<_> = requests
18139            .iter()
18140            .filter(|request| {
18141                request["method"] == "eth_call"
18142                    && request["params"][0]["data"]
18143                        .as_str()
18144                        .is_some_and(|data| data.starts_with(ALLOWANCE_SELECTOR))
18145            })
18146            .collect();
18147        assert_eq!(allowance_calls.len(), 6);
18148        assert!(
18149            allowance_calls[..3]
18150                .iter()
18151                .all(|request| request["params"][1] == "0x1cf0d42")
18152        );
18153        assert!(
18154            allowance_calls[3..]
18155                .iter()
18156                .all(|request| request["params"][1] == "0x1cf0d41")
18157        );
18158
18159        // Unlimited approval policy encoded U256::MAX in the approve calldata
18160        let estimates: Vec<_> = requests
18161            .iter()
18162            .filter(|request| request["method"] == "eth_estimateGas")
18163            .collect();
18164        assert_eq!(estimates.len(), 6);
18165        assert!(estimates[..3].iter().all(|request| {
18166            request["params"].as_array().unwrap().len() == 2
18167                && request["params"][1] == FIXTURE_BLOCK_PARAM
18168        }));
18169        assert!(estimates[3..].iter().all(|request| {
18170            request["params"].as_array().unwrap().len() == 2 && request["params"][1] == "0x1cf0d42"
18171        }));
18172        let approve_data = estimates[3]["params"][0]["data"].as_str().unwrap();
18173        assert!(
18174            approve_data.starts_with("0x095ea7b3"),
18175            "was: {approve_data}"
18176        );
18177        assert!(
18178            approve_data.ends_with(&"f".repeat(64)),
18179            "was: {approve_data}"
18180        );
18181
18182        for selector in [FACTORY_SELECTOR, WETH9_SELECTOR] {
18183            let calls: Vec<_> = requests
18184                .iter()
18185                .filter(|request| {
18186                    request["method"] == "eth_call"
18187                        && request["params"][0]["data"]
18188                            .as_str()
18189                            .is_some_and(|data| data.starts_with(selector))
18190                })
18191                .collect();
18192            assert!(!calls.is_empty(), "selector {selector}");
18193            assert!(
18194                calls.iter().all(|request| request["params"][1]
18195                    .as_str()
18196                    .is_some_and(|block| block.starts_with("0x"))),
18197                "selector {selector}: {calls:?}"
18198            );
18199        }
18200        let latest_blocks = requests
18201            .iter()
18202            .filter(|request| {
18203                request["method"] == "eth_getBlockByNumber"
18204                    && request["params"] == serde_json::json!(["latest", false])
18205            })
18206            .count();
18207        assert_eq!(latest_blocks, 6);
18208
18209        drop_execution_schema(&admin_pool, &schema).await;
18210    }
18211
18212    #[tokio::test]
18213    async fn reverted_receipt_marks_record_reverted_and_errors() {
18214        let state = signing_rpc_state()
18215            .with_response("eth_getTransactionReceipt", RECEIPT_REVERTED)
18216            .with_send_raw_transaction_echo();
18217        let Some((admin_pool, schema, mut client, _)) =
18218            execution_client_with_database("execution_reverted_test", state).await
18219        else {
18220            return;
18221        };
18222
18223        let error = client
18224            .wrap(U256::from(1_000_000_000_000_000u64))
18225            .await
18226            .unwrap_err();
18227
18228        assert!(
18229            error.to_string().contains("reverted on-chain"),
18230            "was: {error}"
18231        );
18232        assert!(client.in_flight.lock().is_none());
18233
18234        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000u64)).await;
18235
18236        let record = client
18237            .cache
18238            .get_execution_transaction(42161, &expected_hash.to_string())
18239            .await
18240            .unwrap()
18241            .unwrap();
18242        assert_eq!(record.status, "reverted");
18243        assert_eq!(
18244            execution_intent_markers(&admin_pool, &schema).await,
18245            vec![("wrap".into(), "reverted".into(), true, false)]
18246        );
18247
18248        drop_execution_schema(&admin_pool, &schema).await;
18249    }
18250
18251    fn market_sell_order_with_id(instrument_id: InstrumentId, client_order_id: &str) -> OrderAny {
18252        OrderTestBuilder::new(OrderType::Market)
18253            .trader_id(TraderId::from("TRADER-001"))
18254            .strategy_id(StrategyId::from("S-001"))
18255            .instrument_id(instrument_id)
18256            .client_order_id(ClientOrderId::from(client_order_id))
18257            .side(OrderSide::Sell)
18258            .quantity(Quantity::from("0.001"))
18259            .build()
18260    }
18261
18262    fn market_buy_order_with_id(instrument_id: InstrumentId, client_order_id: &str) -> OrderAny {
18263        OrderTestBuilder::new(OrderType::Market)
18264            .trader_id(TraderId::from("TRADER-001"))
18265            .strategy_id(StrategyId::from("S-001"))
18266            .instrument_id(instrument_id)
18267            .client_order_id(ClientOrderId::from(client_order_id))
18268            .side(OrderSide::Buy)
18269            .quantity(Quantity::from("0.001"))
18270            .build()
18271    }
18272
18273    fn submit_order_list_cmd(orders: &[OrderAny]) -> SubmitOrderList {
18274        let order_list = OrderList::new(
18275            OrderListId::from("OL-001"),
18276            orders[0].instrument_id(),
18277            orders[0].strategy_id(),
18278            orders.iter().map(|order| order.client_order_id()).collect(),
18279            UnixNanos::default(),
18280        );
18281        SubmitOrderList::new(
18282            TraderId::from("TRADER-001"),
18283            Some(ClientId::from("BLOCKCHAIN-001")),
18284            orders[0].strategy_id(),
18285            order_list,
18286            orders
18287                .iter()
18288                .map(|order| order.init_event().clone())
18289                .collect(),
18290            None,
18291            None,
18292            None,
18293            UUID4::new(),
18294            UnixNanos::default(),
18295            None,
18296        )
18297    }
18298
18299    fn modify_order_cmd(
18300        instrument_id: InstrumentId,
18301        client_order_id: ClientOrderId,
18302    ) -> ModifyOrder {
18303        ModifyOrder::new(
18304            TraderId::from("TRADER-001"),
18305            Some(ClientId::from("BLOCKCHAIN-001")),
18306            StrategyId::from("S-001"),
18307            instrument_id,
18308            client_order_id,
18309            None,
18310            Some(Quantity::from("0.002")),
18311            None,
18312            None,
18313            UUID4::new(),
18314            UnixNanos::default(),
18315            None,
18316            None,
18317        )
18318    }
18319
18320    fn cancel_order_cmd(
18321        instrument_id: InstrumentId,
18322        client_order_id: ClientOrderId,
18323    ) -> CancelOrder {
18324        CancelOrder::new(
18325            TraderId::from("TRADER-001"),
18326            Some(ClientId::from("BLOCKCHAIN-001")),
18327            StrategyId::from("S-001"),
18328            instrument_id,
18329            client_order_id,
18330            None,
18331            UUID4::new(),
18332            UnixNanos::default(),
18333            None,
18334            None,
18335        )
18336    }
18337
18338    fn cancel_all_orders_cmd(instrument_id: InstrumentId) -> CancelAllOrders {
18339        CancelAllOrders::new(
18340            TraderId::from("TRADER-001"),
18341            Some(ClientId::from("BLOCKCHAIN-001")),
18342            StrategyId::from("S-001"),
18343            instrument_id,
18344            Some(OrderSide::Sell),
18345            UUID4::new(),
18346            UnixNanos::default(),
18347            None,
18348            None,
18349        )
18350    }
18351
18352    fn batch_cancel_orders_cmd(cancels: Vec<CancelOrder>) -> BatchCancelOrders {
18353        BatchCancelOrders::new(
18354            TraderId::from("TRADER-001"),
18355            Some(ClientId::from("BLOCKCHAIN-001")),
18356            StrategyId::from("S-001"),
18357            cancels[0].instrument_id,
18358            cancels,
18359            UUID4::new(),
18360            UnixNanos::default(),
18361            None,
18362            None,
18363        )
18364    }
18365
18366    fn query_order_cmd(instrument_id: InstrumentId, client_order_id: ClientOrderId) -> QueryOrder {
18367        QueryOrder::new(
18368            TraderId::from("TRADER-001"),
18369            Some(ClientId::from("BLOCKCHAIN-001")),
18370            StrategyId::from("S-001"),
18371            instrument_id,
18372            client_order_id,
18373            None,
18374            UUID4::new(),
18375            UnixNanos::default(),
18376            None,
18377            None,
18378        )
18379    }
18380
18381    async fn unsupported_client_with_mock_rpc()
18382    -> (BlockchainExecutionClient, MockRpcState, Rc<RefCell<Cache>>) {
18383        let state = ready_rpc_state();
18384        let addr = start_mock_rpc_server(state.clone()).await;
18385        let (client, cache) = swap_client_with_cache(test_config(format!("http://{addr}")));
18386        (client, state, cache)
18387    }
18388
18389    #[tokio::test]
18390    async fn submit_order_denies_reduce_only_without_side_effects() {
18391        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18392        let order = OrderTestBuilder::new(OrderType::Market)
18393            .trader_id(TraderId::from("TRADER-001"))
18394            .strategy_id(StrategyId::from("S-001"))
18395            .instrument_id(test_pool().instrument_id)
18396            .client_order_id(ClientOrderId::from("O-REDUCE-ONLY"))
18397            .side(OrderSide::Sell)
18398            .quantity(Quantity::from("0.001"))
18399            .reduce_only(true)
18400            .build();
18401        cache
18402            .borrow_mut()
18403            .add_order(order.clone(), None, None, false)
18404            .unwrap();
18405        let mut receiver = start_with_events(&mut client);
18406
18407        client.submit_order(submit_order_cmd(&order)).unwrap();
18408
18409        let events = collect_order_events(&mut receiver);
18410        assert_eq!(events.len(), 1, "was: {events:?}");
18411        let OrderEventAny::Denied(denied) = &events[0] else {
18412            panic!("expected OrderDenied, was {:?}", events[0]);
18413        };
18414        assert_eq!(denied.client_order_id, order.client_order_id());
18415        assert_eq!(denied.reason, "UNSUPPORTED_REDUCE_ONLY");
18416        assert!(state.recorded_requests().is_empty());
18417        assert!(client.in_flight.lock().is_none());
18418    }
18419
18420    #[tokio::test]
18421    async fn submit_order_list_denies_every_order_without_side_effects() {
18422        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18423        let pool = test_pool();
18424        let first = test_market_sell_order(pool.instrument_id);
18425        let second = market_sell_order_with_id(pool.instrument_id, "O-SWAP-002");
18426        cache
18427            .borrow_mut()
18428            .add_order(second.clone(), None, None, false)
18429            .unwrap();
18430        let orders = [first.clone(), second.clone()];
18431        let mut receiver = start_with_events(&mut client);
18432
18433        client
18434            .submit_order_list(submit_order_list_cmd(&orders))
18435            .unwrap();
18436
18437        let events = collect_order_events(&mut receiver);
18438        let mut denied_ids = Vec::new();
18439
18440        for event in &events {
18441            let OrderEventAny::Denied(denied) = event else {
18442                panic!("expected OrderDenied, was {event:?}");
18443            };
18444            assert_eq!(denied.reason, ORDER_LIST_UNSUPPORTED);
18445            denied_ids.push(denied.client_order_id);
18446        }
18447        denied_ids.sort();
18448        assert_eq!(
18449            denied_ids,
18450            [first.client_order_id(), second.client_order_id()]
18451        );
18452        assert!(state.recorded_requests().is_empty());
18453        assert!(client.in_flight.lock().is_none());
18454
18455        for order in &orders {
18456            let cache_ref = cache.borrow();
18457            let cached = cache_ref.order(&order.client_order_id()).unwrap();
18458            assert_eq!(cached.status(), OrderStatus::Initialized);
18459        }
18460    }
18461
18462    #[tokio::test]
18463    async fn modify_order_denies_without_side_effects() {
18464        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18465        let order = test_market_sell_order(test_pool().instrument_id);
18466        let mut receiver = start_with_events(&mut client);
18467
18468        let command = modify_order_cmd(order.instrument_id(), order.client_order_id());
18469        let cause = command.command_id;
18470        client.modify_order(command).unwrap();
18471
18472        let events = collect_order_events(&mut receiver);
18473        assert_eq!(events.len(), 1, "was: {events:?}");
18474
18475        let OrderEventAny::ModifyDenied(rejected) = &events[0] else {
18476            panic!("expected OrderModifyDenied, was {:?}", events[0]);
18477        };
18478
18479        assert_eq!(rejected.causation_id, Some(cause));
18480        assert_eq!(rejected.client_order_id, order.client_order_id());
18481        assert_eq!(rejected.reason, ORDER_MODIFY_UNSUPPORTED);
18482        assert!(state.recorded_requests().is_empty());
18483        assert!(client.in_flight.lock().is_none());
18484        let cache_ref = cache.borrow();
18485        let cached = cache_ref.order(&order.client_order_id()).unwrap();
18486        assert_eq!(cached.status(), OrderStatus::Initialized);
18487    }
18488
18489    #[tokio::test]
18490    async fn cancel_order_denies_without_side_effects() {
18491        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18492        let order = test_market_sell_order(test_pool().instrument_id);
18493        let mut receiver = start_with_events(&mut client);
18494
18495        let command = cancel_order_cmd(order.instrument_id(), order.client_order_id());
18496        let cause = command.command_id;
18497        client.cancel_order(command).unwrap();
18498
18499        let events = collect_order_events(&mut receiver);
18500        assert_eq!(events.len(), 1, "was: {events:?}");
18501
18502        let OrderEventAny::CancelDenied(rejected) = &events[0] else {
18503            panic!("expected OrderCancelDenied, was {:?}", events[0]);
18504        };
18505
18506        assert_eq!(rejected.causation_id, Some(cause));
18507        assert_eq!(rejected.client_order_id, order.client_order_id());
18508        assert_eq!(rejected.reason, ORDER_CANCEL_UNSUPPORTED);
18509        assert!(state.recorded_requests().is_empty());
18510        assert!(client.in_flight.lock().is_none());
18511        let cache_ref = cache.borrow();
18512        let cached = cache_ref.order(&order.client_order_id()).unwrap();
18513        assert_eq!(cached.status(), OrderStatus::Initialized);
18514    }
18515
18516    #[tokio::test]
18517    async fn batch_cancel_orders_denies_each_order_without_side_effects() {
18518        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18519        let pool = test_pool();
18520        let first = test_market_sell_order(pool.instrument_id);
18521        let second = market_sell_order_with_id(pool.instrument_id, "O-SWAP-002");
18522        cache
18523            .borrow_mut()
18524            .add_order(second.clone(), None, None, false)
18525            .unwrap();
18526        let orders = [first.clone(), second.clone()];
18527        let cancels = orders
18528            .iter()
18529            .map(|order| cancel_order_cmd(order.instrument_id(), order.client_order_id()))
18530            .collect::<Vec<_>>();
18531        let causes: std::collections::HashMap<_, _> = cancels
18532            .iter()
18533            .map(|command| (command.client_order_id, command.command_id))
18534            .collect();
18535        let mut receiver = start_with_events(&mut client);
18536
18537        client
18538            .batch_cancel_orders(batch_cancel_orders_cmd(cancels))
18539            .unwrap();
18540
18541        let events = collect_order_events(&mut receiver);
18542        let mut rejected_ids = Vec::new();
18543
18544        for event in &events {
18545            let OrderEventAny::CancelDenied(rejected) = event else {
18546                panic!("expected OrderCancelDenied, was {event:?}");
18547            };
18548
18549            assert_eq!(
18550                rejected.causation_id,
18551                Some(causes[&rejected.client_order_id])
18552            );
18553            assert_eq!(rejected.reason, ORDER_CANCEL_UNSUPPORTED);
18554            rejected_ids.push(rejected.client_order_id);
18555        }
18556        rejected_ids.sort();
18557        assert_eq!(
18558            rejected_ids,
18559            [first.client_order_id(), second.client_order_id()]
18560        );
18561        assert!(state.recorded_requests().is_empty());
18562        assert!(client.in_flight.lock().is_none());
18563    }
18564
18565    #[rstest]
18566    #[case::modify(true)]
18567    #[case::cancel(false)]
18568    #[tokio::test]
18569    async fn command_denial_preserves_cached_owner(
18570        #[case] modify: bool,
18571        #[values(false, true)] cached: bool,
18572    ) {
18573        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18574        let mut order = test_market_sell_order(test_pool().instrument_id);
18575        let venue = VenueOrderId::from("V-OWNER-029");
18576        let account = AccountId::from("BLOCKCHAIN-001");
18577        let accepted = TestOrderEventStubs::accepted(&order, account, venue);
18578        order.apply(accepted.clone()).unwrap();
18579        cache.borrow_mut().update_order(&accepted).unwrap();
18580
18581        let target = if cached {
18582            order.client_order_id()
18583        } else {
18584            ClientOrderId::from("O-UNCACHED")
18585        };
18586
18587        let requester = StrategyId::from("REQUESTER-031");
18588        let explicit_venue = VenueOrderId::from("V-REQUESTER-037");
18589        let command_id = UUID4::new();
18590
18591        let pending = if modify {
18592            let mut event = OrderPendingUpdate::new(
18593                order.trader_id(),
18594                order.strategy_id(),
18595                order.instrument_id(),
18596                order.client_order_id(),
18597                Some(account),
18598                UUID4::new(),
18599                UnixNanos::default(),
18600                UnixNanos::default(),
18601                false,
18602                Some(venue),
18603            );
18604            event.causation_id = Some(command_id);
18605            OrderEventAny::PendingUpdate(event)
18606        } else {
18607            let mut event = OrderPendingCancel::new(
18608                order.trader_id(),
18609                order.strategy_id(),
18610                order.instrument_id(),
18611                order.client_order_id(),
18612                Some(account),
18613                UUID4::new(),
18614                UnixNanos::default(),
18615                UnixNanos::default(),
18616                false,
18617                Some(venue),
18618            );
18619            event.causation_id = Some(command_id);
18620            OrderEventAny::PendingCancel(event)
18621        };
18622
18623        if cached {
18624            cache.borrow_mut().update_order(&pending).unwrap();
18625        }
18626
18627        let mut receiver = start_with_events(&mut client);
18628
18629        if modify {
18630            let mut command = modify_order_cmd(order.instrument_id(), target);
18631            command.strategy_id = requester;
18632            command.venue_order_id = Some(explicit_venue);
18633            command.command_id = command_id;
18634            client.modify_order(command).unwrap();
18635        } else {
18636            let mut command = cancel_order_cmd(order.instrument_id(), target);
18637            command.strategy_id = requester;
18638            command.venue_order_id = Some(explicit_venue);
18639            command.command_id = command_id;
18640            client.cancel_order(command).unwrap();
18641        }
18642
18643        let events = collect_order_events(&mut receiver);
18644        assert_eq!(events.len(), 1);
18645        let event = &events[0];
18646        assert_eq!(
18647            event.strategy_id(),
18648            if cached {
18649                order.strategy_id()
18650            } else {
18651                requester
18652            }
18653        );
18654        assert_eq!(event.client_order_id(), target);
18655        assert_eq!(event.instrument_id(), order.instrument_id());
18656        assert_eq!(
18657            event.venue_order_id(),
18658            Some(if cached { venue } else { explicit_venue })
18659        );
18660
18661        let cause = match event {
18662            OrderEventAny::ModifyDenied(denied) => {
18663                assert!(modify);
18664                denied.causation_id
18665            }
18666            OrderEventAny::CancelDenied(denied) => {
18667                assert!(!modify);
18668                denied.causation_id
18669            }
18670            other => panic!("expected command denial, was {other:?}"),
18671        };
18672
18673        assert_eq!(cause, Some(command_id));
18674
18675        if cached {
18676            cache.borrow_mut().update_order(event).unwrap();
18677            let after = cache.borrow().try_order_owned(&target).unwrap();
18678            assert_eq!(after.status(), OrderStatus::Accepted);
18679            assert_eq!(after.quantity(), order.quantity());
18680            assert_eq!(after.filled_qty(), order.filled_qty());
18681            assert!(!after.has_pending_update_command());
18682            assert!(!after.has_pending_cancel_command());
18683        } else {
18684            assert!(cache.borrow().order_ref(&target).is_none());
18685        }
18686
18687        assert!(state.recorded_requests().is_empty());
18688        assert!(client.in_flight.lock().is_none());
18689    }
18690
18691    #[tokio::test]
18692    async fn cancel_all_and_query_order_log_unsupported_without_side_effects() {
18693        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18694        let order = test_market_sell_order(test_pool().instrument_id);
18695        let mut receiver = start_with_events(&mut client);
18696
18697        client
18698            .cancel_all_orders(cancel_all_orders_cmd(order.instrument_id()))
18699            .unwrap();
18700        client
18701            .query_order(query_order_cmd(
18702                order.instrument_id(),
18703                order.client_order_id(),
18704            ))
18705            .unwrap();
18706
18707        let events = collect_order_events(&mut receiver);
18708        assert!(events.is_empty(), "was: {events:?}");
18709        assert!(state.recorded_requests().is_empty());
18710        assert!(client.in_flight.lock().is_none());
18711        let cache_ref = cache.borrow();
18712        let cached = cache_ref.order(&order.client_order_id()).unwrap();
18713        assert_eq!(cached.status(), OrderStatus::Initialized);
18714    }
18715
18716    #[tokio::test]
18717    async fn unsupported_commands_handle_unknown_orders_without_panic() {
18718        let (mut client, state, _) = unsupported_client_with_mock_rpc().await;
18719        let instrument_id = test_pool().instrument_id;
18720        let unknown = ClientOrderId::from("O-UNKNOWN");
18721        let mut receiver = start_with_events(&mut client);
18722
18723        let modify = modify_order_cmd(instrument_id, unknown);
18724        let cancel = cancel_order_cmd(instrument_id, unknown);
18725        let batch_cancel = cancel_order_cmd(instrument_id, unknown);
18726        let expected = vec![
18727            (
18728                true,
18729                instrument_id,
18730                unknown,
18731                Ustr::from(ORDER_MODIFY_UNSUPPORTED),
18732                Some(modify.command_id),
18733            ),
18734            (
18735                false,
18736                instrument_id,
18737                unknown,
18738                Ustr::from(ORDER_CANCEL_UNSUPPORTED),
18739                Some(cancel.command_id),
18740            ),
18741            (
18742                false,
18743                instrument_id,
18744                unknown,
18745                Ustr::from(ORDER_CANCEL_UNSUPPORTED),
18746                Some(batch_cancel.command_id),
18747            ),
18748        ];
18749        client.modify_order(modify).unwrap();
18750        client.cancel_order(cancel).unwrap();
18751        client
18752            .batch_cancel_orders(batch_cancel_orders_cmd(vec![batch_cancel]))
18753            .unwrap();
18754        client
18755            .query_order(query_order_cmd(instrument_id, unknown))
18756            .unwrap();
18757
18758        let events = collect_order_events(&mut receiver);
18759
18760        let outcomes: Vec<_> = events
18761            .iter()
18762            .map(|event| match event {
18763                OrderEventAny::ModifyDenied(event) => (
18764                    true,
18765                    event.instrument_id,
18766                    event.client_order_id,
18767                    event.reason,
18768                    event.causation_id,
18769                ),
18770                OrderEventAny::CancelDenied(event) => (
18771                    false,
18772                    event.instrument_id,
18773                    event.client_order_id,
18774                    event.reason,
18775                    event.causation_id,
18776                ),
18777                other => panic!("Expected unsupported command denial, was {other:?}"),
18778            })
18779            .collect();
18780
18781        assert_eq!(outcomes, expected);
18782        assert!(state.recorded_requests().is_empty());
18783        assert!(client.in_flight.lock().is_none());
18784    }
18785
18786    #[tokio::test]
18787    async fn report_generators_error_except_mass_status_without_side_effects() {
18788        let (client, state, _) = unsupported_client_with_mock_rpc().await;
18789
18790        let report = client
18791            .generate_order_status_report(&GenerateOrderStatusReport::new(
18792                UUID4::new(),
18793                UnixNanos::default(),
18794                None,
18795                None,
18796                None,
18797                None,
18798                None,
18799            ))
18800            .await
18801            .unwrap_err();
18802        assert_eq!(report.to_string(), VENUE_EXECUTION_REPORTS_UNSUPPORTED);
18803
18804        let reports = client
18805            .generate_order_status_reports(&GenerateOrderStatusReports::new(
18806                UUID4::new(),
18807                UnixNanos::default(),
18808                false,
18809                None,
18810                None,
18811                None,
18812                None,
18813                None,
18814            ))
18815            .await
18816            .unwrap_err();
18817        assert_eq!(reports.to_string(), VENUE_EXECUTION_REPORTS_UNSUPPORTED);
18818
18819        let fills = client
18820            .generate_fill_reports(GenerateFillReports::new(
18821                UUID4::new(),
18822                UnixNanos::default(),
18823                None,
18824                None,
18825                None,
18826                None,
18827                None,
18828                None,
18829            ))
18830            .await
18831            .unwrap_err();
18832        assert_eq!(fills.to_string(), VENUE_EXECUTION_REPORTS_UNSUPPORTED);
18833
18834        let positions = client
18835            .generate_position_status_reports(&GeneratePositionStatusReports::new(
18836                UUID4::new(),
18837                UnixNanos::default(),
18838                None,
18839                None,
18840                None,
18841                None,
18842                None,
18843            ))
18844            .await
18845            .unwrap_err();
18846        assert_eq!(positions.to_string(), VENUE_EXECUTION_REPORTS_UNSUPPORTED);
18847
18848        let mass_status = client.generate_mass_status(None).await.unwrap();
18849        assert!(mass_status.is_none());
18850
18851        let mass_status = client.generate_mass_status(Some(60)).await.unwrap();
18852        assert!(mass_status.is_none());
18853
18854        assert!(state.recorded_requests().is_empty());
18855        assert!(client.in_flight.lock().is_none());
18856    }
18857
18858    async fn connect_test_postgres(
18859        test_name: &str,
18860    ) -> Option<(sqlx::PgPool, PostgresConnectOptions)> {
18861        let pg_config = get_postgres_connect_options(None, None, None, None, None);
18862        let admin_options: sqlx::postgres::PgConnectOptions = pg_config.clone().into();
18863        let admin_pool = match PgPoolOptions::new()
18864            .max_connections(1)
18865            .connect_with(admin_options)
18866            .await
18867        {
18868            Ok(pool) => pool,
18869            Err(e) => {
18870                eprintln!("Postgres unavailable; skipping {test_name} test: {e}");
18871                return None;
18872            }
18873        };
18874
18875        Some((admin_pool, pg_config))
18876    }
18877
18878    async fn execution_client_with_database(
18879        test_name: &str,
18880        state: MockRpcState,
18881    ) -> Option<(
18882        sqlx::PgPool,
18883        String,
18884        BlockchainExecutionClient,
18885        MockRpcState,
18886    )> {
18887        let (admin_pool, schema, mut client, state) =
18888            execution_client_with_unprotected_database(test_name, state).await?;
18889        protect_test_storage(&mut client, &schema).await;
18890        Some((admin_pool, schema, client, state))
18891    }
18892
18893    async fn execution_client_with_unprotected_database(
18894        test_name: &str,
18895        state: MockRpcState,
18896    ) -> Option<(
18897        sqlx::PgPool,
18898        String,
18899        BlockchainExecutionClient,
18900        MockRpcState,
18901    )> {
18902        let (admin_pool, pg_config) = connect_test_postgres(test_name).await?;
18903        let schema = format!("{test_name}_{}", std::process::id());
18904        setup_execution_schema(&admin_pool, &schema).await;
18905
18906        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
18907        let db_options = db_options.options([("search_path", schema.clone())]);
18908        let database = connect_test_database(db_options).await.unwrap();
18909        let addr = start_mock_rpc_server(state.clone()).await;
18910        let mut client = test_client(format!("http://{addr}"));
18911        client.cache.database = Some(database);
18912        // Mirror the connect-time migration: tests create the pre-submission table shape
18913        client
18914            .cache
18915            .ensure_execution_transaction_schema()
18916            .await
18917            .unwrap();
18918        initialize_test_verification_ledger(&client).await;
18919        client.signer = Some(Arc::new(
18920            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
18921        ));
18922        client.core.set_connected();
18923
18924        Some((admin_pool, schema, client, state))
18925    }
18926
18927    async fn install_reservation_commit_rejection(admin_pool: &sqlx::PgPool, schema: &str) {
18928        for statement in [
18929            format!(
18930                "CREATE FUNCTION {schema}.reject_execution_reservation_commit() RETURNS trigger \
18931                 LANGUAGE plpgsql AS 'BEGIN RAISE EXCEPTION ''test reservation commit rejection''; \
18932                 RETURN NEW; END'"
18933            ),
18934            format!(
18935                "CREATE CONSTRAINT TRIGGER reject_execution_reservation_commit AFTER INSERT ON \
18936                 {schema}.execution_transaction_transition DEFERRABLE INITIALLY DEFERRED \
18937                 FOR EACH ROW EXECUTE FUNCTION {schema}.reject_execution_reservation_commit()"
18938            ),
18939        ] {
18940            sqlx::query(sqlx::AssertSqlSafe(statement))
18941                .execute(admin_pool)
18942                .await
18943                .unwrap();
18944        }
18945    }
18946
18947    async fn install_recoverable_commit_rejection(admin_pool: &sqlx::PgPool, schema: &str) {
18948        for statement in [
18949            format!(
18950                "CREATE FUNCTION {schema}.reject_recoverable_commit() RETURNS trigger \
18951                 LANGUAGE plpgsql AS 'BEGIN IF NEW.transition_key = ''recoverable'' THEN \
18952                 RAISE EXCEPTION ''test recoverable commit rejection''; END IF; \
18953                 RETURN NEW; END'"
18954            ),
18955            format!(
18956                "CREATE CONSTRAINT TRIGGER reject_recoverable_commit AFTER INSERT ON \
18957                 {schema}.execution_transaction_transition DEFERRABLE INITIALLY DEFERRED \
18958                 FOR EACH ROW EXECUTE FUNCTION {schema}.reject_recoverable_commit()"
18959            ),
18960        ] {
18961            sqlx::query(sqlx::AssertSqlSafe(statement))
18962                .execute(admin_pool)
18963                .await
18964                .unwrap();
18965        }
18966    }
18967
18968    async fn drop_execution_schema(admin_pool: &sqlx::PgPool, schema: &str) {
18969        sqlx::query(sqlx::AssertSqlSafe(format!("DROP SCHEMA {schema} CASCADE")))
18970            .execute(admin_pool)
18971            .await
18972            .unwrap();
18973    }
18974
18975    async fn setup_execution_schema(admin_pool: &sqlx::PgPool, schema: &str) {
18976        for statement in [
18977            format!("CREATE SCHEMA {schema}"),
18978            format!(
18979                r#"CREATE TABLE {schema}."chain" (chain_id INTEGER PRIMARY KEY, name TEXT NOT NULL)"#
18980            ),
18981            format!(r#"INSERT INTO {schema}."chain" (chain_id, name) VALUES (42161, 'Arbitrum')"#),
18982            format!(
18983                r#"CREATE TABLE {schema}."execution_transaction" (
18984                    id BIGSERIAL PRIMARY KEY,
18985                    chain_id INTEGER NOT NULL REFERENCES {schema}."chain"(chain_id) ON DELETE CASCADE,
18986                    nonce BIGINT NOT NULL,
18987                    transaction_hash TEXT NOT NULL,
18988                    purpose TEXT NOT NULL,
18989                    status TEXT NOT NULL,
18990                    UNIQUE (chain_id, transaction_hash)
18991                )"#
18992            ),
18993        ] {
18994            sqlx::query(sqlx::AssertSqlSafe(statement))
18995                .execute(admin_pool)
18996                .await
18997                .unwrap();
18998        }
18999    }
19000
19001    fn execution_transaction_create_sql() -> &'static str {
19002        const TABLES_SQL: &str = include_str!("../../../../../schema/sql/tables.sql");
19003        const START: &str = "CREATE TABLE IF NOT EXISTS \"execution_transaction\"";
19004        let start = TABLES_SQL
19005            .find(START)
19006            .expect("execution_transaction table is missing from tables.sql");
19007        let statement = &TABLES_SQL[start..];
19008        let end = statement
19009            .find(";\n")
19010            .expect("execution_transaction CREATE TABLE is unterminated")
19011            + 1;
19012        &statement[..end]
19013    }
19014
19015    #[rstest]
19016    #[case(17)]
19017    #[case(18)]
19018    fn closed_pool_position_records_high_precision_quote_pnl(#[case] precision: u8) {
19019        use nautilus_model::{
19020            events::{PositionClosed, PositionEvent, order::spec::OrderFilledSpec},
19021            identifiers::PositionId,
19022            instruments::{CurrencyPair, Instrument},
19023            position::Position,
19024        };
19025        use nautilus_portfolio::Portfolio;
19026
19027        let template = test_pool();
19028
19029        let base = Token::new(
19030            Arc::clone(&template.chain),
19031            Address::from([precision; 20]),
19032            "Portfolio base".into(),
19033            format!("PNLBASE{precision}"),
19034            18,
19035        );
19036
19037        let quote_token = Token::new(
19038            Arc::clone(&template.chain),
19039            Address::from([precision + 50; 20]),
19040            "Portfolio quote".into(),
19041            format!("PNLQUOTE{precision}"),
19042            precision,
19043        );
19044        let address = Address::from([precision + 100; 20]);
19045
19046        let pool = Pool::new(
19047            template.chain,
19048            template.dex,
19049            address,
19050            PoolIdentifier::from_address(address),
19051            1,
19052            base,
19053            quote_token,
19054            Some(500),
19055            Some(10),
19056            UnixNanos::default(),
19057        );
19058        let instrument = CurrencyPair::try_from(&pool).unwrap().into_any();
19059        let quote = instrument.quote_currency();
19060        let position_id = PositionId::new(format!("P-QUOTE{precision}"));
19061        let mut fill = OrderFilledSpec::builder()
19062            .instrument_id(instrument.id())
19063            .position_id(position_id)
19064            .order_side(OrderSide::Buy)
19065            .last_qty(Quantity::from("0.1"))
19066            .last_px(Price::from("1.0000000000000000"))
19067            .currency(quote)
19068            .commission(Money::zero(quote))
19069            .ts_event(UnixNanos::from(1))
19070            .build();
19071        let mut position = Position::new(&instrument, fill.clone());
19072        let cache = Rc::new(RefCell::new(Cache::default()));
19073        cache.borrow_mut().add_instrument(instrument).unwrap();
19074        cache
19075            .borrow_mut()
19076            .add_position(&position, OmsType::Netting)
19077            .unwrap();
19078        fill.event_id = UUID4::new();
19079        fill.trade_id = TradeId::new("CLOSE");
19080        fill.client_order_id = ClientOrderId::new("CLOSE");
19081        fill.order_side = OrderSide::Sell;
19082        fill.last_px = Price::from("1.0000000000000001");
19083        fill.ts_event = UnixNanos::from(2);
19084        position.try_apply(&fill).unwrap();
19085        cache.borrow_mut().update_position(&position).unwrap();
19086
19087        let mut portfolio = Portfolio::new(
19088            Rc::new(RefCell::new(VirtualClock::new())),
19089            Rc::clone(&cache),
19090            None,
19091        );
19092        portfolio.update_position(&PositionEvent::PositionClosed(PositionClosed::create(
19093            &position,
19094            &fill,
19095            UUID4::new(),
19096            UnixNanos::from(3),
19097        )));
19098        let records = portfolio.recorded_realized_pnls();
19099        let analyzer = portfolio.analyzer();
19100        let pnl = position.realized_pnl.unwrap();
19101        assert!(position.is_closed());
19102        assert_eq!(quote.precision, precision);
19103        assert_eq!(quote.code.as_str(), format!("PNLQUOTE{precision}@ARBITRUM"));
19104        assert_eq!(pnl.currency.precision, precision);
19105        assert_eq!(pnl.currency, quote);
19106        assert_eq!(
19107            pnl.as_decimal(),
19108            "0.00000000000000001"
19109                .parse::<rust_decimal::Decimal>()
19110                .unwrap()
19111        );
19112        assert_eq!(
19113            records.get(&quote).unwrap(),
19114            &vec![(position_id, UnixNanos::from(2), 1e-17)]
19115        );
19116        assert_eq!(
19117            analyzer.realized_pnls(Some(&quote)).unwrap(),
19118            &[(position_id, UnixNanos::from(2), 1e-17)]
19119        );
19120    }
19121}