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(Vec::as_slice)
5452                .unwrap_or_default();
5453            let current = hashes
5454                .iter()
5455                .copied()
5456                .filter(|hash| hash.current)
5457                .collect::<Vec<_>>();
5458            anyhow::ensure!(
5459                current.len() <= 1,
5460                "Retained execution intent {} has multiple current hashes",
5461                intent.id
5462            );
5463            let current = current.first().copied();
5464            let mut authenticated = HashMap::new();
5465
5466            for hash in hashes {
5467                if hash.payload_expected {
5468                    let raw = open_execution_payload(
5469                        self.payload_keys
5470                            .as_deref()
5471                            .expect("Postgres execution requires payload keys"),
5472                        self.payload_policy(),
5473                        intent,
5474                        hash,
5475                        "verification migration",
5476                    )?;
5477                    authenticated.insert(hash.id, raw);
5478                } else {
5479                    anyhow::ensure!(
5480                        hash.raw_transaction.is_none() && hash.sealed_transaction.is_none(),
5481                        "Unowned replacement hash retains signed bytes"
5482                    );
5483                }
5484            }
5485
5486            if let Some(nonce) = intent.nonce {
5487                anyhow::ensure!(
5488                    nonce_owners.insert(nonce, intent.id).is_none(),
5489                    "Retained execution history has duplicate signer nonce ownership"
5490                );
5491            }
5492
5493            let base_decision = verification_decision(
5494                nonce_verification,
5495                Some(finalized.number),
5496                Some(finalized.number),
5497            );
5498
5499            if !intent.active {
5500                if matches!(intent.status.as_str(), "finalized" | "reverted") {
5501                    let expected_marker =
5502                        if purpose == TransactionPurpose::Swap && intent.status == "finalized" {
5503                            intent.fill_emitted
5504                        } else {
5505                            intent.terminal_emitted
5506                        };
5507                    anyhow::ensure!(
5508                        expected_marker,
5509                        "Released terminal intent {} has no durable event marker",
5510                        intent.id
5511                    );
5512                } else {
5513                    anyhow::ensure!(
5514                        matches!(intent.status.as_str(), "dropped" | "recoverable")
5515                            && authenticated.is_empty(),
5516                        "Released nonterminal intent {} retains signed ownership",
5517                        intent.id
5518                    );
5519                    records.push(ExecutionVerificationMigrationRecord {
5520                        intent_id: intent.id,
5521                        nonce: intent.nonce,
5522                        transaction_hash: None,
5523                        terminal_status: None,
5524                        block_number: None,
5525                        block_hash: None,
5526                        receipt_success: None,
5527                        gas_used: None,
5528                        effective_gas_price: None,
5529                        recover_prepared: false,
5530                        decisions: vec![base_decision],
5531                    });
5532                    continue;
5533                }
5534            }
5535
5536            if intent.active && intent.nonce.is_none() {
5537                anyhow::ensure!(
5538                    intent.status == "prepared" && hashes.is_empty(),
5539                    "Unassigned active intent {} is not an unsigned preparation",
5540                    intent.id
5541                );
5542                records.push(ExecutionVerificationMigrationRecord {
5543                    intent_id: intent.id,
5544                    nonce: None,
5545                    transaction_hash: None,
5546                    terminal_status: None,
5547                    block_number: None,
5548                    block_hash: None,
5549                    receipt_success: None,
5550                    gas_used: None,
5551                    effective_gas_price: None,
5552                    recover_prepared: true,
5553                    decisions: vec![base_decision],
5554                });
5555                continue;
5556            }
5557
5558            let nonce = intent.nonce.ok_or_else(|| {
5559                anyhow::anyhow!("Retained signed intent {} has no nonce", intent.id)
5560            })?;
5561            let current = current.ok_or_else(|| {
5562                anyhow::anyhow!("Retained signed intent {} has no current hash", intent.id)
5563            })?;
5564            let raw_transaction = authenticated.get(&current.id).ok_or_else(|| {
5565                anyhow::anyhow!(
5566                    "Retained signed intent {} has no authenticated current payload",
5567                    intent.id
5568                )
5569            })?;
5570
5571            if intent.active && nonce == next_canonical_nonce {
5572                anyhow::ensure!(
5573                    !matches!(intent.status.as_str(), "finalized" | "reverted"),
5574                    "Active terminal intent conflicts with the canonical nonce ledger"
5575                );
5576                records.push(ExecutionVerificationMigrationRecord {
5577                    intent_id: intent.id,
5578                    nonce: Some(nonce),
5579                    transaction_hash: Some(current.transaction_hash.clone()),
5580                    terminal_status: None,
5581                    block_number: None,
5582                    block_hash: None,
5583                    receipt_success: None,
5584                    gas_used: None,
5585                    effective_gas_price: None,
5586                    recover_prepared: false,
5587                    decisions: vec![base_decision],
5588                });
5589                continue;
5590            }
5591            anyhow::ensure!(
5592                nonce < next_canonical_nonce,
5593                "Retained active nonce {nonce} is above canonical nonce {next_canonical_nonce}"
5594            );
5595
5596            let receipt_verification = required_verification(
5597                self.verification
5598                    .verify_receipt(&B256::from_str(&current.transaction_hash).with_context(
5599                        || {
5600                            format!(
5601                                "Retained transaction hash {} is invalid",
5602                                current.transaction_hash
5603                            )
5604                        },
5605                    )?)
5606                    .await,
5607                "migration receipt",
5608            )?;
5609            let receipt = receipt_verification.value.clone();
5610            anyhow::ensure!(
5611                receipt.block_number <= finalized.number,
5612                "Retained terminal receipt is above the verified finalized boundary"
5613            );
5614            let inclusion_verification = required_verification(
5615                self.verification.verify_block(receipt.block_number).await,
5616                "migration inclusion header",
5617            )?;
5618            anyhow::ensure!(
5619                inclusion_verification.value.hash == receipt.block_hash
5620                    && finalized_headers.iter().any(|header| {
5621                        header.number == receipt.block_number
5622                            && header.hash == receipt.block_hash.to_string()
5623                    }),
5624                "Retained terminal receipt is not on the verified finalized ancestry"
5625            );
5626            let tx_hash = B256::from_str(&current.transaction_hash)
5627                .context("Retained transaction hash is invalid")?;
5628            let included = IncludedTransaction {
5629                intent_id: intent.id,
5630                nonce,
5631                tx_hash,
5632                block_number: receipt.block_number,
5633                receipt: receipt.clone(),
5634                finality: StableFinality {
5635                    decisions: Vec::new(),
5636                    inclusion_header: durable_verified_header(&inclusion_verification.value),
5637                    finalized_headers: finalized_headers.clone(),
5638                },
5639            };
5640            let trace_purpose = match purpose {
5641                TransactionPurpose::Wrap => "wrap",
5642                TransactionPurpose::Approve => "approve",
5643                TransactionPurpose::Swap => {
5644                    match self.restore_swap_plan(intent)?.order.order_side() {
5645                        OrderSide::Sell => "swap_sell",
5646                        OrderSide::Buy => "swap_buy",
5647                    }
5648                }
5649            };
5650            let mut decisions = vec![
5651                verification_decision(
5652                    &receipt_verification,
5653                    Some(receipt.block_number),
5654                    Some(receipt.block_number),
5655                ),
5656                verification_decision(
5657                    &inclusion_verification,
5658                    Some(receipt.block_number),
5659                    Some(receipt.block_number),
5660                ),
5661            ];
5662            decisions.extend(
5663                verify_finalized_transaction_identity(
5664                    &included,
5665                    intent,
5666                    nonce,
5667                    raw_transaction,
5668                    &self.verification,
5669                    self.wallet_address,
5670                    self.chain.chain_id,
5671                    &self
5672                        .config
5673                        .verification
5674                        .as_ref()
5675                        .expect("verification config validated")
5676                        .deployment_manifest,
5677                    trace_purpose,
5678                )
5679                .await?,
5680            );
5681            let terminal_status = if receipt.status {
5682                TransactionStatus::Finalized
5683            } else {
5684                TransactionStatus::Reverted
5685            };
5686
5687            if !intent.active {
5688                anyhow::ensure!(
5689                    intent.status == terminal_status.as_str(),
5690                    "Released terminal intent status conflicts with its verified receipt"
5691                );
5692            }
5693            records.push(ExecutionVerificationMigrationRecord {
5694                intent_id: intent.id,
5695                nonce: Some(nonce),
5696                transaction_hash: Some(current.transaction_hash.clone()),
5697                terminal_status: Some(terminal_status),
5698                block_number: Some(receipt.block_number),
5699                block_hash: Some(receipt.block_hash.to_string()),
5700                receipt_success: Some(receipt.status),
5701                gas_used: Some(receipt.gas_used),
5702                effective_gas_price: Some(receipt.effective_gas_price.to_string()),
5703                recover_prepared: false,
5704                decisions,
5705            });
5706        }
5707
5708        Ok(ExecutionVerificationMigration { snapshot, records })
5709    }
5710}
5711
5712#[async_trait(?Send)]
5713impl ExecutionClient for BlockchainExecutionClient {
5714    fn is_connected(&self) -> bool {
5715        self.core.is_connected()
5716    }
5717
5718    fn client_id(&self) -> ClientId {
5719        self.core.client_id
5720    }
5721
5722    fn account_id(&self) -> AccountId {
5723        self.core.account_id
5724    }
5725
5726    fn venue(&self) -> Venue {
5727        self.core.venue
5728    }
5729
5730    fn handles_order_venue(&self, venue: Venue) -> bool {
5731        venue.parse_dex().is_ok_and(|(blockchain, dex_type)| {
5732            blockchain == self.chain.name && dex_type == DexType::UniswapV3
5733        })
5734    }
5735
5736    fn oms_type(&self) -> OmsType {
5737        self.core.oms_type
5738    }
5739
5740    fn get_account(&self) -> Option<AccountAny> {
5741        self.core.cache().account_owned(&self.core.account_id)
5742    }
5743
5744    fn generate_account_state(
5745        &self,
5746        balances: Vec<AccountBalance>,
5747        margins: Vec<MarginBalance>,
5748        reported: bool,
5749        ts_event: UnixNanos,
5750        info: Option<Params>,
5751    ) -> anyhow::Result<()> {
5752        self.emitter
5753            .try_emit_account_state(balances, margins, reported, ts_event, info)
5754    }
5755
5756    fn start(&mut self) -> anyhow::Result<()> {
5757        if self.core.is_started() {
5758            return Ok(());
5759        }
5760
5761        self.emitter.set_sender(get_exec_event_sender());
5762        self.core.set_started();
5763        log::info!(
5764            "Started: client_id={}, account_id={}",
5765            self.core.client_id,
5766            self.core.account_id
5767        );
5768        Ok(())
5769    }
5770
5771    fn stop(&mut self) -> anyhow::Result<()> {
5772        if self.core.is_stopped() {
5773            return Ok(());
5774        }
5775
5776        self.pending_tasks.begin_shutdown();
5777        self.signer = None;
5778        self.core.set_stopped();
5779        self.core.set_disconnected();
5780        log::info!("Stopped: client_id={}", self.core.client_id);
5781        Ok(())
5782    }
5783
5784    #[allow(
5785        clippy::large_futures,
5786        reason = "keeps transaction verification futures inline without additional boxing"
5787    )]
5788    fn submit_order(&self, cmd: SubmitOrder) -> anyhow::Result<()> {
5789        let order = self.core.cache().try_order_owned(&cmd.client_order_id)?;
5790
5791        if order.is_closed() {
5792            log::warn!("Cannot submit closed order {}", order.client_order_id());
5793            return Ok(());
5794        }
5795
5796        if let Err(reason) = validate_order(&order) {
5797            self.emitter.emit_order_denied(&order, &reason.to_string());
5798            return Ok(());
5799        }
5800
5801        if !self.pending_tasks.is_open() {
5802            self.emitter
5803                .emit_order_denied(&order, "Blockchain execution client is shutting down");
5804            return Ok(());
5805        }
5806
5807        let plan = match self.prepare_swap(&cmd, &order) {
5808            Ok(plan) => plan,
5809            Err(e) => {
5810                self.emitter.emit_order_denied(&order, &e.to_string());
5811                return Ok(());
5812            }
5813        };
5814
5815        let executor = match self.transaction_executor() {
5816            Ok(executor) => executor,
5817            Err(e) => {
5818                self.emitter.emit_order_denied(&order, &e.to_string());
5819                return Ok(());
5820            }
5821        };
5822
5823        let emitter = self.emitter.clone();
5824        let max_quote_age_blocks = self.transaction_limits.max_quote_age_blocks;
5825        let deadline_seconds = self.transaction_limits.deadline_seconds;
5826        let client_order_id = order.client_order_id();
5827
5828        let future = async move {
5829            if let Err(e) = execute_swap(
5830                plan,
5831                executor,
5832                emitter,
5833                max_quote_age_blocks,
5834                deadline_seconds,
5835            )
5836            .await
5837            {
5838                log::warn!("Swap execution for order {client_order_id} failed: {e:?}");
5839            }
5840        };
5841
5842        if let Err(e) = self.pending_tasks.spawn(future) {
5843            release_preparing_slot(&self.in_flight);
5844            log::warn!("Skipping blockchain swap after shutdown began: {e}");
5845        }
5846
5847        Ok(())
5848    }
5849
5850    fn submit_order_list(&self, cmd: SubmitOrderList) -> anyhow::Result<()> {
5851        let orders = self
5852            .core
5853            .cache()
5854            .orders_for_ids(&cmd.order_list.client_order_ids, &cmd);
5855
5856        for order in &orders {
5857            if order.is_closed() {
5858                log::warn!("Cannot submit closed order {}", order.client_order_id());
5859                continue;
5860            }
5861
5862            self.emitter
5863                .emit_order_denied(order, ORDER_LIST_UNSUPPORTED);
5864        }
5865
5866        Ok(())
5867    }
5868
5869    fn modify_order(&self, cmd: ModifyOrder) -> anyhow::Result<()> {
5870        let ts_event = get_atomic_clock_realtime().get_time_ns();
5871
5872        if let Ok(order) = self.core.get_order(&cmd.client_order_id) {
5873            self.emitter.emit_order_modify_denied(
5874                &order,
5875                ORDER_MODIFY_UNSUPPORTED,
5876                ts_event,
5877                Some(cmd.command_id),
5878            );
5879        } else {
5880            self.emitter.emit_order_modify_denied_event(
5881                cmd.strategy_id,
5882                cmd.instrument_id,
5883                cmd.client_order_id,
5884                cmd.venue_order_id,
5885                ORDER_MODIFY_UNSUPPORTED,
5886                ts_event,
5887                Some(cmd.command_id),
5888            );
5889        }
5890
5891        Ok(())
5892    }
5893
5894    fn cancel_order(&self, cmd: CancelOrder) -> anyhow::Result<()> {
5895        let ts_event = get_atomic_clock_realtime().get_time_ns();
5896
5897        if let Ok(order) = self.core.get_order(&cmd.client_order_id) {
5898            self.emitter.emit_order_cancel_denied(
5899                &order,
5900                ORDER_CANCEL_UNSUPPORTED,
5901                ts_event,
5902                Some(cmd.command_id),
5903            );
5904        } else {
5905            self.emitter.emit_order_cancel_denied_event(
5906                cmd.strategy_id,
5907                cmd.instrument_id,
5908                cmd.client_order_id,
5909                cmd.venue_order_id,
5910                ORDER_CANCEL_UNSUPPORTED,
5911                ts_event,
5912                Some(cmd.command_id),
5913            );
5914        }
5915
5916        Ok(())
5917    }
5918
5919    fn cancel_all_orders(&self, cmd: CancelAllOrders) -> anyhow::Result<()> {
5920        log::warn!(
5921            "Cancel-all for {} is not supported on the blockchain execution client",
5922            cmd.instrument_id
5923        );
5924        Ok(())
5925    }
5926
5927    fn batch_cancel_orders(&self, cmd: BatchCancelOrders) -> anyhow::Result<()> {
5928        for cancel in cmd.cancels {
5929            self.cancel_order(cancel)?;
5930        }
5931        Ok(())
5932    }
5933
5934    fn query_account(&self, cmd: QueryAccount) -> anyhow::Result<()> {
5935        anyhow::ensure!(
5936            cmd.account_id == self.core.account_id,
5937            "Query account ID {} does not match client account ID {}",
5938            cmd.account_id,
5939            self.core.account_id
5940        );
5941        anyhow::ensure!(self.core.is_started(), "Execution client is not started");
5942
5943        let balances = self.wallet_balance.lock().as_account_balances()?;
5944        self.generate_account_state(
5945            balances,
5946            vec![],
5947            true,
5948            get_atomic_clock_realtime().get_time_ns(),
5949            None,
5950        )
5951    }
5952
5953    fn query_order(&self, cmd: QueryOrder) -> anyhow::Result<()> {
5954        log::debug!(
5955            "Order queries are not supported on the blockchain execution client; cannot query {}",
5956            cmd.client_order_id
5957        );
5958        Ok(())
5959    }
5960
5961    fn retain_unresolved_submissions(&self) -> bool {
5962        true
5963    }
5964
5965    #[allow(
5966        clippy::large_futures,
5967        reason = "keeps transaction verification futures inline without additional boxing"
5968    )]
5969    async fn connect(&mut self) -> anyhow::Result<()> {
5970        if self.core.is_connected() {
5971            log::warn!("Blockchain execution client already connected");
5972            return Ok(());
5973        }
5974
5975        log::info!(
5976            "Connecting to blockchain execution client on chain {}",
5977            self.chain.name
5978        );
5979
5980        if !self.pending_tasks.is_open() || !self.pending_tasks.is_empty() {
5981            self.pending_tasks.begin_shutdown();
5982            self.pending_tasks
5983                .finish_shutdown(Duration::from_secs(5), Duration::from_secs(2))
5984                .await
5985                .map_err(|e| anyhow::anyhow!("Failed to terminate blockchain submissions: {e}"))?;
5986            self.signer = None;
5987            self.pending_tasks
5988                .start_generation()
5989                .map_err(|e| anyhow::anyhow!("Failed to start blockchain task generation: {e}"))?;
5990        }
5991        release_preparing_slot(&self.in_flight);
5992
5993        let setup_guard = TaskGroupGuard::new(&[&self.pending_tasks], || {});
5994
5995        let payload_keys = PayloadKeySet::load(
5996            self.config.payload_key_env.as_deref(),
5997            &self.config.payload_key_retired_env,
5998            self.config.payload_deployment_id.as_deref(),
5999        )?
6000        .map(Arc::new);
6001
6002        if self.cache.database.is_some() || self.config.postgres_cache_database_config.is_some() {
6003            let keys = payload_keys.as_deref().ok_or_else(|| {
6004                anyhow::anyhow!(
6005                    "Postgres execution requires an active payload key and deployment identity"
6006                )
6007            })?;
6008
6009            if self.cache.database.is_none() {
6010                let pg_options = self
6011                    .config
6012                    .postgres_cache_database_config
6013                    .as_ref()
6014                    .expect("Postgres configuration checked above");
6015                let database = crate::cache::database::BlockchainCacheDatabase::connect(
6016                    pg_options.clone().into(),
6017                )
6018                .await
6019                .map_err(|e| {
6020                    anyhow::anyhow!("Failed to connect to the Postgres cache database: {e}")
6021                })?;
6022                self.cache.database = Some(database);
6023            }
6024            self.cache
6025                .database
6026                .as_ref()
6027                .expect("database was attached")
6028                .require_execution_payload_storage_ready(keys)
6029                .await?;
6030            self.cache.initialize_chain().await;
6031            self.cache.ensure_execution_transaction_schema().await?;
6032            let check = self
6033                .cache
6034                .database
6035                .as_ref()
6036                .expect("database was attached")
6037                .check_execution_payload_storage(
6038                    Some(keys),
6039                    Some(PayloadPolicy {
6040                        chain_id: self.chain.chain_id,
6041                        signer: self.wallet_address,
6042                        gas_limit: self.config.gas_limit,
6043                        max_fee_per_gas: self.config.max_fee_per_gas_wei,
6044                    }),
6045                    100,
6046                )
6047                .await?;
6048            anyhow::ensure!(
6049                check.protected,
6050                "Postgres execution requires protected payload storage"
6051            );
6052        } else {
6053            log::warn!(
6054                "No Postgres cache database configured; transactions will be refused (no durable store)"
6055            );
6056        }
6057        self.payload_keys = payload_keys;
6058
6059        let verification = self
6060            .config
6061            .verification
6062            .as_ref()
6063            .expect("verification config validated at construction");
6064        let position = if let Some(database) = self.cache.database.as_ref() {
6065            database
6066                .load_execution_verification_position(
6067                    self.chain.chain_id,
6068                    &self.config.wallet_address,
6069                    &verification.manifest_version,
6070                    &verification.manifest_digest,
6071                )
6072                .await?
6073        } else {
6074            None
6075        };
6076        let migration_snapshot = if position.is_none() {
6077            if let Some(database) = self.cache.database.as_ref() {
6078                let snapshot = database
6079                    .load_execution_verification_migration_snapshot(
6080                        self.chain.chain_id,
6081                        &self.config.wallet_address,
6082                    )
6083                    .await?;
6084
6085                if snapshot.intents.is_empty() {
6086                    None
6087                } else {
6088                    Some(snapshot)
6089                }
6090            } else {
6091                None
6092            }
6093        } else {
6094            None
6095        };
6096
6097        let chain_id_verification = required_verification(
6098            self.verification.verify_chain_id().await,
6099            "Blockchain chain ID",
6100        )?;
6101        let checkpoint_verification = required_verification(
6102            self.verification.verify_checkpoint().await,
6103            "Blockchain checkpoint",
6104        )?;
6105        let checkpoint = checkpoint_verification.value;
6106        let finalized_verification = required_verification(
6107            self.verification.verify_finalized_header().await,
6108            "Blockchain finalized header",
6109        )?;
6110        let finalized = finalized_verification.value;
6111        let mut connect_decisions = vec![
6112            verification_decision(&chain_id_verification, None, None),
6113            verification_decision(
6114                &checkpoint_verification,
6115                Some(checkpoint.number),
6116                Some(checkpoint.number),
6117            ),
6118            verification_decision(
6119                &finalized_verification,
6120                Some(finalized.number),
6121                Some(finalized.number),
6122            ),
6123        ];
6124        let mut finalized_headers = if let Some(position) = position.as_ref() {
6125            let durable_tip = parse_verified_header(&position.finalized_tip)?;
6126            anyhow::ensure!(
6127                durable_tip.number >= checkpoint.number,
6128                "Durable finalized header tip precedes the trusted checkpoint"
6129            );
6130            let durable_tip_verification = required_verification(
6131                self.verification.verify_block(durable_tip.number).await,
6132                "Blockchain durable finalized tip",
6133            )?;
6134            anyhow::ensure!(
6135                durable_tip_verification.value == durable_tip,
6136                "Durable finalized header tip conflicts with independent sources"
6137            );
6138            connect_decisions.push(verification_decision(
6139                &durable_tip_verification,
6140                Some(durable_tip.number),
6141                Some(durable_tip.number),
6142            ));
6143            vec![durable_tip]
6144        } else {
6145            vec![checkpoint]
6146        };
6147        let mut ancestry_cursor = *finalized_headers
6148            .last()
6149            .expect("finalized header ledger is nonempty");
6150        anyhow::ensure!(
6151            finalized.number >= ancestry_cursor.number,
6152            "Verified finalized height regressed below the durable finalized header tip"
6153        );
6154
6155        while ancestry_cursor.number < finalized.number {
6156            let end = ancestry_cursor
6157                .number
6158                .saturating_add(4_096)
6159                .min(finalized.number);
6160            let start = ancestry_cursor.number.saturating_add(1);
6161            let headers_verification = required_verification(
6162                self.verification
6163                    .verify_header_window(ancestry_cursor, end)
6164                    .await,
6165                "Blockchain finalized ancestry",
6166            )?;
6167            let headers = &headers_verification.value;
6168            ancestry_cursor = *headers
6169                .last()
6170                .expect("nonempty ancestry window advances the cursor");
6171            finalized_headers.extend(headers.iter().copied());
6172            connect_decisions.push(verification_decision(
6173                &headers_verification,
6174                Some(start),
6175                Some(end),
6176            ));
6177        }
6178        anyhow::ensure!(
6179            ancestry_cursor == finalized,
6180            "Verified finalized header conflicts with its ancestry window"
6181        );
6182        let nonce_verification = required_verification(
6183            self.verification
6184                .verify_transaction_count(&self.wallet_address, finalized.number)
6185                .await,
6186            "Blockchain finalized transaction count",
6187        )?;
6188        let observed_canonical_nonce = nonce_verification.value;
6189        let next_canonical_nonce = position
6190            .as_ref()
6191            .map_or(observed_canonical_nonce, |position| {
6192                position.next_canonical_nonce
6193            });
6194
6195        if let Some(position) = position.as_ref() {
6196            log::debug!(
6197                "Resumed execution verification ledger at nonce revision {} with observed finalized nonce {}",
6198                position.revision,
6199                observed_canonical_nonce,
6200            );
6201        }
6202        connect_decisions.push(verification_decision(
6203            &nonce_verification,
6204            Some(finalized.number),
6205            Some(finalized.number),
6206        ));
6207        let deployment_verification = required_verification(
6208            self.verification
6209                .verify_deployment_manifest(&verification.deployment_manifest, finalized.number)
6210                .await,
6211            "Blockchain deployment manifest",
6212        )?;
6213        connect_decisions.push(verification_decision(
6214            &deployment_verification,
6215            Some(finalized.number),
6216            Some(finalized.number),
6217        ));
6218        connect_decisions.extend(
6219            verify_connect_capabilities(
6220                &self.verification,
6221                &verification.deployment_manifest,
6222                self.wallet_address,
6223                self.weth_address,
6224                finalized.number,
6225            )
6226            .await?,
6227        );
6228        let migration = if let Some(snapshot) = migration_snapshot {
6229            Some(
6230                self.build_execution_verification_migration(
6231                    snapshot,
6232                    finalized,
6233                    &finalized_headers,
6234                    &nonce_verification,
6235                )
6236                .await?,
6237            )
6238        } else {
6239            None
6240        };
6241
6242        if let Some(database) = self.cache.database.as_ref() {
6243            let identities = std::iter::once(&verification.authoritative)
6244                .chain(
6245                    verification
6246                        .verifiers
6247                        .iter()
6248                        .map(|provider| &provider.identity),
6249                )
6250                .collect::<Vec<_>>();
6251            let provider_ids = identities
6252                .iter()
6253                .map(|identity| identity.provider_id.clone())
6254                .collect::<Vec<_>>();
6255            let operator_ids = identities
6256                .iter()
6257                .map(|identity| identity.operator_id.clone())
6258                .collect::<Vec<_>>();
6259            let failure_domain_ids = identities
6260                .iter()
6261                .flat_map(|identity| identity.failure_domain_ids.iter().cloned())
6262                .collect::<Vec<_>>();
6263            let finalized_headers = finalized_headers
6264                .iter()
6265                .map(durable_verified_header)
6266                .collect::<Vec<_>>();
6267            database
6268                .ensure_execution_verification_schema(&ExecutionVerificationBootstrap {
6269                    chain_id: self.chain.chain_id,
6270                    wallet_address: &self.config.wallet_address,
6271                    manifest_version: &verification.manifest_version,
6272                    manifest_digest: &verification.manifest_digest,
6273                    checkpoint_number: checkpoint.number,
6274                    checkpoint_hash: &checkpoint.hash.to_string(),
6275                    checkpoint_parent_hash: &checkpoint.parent_hash.to_string(),
6276                    checkpoint_timestamp: checkpoint.timestamp,
6277                    checkpoint_base_fee_per_gas: checkpoint.base_fee_per_gas,
6278                    finalized_headers: &finalized_headers,
6279                    next_canonical_nonce,
6280                    observed_canonical_nonce,
6281                    provider_ids: &provider_ids,
6282                    operator_ids: &operator_ids,
6283                    failure_domain_ids: &failure_domain_ids,
6284                    decisions: &connect_decisions,
6285                    migration: migration.as_ref(),
6286                })
6287                .await?;
6288        }
6289
6290        let payload_connect_lease = if let (Some(database), Some(keys)) =
6291            (self.cache.database.as_ref(), self.payload_keys.as_deref())
6292        {
6293            Some(
6294                database
6295                    .require_execution_payload_storage(keys, self.payload_policy(), 100)
6296                    .await?,
6297            )
6298        } else {
6299            None
6300        };
6301
6302        // Load the signer key from the configured environment variable; the key is never
6303        // logged, serialized, or stored in configuration
6304        let private_key = Zeroizing::new(
6305            std::env::var(&self.config.signer_private_key_env).map_err(|_| {
6306                anyhow::anyhow!(
6307                    "Signer private key environment variable '{}' is not set",
6308                    self.config.signer_private_key_env
6309                )
6310            })?,
6311        );
6312        let encoded_key = private_key.trim();
6313        let encoded_key = encoded_key.strip_prefix("0x").unwrap_or(encoded_key);
6314        let key_bytes = Zeroizing::new(hex::decode_array::<32>(encoded_key).map_err(|_| {
6315            anyhow::anyhow!(
6316                "Signer private key in '{}' is not a valid hex private key",
6317                self.config.signer_private_key_env
6318            )
6319        })?);
6320        let signer = PrivateKeySigner::from_slice(&key_bytes[..]).map_err(|_| {
6321            anyhow::anyhow!(
6322                "Signer private key in '{}' is not a valid secp256k1 private key",
6323                self.config.signer_private_key_env
6324            )
6325        })?;
6326
6327        if signer.address() != self.wallet_address {
6328            anyhow::bail!(
6329                "Signer address {} derived from '{}' does not match configured wallet address {}",
6330                signer.address(),
6331                self.config.signer_private_key_env,
6332                self.wallet_address
6333            );
6334        }
6335
6336        self.signer = Some(Arc::new(signer));
6337        drop(payload_connect_lease);
6338
6339        if self.cache.has_database()
6340            && let Err(e) = self.reconcile_unresolved_execution().await
6341        {
6342            self.signer = None;
6343            return Err(e);
6344        }
6345
6346        if let Err(e) = self.refresh_wallet_balances().await {
6347            self.signer = None;
6348            return Err(e);
6349        }
6350
6351        self.register_migration_check();
6352        self.core.set_connected();
6353        setup_guard.disarm();
6354        log::info!(
6355            "Blockchain execution client connected on chain {}",
6356            self.chain.name
6357        );
6358        Ok(())
6359    }
6360
6361    async fn disconnect(&mut self) -> anyhow::Result<()> {
6362        self.pending_tasks.begin_shutdown();
6363        let tasks_result = self
6364            .pending_tasks
6365            .finish_shutdown(Duration::from_secs(5), Duration::from_secs(2))
6366            .await;
6367        self.signer = None;
6368        self.core.set_disconnected();
6369        tasks_result
6370            .map_err(|e| anyhow::anyhow!("Failed to terminate blockchain submissions: {e}"))?;
6371        Ok(())
6372    }
6373
6374    async fn generate_order_status_report(
6375        &self,
6376        _cmd: &GenerateOrderStatusReport,
6377    ) -> anyhow::Result<Option<OrderStatusReport>> {
6378        anyhow::bail!("{VENUE_EXECUTION_REPORTS_UNSUPPORTED}");
6379    }
6380
6381    async fn generate_order_status_reports(
6382        &self,
6383        _cmd: &GenerateOrderStatusReports,
6384    ) -> anyhow::Result<Vec<OrderStatusReport>> {
6385        anyhow::bail!("{VENUE_EXECUTION_REPORTS_UNSUPPORTED}");
6386    }
6387
6388    async fn generate_fill_reports(
6389        &self,
6390        _cmd: GenerateFillReports,
6391    ) -> anyhow::Result<Vec<FillReport>> {
6392        anyhow::bail!("{VENUE_EXECUTION_REPORTS_UNSUPPORTED}");
6393    }
6394
6395    async fn generate_position_status_reports(
6396        &self,
6397        _cmd: &GeneratePositionStatusReports,
6398    ) -> anyhow::Result<Vec<PositionStatusReport>> {
6399        anyhow::bail!("{VENUE_EXECUTION_REPORTS_UNSUPPORTED}");
6400    }
6401
6402    async fn generate_mass_status(
6403        &self,
6404        _lookback_mins: Option<u64>,
6405    ) -> anyhow::Result<Option<ExecutionMassStatus>> {
6406        // Venue mass status is unsupported; durable intent reconciliation at connect
6407        // covers restart recovery, and Ok(None) keeps LiveNode startup safe
6408        log::info!(
6409            "Mass status is not supported on the blockchain execution client; skipping venue reconciliation"
6410        );
6411        Ok(None)
6412    }
6413}
6414
6415fn validate_order(order: &impl Order) -> Result<(), OrderDeniedReason> {
6416    if order.is_reduce_only() {
6417        return Err(OrderDeniedReason::UnsupportedReduceOnly);
6418    }
6419
6420    Ok(())
6421}
6422
6423#[cfg(test)]
6424mod tests {
6425    #![allow(
6426        clippy::large_futures,
6427        reason = "exercises inline transaction futures without changing their allocation behavior"
6428    )]
6429
6430    use std::{
6431        cell::RefCell,
6432        rc::Rc,
6433        sync::atomic::{AtomicU64, Ordering},
6434    };
6435
6436    use alloy::{
6437        primitives::{address, aliases::I24},
6438        sol_types::SolValue,
6439    };
6440    use nautilus_common::{
6441        cache::Cache,
6442        clock::{Clock, VirtualClock},
6443        live::runner::replace_exec_event_sender,
6444        messages::{ExecutionEvent, execution::TradingCommand},
6445        testing::wait_until_async,
6446    };
6447    use nautilus_core::UUID4;
6448    use nautilus_infrastructure::sql::pg::{PostgresConnectOptions, get_postgres_connect_options};
6449    use nautilus_live::{
6450        execution::{
6451            config::ExecutionManagerConfig,
6452            submission::{SubmissionRecoveryExhausted, SubmissionRecoverySource},
6453        },
6454        manager::ExecutionManager,
6455    };
6456    use nautilus_model::{
6457        defi::{
6458            PoolProfiler,
6459            chain::chains,
6460            data::block::BlockPosition,
6461            pool_analysis::{
6462                position::PoolPosition,
6463                snapshot::{PoolAnalytics, PoolSnapshot, PoolState},
6464            },
6465            tick_map::{tick::PoolTick, tick_math::get_tick_at_sqrt_ratio},
6466        },
6467        enums::{AccountType, CurrencyType},
6468        events::{OrderEventAny, OrderPendingCancel, OrderPendingUpdate},
6469        identifiers::{OrderListId, StrategyId, TraderId},
6470        orders::{OrderList, OrderTestBuilder, stubs::TestOrderEventStubs},
6471        types::Price,
6472    };
6473    use rstest::rstest;
6474    use sqlx::postgres::{PgAdvisoryLock, PgAdvisoryLockKey, PgPoolOptions};
6475    use ustr::Ustr;
6476
6477    use super::*;
6478    use crate::{
6479        cache::database::tests::connect_test_database,
6480        config::{
6481            BlockchainCallEdgeManifest, BlockchainChainAnchorConfig, BlockchainContractManifest,
6482            BlockchainContractProbe, BlockchainContractRole, BlockchainDeploymentManifest,
6483            BlockchainPoolManifest, BlockchainProviderIdentity, BlockchainTokenManifest,
6484            BlockchainVerificationConfig, BlockchainVerificationProviderConfig, QuoteSpendLimit,
6485        },
6486        constants::BLOCKCHAIN_VENUE,
6487        exchanges::arbitrum::UNISWAP_V3,
6488        rpc::http::{
6489            EXECUTION_RPC_TIMEOUT_SECS,
6490            tests::mock::{MockRpcState, start_mock_rpc_server},
6491        },
6492    };
6493
6494    /// Polls for the receipt of a broadcast transaction until it exists or the poll bound
6495    /// is exhausted. A `null` receipt result is a legitimate pending response.
6496    async fn poll_for_receipt(
6497        http_rpc_client: &BlockchainHttpRpcClient,
6498        tx_hash: &B256,
6499        max_polls: u32,
6500        interval: Duration,
6501    ) -> anyhow::Result<Option<RpcTransactionReceipt>> {
6502        let mut last_error = None;
6503        let mut observed_pending = false;
6504
6505        for attempt in 0..max_polls {
6506            if attempt > 0 {
6507                tokio::time::sleep(interval).await;
6508            }
6509
6510            match http_rpc_client.get_transaction_receipt(tx_hash).await {
6511                Ok(Some(receipt)) => return Ok(Some(receipt)),
6512                Ok(None) => observed_pending = true,
6513                Err(e) => {
6514                    log::warn!(
6515                        "Receipt poll {}/{} for transaction {tx_hash} failed: {e}",
6516                        attempt + 1,
6517                        max_polls
6518                    );
6519                    last_error = Some(e);
6520                }
6521            }
6522        }
6523
6524        if !observed_pending && let Some(e) = last_error {
6525            return Err(e);
6526        }
6527
6528        Ok(None)
6529    }
6530
6531    const CHAIN_ID_ARBITRUM: &str =
6532        include_str!("../../test_data/execution/rpc_eth_chain_id_arbitrum.json");
6533    const CHAIN_ID_ETHEREUM: &str =
6534        include_str!("../../test_data/execution/rpc_eth_chain_id_ethereum.json");
6535    const GET_CODE_DEPLOYED: &str =
6536        include_str!("../../test_data/execution/rpc_eth_get_code_deployed.json");
6537    const GET_CODE_EMPTY: &str =
6538        include_str!("../../test_data/execution/rpc_eth_get_code_empty.json");
6539    const GET_BALANCE: &str = include_str!("../../test_data/execution/rpc_eth_get_balance.json");
6540    const GET_BALANCE_ZERO: &str =
6541        include_str!("../../test_data/execution/rpc_eth_get_balance_zero.json");
6542    const GET_BALANCE_INSUFFICIENT: &str =
6543        include_str!("../../test_data/execution/rpc_eth_get_balance_insufficient.json");
6544    const CALL_BALANCE: &str = include_str!("../../test_data/execution/rpc_eth_call_balance.json");
6545    const CALL_BALANCE_AFTER_WRAP: &str =
6546        include_str!("../../test_data/execution/rpc_eth_call_balance_after_wrap.json");
6547    const CALL_BALANCE_WETH: &str =
6548        include_str!("../../test_data/execution/rpc_eth_call_balance_weth.json");
6549    const CALL_BALANCE_USDC: &str =
6550        include_str!("../../test_data/execution/rpc_eth_call_balance_usdc.json");
6551    const CALL_BALANCE_WETH_UPDATED: &str =
6552        include_str!("../../test_data/execution/rpc_eth_call_balance_weth_updated.json");
6553    const CALL_BALANCE_USDC_UPDATED: &str =
6554        include_str!("../../test_data/execution/rpc_eth_call_balance_usdc_updated.json");
6555    const CALL_BOOL_TRUE: &str =
6556        include_str!("../../test_data/execution/rpc_eth_call_bool_true.json");
6557    const CALL_EMPTY: &str = include_str!("../../test_data/execution/rpc_eth_call_empty.json");
6558    const CALL_ZERO: &str = include_str!("../../test_data/execution/rpc_eth_call_zero.json");
6559    const CALL_ALLOWANCE: &str =
6560        include_str!("../../test_data/execution/rpc_eth_call_allowance.json");
6561    const CALL_ALLOWANCE_1000: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x00000000000000000000000000000000000000000000000000000000000003e8\"}";
6562    const CALL_ALLOWANCE_MAX: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"}";
6563    const CALL_FACTORY: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f984\"}";
6564    const CALL_WETH: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1\"}";
6565    const CALL_USDC: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x000000000000000000000000af88d065e77c8cc2239327c5edb3a432268e5831\"}";
6566    const CALL_FEE_500: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x00000000000000000000000000000000000000000000000000000000000001f4\"}";
6567    const CALL_POOL: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x000000000000000000000000c6962004f452be9203591991d15f6b388e09e8d0\"}";
6568    const CALL_REVERTED: &str =
6569        r#"{"jsonrpc":"2.0","id":1,"error":{"code":3,"message":"execution reverted"}}"#;
6570    const STORAGE_ZERO: &str = r#"{"jsonrpc":"2.0","id":1,"result":"0x0000000000000000000000000000000000000000000000000000000000000000"}"#;
6571    const TRACE_UNKNOWN_TRANSACTION: &str =
6572        r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"transaction not found"}}"#;
6573    const CALL_DECIMALS_18: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x0000000000000000000000000000000000000000000000000000000000000012\"}";
6574    const CALL_DECIMALS_6: &str = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x0000000000000000000000000000000000000000000000000000000000000006\"}";
6575    const TRANSACTION_COUNT: &str =
6576        include_str!("../../test_data/execution/rpc_eth_get_transaction_count.json");
6577    const TRANSACTION_COUNT_NEXT: &str =
6578        include_str!("../../test_data/execution/rpc_eth_get_transaction_count_next.json");
6579    const ESTIMATE_GAS: &str = include_str!("../../test_data/execution/rpc_eth_estimate_gas.json");
6580    const MAX_PRIORITY_FEE: &str =
6581        include_str!("../../test_data/execution/rpc_eth_max_priority_fee_per_gas.json");
6582    const BLOCK_BY_NUMBER: &str =
6583        include_str!("../../test_data/execution/rpc_eth_get_block_by_number.json");
6584    const BLOCK_CANONICAL: &str =
6585        include_str!("../../test_data/execution/rpc_eth_get_block_canonical.json");
6586    const BLOCK_FINALIZED: &str =
6587        include_str!("../../test_data/execution/rpc_eth_get_block_finalized.json");
6588    const RECEIPT_SUCCESS: &str =
6589        include_str!("../../test_data/execution/rpc_eth_get_transaction_receipt_success.json");
6590    const RECEIPT_REVERTED: &str =
6591        include_str!("../../test_data/execution/rpc_eth_get_transaction_receipt_reverted.json");
6592    const RECEIPT_NULL: &str =
6593        include_str!("../../test_data/execution/rpc_eth_get_transaction_receipt_null.json");
6594    const SEND_RAW_TRANSACTION: &str =
6595        include_str!("../../test_data/execution/rpc_eth_send_raw_transaction.json");
6596    const SEND_RAW_TRANSACTION_REJECTED: &str =
6597        include_str!("../../test_data/execution/rpc_eth_send_raw_transaction_rejected.json");
6598    const SEND_RAW_TRANSACTION_NONCE_TOO_LOW: &str =
6599        include_str!("../../test_data/execution/rpc_eth_send_raw_transaction_nonce_too_low.json");
6600    const RPC_METHOD_NOT_FOUND: &str =
6601        include_str!("../../test_data/execution/rpc_error_method_not_found.json");
6602
6603    const WALLET: &str = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266";
6604    const ROUTER: &str = "0xE592427A0AEce92De3Edee1F18E0157C05861564";
6605    const WETH: &str = "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1";
6606    const USDC: &str = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831";
6607    const TEST_TIMEOUT: Duration = Duration::from_secs(10);
6608
6609    const WETH_ADDRESS: Address = address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1");
6610    const USDC_ADDRESS: Address = address!("af88d065e77c8cC2239327C5EDb3A432268e5831");
6611    const ROUTER_ADDRESS: Address = address!("E592427A0AEce92De3Edee1F18E0157C05861564");
6612
6613    // Anvil development key for WALLET (public, test-only)
6614    const TEST_PRIVATE_KEY: &str =
6615        "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
6616
6617    const BALANCE_OF_SELECTOR: &str = "0x70a08231";
6618    const ALLOWANCE_SELECTOR: &str = "0xdd62ed3e";
6619    const POOL_TOKEN0_SELECTOR: &str = "0x0dfe1681";
6620    const POOL_TOKEN1_SELECTOR: &str = "0xd21220a7";
6621    const POOL_FEE_SELECTOR: &str = "0xddca3f43";
6622    const DECIMALS_SELECTOR: &str = "0x313ce567";
6623    const FACTORY_SELECTOR: &str = "0xc45a0155";
6624    const WETH9_SELECTOR: &str = "0x4aa4a4fc";
6625    const GET_POOL_SELECTOR: &str = "0x1698ee82";
6626    const QUOTE_EXACT_INPUT_SELECTOR: &str = "0xc6a5026a";
6627    const QUOTE_EXACT_OUTPUT_SELECTOR: &str = "0xbd21704a";
6628
6629    fn test_pool() -> Pool {
6630        let chain = Arc::new(chains::ARBITRUM.clone());
6631        let dex = Arc::clone(&UNISWAP_V3.dex);
6632        let weth = Token::new(
6633            Arc::clone(&chain),
6634            address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
6635            "Wrapped Ether".to_string(),
6636            "WETH".to_string(),
6637            18,
6638        );
6639        let usdc = Token::new(
6640            Arc::clone(&chain),
6641            address!("af88d065e77c8cC2239327C5EDb3A432268e5831"),
6642            "USD Coin".to_string(),
6643            "USDC".to_string(),
6644            6,
6645        );
6646
6647        Pool::new(
6648            chain,
6649            dex,
6650            address!("C6962004f452bE9203591991D15f6b388e09E8D0"),
6651            PoolIdentifier::from_address(address!("C6962004f452bE9203591991D15f6b388e09E8D0")),
6652            55_000_000,
6653            weth,
6654            usdc,
6655            Some(500),
6656            Some(10),
6657            UnixNanos::default(),
6658        )
6659    }
6660
6661    fn test_config(http_rpc_url: String) -> BlockchainExecutionClientConfig {
6662        test_config_with_signer_env(http_rpc_url, "BLOCKCHAIN_TEST_PRIVATE_KEY")
6663    }
6664
6665    fn test_config_with_signer_env(
6666        http_rpc_url: String,
6667        signer_env: &str,
6668    ) -> BlockchainExecutionClientConfig {
6669        let verifier_separator = if http_rpc_url.contains('?') { '&' } else { '?' };
6670        let code_hash = keccak256(
6671            hex::decode("6080604052348015600e575f5ffd5b5060").expect("valid test bytecode"),
6672        )
6673        .to_string();
6674        let result = |response: &str| {
6675            serde_json::from_str::<serde_json::Value>(response).unwrap()["result"]
6676                .as_str()
6677                .unwrap()
6678                .to_string()
6679        };
6680        let probe = |call_data: &str, expected_output: String| BlockchainContractProbe {
6681            call_data: call_data.to_string(),
6682            expected_output,
6683        };
6684        let contract = |address: &str, role| {
6685            let probes = match role {
6686                BlockchainContractRole::Router => vec![
6687                    probe(FACTORY_SELECTOR, result(CALL_FACTORY)),
6688                    probe(WETH9_SELECTOR, result(CALL_WETH)),
6689                ],
6690                BlockchainContractRole::Factory => vec![probe(
6691                    &hex::encode_prefixed(
6692                        UniswapV3Factory::getPoolCall {
6693                            tokenA: WETH_ADDRESS,
6694                            tokenB: USDC_ADDRESS,
6695                            fee: U24::try_from(500u32).unwrap(),
6696                        }
6697                        .abi_encode(),
6698                    ),
6699                    result(CALL_POOL),
6700                )],
6701                BlockchainContractRole::WrappedNative => {
6702                    vec![probe(DECIMALS_SELECTOR, result(CALL_DECIMALS_18))]
6703                }
6704                BlockchainContractRole::Quote => {
6705                    vec![probe(FACTORY_SELECTOR, result(CALL_FACTORY))]
6706                }
6707                BlockchainContractRole::Token => {
6708                    vec![probe(DECIMALS_SELECTOR, result(CALL_DECIMALS_6))]
6709                }
6710                BlockchainContractRole::Pool => vec![
6711                    probe(POOL_TOKEN0_SELECTOR, result(CALL_WETH)),
6712                    probe(POOL_TOKEN1_SELECTOR, result(CALL_USDC)),
6713                    probe(POOL_FEE_SELECTOR, result(CALL_FEE_500)),
6714                ],
6715                BlockchainContractRole::Implementation => Vec::new(),
6716            };
6717            BlockchainContractManifest {
6718                address: address.to_string(),
6719                role,
6720                runtime_code_hash: code_hash.clone(),
6721                proxy: None,
6722                probes,
6723            }
6724        };
6725        let deployment_manifest = BlockchainDeploymentManifest {
6726            version: "test-v1".to_string(),
6727            chain_id: chains::ARBITRUM.chain_id,
6728            chain_name: chains::ARBITRUM.name.to_string(),
6729            contracts: vec![
6730                contract(ROUTER, BlockchainContractRole::Router),
6731                contract(
6732                    "0x1F98431c8aD98523631AE4a59f267346ea31F984",
6733                    BlockchainContractRole::Factory,
6734                ),
6735                contract(WETH, BlockchainContractRole::WrappedNative),
6736                contract(
6737                    "0x61fFE014bA17989E743c5F6cB21bF9697530B21e",
6738                    BlockchainContractRole::Quote,
6739                ),
6740                contract(USDC, BlockchainContractRole::Token),
6741                contract(
6742                    "0xC6962004f452bE9203591991D15f6b388e09E8D0",
6743                    BlockchainContractRole::Pool,
6744                ),
6745            ],
6746            tokens: vec![
6747                BlockchainTokenManifest {
6748                    address: WETH.to_string(),
6749                    name: "Wrapped Ether".to_string(),
6750                    symbol: "WETH".to_string(),
6751                    decimals: 18,
6752                    asset_role: "both".to_string(),
6753                },
6754                BlockchainTokenManifest {
6755                    address: USDC.to_string(),
6756                    name: "USD Coin".to_string(),
6757                    symbol: "USDC".to_string(),
6758                    decimals: 6,
6759                    asset_role: "both".to_string(),
6760                },
6761            ],
6762            pools: vec![BlockchainPoolManifest {
6763                address: "0xC6962004f452bE9203591991D15f6b388e09E8D0".to_string(),
6764                token0: WETH.to_string(),
6765                token1: USDC.to_string(),
6766                fee: 500,
6767                factory: "0x1F98431c8aD98523631AE4a59f267346ea31F984".to_string(),
6768                quote_contract: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e".to_string(),
6769            }],
6770            call_edges: ["swap_sell", "swap_buy"]
6771                .into_iter()
6772                .map(|purpose| BlockchainCallEdgeManifest {
6773                    purpose: purpose.to_string(),
6774                    caller: ROUTER.to_string(),
6775                    target: "0xC6962004f452bE9203591991D15f6b388e09E8D0".to_string(),
6776                    call_type: "call".to_string(),
6777                })
6778                .collect(),
6779        };
6780        let manifest_digest =
6781            keccak256(serde_json::to_vec(&deployment_manifest).unwrap()).to_string();
6782        let verification = BlockchainVerificationConfig {
6783            authoritative: BlockchainProviderIdentity {
6784                provider_id: "authoritative".to_string(),
6785                operator_id: "operator-a".to_string(),
6786                failure_domain_ids: vec!["domain-a".to_string()],
6787            },
6788            verifiers: vec![
6789                BlockchainVerificationProviderConfig {
6790                    identity: BlockchainProviderIdentity {
6791                        provider_id: "verifier-a".to_string(),
6792                        operator_id: "operator-b".to_string(),
6793                        failure_domain_ids: vec!["domain-b".to_string()],
6794                    },
6795                    http_rpc_url: format!("{http_rpc_url}{verifier_separator}source=verifier-a")
6796                        .into(),
6797                },
6798                BlockchainVerificationProviderConfig {
6799                    identity: BlockchainProviderIdentity {
6800                        provider_id: "verifier-b".to_string(),
6801                        operator_id: "operator-c".to_string(),
6802                        failure_domain_ids: vec!["domain-c".to_string()],
6803                    },
6804                    http_rpc_url: format!("{http_rpc_url}{verifier_separator}source=verifier-b")
6805                        .into(),
6806                },
6807            ],
6808            chain_anchor: BlockchainChainAnchorConfig {
6809                chain_id: chains::ARBITRUM.chain_id,
6810                chain_name: chains::ARBITRUM.name.to_string(),
6811                checkpoint_height: 30_346_560,
6812                checkpoint_hash:
6813                    "0x1111111111111111111111111111111111111111111111111111111111111111".to_string(),
6814                checkpoint_timestamp: 1_761_888_800,
6815                max_head_skew_blocks: 3,
6816                max_head_age_secs: u64::MAX,
6817                max_future_drift_secs: u64::MAX,
6818            },
6819            manifest_version: "test-v1".to_string(),
6820            manifest_digest,
6821            deployment_manifest,
6822        };
6823        BlockchainExecutionClientConfig::builder()
6824            .client_id(AccountId::from("BLOCKCHAIN-001"))
6825            .chain(chains::ARBITRUM.clone())
6826            .wallet_address(WALLET.to_string())
6827            .http_rpc_url(http_rpc_url.into())
6828            .verification(verification)
6829            .signer_private_key_env(signer_env.to_string())
6830            .router_addresses(vec![ROUTER.to_string()])
6831            .weth_address(WETH.to_string())
6832            .max_fee_per_gas_wei(1_000_000_000)
6833            .base_fee_buffer_bps(2_000)
6834            .gas_limit(1_000_000)
6835            .gas_buffer_bps(2_000)
6836            .allowed_token_pairs(vec![(WETH.to_string(), USDC.to_string())])
6837            .slippage_bps(50)
6838            .max_slippage_bps(200)
6839            .max_order_amount(1_000_000_000_000_000_000)
6840            .deadline_seconds(300)
6841            .max_quote_age_blocks(100)
6842            .receipt_timeout_secs(1)
6843            .build()
6844    }
6845
6846    fn buy_test_config(http_rpc_url: String) -> BlockchainExecutionClientConfig {
6847        let max_amount = expected_buy_amount_in().to_string();
6848        let mut config = test_config(http_rpc_url);
6849        config.allowed_token_pairs = Some(vec![
6850            (WETH.to_string(), USDC.to_string()),
6851            (USDC.to_string(), WETH.to_string()),
6852        ]);
6853        config.quote_spend_limits = Some(vec![quote_spend_limit(USDC, WETH, 6, &max_amount)]);
6854        config
6855    }
6856
6857    fn refresh_test_manifest_digest(config: &mut BlockchainExecutionClientConfig) {
6858        let verification = config.verification.as_mut().unwrap();
6859        verification.manifest_digest =
6860            keccak256(serde_json::to_vec(&verification.deployment_manifest).unwrap()).to_string();
6861    }
6862
6863    fn quote_spend_limit(
6864        token_in: &str,
6865        token_out: &str,
6866        spend_token_decimals: u8,
6867        max_amount: &str,
6868    ) -> QuoteSpendLimit {
6869        QuoteSpendLimit::builder()
6870            .token_in(token_in.to_string())
6871            .token_out(token_out.to_string())
6872            .spend_token(token_in.to_string())
6873            .spend_token_decimals(spend_token_decimals)
6874            .max_amount(max_amount.to_string())
6875            .build()
6876    }
6877
6878    fn test_client_from_config(
6879        config: BlockchainExecutionClientConfig,
6880        pool: Pool,
6881    ) -> BlockchainExecutionClient {
6882        test_client_result(config, pool).unwrap()
6883    }
6884
6885    fn test_client_result(
6886        config: BlockchainExecutionClientConfig,
6887        pool: Pool,
6888    ) -> anyhow::Result<BlockchainExecutionClient> {
6889        test_client_and_cache(config, pool).map(|(client, _)| client)
6890    }
6891
6892    fn test_client_and_cache(
6893        config: BlockchainExecutionClientConfig,
6894        pool: Pool,
6895    ) -> anyhow::Result<(BlockchainExecutionClient, Rc<RefCell<Cache>>)> {
6896        let cache = Rc::new(RefCell::new(Cache::default()));
6897        cache.borrow_mut().add_pool(pool).unwrap();
6898        let core = ExecutionClientCore::new(
6899            TraderId::from("TRADER-001"),
6900            ClientId::from("BLOCKCHAIN-001"),
6901            *BLOCKCHAIN_VENUE,
6902            OmsType::Netting,
6903            AccountId::from("BLOCKCHAIN-001"),
6904            AccountType::Wallet,
6905            None,
6906            Rc::clone(&cache),
6907        );
6908
6909        let client = BlockchainExecutionClient::new(core, config)?;
6910        Ok((client, cache))
6911    }
6912
6913    fn test_client(http_rpc_url: String) -> BlockchainExecutionClient {
6914        test_client_from_config(test_config(http_rpc_url), test_pool())
6915    }
6916
6917    async fn client_with_mock_rpc(
6918        state: MockRpcState,
6919    ) -> (BlockchainExecutionClient, MockRpcState) {
6920        let addr = start_mock_rpc_server(state.clone()).await;
6921        (test_client(format!("http://{addr}")), state)
6922    }
6923
6924    async fn client_with_token_mock_rpc(
6925        state: MockRpcState,
6926        signer_env: &str,
6927    ) -> (BlockchainExecutionClient, MockRpcState, Rc<RefCell<Cache>>) {
6928        let state = with_connect_capabilities(state);
6929        let addr = start_mock_rpc_server(state.clone()).await;
6930        let pool = test_pool();
6931        let tokens = [pool.token0.clone(), pool.token1.clone()];
6932        let mut config = test_config_with_signer_env(format!("http://{addr}"), signer_env);
6933        config.tokens = Some(vec![WETH.to_string(), USDC.to_string()]);
6934        let (mut client, cache) = test_client_and_cache(config, pool).unwrap();
6935        for token in tokens {
6936            client.cache.add_token(token).await.unwrap();
6937        }
6938        (client, state, cache)
6939    }
6940
6941    fn execution_rpc_state() -> MockRpcState {
6942        MockRpcState::default()
6943            .with_receipt_hash_from_request()
6944            .with_response("eth_chainId", CHAIN_ID_ARBITRUM)
6945            .with_response("eth_getCode", GET_CODE_DEPLOYED)
6946            .with_response("eth_getBalance", GET_BALANCE)
6947            .with_response("eth_getBlockByNumber", BLOCK_BY_NUMBER)
6948            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
6949            .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", BLOCK_CANONICAL)
6950            .with_parameter_response("eth_getBlockByNumber", "finalized", BLOCK_FINALIZED)
6951            .with_parameter_response("eth_getBlockByNumber", "0x1cf0d42", BLOCK_FINALIZED)
6952            .with_response("eth_maxPriorityFeePerGas", MAX_PRIORITY_FEE)
6953            .with_call_response(FACTORY_SELECTOR, CALL_FACTORY)
6954            .with_call_response(WETH9_SELECTOR, CALL_WETH)
6955            .with_call_response(GET_POOL_SELECTOR, CALL_POOL)
6956            .with_call_response(POOL_TOKEN0_SELECTOR, CALL_WETH)
6957            .with_call_response(POOL_TOKEN1_SELECTOR, CALL_USDC)
6958            .with_call_response(POOL_FEE_SELECTOR, CALL_FEE_500)
6959            .with_contract_call_response(WETH, DECIMALS_SELECTOR, CALL_DECIMALS_18)
6960            .with_contract_call_response(USDC, DECIMALS_SELECTOR, CALL_DECIMALS_6)
6961            .with_call_response(
6962                QUOTE_EXACT_INPUT_SELECTOR,
6963                &quote_response(expected_sell_quote_amount()),
6964            )
6965            .with_call_response(
6966                QUOTE_EXACT_OUTPUT_SELECTOR,
6967                &quote_response(expected_buy_amount_in()),
6968            )
6969    }
6970
6971    fn ready_rpc_state() -> MockRpcState {
6972        with_connect_capabilities(execution_rpc_state())
6973            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE)
6974            .with_call_response(ALLOWANCE_SELECTOR, CALL_ALLOWANCE)
6975    }
6976
6977    fn with_connect_capabilities(state: MockRpcState) -> MockRpcState {
6978        state
6979            .with_response("eth_getStorageAt", STORAGE_ZERO)
6980            .with_response("eth_estimateGas", ESTIMATE_GAS)
6981            .with_parameter_response(
6982                "debug_traceTransaction",
6983                &B256::ZERO.to_string(),
6984                TRACE_UNKNOWN_TRANSACTION,
6985            )
6986    }
6987
6988    fn signing_rpc_state() -> MockRpcState {
6989        ready_rpc_state()
6990            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
6991            .with_response("eth_estimateGas", ESTIMATE_GAS)
6992    }
6993
6994    fn broadcast_rpc_state() -> MockRpcState {
6995        execution_rpc_state()
6996            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
6997            .with_response("eth_estimateGas", ESTIMATE_GAS)
6998            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS)
6999            .with_send_raw_transaction_echo()
7000            .with_call_response_sequence(ALLOWANCE_SELECTOR, &[CALL_ZERO, CALL_ALLOWANCE_1000])
7001    }
7002
7003    async fn expected_wrap_tx_hash(value: U256) -> B256 {
7004        expected_tx_hash(
7005            WETH_ADDRESS,
7006            value,
7007            Bytes::from(nautilus_core::hex::decode("d0e30db0").unwrap()),
7008        )
7009        .await
7010    }
7011
7012    async fn expected_approve_tx_hash(amount: U256) -> B256 {
7013        let calldata = ERC20::approveCall {
7014            spender: ROUTER_ADDRESS,
7015            amount,
7016        }
7017        .abi_encode();
7018        expected_tx_hash(WETH_ADDRESS, U256::ZERO, Bytes::from(calldata)).await
7019    }
7020
7021    async fn expected_tx_hash(to: Address, value: U256, input: Bytes) -> B256 {
7022        // The orchestration's policy math is deterministic: nonce 7 from the fixture,
7023        // buffered gas 78000, buffered max fee 130000000, priority fee 10000000
7024        let expected_tx =
7025            build_eip1559_transaction(42161, 7, 78_000, 130_000_000, 10_000_000, to, value, input);
7026        let (expected_hash, _) = sign_eip1559_transaction(
7027            expected_tx,
7028            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7029        )
7030        .await
7031        .unwrap();
7032        expected_hash
7033    }
7034
7035    async fn await_recorded_requests(state: &MockRpcState, method: &str, expected: usize) {
7036        wait_until_async(
7037            || async {
7038                state
7039                    .recorded_requests()
7040                    .iter()
7041                    .filter(|request| request["method"] == method)
7042                    .count()
7043                    >= expected
7044            },
7045            TEST_TIMEOUT,
7046        )
7047        .await;
7048    }
7049
7050    /// The block number served by the `eth_getBlockByNumber` fixture; swap quotes pin their
7051    /// profiler state to it so the freshness check passes.
7052    const FIXTURE_BLOCK: u64 = 30_346_560;
7053    const FIXTURE_BLOCK_PARAM: &str = "0x1cf0d40";
7054    const FIXTURE_BLOCK_HASH: &str =
7055        "0x1111111111111111111111111111111111111111111111111111111111111111";
7056    /// The timestamp served by the `eth_getBlockByNumber` fixture.
7057    const FIXTURE_BLOCK_TIMESTAMP: u64 = 1_761_888_800;
7058    /// Synthetic full-range liquidity for the test pool profiler.
7059    const TEST_LIQUIDITY: u128 = 1_000_000_000_000_000_000_000;
7060
7061    fn test_profiler(pool: &Pool, block_number: u64) -> PoolProfiler {
7062        test_profiler_at_block(pool, block_number, FIXTURE_BLOCK_HASH)
7063    }
7064
7065    fn test_profiler_at_block(pool: &Pool, block_number: u64, block_hash: &str) -> PoolProfiler {
7066        test_profiler_with_range(
7067            pool,
7068            block_number,
7069            block_hash,
7070            U160::from(1u128 << 96),
7071            -887_220,
7072            887_220,
7073            TEST_LIQUIDITY,
7074        )
7075    }
7076
7077    fn test_profiler_with_state(
7078        pool: &Pool,
7079        block_number: u64,
7080        sqrt_price_x96: U160,
7081        liquidity: u128,
7082    ) -> PoolProfiler {
7083        test_profiler_with_range(
7084            pool,
7085            block_number,
7086            FIXTURE_BLOCK_HASH,
7087            sqrt_price_x96,
7088            -887_220,
7089            887_220,
7090            liquidity,
7091        )
7092    }
7093
7094    /// Builds a profiler from a synthetic snapshot with a single position over
7095    /// `[tick_lower, tick_upper]`: exact-input quotes within the range match the
7096    /// constant-product curve, and a tiny test swap never crosses a tick.
7097    fn test_profiler_with_range(
7098        pool: &Pool,
7099        block_number: u64,
7100        block_hash: &str,
7101        sqrt_price_x96: U160,
7102        tick_lower: i32,
7103        tick_upper: i32,
7104        liquidity: u128,
7105    ) -> PoolProfiler {
7106        let snapshot = PoolSnapshot::new(
7107            pool.instrument_id,
7108            PoolState {
7109                current_tick: get_tick_at_sqrt_ratio(sqrt_price_x96),
7110                price_sqrt_ratio_x96: sqrt_price_x96,
7111                liquidity,
7112                protocol_fees_token0: U256::ZERO,
7113                protocol_fees_token1: U256::ZERO,
7114                fee_protocol: 0,
7115                fee_protocol0_basis_points: None,
7116                fee_protocol1_basis_points: None,
7117                fee_growth_global_0: U256::ZERO,
7118                fee_growth_global_1: U256::ZERO,
7119            },
7120            vec![PoolPosition::new(
7121                address!("DeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF"),
7122                tick_lower,
7123                tick_upper,
7124                liquidity as i128,
7125            )],
7126            vec![
7127                PoolTick::new(
7128                    tick_lower,
7129                    liquidity,
7130                    liquidity as i128,
7131                    U256::ZERO,
7132                    U256::ZERO,
7133                    true,
7134                    0,
7135                ),
7136                PoolTick::new(
7137                    tick_upper,
7138                    liquidity,
7139                    -(liquidity as i128),
7140                    U256::ZERO,
7141                    U256::ZERO,
7142                    true,
7143                    0,
7144                ),
7145            ],
7146            PoolAnalytics::default(),
7147            BlockPosition::new(
7148                block_number,
7149                block_hash.to_string(),
7150                BLOCK_SCOPED_SNAPSHOT_INDEX,
7151                BLOCK_SCOPED_SNAPSHOT_INDEX,
7152            )
7153            .with_block_hash(Some(block_hash.to_string())),
7154            UnixNanos::default(),
7155            UnixNanos::default(),
7156        );
7157        let mut profiler = PoolProfiler::new(Arc::new(pool.clone()));
7158        profiler.restore_from_snapshot(snapshot).unwrap();
7159        profiler
7160    }
7161
7162    fn test_market_sell_order(instrument_id: InstrumentId) -> OrderAny {
7163        market_sell_order_with_id(instrument_id, "O-SWAP-001")
7164    }
7165
7166    fn test_market_buy_order(instrument_id: InstrumentId) -> OrderAny {
7167        market_buy_order_with_id(instrument_id, "O-SWAP-BUY-001")
7168    }
7169
7170    fn submit_order_cmd(order: &OrderAny) -> SubmitOrder {
7171        SubmitOrder::new(
7172            TraderId::from("TRADER-001"),
7173            Some(ClientId::from("BLOCKCHAIN-001")),
7174            order.strategy_id(),
7175            order.instrument_id(),
7176            order.client_order_id(),
7177            order.init_event().clone(),
7178            None,
7179            None,
7180            None,
7181            UUID4::new(),
7182            UnixNanos::default(),
7183            None,
7184        )
7185    }
7186
7187    /// Builds a client whose shared cache holds the test pool, a live profiler at
7188    /// `FIXTURE_BLOCK`, and a SELL market order, without a durable store.
7189    fn swap_client_with_cache(
7190        config: BlockchainExecutionClientConfig,
7191    ) -> (BlockchainExecutionClient, Rc<RefCell<Cache>>) {
7192        let cache = Rc::new(RefCell::new(Cache::default()));
7193        let pool = test_pool();
7194        cache.borrow_mut().add_pool(pool.clone()).unwrap();
7195        cache
7196            .borrow_mut()
7197            .add_order(
7198                test_market_sell_order(pool.instrument_id),
7199                None,
7200                None,
7201                false,
7202            )
7203            .unwrap();
7204        cache
7205            .borrow_mut()
7206            .add_pool_profiler(test_profiler_at_block(
7207                &pool,
7208                FIXTURE_BLOCK,
7209                FIXTURE_BLOCK_HASH,
7210            ))
7211            .unwrap();
7212        let core = ExecutionClientCore::new(
7213            TraderId::from("TRADER-001"),
7214            ClientId::from("BLOCKCHAIN-001"),
7215            *BLOCKCHAIN_VENUE,
7216            OmsType::Netting,
7217            AccountId::from("BLOCKCHAIN-001"),
7218            AccountType::Wallet,
7219            None,
7220            Rc::clone(&cache),
7221        );
7222
7223        let client = BlockchainExecutionClient::new(core, config).unwrap();
7224        (client, cache)
7225    }
7226
7227    /// Builds a connected, signer-equipped swap client backed by a fresh Postgres schema.
7228    async fn swap_client_with_database(
7229        test_name: &str,
7230        state: MockRpcState,
7231    ) -> Option<(
7232        sqlx::PgPool,
7233        String,
7234        BlockchainExecutionClient,
7235        MockRpcState,
7236        Rc<RefCell<Cache>>,
7237    )> {
7238        swap_client_with_database_config(test_name, state, test_config).await
7239    }
7240
7241    async fn swap_client_with_buy_database(
7242        test_name: &str,
7243        state: MockRpcState,
7244    ) -> Option<(
7245        sqlx::PgPool,
7246        String,
7247        BlockchainExecutionClient,
7248        MockRpcState,
7249        Rc<RefCell<Cache>>,
7250    )> {
7251        swap_client_with_database_config(test_name, state, buy_test_config).await
7252    }
7253
7254    async fn swap_client_with_database_config<F>(
7255        test_name: &str,
7256        state: MockRpcState,
7257        config: F,
7258    ) -> Option<(
7259        sqlx::PgPool,
7260        String,
7261        BlockchainExecutionClient,
7262        MockRpcState,
7263        Rc<RefCell<Cache>>,
7264    )>
7265    where
7266        F: FnOnce(String) -> BlockchainExecutionClientConfig,
7267    {
7268        let (admin_pool, pg_config) = connect_test_postgres(test_name).await?;
7269        let schema = format!("{test_name}_{}", std::process::id());
7270        setup_execution_schema(&admin_pool, &schema).await;
7271
7272        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
7273        let db_options = db_options.options([("search_path", schema.clone())]);
7274        let database = connect_test_database(db_options).await.unwrap();
7275        let addr = start_mock_rpc_server(state.clone()).await;
7276        let (mut client, cache) = swap_client_with_cache(config(format!("http://{addr}")));
7277        client.cache.database = Some(database);
7278        // Mirror the connect-time migration: tests create the pre-submission table shape
7279        client
7280            .cache
7281            .ensure_execution_transaction_schema()
7282            .await
7283            .unwrap();
7284        protect_test_storage(&mut client, &schema).await;
7285        initialize_test_verification_ledger(&client).await;
7286        client.signer = Some(Arc::new(
7287            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7288        ));
7289        client.core.set_connected();
7290
7291        Some((admin_pool, schema, client, state, cache))
7292    }
7293
7294    async fn initialize_test_verification_ledger(client: &BlockchainExecutionClient) {
7295        initialize_test_verification_ledger_with_headers(
7296            client,
7297            &[ExecutionVerifiedHeader {
7298                number: FIXTURE_BLOCK,
7299                hash: FIXTURE_BLOCK_HASH.to_string(),
7300                parent_hash: "0x0000000000000000000000000000000000000000000000000000000000000001"
7301                    .to_string(),
7302                timestamp: FIXTURE_BLOCK_TIMESTAMP,
7303                base_fee_per_gas: Some(100_000_000),
7304            }],
7305        )
7306        .await;
7307    }
7308
7309    async fn initialize_test_verification_ledger_with_headers(
7310        client: &BlockchainExecutionClient,
7311        finalized_headers: &[ExecutionVerifiedHeader],
7312    ) {
7313        ensure_test_verification_ledger(client, finalized_headers, 7, 7)
7314            .await
7315            .unwrap();
7316    }
7317
7318    async fn ensure_test_verification_ledger(
7319        client: &BlockchainExecutionClient,
7320        finalized_headers: &[ExecutionVerifiedHeader],
7321        next_canonical_nonce: u64,
7322        observed_canonical_nonce: u64,
7323    ) -> anyhow::Result<()> {
7324        let verification = client.config.verification.as_ref().unwrap();
7325        let provider_ids = vec![
7326            "authoritative".to_string(),
7327            "verifier-a".to_string(),
7328            "verifier-b".to_string(),
7329        ];
7330        let operator_ids = vec![
7331            "operator-a".to_string(),
7332            "operator-b".to_string(),
7333            "operator-c".to_string(),
7334        ];
7335        let failure_domain_ids = vec![
7336            "domain-a".to_string(),
7337            "domain-b".to_string(),
7338            "domain-c".to_string(),
7339        ];
7340        let decisions = [ExecutionVerificationDecision {
7341            read_class: "numbered_block",
7342            height_start: Some(FIXTURE_BLOCK),
7343            height_end: Some(FIXTURE_BLOCK),
7344            normalized_value_digest: B256::ZERO.to_string(),
7345        }];
7346        client
7347            .cache
7348            .database
7349            .as_ref()
7350            .unwrap()
7351            .ensure_execution_verification_schema(&ExecutionVerificationBootstrap {
7352                chain_id: 42_161,
7353                wallet_address: WALLET,
7354                manifest_version: &verification.manifest_version,
7355                manifest_digest: &verification.manifest_digest,
7356                checkpoint_number: FIXTURE_BLOCK,
7357                checkpoint_hash: FIXTURE_BLOCK_HASH,
7358                checkpoint_parent_hash:
7359                    "0x0000000000000000000000000000000000000000000000000000000000000001",
7360                checkpoint_timestamp: FIXTURE_BLOCK_TIMESTAMP,
7361                checkpoint_base_fee_per_gas: Some(100_000_000),
7362                finalized_headers,
7363                next_canonical_nonce,
7364                observed_canonical_nonce,
7365                provider_ids: &provider_ids,
7366                operator_ids: &operator_ids,
7367                failure_domain_ids: &failure_domain_ids,
7368                decisions: &decisions,
7369                migration: None,
7370            })
7371            .await
7372    }
7373
7374    async fn initialize_test_verification_migration(
7375        client: &BlockchainExecutionClient,
7376        finalized_headers: &[ExecutionVerifiedHeader],
7377        next_canonical_nonce: u64,
7378        decisions: &[ExecutionVerificationDecision],
7379        migration: &ExecutionVerificationMigration,
7380    ) {
7381        let verification = client.config.verification.as_ref().unwrap();
7382        let provider_ids = vec![
7383            "authoritative".to_string(),
7384            "verifier-a".to_string(),
7385            "verifier-b".to_string(),
7386        ];
7387        let operator_ids = vec![
7388            "operator-a".to_string(),
7389            "operator-b".to_string(),
7390            "operator-c".to_string(),
7391        ];
7392        let failure_domain_ids = vec![
7393            "domain-a".to_string(),
7394            "domain-b".to_string(),
7395            "domain-c".to_string(),
7396        ];
7397        client
7398            .cache
7399            .database
7400            .as_ref()
7401            .unwrap()
7402            .ensure_execution_verification_schema(&ExecutionVerificationBootstrap {
7403                chain_id: 42_161,
7404                wallet_address: WALLET,
7405                manifest_version: &verification.manifest_version,
7406                manifest_digest: &verification.manifest_digest,
7407                checkpoint_number: FIXTURE_BLOCK,
7408                checkpoint_hash: FIXTURE_BLOCK_HASH,
7409                checkpoint_parent_hash:
7410                    "0x0000000000000000000000000000000000000000000000000000000000000001",
7411                checkpoint_timestamp: FIXTURE_BLOCK_TIMESTAMP,
7412                checkpoint_base_fee_per_gas: Some(100_000_000),
7413                finalized_headers,
7414                next_canonical_nonce,
7415                observed_canonical_nonce: next_canonical_nonce,
7416                provider_ids: &provider_ids,
7417                operator_ids: &operator_ids,
7418                failure_domain_ids: &failure_domain_ids,
7419                decisions,
7420                migration: Some(migration),
7421            })
7422            .await
7423            .unwrap();
7424    }
7425
7426    async fn swap_rpc_state() -> MockRpcState {
7427        let min_amount_out = expected_min_amount_out(50);
7428        swap_rpc_state_with_min_amount_out(min_amount_out).await
7429    }
7430
7431    async fn swap_rpc_state_with_min_amount_out(min_amount_out: U256) -> MockRpcState {
7432        let (tx_hash, _) = expected_swap_tx(min_amount_out).await;
7433        finalized_swap_rpc_state(tx_hash, min_amount_out)
7434    }
7435
7436    async fn swap_rpc_state_for_mismatch() -> MockRpcState {
7437        swap_rpc_state()
7438            .await
7439            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION)
7440    }
7441
7442    fn awaiting_in_flight(client: &BlockchainExecutionClient) -> InFlightTransaction {
7443        let slot = *client.in_flight.lock();
7444        let Some(InFlightSlot::AwaitingFinality(in_flight)) = slot else {
7445            panic!("expected an awaiting-finality transaction, was {slot:?}");
7446        };
7447        in_flight
7448    }
7449
7450    fn recovering_in_flight(client: &BlockchainExecutionClient) -> RecoveryTransaction {
7451        let slot = *client.in_flight.lock();
7452        let Some(InFlightSlot::Recovering(recovery)) = slot else {
7453            panic!("expected a recovery transaction, was {slot:?}");
7454        };
7455        recovery
7456    }
7457
7458    async fn execution_intent_markers(
7459        admin_pool: &sqlx::PgPool,
7460        schema: &str,
7461    ) -> Vec<(String, String, bool, bool)> {
7462        sqlx::query_as(sqlx::AssertSqlSafe(format!(
7463            "SELECT purpose, status, terminal_emitted, active \
7464             FROM {schema}.execution_intent ORDER BY id"
7465        )))
7466        .fetch_all(admin_pool)
7467        .await
7468        .unwrap()
7469    }
7470
7471    #[allow(unsafe_code)] // env-var mutation in tests; unique names avoid cross-test races
7472    fn payload_test_keys(
7473        active: [u8; 32],
7474        retired: Vec<[u8; 32]>,
7475        deployment_id: &str,
7476    ) -> PayloadKeySet {
7477        static NEXT_ENV_ID: AtomicU64 = AtomicU64::new(0);
7478
7479        let env_id = NEXT_ENV_ID.fetch_add(1, Ordering::Relaxed);
7480        let active_env = format!("BLOCKCHAIN_TEST_PAYLOAD_KEY_{env_id}_ACTIVE");
7481        let retired_envs = retired
7482            .iter()
7483            .enumerate()
7484            .map(|(index, _)| format!("BLOCKCHAIN_TEST_PAYLOAD_KEY_{env_id}_RETIRED_{index}"))
7485            .collect::<Vec<_>>();
7486        // SAFETY: each invocation uses unique variable names and removes them before returning
7487        unsafe { std::env::set_var(&active_env, hex::encode(active)) };
7488
7489        for (env, key) in retired_envs.iter().zip(retired) {
7490            // SAFETY: the retired variable name is unique to this invocation
7491            unsafe { std::env::set_var(env, hex::encode(key)) };
7492        }
7493
7494        let keys = PayloadKeySet::load(Some(&active_env), &retired_envs, Some(deployment_id))
7495            .unwrap()
7496            .unwrap();
7497
7498        // SAFETY: no other test or thread uses these unique variable names
7499        unsafe { std::env::remove_var(active_env) };
7500        for env in retired_envs {
7501            // SAFETY: the retired variable name is unique to this invocation
7502            unsafe { std::env::remove_var(env) };
7503        }
7504        keys
7505    }
7506
7507    #[allow(unsafe_code)] // env-var mutation in tests; unique names avoid cross-test races
7508    fn set_test_payload_key(
7509        client: &mut BlockchainExecutionClient,
7510        key: [u8; 32],
7511        deployment_id: &str,
7512    ) -> PayloadKeySet {
7513        static NEXT_ENV_ID: AtomicU64 = AtomicU64::new(0);
7514
7515        let env_id = NEXT_ENV_ID.fetch_add(1, Ordering::Relaxed);
7516        let active_env = format!("BLOCKCHAIN_TEST_EXECUTION_KEY_{env_id}");
7517        // SAFETY: each invocation uses a unique variable name retained for reconnect tests
7518        unsafe { std::env::set_var(&active_env, hex::encode(key)) };
7519        client.config.payload_key_env = Some(active_env);
7520        client.config.payload_deployment_id = Some(deployment_id.to_string());
7521        client.load_payload_keys().unwrap().unwrap()
7522    }
7523
7524    async fn protect_test_storage(client: &mut BlockchainExecutionClient, deployment_id: &str) {
7525        let keys = set_test_payload_key(client, [0xa5; 32], deployment_id);
7526        client
7527            .cache
7528            .database
7529            .as_ref()
7530            .unwrap()
7531            .ensure_execution_payload_storage(&keys)
7532            .await
7533            .unwrap();
7534        client.payload_keys = Some(Arc::new(keys));
7535    }
7536
7537    async fn reserve_test_wrap_intent(database: &BlockchainCacheDatabase) -> ExecutionIntentRow {
7538        reserve_test_wrap_intent_for_wallet(database, WALLET).await
7539    }
7540
7541    async fn reserve_test_wrap_intent_for_wallet(
7542        database: &BlockchainCacheDatabase,
7543        wallet: &str,
7544    ) -> ExecutionIntentRow {
7545        database
7546            .reserve_execution_intent(&ExecutionIntentInsert {
7547                chain_id: 42161,
7548                wallet_address: wallet.to_string(),
7549                purpose: "wrap".to_string(),
7550                client_order_id: None,
7551                trader_id: None,
7552                strategy_id: None,
7553                account_id: None,
7554                instrument_id: None,
7555                pool_address: None,
7556                transaction_to: WETH_ADDRESS.to_string(),
7557                transaction_input: "0xd0e30db0".to_string(),
7558                transaction_value: "1".to_string(),
7559                amount_in: None,
7560                created_block: FIXTURE_BLOCK,
7561            })
7562            .await
7563            .unwrap()
7564    }
7565
7566    async fn persist_test_wrap_broadcast(
7567        database: &BlockchainCacheDatabase,
7568        keys: Option<&PayloadKeySet>,
7569    ) -> (ExecutionIntentRow, B256, Vec<u8>) {
7570        let intent = reserve_test_wrap_intent(database).await;
7571        database
7572            .assign_execution_intent_nonce(intent.id, 7)
7573            .await
7574            .unwrap();
7575        let intent = database.get_execution_intent(intent.id).await.unwrap();
7576        let transaction = build_eip1559_transaction(
7577            42161,
7578            7,
7579            78_000,
7580            130_000_000,
7581            10_000_000,
7582            WETH_ADDRESS,
7583            U256::from(1u64),
7584            Bytes::from(nautilus_core::hex::decode("d0e30db0").unwrap()),
7585        );
7586        let (tx_hash, raw_tx) = sign_eip1559_transaction(
7587            transaction,
7588            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7589        )
7590        .await
7591        .unwrap();
7592        persist_test_payload(database, keys, &intent, tx_hash, &raw_tx).await;
7593        database
7594            .record_execution_status(
7595                intent.id,
7596                &tx_hash.to_string(),
7597                TransactionStatus::Broadcast,
7598                None,
7599                None,
7600                None,
7601                None,
7602                None,
7603            )
7604            .await
7605            .unwrap();
7606        (intent, tx_hash, raw_tx)
7607    }
7608
7609    #[tokio::test]
7610    async fn migration_check_reads_authoritative_swap_intents() {
7611        let (admin, config) = connect_test_postgres("migration_check")
7612            .await
7613            .expect("Postgres required");
7614        let schema = format!("migration_check_{}", UUID4::new()).replace('-', "_");
7615        setup_execution_schema(&admin, &schema).await;
7616        let options: sqlx::postgres::PgConnectOptions = config.into();
7617        let database = connect_test_database(options.options([("search_path", schema.clone())]))
7618            .await
7619            .unwrap();
7620        database
7621            .ensure_execution_transaction_schema()
7622            .await
7623            .unwrap();
7624        let id = test_pool().instrument_id;
7625        database.check_instrument_migration(id).await.unwrap();
7626        let intent = reserve_test_swap_intent(&database).await;
7627
7628        let active = database.check_instrument_migration(id).await.unwrap_err();
7629        let unrelated = database
7630            .check_instrument_migration(InstrumentId::from("UNRELATED.DEFI"))
7631            .await;
7632        sqlx::query(sqlx::AssertSqlSafe(format!(
7633            "UPDATE {schema}.execution_intent SET active = FALSE WHERE id = $1"
7634        )))
7635        .bind(intent.id)
7636        .execute(&admin)
7637        .await
7638        .unwrap();
7639        let inactive = database.check_instrument_migration(id).await;
7640        drop_execution_schema(&admin, &schema).await;
7641        let unavailable = database.check_instrument_migration(id).await.unwrap_err();
7642
7643        assert_eq!(
7644            active.to_string(),
7645            format!("Instrument {id} has active swap intents")
7646        );
7647        unrelated.unwrap();
7648        inactive.unwrap();
7649        assert_eq!(
7650            unavailable.to_string(),
7651            "failed to check active swap intents before instrument replacement"
7652        );
7653    }
7654
7655    async fn reserve_test_swap_intent(database: &BlockchainCacheDatabase) -> ExecutionIntentRow {
7656        let pool = test_pool();
7657        let order = test_market_sell_order(pool.instrument_id);
7658        let calldata = expected_swap_calldata(expected_min_amount_out(50));
7659
7660        database
7661            .reserve_execution_intent(&ExecutionIntentInsert {
7662                chain_id: 42161,
7663                wallet_address: WALLET.to_string(),
7664                purpose: "swap".to_string(),
7665                client_order_id: Some(order.client_order_id().to_string()),
7666                trader_id: Some(order.trader_id().to_string()),
7667                strategy_id: Some(order.strategy_id().to_string()),
7668                account_id: Some("BLOCKCHAIN-001".to_string()),
7669                instrument_id: Some(pool.instrument_id.to_string()),
7670                pool_address: Some(pool.address.to_string()),
7671                transaction_to: ROUTER_ADDRESS.to_string(),
7672                transaction_input: hex::encode_prefixed(&calldata),
7673                transaction_value: U256::ZERO.to_string(),
7674                amount_in: Some("1000000000000000".to_string()),
7675                created_block: FIXTURE_BLOCK,
7676            })
7677            .await
7678            .unwrap()
7679    }
7680
7681    async fn persist_invalid_test_swap(
7682        database: &BlockchainCacheDatabase,
7683        keys: Option<&PayloadKeySet>,
7684    ) -> (ExecutionIntentRow, B256) {
7685        let intent = reserve_test_swap_intent(database).await;
7686        database
7687            .assign_execution_intent_nonce(intent.id, 7)
7688            .await
7689            .unwrap();
7690        let intent = database.get_execution_intent(intent.id).await.unwrap();
7691        let (tx_hash, raw_transaction) = expected_swap_tx(expected_min_amount_out(50)).await;
7692        let mut raw_transaction = hex::decode(raw_transaction.strip_prefix("0x").unwrap()).unwrap();
7693        raw_transaction.push(0xff);
7694        persist_test_payload(database, keys, &intent, tx_hash, &raw_transaction).await;
7695        database
7696            .record_execution_status(
7697                intent.id,
7698                &tx_hash.to_string(),
7699                TransactionStatus::Broadcast,
7700                None,
7701                None,
7702                None,
7703                None,
7704                None,
7705            )
7706            .await
7707            .unwrap();
7708
7709        (intent, tx_hash)
7710    }
7711
7712    async fn persist_test_swap_broadcast(
7713        database: &BlockchainCacheDatabase,
7714        keys: Option<&PayloadKeySet>,
7715    ) -> (ExecutionIntentRow, B256, Vec<u8>) {
7716        let intent = reserve_test_swap_intent(database).await;
7717        database
7718            .assign_execution_intent_nonce(intent.id, 7)
7719            .await
7720            .unwrap();
7721        let intent = database.get_execution_intent(intent.id).await.unwrap();
7722        let (tx_hash, raw_transaction) = expected_swap_tx(expected_min_amount_out(50)).await;
7723        let raw_transaction = hex::decode(raw_transaction.strip_prefix("0x").unwrap()).unwrap();
7724        persist_test_payload(database, keys, &intent, tx_hash, &raw_transaction).await;
7725        database
7726            .record_execution_status(
7727                intent.id,
7728                &tx_hash.to_string(),
7729                TransactionStatus::Broadcast,
7730                None,
7731                None,
7732                None,
7733                None,
7734                None,
7735            )
7736            .await
7737            .unwrap();
7738        (intent, tx_hash, raw_transaction)
7739    }
7740
7741    async fn persist_test_payload(
7742        database: &BlockchainCacheDatabase,
7743        keys: Option<&PayloadKeySet>,
7744        intent: &ExecutionIntentRow,
7745        tx_hash: B256,
7746        raw_transaction: &[u8],
7747    ) {
7748        if let Some(keys) = keys {
7749            database.reserve_execution_payload_seal(keys).await.unwrap();
7750            let transaction_hash = tx_hash.to_string();
7751            let context =
7752                payload_context_identity(intent, &transaction_hash, 42_161, keys.deployment_id())
7753                    .unwrap();
7754            let envelope = keys.seal(raw_transaction, &context).unwrap();
7755            database
7756                .add_execution_transaction_envelope(intent.id, 42_161, &transaction_hash, &envelope)
7757                .await
7758                .unwrap();
7759        } else {
7760            database
7761                .add_execution_transaction_hash(
7762                    intent.id,
7763                    42_161,
7764                    &tx_hash.to_string(),
7765                    raw_transaction,
7766                )
7767                .await
7768                .unwrap();
7769        }
7770    }
7771
7772    async fn later_reconnect(
7773        previous: BlockchainExecutionClient,
7774        http_rpc_url: String,
7775    ) -> anyhow::Error {
7776        let database = previous.cache.database.as_ref().unwrap().clone();
7777        let payload_keys = previous.payload_keys.clone();
7778        drop(previous);
7779        let mut next = test_client(http_rpc_url);
7780        next.cache.database = Some(database);
7781        next.payload_keys = payload_keys;
7782        next.signer = Some(Arc::new(
7783            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7784        ));
7785        next.reconcile_unresolved_execution().await.unwrap_err()
7786    }
7787
7788    fn start_with_events(
7789        client: &mut BlockchainExecutionClient,
7790    ) -> tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent> {
7791        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
7792        replace_exec_event_sender(sender);
7793        client.start().unwrap();
7794        receiver
7795    }
7796
7797    async fn await_pending_tasks(client: &BlockchainExecutionClient) {
7798        tokio::time::timeout(TEST_TIMEOUT, async {
7799            while !client.pending_tasks.all_finished() {
7800                tokio::time::sleep(Duration::from_millis(1)).await;
7801            }
7802        })
7803        .await
7804        .unwrap();
7805    }
7806
7807    fn collect_order_events(
7808        receiver: &mut tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
7809    ) -> Vec<OrderEventAny> {
7810        let mut events = Vec::new();
7811
7812        while let Ok(event) = receiver.try_recv() {
7813            if let ExecutionEvent::Order(order_event) = event {
7814                events.push(order_event);
7815            }
7816        }
7817        events
7818    }
7819
7820    fn assert_swap_quarantined_without_terminal_event(events: &[OrderEventAny]) {
7821        assert_eq!(events.len(), 1, "was: {events:?}");
7822        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
7823    }
7824
7825    fn assert_swap_submitted_and_filled(events: &[OrderEventAny]) {
7826        assert_eq!(events.len(), 2, "was: {events:?}");
7827        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
7828        assert!(matches!(&events[1], OrderEventAny::Filled(_)));
7829    }
7830
7831    fn expected_swap_calldata(min_amount_out: U256) -> Vec<u8> {
7832        UniswapV3SwapRouter::exactInputSingleCall {
7833            params: UniswapV3SwapRouter::ExactInputSingleParams {
7834                tokenIn: WETH_ADDRESS,
7835                tokenOut: address!("af88d065e77c8cC2239327C5EDb3A432268e5831"),
7836                fee: U24::try_from(500u32).unwrap(),
7837                recipient: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"),
7838                deadline: U256::from(FIXTURE_BLOCK_TIMESTAMP + 300),
7839                amountIn: U256::from(1_000_000_000_000_000u64),
7840                amountOutMinimum: min_amount_out,
7841                sqrtPriceLimitX96: U160::ZERO,
7842            },
7843        }
7844        .abi_encode()
7845    }
7846
7847    fn expected_min_amount_out(slippage_bps: u32) -> U256 {
7848        expected_min_amount_out_for(&test_pool(), true, slippage_bps)
7849    }
7850
7851    fn expected_min_amount_out_for(pool: &Pool, zero_for_one: bool, slippage_bps: u32) -> U256 {
7852        let profiler = test_profiler(pool, FIXTURE_BLOCK);
7853        let quote = profiler
7854            .swap_exact_in(U256::from(1_000_000_000_000_000u64), zero_for_one, None)
7855            .unwrap();
7856        let quoted = exact_output_amount(&quote, zero_for_one).unwrap();
7857        derive_min_amount_out(quoted, slippage_bps).unwrap()
7858    }
7859
7860    fn expected_sell_quote_amount() -> U256 {
7861        let profiler = test_profiler(&test_pool(), FIXTURE_BLOCK);
7862        let quote = profiler
7863            .swap_exact_in(U256::from(1_000_000_000_000_000u64), true, None)
7864            .unwrap();
7865        exact_output_amount(&quote, true).unwrap()
7866    }
7867
7868    fn quote_response(amount: U256) -> String {
7869        let result = (amount, U160::from(1u128 << 96), 0u32, U256::from(50_000u64)).abi_encode();
7870        serde_json::json!({
7871            "jsonrpc": "2.0",
7872            "id": 1,
7873            "result": hex::encode_prefixed(result),
7874        })
7875        .to_string()
7876    }
7877
7878    async fn expected_swap_tx(min_amount_out: U256) -> (B256, String) {
7879        // The orchestration's policy math is deterministic: nonce 7 from the fixture,
7880        // buffered gas 78000, buffered max fee 130000000, priority fee 10000000
7881        let expected_tx = build_eip1559_transaction(
7882            42161,
7883            7,
7884            78_000,
7885            130_000_000,
7886            10_000_000,
7887            ROUTER_ADDRESS,
7888            U256::ZERO,
7889            Bytes::from(expected_swap_calldata(min_amount_out)),
7890        );
7891        sign_eip1559_transaction(
7892            expected_tx,
7893            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7894        )
7895        .await
7896        .map(|(hash, raw)| (hash, nautilus_core::hex::encode_prefixed(&raw)))
7897        .unwrap()
7898    }
7899
7900    fn expected_buy_base_amount() -> U256 {
7901        U256::from(1_000_000_000_000_000u64)
7902    }
7903
7904    fn expected_buy_amount_in() -> U256 {
7905        let profiler = test_profiler(&test_pool(), FIXTURE_BLOCK);
7906        profiler
7907            .swap_exact_out(expected_buy_base_amount(), false, None)
7908            .unwrap()
7909            .get_input_amount()
7910    }
7911
7912    fn expected_buy_min_amount_out(slippage_bps: u32) -> U256 {
7913        derive_min_amount_out(expected_buy_base_amount(), slippage_bps).unwrap()
7914    }
7915
7916    fn expected_buy_swap_calldata(min_amount_out: U256, amount_in: U256) -> Vec<u8> {
7917        UniswapV3SwapRouter::exactInputSingleCall {
7918            params: UniswapV3SwapRouter::ExactInputSingleParams {
7919                tokenIn: USDC_ADDRESS,
7920                tokenOut: WETH_ADDRESS,
7921                fee: U24::try_from(500u32).unwrap(),
7922                recipient: address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266"),
7923                deadline: U256::from(FIXTURE_BLOCK_TIMESTAMP + 300),
7924                amountIn: amount_in,
7925                amountOutMinimum: min_amount_out,
7926                sqrtPriceLimitX96: U160::ZERO,
7927            },
7928        }
7929        .abi_encode()
7930    }
7931
7932    async fn expected_buy_swap_tx(min_amount_out: U256, amount_in: U256) -> (B256, String) {
7933        let expected_tx = build_eip1559_transaction(
7934            42161,
7935            7,
7936            78_000,
7937            130_000_000,
7938            10_000_000,
7939            ROUTER_ADDRESS,
7940            U256::ZERO,
7941            Bytes::from(expected_buy_swap_calldata(min_amount_out, amount_in)),
7942        );
7943        sign_eip1559_transaction(
7944            expected_tx,
7945            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
7946        )
7947        .await
7948        .map(|(hash, raw)| (hash, nautilus_core::hex::encode_prefixed(&raw)))
7949        .unwrap()
7950    }
7951
7952    fn finalized_buy_swap_receipt(tx_hash: B256, amount_in: U256) -> String {
7953        finalized_buy_swap_receipt_with_base_out(tx_hash, amount_in, expected_buy_base_amount())
7954    }
7955
7956    fn finalized_buy_swap_receipt_with_base_out(
7957        tx_hash: B256,
7958        amount_in: U256,
7959        base_out: U256,
7960    ) -> String {
7961        let data = (
7962            -I256::try_from(u128::try_from(base_out).unwrap()).unwrap(),
7963            I256::try_from(u128::try_from(amount_in).unwrap()).unwrap(),
7964            U160::from(1_u128 << 96),
7965            TEST_LIQUIDITY,
7966            I24::try_from(0).unwrap(),
7967        )
7968            .abi_encode();
7969        serde_json::json!({
7970            "jsonrpc": "2.0",
7971            "id": 1,
7972            "result": {
7973                "transactionHash": tx_hash.to_string(),
7974                "blockHash": "0x2222222222222222222222222222222222222222222222222222222222222222",
7975                "blockNumber": "0x1cf0d41",
7976                "transactionIndex": "0x2",
7977                "gasUsed": "0xc3c0",
7978                "effectiveGasPrice": "0x5f5e100",
7979                "status": "0x1",
7980                "logs": [{
7981                    "removed": false,
7982                    "logIndex": "0x6",
7983                    "transactionIndex": "0x2",
7984                    "transactionHash": tx_hash.to_string(),
7985                    "blockHash": "0x2222222222222222222222222222222222222222222222222222222222222222",
7986                    "blockNumber": "0x1cf0d41",
7987                    "address": test_pool().address.to_string(),
7988                    "data": hex::encode_prefixed(data),
7989                    "topics": [
7990                        "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67",
7991                        "0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266",
7992                        "0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266"
7993                    ]
7994                }]
7995            }
7996        })
7997        .to_string()
7998    }
7999
8000    fn finalized_buy_swap_block(tx_hash: B256, min_amount_out: U256, amount_in: U256) -> String {
8001        serde_json::json!({
8002            "jsonrpc": "2.0",
8003            "id": 1,
8004            "result": {
8005                "number": "0x1cf0d41",
8006                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8007                "parentHash": FIXTURE_BLOCK_HASH,
8008                "timestamp": "0x69044a21",
8009                "baseFeePerGas": "0x5f5e100",
8010                "transactions": [{
8011                    "hash": tx_hash.to_string(),
8012                    "from": WALLET,
8013                    "nonce": "0x7",
8014                    "chainId": "0xa4b1",
8015                    "type": "0x2",
8016                    "to": ROUTER,
8017                    "input": hex::encode_prefixed(expected_buy_swap_calldata(min_amount_out, amount_in)),
8018                    "value": "0x0",
8019                    "gas": "0x130b0",
8020                    "maxFeePerGas": "0x7bfa480",
8021                    "maxPriorityFeePerGas": "0x989680"
8022                }]
8023            }
8024        })
8025        .to_string()
8026    }
8027
8028    fn finalized_buy_swap_rpc_state(
8029        tx_hash: B256,
8030        min_amount_out: U256,
8031        amount_in: U256,
8032    ) -> MockRpcState {
8033        let receipt = finalized_buy_swap_receipt(tx_hash, amount_in);
8034        let block = finalized_buy_swap_block(tx_hash, min_amount_out, amount_in);
8035        with_finalized_identity(
8036            signing_rpc_state()
8037                .with_response("eth_getTransactionReceipt", &receipt)
8038                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
8039                .with_send_raw_transaction_echo()
8040                .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE)
8041                .with_call_response(ALLOWANCE_SELECTOR, CALL_ALLOWANCE),
8042            &block,
8043            &receipt,
8044        )
8045    }
8046
8047    fn finalized_swap_receipt(tx_hash: B256) -> String {
8048        let data = (
8049            I256::try_from(1_000_000_000_000_000_i128).unwrap(),
8050            I256::try_from(-1_000_000_i128).unwrap(),
8051            U160::from(1_u128 << 96),
8052            TEST_LIQUIDITY,
8053            I24::try_from(0).unwrap(),
8054        )
8055            .abi_encode();
8056        serde_json::json!({
8057            "jsonrpc": "2.0",
8058            "id": 1,
8059            "result": {
8060                "transactionHash": tx_hash.to_string(),
8061                "blockHash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8062                "blockNumber": "0x1cf0d41",
8063                "transactionIndex": "0x2",
8064                "gasUsed": "0xc3c0",
8065                "effectiveGasPrice": "0x5f5e100",
8066                "status": "0x1",
8067                "logs": [{
8068                    "removed": false,
8069                    "logIndex": "0x6",
8070                    "transactionIndex": "0x2",
8071                    "transactionHash": tx_hash.to_string(),
8072                    "blockHash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8073                    "blockNumber": "0x1cf0d41",
8074                    "address": test_pool().address.to_string(),
8075                    "data": hex::encode_prefixed(data),
8076                    "topics": [
8077                        "0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67",
8078                        "0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266",
8079                        "0x000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266"
8080                    ]
8081                }]
8082            }
8083        })
8084        .to_string()
8085    }
8086
8087    fn finalized_swap_receipt_with_unrelated_swap(tx_hash: B256) -> String {
8088        let mut receipt: serde_json::Value =
8089            serde_json::from_str(&finalized_swap_receipt(tx_hash)).unwrap();
8090        let logs = receipt["result"]["logs"].as_array_mut().unwrap();
8091        let mut unrelated = logs[0].clone();
8092        unrelated["address"] = serde_json::json!(ROUTER);
8093        unrelated["logIndex"] = serde_json::json!("0x7");
8094        logs.push(unrelated);
8095        receipt.to_string()
8096    }
8097
8098    fn finalized_swap_block(tx_hash: B256, min_amount_out: U256) -> String {
8099        serde_json::json!({
8100            "jsonrpc": "2.0",
8101            "id": 1,
8102            "result": {
8103                "number": "0x1cf0d41",
8104                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8105                "parentHash": FIXTURE_BLOCK_HASH,
8106                "timestamp": "0x69044a21",
8107                "baseFeePerGas": "0x5f5e100",
8108                "transactions": [{
8109                    "hash": tx_hash.to_string(),
8110                    "from": WALLET,
8111                    "nonce": "0x7",
8112                    "chainId": "0xa4b1",
8113                    "type": "0x2",
8114                    "to": ROUTER,
8115                    "input": hex::encode_prefixed(expected_swap_calldata(min_amount_out)),
8116                    "value": "0x0",
8117                    "gas": "0x130b0",
8118                    "maxFeePerGas": "0x7bfa480",
8119                    "maxPriorityFeePerGas": "0x989680"
8120                }]
8121            }
8122        })
8123        .to_string()
8124    }
8125
8126    fn finalized_swap_rpc_state(tx_hash: B256, min_amount_out: U256) -> MockRpcState {
8127        let receipt = finalized_swap_receipt(tx_hash);
8128        let block = finalized_swap_block(tx_hash, min_amount_out);
8129        with_finalized_identity(
8130            signing_rpc_state()
8131                .with_response("eth_getTransactionReceipt", &receipt)
8132                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
8133                .with_send_raw_transaction_echo()
8134                .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE)
8135                .with_call_response(ALLOWANCE_SELECTOR, CALL_ALLOWANCE),
8136            &block,
8137            &receipt,
8138        )
8139    }
8140
8141    fn with_finalized_identity(
8142        state: MockRpcState,
8143        block_response: &str,
8144        receipt_response: &str,
8145    ) -> MockRpcState {
8146        let block: serde_json::Value = serde_json::from_str(block_response).unwrap();
8147        let receipt: serde_json::Value = serde_json::from_str(receipt_response).unwrap();
8148        let transaction = block["result"]["transactions"][0].clone();
8149        let transaction_response = serde_json::json!({
8150            "jsonrpc": "2.0",
8151            "id": 1,
8152            "result": transaction,
8153        })
8154        .to_string();
8155        let success = receipt["result"]["status"] == "0x1";
8156        let mut trace = serde_json::json!({
8157            "type": "CALL",
8158            "from": transaction["from"],
8159            "to": transaction["to"],
8160            "value": transaction["value"],
8161            "gas": transaction["gas"],
8162            "gasUsed": receipt["result"]["gasUsed"],
8163            "input": transaction["input"],
8164            "output": "0x",
8165            "calls": [],
8166        });
8167
8168        if !success {
8169            trace["error"] = serde_json::json!("execution reverted");
8170        }
8171        let trace_response = serde_json::json!({
8172            "jsonrpc": "2.0",
8173            "id": 1,
8174            "result": trace,
8175        })
8176        .to_string();
8177        state
8178            .with_response("eth_getTransactionByHash", &transaction_response)
8179            .with_response("debug_traceTransaction", &trace_response)
8180    }
8181
8182    fn receipt_with_transaction_hash(receipt_response: &str, tx_hash: B256) -> String {
8183        let mut receipt: serde_json::Value = serde_json::from_str(receipt_response).unwrap();
8184        receipt["result"]["transactionHash"] = serde_json::json!(tx_hash.to_string());
8185        receipt.to_string()
8186    }
8187
8188    fn replacement_head_block(tx_hash: B256) -> String {
8189        serde_json::json!({
8190            "jsonrpc": "2.0",
8191            "id": 1,
8192            "result": {
8193                "number": "0x1cf0d40",
8194                "hash": "0x1111111111111111111111111111111111111111111111111111111111111111",
8195                "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000001",
8196                "timestamp": "0x69044a20",
8197                "baseFeePerGas": "0x5f5e100",
8198                "transactions": [{
8199                    "hash": "0x3333333333333333333333333333333333333333333333333333333333333333",
8200                    "from": "0x0000000000000000000000000000000000000001",
8201                    "nonce": "0x1",
8202                    "type": "0x0",
8203                    "to": WETH,
8204                    "input": "0x",
8205                    "value": "0x0",
8206                    "gas": "0x5208"
8207                }, {
8208                    "hash": tx_hash.to_string(),
8209                    "from": WALLET,
8210                    "nonce": "0x7",
8211                    "chainId": "0xa4b1",
8212                    "type": "0x2",
8213                    "to": WETH,
8214                    "input": "0xd0e30db0",
8215                    "value": "0x38d7ea4c68000",
8216                    "gas": "0x130b0",
8217                    "maxFeePerGas": "0x7bfa480",
8218                    "maxPriorityFeePerGas": "0x989680"
8219                }]
8220            }
8221        })
8222        .to_string()
8223    }
8224
8225    fn finalized_wrap_block(tx_hash: B256) -> String {
8226        serde_json::json!({
8227            "jsonrpc": "2.0",
8228            "id": 1,
8229            "result": {
8230                "number": "0x1cf0d41",
8231                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8232                "parentHash": FIXTURE_BLOCK_HASH,
8233                "timestamp": "0x69044a21",
8234                "baseFeePerGas": "0x5f5e100",
8235                "transactions": [{
8236                    "hash": tx_hash.to_string(),
8237                    "from": WALLET,
8238                    "nonce": "0x7",
8239                    "chainId": "0xa4b1",
8240                    "type": "0x2",
8241                    "to": WETH,
8242                    "input": "0xd0e30db0",
8243                    "value": "0x38d7ea4c68000",
8244                    "gas": "0x130b0",
8245                    "maxFeePerGas": "0x7bfa480",
8246                    "maxPriorityFeePerGas": "0x989680"
8247                }]
8248            }
8249        })
8250        .to_string()
8251    }
8252
8253    fn finalized_approve_block(tx_hash: B256, amount: U256) -> String {
8254        let calldata = ERC20::approveCall {
8255            spender: ROUTER_ADDRESS,
8256            amount,
8257        }
8258        .abi_encode();
8259        serde_json::json!({
8260            "jsonrpc": "2.0",
8261            "id": 1,
8262            "result": {
8263                "number": "0x1cf0d41",
8264                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
8265                "parentHash": FIXTURE_BLOCK_HASH,
8266                "timestamp": "0x69044a21",
8267                "baseFeePerGas": "0x5f5e100",
8268                "transactions": [{
8269                    "hash": tx_hash.to_string(),
8270                    "from": WALLET,
8271                    "nonce": "0x7",
8272                    "chainId": "0xa4b1",
8273                    "type": "0x2",
8274                    "to": WETH,
8275                    "input": hex::encode_prefixed(calldata),
8276                    "value": "0x0",
8277                    "gas": "0x130b0",
8278                    "maxFeePerGas": "0x7bfa480",
8279                    "maxPriorityFeePerGas": "0x989680"
8280                }]
8281            }
8282        })
8283        .to_string()
8284    }
8285
8286    fn fixture_sell_plan() -> SwapPlan {
8287        let pool = test_pool();
8288        let order = test_market_sell_order(pool.instrument_id);
8289        let quote_token = pool.get_quote_token();
8290        SwapPlan {
8291            order,
8292            quote_currency: quote_token.currency().unwrap(),
8293            instrument_id: pool.instrument_id,
8294            pool_address: pool.address,
8295            router: ROUTER_ADDRESS,
8296            factory: UNISWAP_V3.dex.factory,
8297            weth: WETH_ADDRESS,
8298            token_in: WETH_ADDRESS,
8299            token_out: USDC_ADDRESS,
8300            fee: U24::try_from(500u32).unwrap(),
8301            amount_in: U256::from(1_000_000_000_000_000u64),
8302            min_amount_out: expected_min_amount_out(50),
8303            slippage_bps: 50,
8304            quote_spend_ceiling: None,
8305            profiler_position: Some(profiler_event_position()),
8306            pool,
8307        }
8308    }
8309
8310    fn fixture_block_response(number: u64, hash: B256) -> String {
8311        let parent_hash = if number == FIXTURE_BLOCK {
8312            B256::from_str("0x0000000000000000000000000000000000000000000000000000000000000001")
8313                .unwrap()
8314        } else {
8315            B256::from_str(FIXTURE_BLOCK_HASH).unwrap()
8316        };
8317        serde_json::json!({
8318            "jsonrpc": "2.0",
8319            "id": 1,
8320            "result": {
8321                "number": format!("0x{number:x}"),
8322                "hash": hash.to_string(),
8323                "parentHash": parent_hash.to_string(),
8324                "timestamp": format!("0x{:x}", FIXTURE_BLOCK_TIMESTAMP + number - FIXTURE_BLOCK),
8325                "baseFeePerGas": "0x5f5e100",
8326                "transactions": []
8327            }
8328        })
8329        .to_string()
8330    }
8331
8332    fn profiler_event_receipt(pool_address: Address) -> String {
8333        let transaction_hash = B256::from([0x33; 32]);
8334        serde_json::json!({
8335            "jsonrpc": "2.0",
8336            "id": 1,
8337            "result": {
8338                "transactionHash": transaction_hash.to_string(),
8339                "blockHash": FIXTURE_BLOCK_HASH,
8340                "blockNumber": "0x1cf0d40",
8341                "transactionIndex": "0x2",
8342                "gasUsed": "0xc3c0",
8343                "effectiveGasPrice": "0x5f5e100",
8344                "status": "0x1",
8345                "logs": [{
8346                    "removed": false,
8347                    "logIndex": "0x6",
8348                    "transactionIndex": "0x2",
8349                    "transactionHash": transaction_hash.to_string(),
8350                    "blockHash": FIXTURE_BLOCK_HASH,
8351                    "blockNumber": "0x1cf0d40",
8352                    "address": pool_address.to_string(),
8353                    "data": "0x",
8354                    "topics": [test_pool().dex.swap_created_event.as_ref()]
8355                }]
8356            }
8357        })
8358        .to_string()
8359    }
8360
8361    fn profiler_event_position() -> BlockPosition {
8362        BlockPosition::new(FIXTURE_BLOCK, B256::from([0x33; 32]).to_string(), 2, 6)
8363            .with_block_hash(Some(FIXTURE_BLOCK_HASH.to_string()))
8364    }
8365
8366    #[rstest]
8367    fn quantity_to_raw_amount_scales_by_token_decimals() {
8368        assert_eq!(
8369            quantity_to_raw_amount(Quantity::from("0.001"), 18).unwrap(),
8370            U256::from(1_000_000_000_000_000u64)
8371        );
8372        assert_eq!(
8373            quantity_to_raw_amount(Quantity::from("1.5"), 18).unwrap(),
8374            U256::from(1_500_000_000_000_000_000u128)
8375        );
8376        assert_eq!(
8377            quantity_to_raw_amount(Quantity::from("12.5"), 6).unwrap(),
8378            U256::from(12_500_000u64)
8379        );
8380    }
8381
8382    #[rstest]
8383    fn quantity_to_raw_amount_uses_defi_quantity_precision() {
8384        let amount = U256::from(10_000_000_000_000_000u64);
8385        let quantity = Quantity::from_u256(amount, 18).unwrap();
8386
8387        assert_eq!(quantity_to_raw_amount(quantity, 18).unwrap(), amount);
8388    }
8389
8390    #[rstest]
8391    fn quantity_to_raw_amount_rejects_zero() {
8392        let error = quantity_to_raw_amount(Quantity::from("0.0"), 18).unwrap_err();
8393
8394        assert_eq!(error.to_string(), "Order quantity must be positive");
8395    }
8396
8397    #[rstest]
8398    fn quantity_to_raw_amount_rejects_inexact_token_units() {
8399        let error = quantity_to_raw_amount(Quantity::from("0.0000001"), 6).unwrap_err();
8400
8401        assert!(
8402            error
8403                .to_string()
8404                .contains("is not exactly representable in 6 base token decimals"),
8405            "was: {error}"
8406        );
8407    }
8408
8409    #[rstest]
8410    fn raw_amount_to_quantity_inverts_base_quantity() {
8411        let quantity = Quantity::from("0.001");
8412        let amount = quantity_to_raw_amount(quantity, 18).unwrap();
8413
8414        assert_eq!(raw_amount_to_quantity(amount, 18).unwrap(), quantity);
8415    }
8416
8417    #[rstest]
8418    fn raw_amount_to_quantity_rejects_positive_amount_truncated_to_zero() {
8419        let error = raw_amount_to_quantity(U256::from(99u64), 18).unwrap_err();
8420
8421        assert!(
8422            error
8423                .to_string()
8424                .contains("is below representable quantity precision"),
8425            "was: {error}"
8426        );
8427    }
8428
8429    #[rstest]
8430    fn fill_price_from_quote_recovers_spent_quote_after_quantity_truncation() {
8431        let last_qty = raw_amount_to_quantity(U256::from(1_000_000_403_079_044u64), 18).unwrap();
8432        let quote_amount = U256::from(1_891_348u64);
8433        let quote = Currency::new_checked("USDC", 6, 0, "USD Coin", CurrencyType::Crypto).unwrap();
8434        let last_px = fill_price_from_quote(last_qty, quote_amount, quote).unwrap();
8435
8436        assert_eq!(
8437            Money::from_decimal(last_qty.as_decimal() * last_px.as_decimal(), quote).unwrap(),
8438            Money::from_u256(quote_amount, quote).unwrap()
8439        );
8440    }
8441
8442    #[rstest]
8443    fn swap_token_pair_is_directional() {
8444        assert_eq!(
8445            swap_token_pair(OrderSide::Sell, WETH_ADDRESS, USDC_ADDRESS),
8446            (WETH_ADDRESS, USDC_ADDRESS)
8447        );
8448        assert_eq!(
8449            swap_token_pair(OrderSide::Buy, WETH_ADDRESS, USDC_ADDRESS),
8450            (USDC_ADDRESS, WETH_ADDRESS)
8451        );
8452    }
8453
8454    #[rstest]
8455    fn restore_swap_plan_buy_uses_quote_input() {
8456        let (client, cache) =
8457            swap_client_with_cache(buy_test_config("http://127.0.0.1:1".to_string()));
8458        let order = test_market_buy_order(test_pool().instrument_id);
8459        cache
8460            .borrow_mut()
8461            .add_order(order.clone(), None, None, true)
8462            .unwrap();
8463        let amount_in = U256::from(2_345_678u64);
8464        let intent = ExecutionIntentRow {
8465            id: 7,
8466            schema_version: crate::execution::transaction::EXECUTION_SCHEMA_VERSION,
8467            chain_id: 42161,
8468            wallet_address: WALLET.to_string(),
8469            nonce: Some(7),
8470            purpose: "swap".to_string(),
8471            status: "finalized".to_string(),
8472            client_order_id: Some(order.client_order_id().to_string()),
8473            trader_id: Some(order.trader_id().to_string()),
8474            strategy_id: Some(order.strategy_id().to_string()),
8475            account_id: Some("BLOCKCHAIN-001".to_string()),
8476            instrument_id: Some(order.instrument_id().to_string()),
8477            pool_address: Some(test_pool().address.to_string()),
8478            transaction_to: ROUTER.to_string(),
8479            transaction_input: "0x".to_string(),
8480            transaction_value: "0".to_string(),
8481            amount_in: Some(amount_in.to_string()),
8482            created_block: FIXTURE_BLOCK,
8483            acknowledgement_emitted: true,
8484            fill_emitted: false,
8485            terminal_emitted: false,
8486            active: true,
8487        };
8488
8489        let plan = client.restore_swap_plan(&intent).unwrap();
8490
8491        assert_eq!(plan.token_in, USDC_ADDRESS);
8492        assert_eq!(plan.token_out, WETH_ADDRESS);
8493        assert_eq!(plan.amount_in, amount_in);
8494    }
8495
8496    #[rstest]
8497    #[case(1_000_000, 50, 995_000)]
8498    #[case(1_000_000, 0, 1_000_000)]
8499    #[case(1_000_000, 200, 980_000)]
8500    #[case(10_000, 9_999, 1)]
8501    fn derive_min_amount_out_applies_slippage(
8502        #[case] quoted: u64,
8503        #[case] slippage_bps: u32,
8504        #[case] expected: u64,
8505    ) {
8506        assert_eq!(
8507            derive_min_amount_out(U256::from(quoted), slippage_bps).unwrap(),
8508            U256::from(expected)
8509        );
8510    }
8511
8512    #[rstest]
8513    fn derive_min_amount_out_rejects_zero_result() {
8514        let error = derive_min_amount_out(U256::from(9_999u64), 9_999).unwrap_err();
8515
8516        assert!(
8517            error.to_string().contains("Derived minimum output is zero"),
8518            "was: {error}"
8519        );
8520    }
8521
8522    #[rstest]
8523    fn derive_min_amount_out_rejects_full_slippage() {
8524        let error = derive_min_amount_out(U256::from(1_000_000u64), 10_000).unwrap_err();
8525
8526        assert!(
8527            error.to_string().contains("must be below 10000"),
8528            "was: {error}"
8529        );
8530    }
8531
8532    #[rstest]
8533    fn replacement_scan_range_is_bounded_and_checked() {
8534        assert_eq!(
8535            replacement_scan_range(10, 10).unwrap(),
8536            RangeInclusive::new(10, 10)
8537        );
8538        assert_eq!(
8539            replacement_scan_range(10, 10 + MAX_REPLACEMENT_SCAN_BLOCKS).unwrap(),
8540            RangeInclusive::new(10, 10 + MAX_REPLACEMENT_SCAN_BLOCKS - 1)
8541        );
8542        assert!(
8543            replacement_scan_range(11, 10)
8544                .unwrap_err()
8545                .to_string()
8546                .contains("is behind execution creation block")
8547        );
8548        assert_eq!(
8549            replacement_scan_range(u64::MAX - 1, u64::MAX).unwrap(),
8550            RangeInclusive::new(u64::MAX - 1, u64::MAX)
8551        );
8552    }
8553
8554    #[rstest]
8555    fn terminal_execution_event_ids_are_stable_and_kind_specific() {
8556        let transaction_hash = B256::from([0x42; 32]);
8557
8558        let fill = execution_event_id(transaction_hash, b"fill");
8559        let fill_retry = execution_event_id(transaction_hash, b"fill");
8560        let reverted = execution_event_id(transaction_hash, b"reverted");
8561
8562        assert_eq!(fill, fill_retry);
8563        assert_ne!(fill, reverted);
8564    }
8565
8566    #[rstest]
8567    fn prepared_transaction_debug_redacts_raw_transaction() {
8568        let prepared = PreparedTransaction {
8569            intent_id: 1,
8570            created_block: 2,
8571            nonce: 3,
8572            tx_hash: B256::ZERO,
8573            raw_tx: vec![0xde, 0xad, 0xbe, 0xef],
8574            payload_lease: None,
8575        };
8576
8577        let debug = format!("{prepared:?}");
8578
8579        assert!(debug.contains("raw_tx: \"<redacted>\""));
8580        assert!(!debug.contains("[222, 173, 190, 239]"));
8581    }
8582
8583    #[rstest]
8584    fn call_trace_rejects_unreviewed_internal_edge() {
8585        let signed = crate::execution::transaction::DecodedSignedTransaction {
8586            hash: B256::from([1; 32]),
8587            signer: Address::from_str(WALLET).unwrap(),
8588            chain_id: 42_161,
8589            nonce: 7,
8590            to: ROUTER_ADDRESS,
8591            value: U256::ZERO,
8592            input: Bytes::from(expected_swap_calldata(expected_min_amount_out(50))),
8593            gas_limit: 78_000,
8594            max_fee_per_gas: 130_000_000,
8595            max_priority_fee_per_gas: 10_000_000,
8596        };
8597        let input_digest = keccak256(&signed.input);
8598        let trace = VerifiedCallTrace {
8599            call_type: RpcCallType::Call,
8600            from: signed.signer,
8601            to: Some(signed.to),
8602            value: signed.value,
8603            input_selector: signed
8604                .input
8605                .get(..4)
8606                .map(|selector| selector.try_into().unwrap()),
8607            input_digest,
8608            success: true,
8609            calls: vec![VerifiedCallTrace {
8610                call_type: RpcCallType::Call,
8611                from: ROUTER_ADDRESS,
8612                to: Some(WETH_ADDRESS),
8613                value: U256::ZERO,
8614                input_selector: None,
8615                input_digest: B256::ZERO,
8616                success: true,
8617                calls: Vec::new(),
8618            }],
8619        };
8620        let manifest = &test_config("http://127.0.0.1:1".to_string())
8621            .verification
8622            .unwrap()
8623            .deployment_manifest;
8624
8625        let error = validate_call_trace(&trace, &signed, true, "swap_sell", manifest).unwrap_err();
8626
8627        assert!(
8628            error.to_string().contains("unreviewed call edge"),
8629            "was: {error}"
8630        );
8631    }
8632
8633    #[rstest]
8634    fn call_trace_rejects_unlisted_precompile_target() {
8635        let manifest = test_config("http://127.0.0.1:1".to_string())
8636            .verification
8637            .unwrap()
8638            .deployment_manifest;
8639        let calls = [VerifiedCallTrace {
8640            call_type: RpcCallType::Call,
8641            from: ROUTER_ADDRESS,
8642            to: Some(address!("0000000000000000000000000000000000000007")),
8643            value: U256::ZERO,
8644            input_selector: None,
8645            input_digest: B256::ZERO,
8646            success: true,
8647            calls: Vec::new(),
8648        }];
8649
8650        let error =
8651            validate_internal_calls(&calls, ROUTER_ADDRESS, "swap_sell", &manifest).unwrap_err();
8652
8653        assert_eq!(
8654            error.to_string(),
8655            format!(
8656                "Verified call trace contains an unreviewed call edge {ROUTER_ADDRESS} -> {} for swap_sell",
8657                address!("0000000000000000000000000000000000000007")
8658            )
8659        );
8660    }
8661
8662    #[rstest]
8663    fn call_trace_requires_exact_call_type() {
8664        let manifest = test_config("http://127.0.0.1:1".to_string())
8665            .verification
8666            .unwrap()
8667            .deployment_manifest;
8668        let calls = [VerifiedCallTrace {
8669            call_type: RpcCallType::Staticcall,
8670            from: ROUTER_ADDRESS,
8671            to: Some(test_pool().address),
8672            value: U256::ZERO,
8673            input_selector: None,
8674            input_digest: B256::ZERO,
8675            success: true,
8676            calls: Vec::new(),
8677        }];
8678
8679        let error =
8680            validate_internal_calls(&calls, ROUTER_ADDRESS, "swap_sell", &manifest).unwrap_err();
8681
8682        assert!(
8683            error.to_string().contains("unreviewed staticcall edge"),
8684            "was: {error}"
8685        );
8686    }
8687
8688    #[rstest]
8689    fn call_trace_requires_exact_caller() {
8690        let manifest = test_config("http://127.0.0.1:1".to_string())
8691            .verification
8692            .unwrap()
8693            .deployment_manifest;
8694        let calls = [VerifiedCallTrace {
8695            call_type: RpcCallType::Call,
8696            from: WETH_ADDRESS,
8697            to: Some(test_pool().address),
8698            value: U256::ZERO,
8699            input_selector: None,
8700            input_digest: B256::ZERO,
8701            success: true,
8702            calls: Vec::new(),
8703        }];
8704
8705        let error =
8706            validate_internal_calls(&calls, ROUTER_ADDRESS, "swap_sell", &manifest).unwrap_err();
8707
8708        assert_eq!(
8709            error.to_string(),
8710            "Verified call trace child has an invalid caller context"
8711        );
8712    }
8713
8714    #[rstest]
8715    fn call_trace_rejects_contract_creation() {
8716        let signed = crate::execution::transaction::DecodedSignedTransaction {
8717            hash: B256::from([1; 32]),
8718            signer: Address::from_str(WALLET).unwrap(),
8719            chain_id: 42_161,
8720            nonce: 7,
8721            to: ROUTER_ADDRESS,
8722            value: U256::ZERO,
8723            input: Bytes::from(expected_swap_calldata(expected_min_amount_out(50))),
8724            gas_limit: 78_000,
8725            max_fee_per_gas: 130_000_000,
8726            max_priority_fee_per_gas: 10_000_000,
8727        };
8728        let trace = VerifiedCallTrace {
8729            call_type: RpcCallType::Call,
8730            from: signed.signer,
8731            to: Some(signed.to),
8732            value: signed.value,
8733            input_selector: signed
8734                .input
8735                .get(..4)
8736                .map(|selector| selector.try_into().unwrap()),
8737            input_digest: keccak256(&signed.input),
8738            success: true,
8739            calls: vec![VerifiedCallTrace {
8740                call_type: RpcCallType::Create,
8741                from: ROUTER_ADDRESS,
8742                to: Some(address!("0000000000000000000000000000000000000007")),
8743                value: U256::ZERO,
8744                input_selector: None,
8745                input_digest: B256::ZERO,
8746                success: true,
8747                calls: Vec::new(),
8748            }],
8749        };
8750        let manifest = &test_config("http://127.0.0.1:1".to_string())
8751            .verification
8752            .unwrap()
8753            .deployment_manifest;
8754
8755        let error = validate_call_trace(&trace, &signed, true, "swap_sell", manifest).unwrap_err();
8756
8757        assert!(
8758            error
8759                .to_string()
8760                .contains("forbidden state-changing operation"),
8761            "was: {error}"
8762        );
8763    }
8764
8765    #[tokio::test]
8766    async fn swap_quote_rejects_missing_ingestion_block_hash() {
8767        let (client, state) = client_with_mock_rpc(execution_rpc_state()).await;
8768        let plan = fixture_sell_plan();
8769        let position = BlockPosition::new(
8770            FIXTURE_BLOCK,
8771            FIXTURE_BLOCK_HASH.to_string(),
8772            BLOCK_SCOPED_SNAPSHOT_INDEX,
8773            BLOCK_SCOPED_SNAPSHOT_INDEX,
8774        );
8775
8776        let error = validate_swap_quote(
8777            &position,
8778            &plan,
8779            100,
8780            &client.verification,
8781            &client
8782                .config
8783                .verification
8784                .as_ref()
8785                .unwrap()
8786                .deployment_manifest,
8787        )
8788        .await
8789        .unwrap_err();
8790
8791        assert!(
8792            error.to_string().contains("no ingestion-time block hash"),
8793            "was: {error}"
8794        );
8795        assert!(state.recorded_requests().is_empty());
8796    }
8797
8798    #[tokio::test]
8799    async fn swap_quote_rejects_replaced_ingestion_block() {
8800        let changed = fixture_block_response(FIXTURE_BLOCK, B256::from([0x44; 32]));
8801        let state = execution_rpc_state().with_parameter_response(
8802            "eth_getBlockByNumber",
8803            "0x1cf0d40",
8804            &changed,
8805        );
8806        let (client, _) = client_with_mock_rpc(state).await;
8807        let plan = fixture_sell_plan();
8808        let position = BlockPosition::new(
8809            FIXTURE_BLOCK,
8810            FIXTURE_BLOCK_HASH.to_string(),
8811            BLOCK_SCOPED_SNAPSHOT_INDEX,
8812            BLOCK_SCOPED_SNAPSHOT_INDEX,
8813        )
8814        .with_block_hash(Some(FIXTURE_BLOCK_HASH.to_string()));
8815
8816        let error = validate_swap_quote(
8817            &position,
8818            &plan,
8819            100,
8820            &client.verification,
8821            &client
8822                .config
8823                .verification
8824                .as_ref()
8825                .unwrap()
8826                .deployment_manifest,
8827        )
8828        .await
8829        .unwrap_err();
8830
8831        assert!(error.to_string().contains("changed from"), "was: {error}");
8832    }
8833
8834    #[tokio::test]
8835    async fn swap_quote_accepts_exact_canonical_event_watermark() {
8836        let pool = test_pool();
8837        let receipt = profiler_event_receipt(pool.address);
8838        let state = execution_rpc_state().with_response("eth_getTransactionReceipt", &receipt);
8839        let (client, _) = client_with_mock_rpc(state).await;
8840        let plan = fixture_sell_plan();
8841
8842        let anchors = validate_swap_quote(
8843            &profiler_event_position(),
8844            &plan,
8845            100,
8846            &client.verification,
8847            &client
8848                .config
8849                .verification
8850                .as_ref()
8851                .unwrap()
8852                .deployment_manifest,
8853        )
8854        .await
8855        .unwrap();
8856
8857        assert_eq!(anchors.watermark.number, profiler_event_position().number);
8858        assert_eq!(anchors.state.number, FIXTURE_BLOCK);
8859        assert_eq!(anchors.state.hash, B256::from([0x11; 32]));
8860        assert_eq!(anchors.state.timestamp, FIXTURE_BLOCK_TIMESTAMP);
8861    }
8862
8863    #[tokio::test]
8864    async fn swap_quote_rejects_mismatched_receipt_position() {
8865        let pool = test_pool();
8866        let mut receipt: serde_json::Value =
8867            serde_json::from_str(&profiler_event_receipt(pool.address)).unwrap();
8868        receipt["result"]["transactionIndex"] = serde_json::json!("0x3");
8869        let state =
8870            execution_rpc_state().with_response("eth_getTransactionReceipt", &receipt.to_string());
8871        let (client, _) = client_with_mock_rpc(state).await;
8872        let plan = fixture_sell_plan();
8873
8874        let error = validate_swap_quote(
8875            &profiler_event_position(),
8876            &plan,
8877            100,
8878            &client.verification,
8879            &client
8880                .config
8881                .verification
8882                .as_ref()
8883                .unwrap()
8884                .deployment_manifest,
8885        )
8886        .await
8887        .unwrap_err();
8888
8889        assert_eq!(
8890            error.to_string(),
8891            "Profiler receipt position does not match its ingestion watermark"
8892        );
8893    }
8894
8895    #[tokio::test]
8896    async fn swap_quote_rejects_watermark_from_different_pool() {
8897        let receipt = profiler_event_receipt(ROUTER_ADDRESS);
8898        let state = execution_rpc_state().with_response("eth_getTransactionReceipt", &receipt);
8899        let (client, _) = client_with_mock_rpc(state).await;
8900        let plan = fixture_sell_plan();
8901
8902        let error = validate_swap_quote(
8903            &profiler_event_position(),
8904            &plan,
8905            100,
8906            &client.verification,
8907            &client
8908                .config
8909                .verification
8910                .as_ref()
8911                .unwrap()
8912                .deployment_manifest,
8913        )
8914        .await
8915        .unwrap_err();
8916
8917        assert!(
8918            error
8919                .to_string()
8920                .contains("did not come from expected pool"),
8921            "was: {error}"
8922        );
8923    }
8924
8925    #[rstest]
8926    fn verified_sell_quote_sets_signed_amounts() {
8927        let plan = fixture_sell_plan();
8928        let quote = UniswapV3Quote {
8929            amount: expected_sell_quote_amount(),
8930            sqrt_price_x96_after: U160::from(1u128 << 96),
8931            initialized_ticks_crossed: 0,
8932            gas_estimate: U256::from(50_000u64),
8933        };
8934
8935        let (amount_in, min_amount_out) = verified_swap_amounts(&plan, quote).unwrap();
8936
8937        assert_eq!(amount_in, U256::from(1_000_000_000_000_000u64));
8938        assert_eq!(min_amount_out, expected_min_amount_out(50));
8939    }
8940
8941    #[rstest]
8942    fn exact_output_amount_extracts_negative_leg() {
8943        let pool = test_pool();
8944        let profiler = test_profiler(&pool, FIXTURE_BLOCK);
8945        let quote = profiler
8946            .swap_exact_in(U256::from(1_000_000_000_000_000u64), true, None)
8947            .unwrap();
8948
8949        let amount = exact_output_amount(&quote, true).unwrap();
8950
8951        assert!(amount < U256::from(1_000_000_000_000_000u64));
8952        assert!(amount > U256::from(990_000_000_000_000u64));
8953
8954        let error = exact_output_amount(&quote, false).unwrap_err();
8955        assert!(
8956            error.to_string().contains("is not a positive output"),
8957            "was: {error}"
8958        );
8959    }
8960
8961    #[rstest]
8962    #[case("0xC6962004f452bE9203591991D15f6b388e09E8D0.Arbitrum:UniswapV3", true)]
8963    #[case("0xC6962004f452bE9203591991D15f6b388e09E8D0.Ethereum:UniswapV3", false)]
8964    #[case("0xC6962004f452bE9203591991D15f6b388e09E8D0.Arbitrum:UniswapV4", false)]
8965    #[case("ETHUSDT-PERP.BINANCE", false)]
8966    fn handles_order_venue_matches_chain_and_dex(#[case] instrument: &str, #[case] expected: bool) {
8967        let client = test_client("http://127.0.0.1:1".to_string());
8968        let instrument_id: InstrumentId = instrument.parse().unwrap();
8969
8970        assert_eq!(client.handles_order_venue(instrument_id.venue), expected);
8971    }
8972
8973    #[tokio::test]
8974    async fn submit_order_denies_buy_without_allowlisted_pair() {
8975        let (mut client, cache) =
8976            swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
8977        let pool = test_pool();
8978        let order = test_market_buy_order(pool.instrument_id);
8979        cache
8980            .borrow_mut()
8981            .add_order(order.clone(), None, None, true)
8982            .unwrap();
8983        let mut receiver = start_with_events(&mut client);
8984
8985        client.submit_order(submit_order_cmd(&order)).unwrap();
8986
8987        let events = collect_order_events(&mut receiver);
8988        assert_eq!(events.len(), 1);
8989        let OrderEventAny::Denied(denied) = &events[0] else {
8990            panic!("expected OrderDenied, was {:?}", events[0]);
8991        };
8992        assert!(
8993            denied
8994                .reason
8995                .contains("not in the `allowed_token_pairs` allowlist"),
8996            "was: {}",
8997            denied.reason
8998        );
8999        assert!(
9000            denied.reason.contains(&USDC_ADDRESS.to_string()),
9001            "was: {}",
9002            denied.reason
9003        );
9004    }
9005
9006    #[tokio::test]
9007    async fn submit_order_denies_buy_quote_denominated_quantity() {
9008        let (mut client, cache) =
9009            swap_client_with_cache(buy_test_config("http://127.0.0.1:1".to_string()));
9010        let pool = test_pool();
9011        let order = OrderTestBuilder::new(OrderType::Market)
9012            .trader_id(TraderId::from("TRADER-001"))
9013            .strategy_id(StrategyId::from("S-001"))
9014            .instrument_id(pool.instrument_id)
9015            .client_order_id(ClientOrderId::from("O-SWAP-BUY-001"))
9016            .side(OrderSide::Buy)
9017            .quantity(Quantity::from("0.001"))
9018            .quote_quantity(true)
9019            .build();
9020        cache
9021            .borrow_mut()
9022            .add_order(order.clone(), None, None, true)
9023            .unwrap();
9024        let mut receiver = start_with_events(&mut client);
9025
9026        client.submit_order(submit_order_cmd(&order)).unwrap();
9027
9028        let events = collect_order_events(&mut receiver);
9029        assert_eq!(events.len(), 1);
9030        let OrderEventAny::Denied(denied) = &events[0] else {
9031            panic!("expected OrderDenied, was {:?}", events[0]);
9032        };
9033
9034        assert_eq!(denied.reason.as_str(), "UNSUPPORTED_QUOTE_QUANTITY");
9035    }
9036
9037    #[tokio::test]
9038    async fn submit_order_denies_buy_amount_above_max_order_amount() {
9039        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9040        config.max_order_amount = Some(999_999_999_999_999);
9041        let (mut client, cache) = swap_client_with_cache(config);
9042        let order = test_market_buy_order(test_pool().instrument_id);
9043        cache
9044            .borrow_mut()
9045            .add_order(order.clone(), None, None, true)
9046            .unwrap();
9047        let mut receiver = start_with_events(&mut client);
9048
9049        client.submit_order(submit_order_cmd(&order)).unwrap();
9050
9051        let events = collect_order_events(&mut receiver);
9052        assert_eq!(events.len(), 1);
9053        let OrderEventAny::Denied(denied) = &events[0] else {
9054            panic!("expected OrderDenied, was {:?}", events[0]);
9055        };
9056        assert!(
9057            denied
9058                .reason
9059                .contains("exceeds the configured `max_order_amount`"),
9060            "was: {}",
9061            denied.reason
9062        );
9063    }
9064
9065    #[tokio::test]
9066    async fn submit_order_denies_buy_without_quote_spend_limit() {
9067        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9068        config.quote_spend_limits = None;
9069        let (mut client, cache) = swap_client_with_cache(config);
9070        let order = test_market_buy_order(test_pool().instrument_id);
9071        cache
9072            .borrow_mut()
9073            .add_order(order.clone(), None, None, true)
9074            .unwrap();
9075        let mut receiver = start_with_events(&mut client);
9076
9077        client.submit_order(submit_order_cmd(&order)).unwrap();
9078
9079        let events = collect_order_events(&mut receiver);
9080        assert_eq!(events.len(), 1);
9081        let OrderEventAny::Denied(denied) = &events[0] else {
9082            panic!("expected OrderDenied, was {:?}", events[0]);
9083        };
9084        assert!(
9085            denied
9086                .reason
9087                .contains("No `quote_spend_limits` entry for BUY token pair"),
9088            "was: {}",
9089            denied.reason
9090        );
9091    }
9092
9093    #[tokio::test]
9094    async fn submit_order_uses_pair_specific_quote_spend_limit() {
9095        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9096        config.quote_spend_limits = Some(vec![quote_spend_limit(
9097            WETH,
9098            USDC,
9099            18,
9100            "1000000000000000000",
9101        )]);
9102        let (mut client, cache) = swap_client_with_cache(config);
9103        let order = test_market_buy_order(test_pool().instrument_id);
9104        cache
9105            .borrow_mut()
9106            .add_order(order.clone(), None, None, true)
9107            .unwrap();
9108        let mut receiver = start_with_events(&mut client);
9109
9110        client.submit_order(submit_order_cmd(&order)).unwrap();
9111
9112        let events = collect_order_events(&mut receiver);
9113        assert_eq!(events.len(), 1);
9114        let OrderEventAny::Denied(denied) = &events[0] else {
9115            panic!("expected OrderDenied, was {:?}", events[0]);
9116        };
9117        assert!(
9118            denied
9119                .reason
9120                .contains("No `quote_spend_limits` entry for BUY token pair"),
9121            "was: {}",
9122            denied.reason
9123        );
9124    }
9125
9126    #[tokio::test]
9127    async fn submit_order_denies_buy_with_quote_spend_precision_mismatch() {
9128        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9129        config.quote_spend_limits.as_mut().unwrap()[0].spend_token_decimals = 18;
9130        let error = test_client_result(config, test_pool()).unwrap_err();
9131        assert!(
9132            error
9133                .to_string()
9134                .contains("Quote spend limit decimals do not match the deployment manifest"),
9135            "was: {error}"
9136        );
9137    }
9138
9139    #[tokio::test]
9140    async fn submit_order_denies_buy_with_zero_quote_spend_limit() {
9141        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9142        config.quote_spend_limits.as_mut().unwrap()[0].max_amount = "0".to_string();
9143        let (mut client, cache) = swap_client_with_cache(config);
9144        let order = test_market_buy_order(test_pool().instrument_id);
9145        cache
9146            .borrow_mut()
9147            .add_order(order.clone(), None, None, true)
9148            .unwrap();
9149        let mut receiver = start_with_events(&mut client);
9150
9151        client.submit_order(submit_order_cmd(&order)).unwrap();
9152
9153        let events = collect_order_events(&mut receiver);
9154        assert_eq!(events.len(), 1);
9155        let OrderEventAny::Denied(denied) = &events[0] else {
9156            panic!("expected OrderDenied, was {:?}", events[0]);
9157        };
9158        assert!(
9159            denied
9160                .reason
9161                .contains("exceeds the configured `quote_spend_limits` maximum 0"),
9162            "was: {}",
9163            denied.reason
9164        );
9165    }
9166
9167    #[tokio::test]
9168    async fn submit_order_denies_buy_one_raw_unit_above_quote_spend_limit_before_readiness() {
9169        let amount_in = expected_buy_amount_in();
9170        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
9171        config.quote_spend_limits.as_mut().unwrap()[0].max_amount =
9172            (amount_in - U256::from(1u8)).to_string();
9173        let (mut client, cache) = swap_client_with_cache(config);
9174        let order = test_market_buy_order(test_pool().instrument_id);
9175        cache
9176            .borrow_mut()
9177            .add_order(order.clone(), None, None, true)
9178            .unwrap();
9179        let mut receiver = start_with_events(&mut client);
9180
9181        client.submit_order(submit_order_cmd(&order)).unwrap();
9182
9183        let events = collect_order_events(&mut receiver);
9184        assert_eq!(events.len(), 1);
9185        let OrderEventAny::Denied(denied) = &events[0] else {
9186            panic!("expected OrderDenied, was {:?}", events[0]);
9187        };
9188        assert!(
9189            denied.reason.contains(&format!(
9190                "BUY quote amount {amount_in} exceeds the configured `quote_spend_limits`"
9191            )),
9192            "was: {}",
9193            denied.reason
9194        );
9195        assert!(!client.core.is_connected());
9196        assert!(!client.cache.has_database());
9197        assert!(client.signer.is_none());
9198        assert!(client.pending_tasks.is_empty());
9199    }
9200
9201    #[tokio::test]
9202    async fn submit_order_denies_non_market_order_type() {
9203        let (mut client, cache) =
9204            swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9205        let pool = test_pool();
9206        let order = OrderTestBuilder::new(OrderType::Limit)
9207            .trader_id(TraderId::from("TRADER-001"))
9208            .strategy_id(StrategyId::from("S-001"))
9209            .instrument_id(pool.instrument_id)
9210            .client_order_id(ClientOrderId::from("O-SWAP-001"))
9211            .side(OrderSide::Sell)
9212            .quantity(Quantity::from("0.001"))
9213            .price(Price::from("2000"))
9214            .build();
9215        cache
9216            .borrow_mut()
9217            .add_order(order.clone(), None, None, true)
9218            .unwrap();
9219        let mut receiver = start_with_events(&mut client);
9220
9221        client.submit_order(submit_order_cmd(&order)).unwrap();
9222
9223        let events = collect_order_events(&mut receiver);
9224        assert_eq!(events.len(), 1);
9225        let OrderEventAny::Denied(denied) = &events[0] else {
9226            panic!("expected OrderDenied, was {:?}", events[0]);
9227        };
9228        assert!(
9229            denied.reason.contains("only Market is supported"),
9230            "was: {}",
9231            denied.reason
9232        );
9233    }
9234
9235    #[tokio::test]
9236    async fn submit_order_denies_quote_denominated_quantity() {
9237        let (mut client, cache) =
9238            swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9239        let pool = test_pool();
9240        let order = OrderTestBuilder::new(OrderType::Market)
9241            .trader_id(TraderId::from("TRADER-001"))
9242            .strategy_id(StrategyId::from("S-001"))
9243            .instrument_id(pool.instrument_id)
9244            .client_order_id(ClientOrderId::from("O-SWAP-001"))
9245            .side(OrderSide::Sell)
9246            .quantity(Quantity::from("0.001"))
9247            .quote_quantity(true)
9248            .build();
9249        cache
9250            .borrow_mut()
9251            .add_order(order.clone(), None, None, true)
9252            .unwrap();
9253        let mut receiver = start_with_events(&mut client);
9254
9255        client.submit_order(submit_order_cmd(&order)).unwrap();
9256
9257        let events = collect_order_events(&mut receiver);
9258        assert_eq!(events.len(), 1);
9259        let OrderEventAny::Denied(denied) = &events[0] else {
9260            panic!("expected OrderDenied, was {:?}", events[0]);
9261        };
9262
9263        assert_eq!(denied.reason.as_str(), "UNSUPPORTED_QUOTE_QUANTITY");
9264    }
9265
9266    #[tokio::test]
9267    async fn submit_order_denies_unknown_pool() {
9268        let (mut client, cache) =
9269            swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9270        let unknown: InstrumentId = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45.Arbitrum:UniswapV3"
9271            .parse()
9272            .unwrap();
9273        let order = OrderTestBuilder::new(OrderType::Market)
9274            .trader_id(TraderId::from("TRADER-001"))
9275            .strategy_id(StrategyId::from("S-001"))
9276            .instrument_id(unknown)
9277            .client_order_id(ClientOrderId::from("O-SWAP-001"))
9278            .side(OrderSide::Sell)
9279            .quantity(Quantity::from("0.001"))
9280            .build();
9281        cache
9282            .borrow_mut()
9283            .add_order(order.clone(), None, None, true)
9284            .unwrap();
9285        let mut receiver = start_with_events(&mut client);
9286
9287        client.submit_order(submit_order_cmd(&order)).unwrap();
9288
9289        let events = collect_order_events(&mut receiver);
9290        assert_eq!(events.len(), 1);
9291        let OrderEventAny::Denied(denied) = &events[0] else {
9292            panic!("expected OrderDenied, was {:?}", events[0]);
9293        };
9294        assert!(
9295            denied.reason.contains("Unknown pool"),
9296            "was: {}",
9297            denied.reason
9298        );
9299    }
9300
9301    #[tokio::test]
9302    async fn submit_order_denies_sell_when_only_buy_pair_allowlisted() {
9303        let mut config = test_config("http://127.0.0.1:1".to_string());
9304        config.allowed_token_pairs = Some(vec![(USDC.to_string(), WETH.to_string())]);
9305        let (mut client, _) = swap_client_with_cache(config);
9306        let order = test_market_sell_order(test_pool().instrument_id);
9307        let mut receiver = start_with_events(&mut client);
9308
9309        client.submit_order(submit_order_cmd(&order)).unwrap();
9310
9311        let events = collect_order_events(&mut receiver);
9312        assert_eq!(events.len(), 1);
9313        let OrderEventAny::Denied(denied) = &events[0] else {
9314            panic!("expected OrderDenied, was {:?}", events[0]);
9315        };
9316        assert!(
9317            denied
9318                .reason
9319                .contains("not in the `allowed_token_pairs` allowlist"),
9320            "was: {}",
9321            denied.reason
9322        );
9323        assert!(
9324            denied.reason.contains(&WETH_ADDRESS.to_string()),
9325            "was: {}",
9326            denied.reason
9327        );
9328    }
9329
9330    #[tokio::test]
9331    async fn submit_order_sell_ignores_quote_spend_limits() {
9332        let mut config = test_config("http://127.0.0.1:1".to_string());
9333        config.quote_spend_limits = Some(vec![quote_spend_limit(WETH, USDC, 18, "0")]);
9334        let (mut client, _) = swap_client_with_cache(config);
9335        let order = test_market_sell_order(test_pool().instrument_id);
9336        let mut receiver = start_with_events(&mut client);
9337
9338        client.submit_order(submit_order_cmd(&order)).unwrap();
9339
9340        let events = collect_order_events(&mut receiver);
9341        assert_eq!(events.len(), 1);
9342        let OrderEventAny::Denied(denied) = &events[0] else {
9343            panic!("expected OrderDenied, was {:?}", events[0]);
9344        };
9345        assert!(
9346            denied
9347                .reason
9348                .contains("Blockchain execution client is not connected"),
9349            "was: {}",
9350            denied.reason
9351        );
9352    }
9353
9354    #[tokio::test]
9355    async fn submit_order_denies_token_pair_outside_allowlist() {
9356        let mut config = test_config("http://127.0.0.1:1".to_string());
9357        config.allowed_token_pairs = Some(Vec::new());
9358        let (mut client, _) = swap_client_with_cache(config);
9359        let order = test_market_sell_order(test_pool().instrument_id);
9360        let mut receiver = start_with_events(&mut client);
9361
9362        client.submit_order(submit_order_cmd(&order)).unwrap();
9363
9364        let events = collect_order_events(&mut receiver);
9365        assert_eq!(events.len(), 1);
9366        let OrderEventAny::Denied(denied) = &events[0] else {
9367            panic!("expected OrderDenied, was {:?}", events[0]);
9368        };
9369        assert!(
9370            denied
9371                .reason
9372                .contains("not in the `allowed_token_pairs` allowlist"),
9373            "was: {}",
9374            denied.reason
9375        );
9376    }
9377
9378    #[tokio::test]
9379    async fn submit_order_denies_amount_above_max_order_amount() {
9380        let mut config = test_config("http://127.0.0.1:1".to_string());
9381        config.max_order_amount = Some(999_999_999_999_999); // 0.001 WETH in raw units minus one
9382        let (mut client, _) = swap_client_with_cache(config);
9383        let order = test_market_sell_order(test_pool().instrument_id);
9384        let mut receiver = start_with_events(&mut client);
9385
9386        client.submit_order(submit_order_cmd(&order)).unwrap();
9387
9388        let events = collect_order_events(&mut receiver);
9389        assert_eq!(events.len(), 1);
9390        let OrderEventAny::Denied(denied) = &events[0] else {
9391            panic!("expected OrderDenied, was {:?}", events[0]);
9392        };
9393        assert!(
9394            denied
9395                .reason
9396                .contains("exceeds the configured `max_order_amount`"),
9397            "was: {}",
9398            denied.reason
9399        );
9400    }
9401
9402    #[tokio::test]
9403    async fn submit_order_denies_slippage_param_above_ceiling() {
9404        let (mut client, _) = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9405        let order = test_market_sell_order(test_pool().instrument_id);
9406        let mut cmd = submit_order_cmd(&order);
9407        cmd.params = Some(serde_json::from_str(r#"{"slippage_bps": 201}"#).unwrap());
9408        let mut receiver = start_with_events(&mut client);
9409
9410        client.submit_order(cmd).unwrap();
9411
9412        let events = collect_order_events(&mut receiver);
9413        assert_eq!(events.len(), 1);
9414        let OrderEventAny::Denied(denied) = &events[0] else {
9415            panic!("expected OrderDenied, was {:?}", events[0]);
9416        };
9417        assert!(
9418            denied
9419                .reason
9420                .contains("exceeds the configured `max_slippage_bps`"),
9421            "was: {}",
9422            denied.reason
9423        );
9424    }
9425
9426    #[tokio::test]
9427    async fn submit_order_denies_pool_without_fee_tier() {
9428        let addr = start_mock_rpc_server(MockRpcState::default()).await;
9429        let mut pool = test_pool();
9430        pool.fee = None;
9431        let cache = Rc::new(RefCell::new(Cache::default()));
9432        cache.borrow_mut().add_pool(pool.clone()).unwrap();
9433        let order = test_market_sell_order(pool.instrument_id);
9434        cache
9435            .borrow_mut()
9436            .add_order(order.clone(), None, None, false)
9437            .unwrap();
9438        let core = ExecutionClientCore::new(
9439            TraderId::from("TRADER-001"),
9440            ClientId::from("BLOCKCHAIN-001"),
9441            *BLOCKCHAIN_VENUE,
9442            OmsType::Netting,
9443            AccountId::from("BLOCKCHAIN-001"),
9444            AccountType::Wallet,
9445            None,
9446            cache,
9447        );
9448        let mut client =
9449            BlockchainExecutionClient::new(core, test_config(format!("http://{addr}"))).unwrap();
9450        let mut receiver = start_with_events(&mut client);
9451
9452        client.submit_order(submit_order_cmd(&order)).unwrap();
9453
9454        let events = collect_order_events(&mut receiver);
9455        assert_eq!(events.len(), 1);
9456        let OrderEventAny::Denied(denied) = &events[0] else {
9457            panic!("expected OrderDenied, was {:?}", events[0]);
9458        };
9459        assert!(
9460            denied.reason.contains("no fee tier"),
9461            "was: {}",
9462            denied.reason
9463        );
9464    }
9465
9466    #[tokio::test]
9467    async fn submit_order_denies_without_live_profiler() {
9468        let addr = start_mock_rpc_server(MockRpcState::default()).await;
9469        let cache = Rc::new(RefCell::new(Cache::default()));
9470        let pool = test_pool();
9471        cache.borrow_mut().add_pool(pool.clone()).unwrap();
9472        let order = test_market_sell_order(pool.instrument_id);
9473        cache
9474            .borrow_mut()
9475            .add_order(order.clone(), None, None, false)
9476            .unwrap();
9477        let core = ExecutionClientCore::new(
9478            TraderId::from("TRADER-001"),
9479            ClientId::from("BLOCKCHAIN-001"),
9480            *BLOCKCHAIN_VENUE,
9481            OmsType::Netting,
9482            AccountId::from("BLOCKCHAIN-001"),
9483            AccountType::Wallet,
9484            None,
9485            cache,
9486        );
9487        let mut client =
9488            BlockchainExecutionClient::new(core, test_config(format!("http://{addr}"))).unwrap();
9489        let mut receiver = start_with_events(&mut client);
9490
9491        client.submit_order(submit_order_cmd(&order)).unwrap();
9492
9493        let events = collect_order_events(&mut receiver);
9494        assert_eq!(events.len(), 1);
9495        let OrderEventAny::Denied(denied) = &events[0] else {
9496            panic!("expected OrderDenied, was {:?}", events[0]);
9497        };
9498        assert!(
9499            denied.reason.contains("No pool profiler"),
9500            "was: {}",
9501            denied.reason
9502        );
9503    }
9504
9505    #[tokio::test]
9506    async fn submit_order_denies_when_not_connected() {
9507        let (mut client, _) = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9508        let order = test_market_sell_order(test_pool().instrument_id);
9509        let mut receiver = start_with_events(&mut client);
9510
9511        client.submit_order(submit_order_cmd(&order)).unwrap();
9512
9513        let events = collect_order_events(&mut receiver);
9514        assert_eq!(events.len(), 1);
9515        let OrderEventAny::Denied(denied) = &events[0] else {
9516            panic!("expected OrderDenied, was {:?}", events[0]);
9517        };
9518        assert!(
9519            denied.reason.contains("is not connected"),
9520            "was: {}",
9521            denied.reason
9522        );
9523    }
9524
9525    #[tokio::test]
9526    async fn submit_order_denies_without_durable_store() {
9527        let (mut client, _) = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9528        client.core.set_connected();
9529        let order = test_market_sell_order(test_pool().instrument_id);
9530        let mut receiver = start_with_events(&mut client);
9531
9532        client.submit_order(submit_order_cmd(&order)).unwrap();
9533
9534        let events = collect_order_events(&mut receiver);
9535        assert_eq!(events.len(), 1);
9536        let OrderEventAny::Denied(denied) = &events[0] else {
9537            panic!("expected OrderDenied, was {:?}", events[0]);
9538        };
9539        assert!(
9540            denied.reason.contains("No durable store configured"),
9541            "was: {}",
9542            denied.reason
9543        );
9544    }
9545
9546    #[tokio::test]
9547    async fn submit_order_denies_when_transaction_in_flight() {
9548        let (mut client, _) = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string()));
9549        client.core.set_connected();
9550        *client.in_flight.lock() = Some(InFlightSlot::AwaitingFinality(InFlightTransaction {
9551            intent_id: 1,
9552            nonce: 7,
9553            tx_hash: B256::ZERO,
9554            purpose: TransactionPurpose::Wrap,
9555        }));
9556        let order = test_market_sell_order(test_pool().instrument_id);
9557        let mut receiver = start_with_events(&mut client);
9558
9559        client.submit_order(submit_order_cmd(&order)).unwrap();
9560
9561        let events = collect_order_events(&mut receiver);
9562        assert_eq!(events.len(), 1);
9563        let OrderEventAny::Denied(denied) = &events[0] else {
9564            panic!("expected OrderDenied, was {:?}", events[0]);
9565        };
9566        assert!(
9567            denied.reason.contains("still awaiting finality"),
9568            "was: {}",
9569            denied.reason
9570        );
9571    }
9572
9573    #[tokio::test]
9574    async fn submit_order_denies_without_signer() {
9575        let Some((admin_pool, schema, mut client, _, _)) =
9576            swap_client_with_database("execution_submit_no_signer_test", swap_rpc_state().await)
9577                .await
9578        else {
9579            return;
9580        };
9581        client.signer = None;
9582        let order = test_market_sell_order(test_pool().instrument_id);
9583        let mut receiver = start_with_events(&mut client);
9584
9585        client.submit_order(submit_order_cmd(&order)).unwrap();
9586
9587        let events = collect_order_events(&mut receiver);
9588        assert_eq!(events.len(), 1);
9589        let OrderEventAny::Denied(denied) = &events[0] else {
9590            panic!("expected OrderDenied, was {:?}", events[0]);
9591        };
9592        assert!(
9593            denied.reason.contains("Signer not initialized"),
9594            "was: {}",
9595            denied.reason
9596        );
9597
9598        drop_execution_schema(&admin_pool, &schema).await;
9599    }
9600
9601    #[tokio::test]
9602    async fn submit_order_broadcasts_swap_and_records_client_order_id() {
9603        let Some((admin_pool, schema, mut client, state, _)) =
9604            swap_client_with_database("execution_submit_success_test", swap_rpc_state().await)
9605                .await
9606        else {
9607            return;
9608        };
9609        let order = test_market_sell_order(test_pool().instrument_id);
9610        let mut receiver = start_with_events(&mut client);
9611        let expected_min_out = expected_min_amount_out(50);
9612
9613        client.submit_order(submit_order_cmd(&order)).unwrap();
9614        await_pending_tasks(&client).await;
9615
9616        let events = collect_order_events(&mut receiver);
9617        assert_swap_submitted_and_filled(&events);
9618        let OrderEventAny::Submitted(submitted) = &events[0] else {
9619            panic!("expected OrderSubmitted, was {:?}", events[0]);
9620        };
9621        assert_eq!(submitted.client_order_id, order.client_order_id());
9622
9623        // The recorded broadcast matches the fully signed expected transaction
9624        let (expected_hash, expected_raw) = expected_swap_tx(expected_min_out).await;
9625        let broadcasts: Vec<_> = state
9626            .recorded_requests()
9627            .into_iter()
9628            .filter(|request| request["method"] == "eth_sendRawTransaction")
9629            .collect();
9630        assert_eq!(broadcasts.len(), 1);
9631        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
9632
9633        let record = client
9634            .cache
9635            .get_execution_transaction(42161, &expected_hash.to_string())
9636            .await
9637            .unwrap()
9638            .unwrap();
9639        assert_eq!(record.nonce, 7);
9640        assert_eq!(record.purpose, "swap");
9641        assert_eq!(record.status, "finalized");
9642        assert_eq!(
9643            record.client_order_id.as_deref(),
9644            Some(order.client_order_id().as_str())
9645        );
9646        assert!(client.in_flight.lock().is_none());
9647        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
9648            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
9649        )))
9650        .fetch_one(&admin_pool)
9651        .await
9652        .unwrap();
9653        let decision_count = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
9654            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
9655             WHERE outcome = 'verified'"
9656        )))
9657        .fetch_one(&admin_pool)
9658        .await
9659        .unwrap();
9660        let connect_decision_count = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(format!(
9661            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
9662                 WHERE decision_class = 'connect' AND outcome = 'verified'"
9663        )))
9664        .fetch_one(&admin_pool)
9665        .await
9666        .unwrap();
9667        assert_eq!(nonce_state, (8, 1));
9668        assert_eq!(decision_count, 35);
9669        assert_eq!(connect_decision_count, 1);
9670
9671        drop_execution_schema(&admin_pool, &schema).await;
9672    }
9673
9674    #[tokio::test]
9675    async fn submit_order_pins_every_pre_sign_state_read_to_swap_anchor() {
9676        let Some((admin_pool, schema, mut client, state, _)) =
9677            swap_client_with_database("execution_submit_anchor_reads_test", swap_rpc_state().await)
9678                .await
9679        else {
9680            return;
9681        };
9682        let order = test_market_sell_order(test_pool().instrument_id);
9683        let mut receiver = start_with_events(&mut client);
9684
9685        client.submit_order(submit_order_cmd(&order)).unwrap();
9686        await_pending_tasks(&client).await;
9687
9688        let events = collect_order_events(&mut receiver);
9689        assert_swap_submitted_and_filled(&events);
9690        let requests = state.recorded_requests();
9691        let broadcast_index = requests
9692            .iter()
9693            .position(|request| request["method"] == "eth_sendRawTransaction")
9694            .unwrap();
9695        let pre_broadcast = &requests[..broadcast_index];
9696        let latest_reads: Vec<_> = pre_broadcast
9697            .iter()
9698            .filter(|request| {
9699                request["method"] == "eth_getBlockByNumber" && request["params"][0] == "latest"
9700            })
9701            .collect();
9702        assert_eq!(latest_reads.len(), 3);
9703        assert!(
9704            latest_reads
9705                .iter()
9706                .all(|request| request["params"] == serde_json::json!(["latest", false]))
9707        );
9708
9709        for method in [
9710            "eth_getCode",
9711            "eth_call",
9712            "eth_estimateGas",
9713            "eth_getBalance",
9714        ] {
9715            let pinned: Vec<_> = pre_broadcast
9716                .iter()
9717                .filter(|request| request["method"] == method)
9718                .collect();
9719            assert!(!pinned.is_empty(), "method {method}");
9720            assert_eq!(pinned.len() % 3, 0, "method {method}: {pinned:?}");
9721            assert!(
9722                pinned
9723                    .iter()
9724                    .all(|request| request["params"][1] == FIXTURE_BLOCK_PARAM),
9725                "method {method}: {pinned:?}"
9726            );
9727        }
9728
9729        let numbered_blocks: Vec<_> = pre_broadcast
9730            .iter()
9731            .filter(|request| {
9732                request["method"] == "eth_getBlockByNumber"
9733                    && request["params"][0] == FIXTURE_BLOCK_PARAM
9734            })
9735            .collect();
9736        assert!(!numbered_blocks.is_empty());
9737        assert_eq!(numbered_blocks.len() % 3, 0);
9738        assert!(
9739            numbered_blocks
9740                .iter()
9741                .all(|request| request["params"][1] == false)
9742        );
9743
9744        let chain_ids: Vec<_> = pre_broadcast
9745            .iter()
9746            .filter(|request| request["method"] == "eth_chainId")
9747            .collect();
9748        assert_eq!(chain_ids.len(), 3);
9749        assert!(
9750            chain_ids
9751                .iter()
9752                .all(|request| request["params"] == serde_json::json!([]))
9753        );
9754        let nonces: Vec<_> = pre_broadcast
9755            .iter()
9756            .filter(|request| request["method"] == "eth_getTransactionCount")
9757            .collect();
9758        assert_eq!(nonces.len(), 6);
9759        assert_eq!(
9760            nonces
9761                .iter()
9762                .filter(|request| {
9763                    request["params"] == serde_json::json!([WALLET.to_ascii_lowercase(), "pending"])
9764                })
9765                .count(),
9766            3
9767        );
9768        assert_eq!(
9769            nonces
9770                .iter()
9771                .filter(|request| {
9772                    request["params"]
9773                        == serde_json::json!([WALLET.to_ascii_lowercase(), FIXTURE_BLOCK_PARAM])
9774                })
9775                .count(),
9776            3
9777        );
9778        let priority_fees: Vec<_> = pre_broadcast
9779            .iter()
9780            .filter(|request| request["method"] == "eth_maxPriorityFeePerGas")
9781            .collect();
9782        assert_eq!(priority_fees.len(), 3);
9783        assert!(
9784            priority_fees
9785                .iter()
9786                .all(|request| request["params"] == serde_json::json!([]))
9787        );
9788
9789        let (_, expected_raw) = expected_swap_tx(expected_min_amount_out(50)).await;
9790        assert_eq!(
9791            requests[broadcast_index]["params"][0].as_str().unwrap(),
9792            expected_raw
9793        );
9794        let created_block: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
9795            "SELECT created_block FROM {schema}.execution_intent"
9796        )))
9797        .fetch_one(&admin_pool)
9798        .await
9799        .unwrap();
9800        assert_eq!(created_block, i64::try_from(FIXTURE_BLOCK).unwrap());
9801
9802        drop_execution_schema(&admin_pool, &schema).await;
9803    }
9804
9805    #[tokio::test]
9806    async fn submit_order_denies_changed_swap_anchor_before_signing() {
9807        let canonical = fixture_block_response(FIXTURE_BLOCK, B256::from([0x11; 32]));
9808        let changed = fixture_block_response(FIXTURE_BLOCK, B256::from([0x44; 32]));
9809        let state = swap_rpc_state().await.with_parameter_response_sequence(
9810            "eth_getBlockByNumber",
9811            FIXTURE_BLOCK_PARAM,
9812            &[
9813                &canonical, &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9814                &canonical, &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9815                &canonical, &changed, &changed, &changed,
9816            ],
9817        );
9818        let Some((admin_pool, schema, mut client, state, _)) =
9819            swap_client_with_database("execution_submit_anchor_change_test", state).await
9820        else {
9821            return;
9822        };
9823        let order = test_market_sell_order(test_pool().instrument_id);
9824        let mut receiver = start_with_events(&mut client);
9825
9826        client.submit_order(submit_order_cmd(&order)).unwrap();
9827        await_pending_tasks(&client).await;
9828
9829        let events = collect_order_events(&mut receiver);
9830        assert_eq!(events.len(), 1, "was: {events:?}");
9831        let OrderEventAny::Denied(denied) = &events[0] else {
9832            panic!("expected OrderDenied, was {:?}", events[0]);
9833        };
9834        assert!(
9835            denied
9836                .reason
9837                .contains("pre-sign checkpoint reread verification disagreed"),
9838            "was: {}",
9839            denied.reason
9840        );
9841        assert_eq!(
9842            execution_intent_markers(&admin_pool, &schema).await,
9843            vec![("swap".into(), "recoverable".into(), false, false)]
9844        );
9845        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
9846            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
9847        )))
9848        .fetch_one(&admin_pool)
9849        .await
9850        .unwrap();
9851        assert_eq!(signed_count, 0);
9852        assert!(
9853            state
9854                .recorded_requests()
9855                .iter()
9856                .all(|request| { request["method"] != "eth_sendRawTransaction" })
9857        );
9858        assert!(client.in_flight.lock().is_none());
9859
9860        drop_execution_schema(&admin_pool, &schema).await;
9861    }
9862
9863    #[tokio::test]
9864    async fn submit_order_keeps_verified_swap_anchor_when_latest_advances() {
9865        let canonical = fixture_block_response(FIXTURE_BLOCK, B256::from([0x11; 32]));
9866        let newer = fixture_block_response(FIXTURE_BLOCK + 1, B256::from([0x44; 32]));
9867        let state = swap_rpc_state().await.with_parameter_response_sequence(
9868            "eth_getBlockByNumber",
9869            "latest",
9870            &[&canonical, &canonical, &canonical, &newer, &newer, &newer],
9871        );
9872        let Some((admin_pool, schema, mut client, state, _)) =
9873            swap_client_with_database("execution_submit_advancing_head_test", state).await
9874        else {
9875            return;
9876        };
9877        let order = test_market_sell_order(test_pool().instrument_id);
9878        let mut receiver = start_with_events(&mut client);
9879
9880        client.submit_order(submit_order_cmd(&order)).unwrap();
9881        await_pending_tasks(&client).await;
9882
9883        let events = collect_order_events(&mut receiver);
9884        assert_swap_submitted_and_filled(&events);
9885        let latest_reads = state
9886            .recorded_requests()
9887            .iter()
9888            .filter(|request| {
9889                request["method"] == "eth_getBlockByNumber" && request["params"][0] == "latest"
9890            })
9891            .count();
9892        assert_eq!(latest_reads, 3);
9893
9894        drop_execution_schema(&admin_pool, &schema).await;
9895    }
9896
9897    #[tokio::test]
9898    async fn submit_order_denies_changed_quote_watermark_before_signing() {
9899        let watermark_number = FIXTURE_BLOCK;
9900        let watermark_hash = B256::from([0x11; 32]);
9901        let canonical = fixture_block_response(watermark_number, watermark_hash);
9902        let changed = fixture_block_response(watermark_number, B256::from([0x66; 32]));
9903        let watermark_param = format!("0x{watermark_number:x}");
9904        let min_amount_out = expected_min_amount_out(50);
9905        let (tx_hash, _) = expected_swap_tx(min_amount_out).await;
9906        let head = finalized_swap_block(tx_hash, min_amount_out);
9907        let state = swap_rpc_state()
9908            .await
9909            .with_response("eth_getBlockByNumber", &head)
9910            .with_parameter_response_sequence(
9911                "eth_getBlockByNumber",
9912                &watermark_param,
9913                &[
9914                    &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9915                    &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9916                    &changed, &changed, &changed,
9917                ],
9918            );
9919        let Some((admin_pool, schema, mut client, state, cache)) =
9920            swap_client_with_database("execution_submit_watermark_change_test", state).await
9921        else {
9922            return;
9923        };
9924        let pool = test_pool();
9925        cache
9926            .borrow_mut()
9927            .add_pool_profiler(test_profiler_at_block(
9928                &pool,
9929                watermark_number,
9930                &watermark_hash.to_string(),
9931            ))
9932            .unwrap();
9933        let order = test_market_sell_order(pool.instrument_id);
9934        let mut receiver = start_with_events(&mut client);
9935
9936        client.submit_order(submit_order_cmd(&order)).unwrap();
9937        await_pending_tasks(&client).await;
9938
9939        let events = collect_order_events(&mut receiver);
9940        assert_eq!(events.len(), 1, "was: {events:?}");
9941        let OrderEventAny::Denied(denied) = &events[0] else {
9942            panic!("expected OrderDenied, was {:?}", events[0]);
9943        };
9944        assert!(
9945            denied.reason.contains("changed before signing"),
9946            "was: {}",
9947            denied.reason
9948        );
9949        assert_eq!(
9950            execution_intent_markers(&admin_pool, &schema).await,
9951            vec![("swap".into(), "recoverable".into(), false, false)]
9952        );
9953        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
9954            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
9955        )))
9956        .fetch_one(&admin_pool)
9957        .await
9958        .unwrap();
9959        assert_eq!(signed_count, 0);
9960        assert!(
9961            state
9962                .recorded_requests()
9963                .iter()
9964                .all(|request| { request["method"] != "eth_sendRawTransaction" })
9965        );
9966        assert!(client.in_flight.lock().is_none());
9967
9968        drop_execution_schema(&admin_pool, &schema).await;
9969    }
9970
9971    #[tokio::test]
9972    async fn changed_swap_anchor_retains_ownership_when_recovery_commit_fails() {
9973        let canonical = fixture_block_response(FIXTURE_BLOCK, B256::from([0x11; 32]));
9974        let changed = fixture_block_response(FIXTURE_BLOCK, B256::from([0x44; 32]));
9975        let state = swap_rpc_state().await.with_parameter_response_sequence(
9976            "eth_getBlockByNumber",
9977            FIXTURE_BLOCK_PARAM,
9978            &[
9979                &canonical, &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9980                &canonical, &canonical, &canonical, &canonical, &canonical, &canonical, &canonical,
9981                &canonical, &changed, &changed, &changed,
9982            ],
9983        );
9984        let Some((admin_pool, schema, mut client, state, _)) =
9985            swap_client_with_database("execution_submit_anchor_recovery_fail_test", state).await
9986        else {
9987            return;
9988        };
9989        install_recoverable_commit_rejection(&admin_pool, &schema).await;
9990        let order = test_market_sell_order(test_pool().instrument_id);
9991        let mut receiver = start_with_events(&mut client);
9992
9993        client.submit_order(submit_order_cmd(&order)).unwrap();
9994        await_pending_tasks(&client).await;
9995
9996        let events = collect_order_events(&mut receiver);
9997        assert_eq!(events.len(), 1, "was: {events:?}");
9998        let OrderEventAny::Denied(denied) = &events[0] else {
9999            panic!("expected OrderDenied, was {:?}", events[0]);
10000        };
10001        assert!(
10002            denied
10003                .reason
10004                .contains("pre-sign checkpoint reread verification disagreed"),
10005            "was: {}",
10006            denied.reason
10007        );
10008        assert_eq!(
10009            execution_intent_markers(&admin_pool, &schema).await,
10010            vec![("swap".into(), "prepared".into(), false, true)]
10011        );
10012        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
10013            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
10014        )))
10015        .fetch_one(&admin_pool)
10016        .await
10017        .unwrap();
10018        assert_eq!(signed_count, 0);
10019        assert!(
10020            state
10021                .recorded_requests()
10022                .iter()
10023                .all(|request| { request["method"] != "eth_sendRawTransaction" })
10024        );
10025        assert!(matches!(
10026            *client.in_flight.lock(),
10027            Some(InFlightSlot::Preparing(TransactionPurpose::Swap))
10028        ));
10029
10030        drop_execution_schema(&admin_pool, &schema).await;
10031    }
10032
10033    #[rstest]
10034    #[case::filled("execution_inflight_finality_fill_test", false)]
10035    #[case::reverted("execution_inflight_finality_revert_test", true)]
10036    #[tokio::test]
10037    async fn swap_awaiting_finality_survives_inflight_exhaustion(
10038        #[case] test_name: &str,
10039        #[case] reverted: bool,
10040    ) {
10041        let min_amount_out = expected_min_amount_out(50);
10042        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10043
10044        let state = if reverted {
10045            let block = finalized_swap_block(expected_hash, min_amount_out);
10046            let receipt = receipt_with_transaction_hash(RECEIPT_REVERTED, expected_hash);
10047            with_finalized_identity(
10048                swap_rpc_state()
10049                    .await
10050                    .with_response("eth_getTransactionReceipt", &receipt),
10051                &block,
10052                &receipt,
10053            )
10054        } else {
10055            finalized_swap_rpc_state(expected_hash, min_amount_out)
10056        };
10057
10058        let Some((admin_pool, schema, mut client, _state, cache)) =
10059            swap_client_with_database(test_name, state).await
10060        else {
10061            return;
10062        };
10063
10064        let order = test_market_sell_order(test_pool().instrument_id);
10065        let client_order_id = order.client_order_id();
10066        let mut receiver = start_with_events(&mut client);
10067
10068        let plan = client
10069            .prepare_swap(&submit_order_cmd(&order), &order)
10070            .unwrap();
10071        execute_swap(
10072            plan,
10073            client.transaction_executor().unwrap(),
10074            client.emitter.clone(),
10075            client.transaction_limits.max_quote_age_blocks,
10076            client.transaction_limits.deadline_seconds,
10077        )
10078        .await
10079        .unwrap();
10080        let swap_events = collect_order_events(&mut receiver);
10081        assert_eq!(swap_events.len(), 2, "was: {swap_events:?}");
10082        assert!(matches!(&swap_events[0], OrderEventAny::Submitted(_)));
10083
10084        let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
10085        let config = ExecutionManagerConfig::default();
10086        let max_retries = config.inflight_max_retries;
10087        let mut manager = ExecutionManager::new(clock, Rc::clone(&cache), config).unwrap();
10088
10089        // The open-order check registers the client's retention requirement, as LiveNode does
10090        assert!(manager.check_open_orders(&[&client]).await.is_empty());
10091        cache.borrow_mut().update_order(&swap_events[0]).unwrap();
10092        tokio::time::pause();
10093        manager.register_submission(order.init_event(), Some(client.client_id()));
10094
10095        // Hold the finality outcome until well past the default in-flight budget
10096        let mut inflight_events = Vec::new();
10097        let mut queries_sent = 0;
10098
10099        for _ in 0..60 {
10100            tokio::time::advance(Duration::from_secs(1)).await;
10101            let result = manager.check_inflight_orders();
10102            inflight_events.extend(result.events);
10103
10104            for query in result.queries {
10105                let TradingCommand::QueryOrder(query) = query else {
10106                    panic!("expected QueryOrder, was {query:?}");
10107                };
10108
10109                client.query_order(query).unwrap();
10110                queries_sent += 1;
10111            }
10112        }
10113
10114        let exhaustions = manager.take_submission_recovery_exhaustions();
10115        let status_before_finality = cache.borrow().order(&client_order_id).unwrap().status();
10116        cache.borrow_mut().update_order(&swap_events[1]).unwrap();
10117        tokio::time::resume();
10118        drop_execution_schema(&admin_pool, &schema).await;
10119
10120        assert!(inflight_events.is_empty(), "was: {inflight_events:?}");
10121        assert_eq!(queries_sent, max_retries - 1);
10122        assert!(collect_order_events(&mut receiver).is_empty());
10123        assert_eq!(
10124            exhaustions,
10125            vec![SubmissionRecoveryExhausted {
10126                trader_id: order.trader_id(),
10127                client_id: Some(client.client_id()),
10128                strategy_id: order.strategy_id(),
10129                instrument_id: order.instrument_id(),
10130                client_order_id,
10131                source: SubmissionRecoverySource::Inflight,
10132                retry_count: max_retries,
10133                ts_event: UnixNanos::default(),
10134            }]
10135        );
10136        assert_eq!(status_before_finality, OrderStatus::Submitted);
10137        let cache = cache.borrow();
10138        let resolved = cache.order(&client_order_id).unwrap();
10139
10140        if reverted {
10141            let OrderEventAny::Rejected(rejected) = &swap_events[1] else {
10142                panic!("expected OrderRejected, was {:?}", swap_events[1]);
10143            };
10144
10145            assert_eq!(
10146                rejected.reason.as_str(),
10147                format!("Transaction {expected_hash} reverted on-chain")
10148            );
10149            assert!(!rejected.reconciliation);
10150            assert_eq!(resolved.status(), OrderStatus::Rejected);
10151            assert_eq!(
10152                resolved.filled_qty(),
10153                Quantity::zero(order.quantity().precision)
10154            );
10155        } else {
10156            assert!(matches!(&swap_events[1], OrderEventAny::Filled(_)));
10157            assert_eq!(resolved.status(), OrderStatus::Filled);
10158            assert_eq!(resolved.filled_qty(), order.quantity());
10159        }
10160    }
10161
10162    #[tokio::test]
10163    async fn finalized_swap_emits_exact_fill_once_and_refreshes_wallet() {
10164        let min_amount_out = expected_min_amount_out(50);
10165        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10166        let state = finalized_swap_rpc_state(expected_hash, min_amount_out);
10167        let Some((admin_pool, schema, mut client, state, _)) =
10168            swap_client_with_database("execution_submit_fill_test", state).await
10169        else {
10170            return;
10171        };
10172        let order = test_market_sell_order(test_pool().instrument_id);
10173        let mut receiver = start_with_events(&mut client);
10174
10175        let plan = client
10176            .prepare_swap(&submit_order_cmd(&order), &order)
10177            .unwrap();
10178        execute_swap(
10179            plan,
10180            client.transaction_executor().unwrap(),
10181            client.emitter.clone(),
10182            client.transaction_limits.max_quote_age_blocks,
10183            client.transaction_limits.deadline_seconds,
10184        )
10185        .await
10186        .unwrap();
10187
10188        let (nonce, wallet_address, transaction_to, transaction_input, transaction_value): (
10189            i64,
10190            String,
10191            String,
10192            String,
10193            String,
10194        ) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10195            "SELECT nonce, wallet_address, transaction_to, transaction_input, transaction_value \
10196             FROM {schema}.execution_intent"
10197        )))
10198        .fetch_one(&admin_pool)
10199        .await
10200        .unwrap();
10201        let finalized_block = client
10202            .http_rpc_client
10203            .block_by_number(FIXTURE_BLOCK + 1, true)
10204            .await
10205            .unwrap();
10206        let finalized_transaction = finalized_block
10207            .transactions
10208            .iter()
10209            .find(|transaction| transaction.hash == expected_hash)
10210            .unwrap();
10211        assert_eq!(finalized_transaction.from.to_string(), wallet_address);
10212        assert_eq!(finalized_transaction.nonce, u64::try_from(nonce).unwrap());
10213        assert_eq!(
10214            finalized_transaction.to,
10215            Some(Address::from_str(&transaction_to).unwrap())
10216        );
10217        assert_eq!(
10218            finalized_transaction.input.as_ref(),
10219            hex::decode(transaction_input.strip_prefix("0x").unwrap()).unwrap()
10220        );
10221        assert_eq!(
10222            finalized_transaction.value,
10223            U256::from_str(&transaction_value).unwrap()
10224        );
10225
10226        let mut order_events = Vec::new();
10227        let mut account_states = Vec::new();
10228
10229        while let Ok(event) = receiver.try_recv() {
10230            match event {
10231                ExecutionEvent::Order(event) => order_events.push(event),
10232                ExecutionEvent::Account(state) => account_states.push(state),
10233                other => panic!("unexpected execution event: {other:?}"),
10234            }
10235        }
10236        assert_eq!(order_events.len(), 2, "was: {order_events:?}");
10237        assert!(matches!(&order_events[0], OrderEventAny::Submitted(_)));
10238        let OrderEventAny::Filled(fill) = &order_events[1] else {
10239            panic!("expected OrderFilled, was {:?}", order_events[1]);
10240        };
10241        let expected_commission = Money::from_u256(
10242            U256::from(50_112_u64) * U256::from(100_000_000_u64),
10243            test_pool().chain.native_currency(),
10244        )
10245        .unwrap();
10246        assert_eq!(fill.client_order_id, order.client_order_id());
10247        assert_eq!(fill.venue_order_id.as_str(), expected_hash.to_string());
10248        assert_eq!(fill.order_side, OrderSide::Sell);
10249        assert_eq!(fill.last_qty, Quantity::from("0.001"));
10250        assert_eq!(fill.last_px, Price::from("1000"));
10251        assert_eq!(fill.currency.code, "USDC@ARBITRUM");
10252        assert_eq!(fill.commission, Some(expected_commission));
10253        assert_eq!(fill.liquidity_side, LiquiditySide::Taker);
10254        assert_eq!(account_states.len(), 1);
10255        let account_state = &account_states[0];
10256        assert_eq!(account_state.account_id, AccountId::from("BLOCKCHAIN-001"));
10257        assert_eq!(account_state.account_type, AccountType::Wallet);
10258        assert_eq!(account_state.base_currency, None);
10259        assert_eq!(account_state.balances.len(), 3);
10260        assert!(account_state.margins.is_empty());
10261        assert!(account_state.is_reported);
10262        assert_eq!(
10263            account_state.balances,
10264            client.wallet_balance.lock().as_account_balances().unwrap()
10265        );
10266
10267        let (fill_emitted, active): (bool, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10268            "SELECT fill_emitted, active FROM {schema}.execution_intent"
10269        )))
10270        .fetch_one(&admin_pool)
10271        .await
10272        .unwrap();
10273        assert!(fill_emitted);
10274        assert!(!active);
10275
10276        let database = client.cache.database.as_ref().unwrap().clone();
10277        let payload_keys = client.payload_keys.clone();
10278        let restart_config = client.config.clone();
10279        drop(client);
10280        let (mut restarted, _) = swap_client_with_cache(restart_config);
10281        restarted.cache.database = Some(database);
10282        restarted.payload_keys = payload_keys;
10283        restarted.signer = Some(Arc::new(
10284            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
10285        ));
10286        let mut restart_receiver = start_with_events(&mut restarted);
10287        restarted.reconcile_unresolved_execution().await.unwrap();
10288        restarted.reconcile_unresolved_execution().await.unwrap();
10289        assert!(collect_order_events(&mut restart_receiver).is_empty());
10290        let requests = state.recorded_requests();
10291        assert_eq!(
10292            requests
10293                .iter()
10294                .filter(|request| request["method"] == "eth_sendRawTransaction")
10295                .count(),
10296            1
10297        );
10298        assert_eq!(
10299            requests
10300                .iter()
10301                .filter(|request| {
10302                    request["method"] == "eth_call"
10303                        && request["params"][0]["data"]
10304                            .as_str()
10305                            .is_some_and(|data| data.starts_with(BALANCE_OF_SELECTOR))
10306                })
10307                .count(),
10308            9
10309        );
10310        assert_eq!(
10311            requests
10312                .iter()
10313                .filter(|request| request["method"] == "eth_getBalance")
10314                .count(),
10315            6
10316        );
10317
10318        drop_execution_schema(&admin_pool, &schema).await;
10319    }
10320
10321    #[tokio::test]
10322    async fn restart_emits_committed_swap_from_verified_inclusion_header() {
10323        let min_amount_out = expected_min_amount_out(50);
10324        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10325        let state = finalized_swap_rpc_state(expected_hash, min_amount_out);
10326        let Some((admin_pool, schema, mut client, _, _)) =
10327            swap_client_with_database("execution_committed_fill_restart_test", state).await
10328        else {
10329            return;
10330        };
10331        let order = test_market_sell_order(test_pool().instrument_id);
10332        let mut receiver = start_with_events(&mut client);
10333        let plan = client
10334            .prepare_swap(&submit_order_cmd(&order), &order)
10335            .unwrap();
10336
10337        execute_swap(
10338            plan,
10339            client.transaction_executor().unwrap(),
10340            client.emitter.clone(),
10341            client.transaction_limits.max_quote_age_blocks,
10342            client.transaction_limits.deadline_seconds,
10343        )
10344        .await
10345        .unwrap();
10346        assert_swap_submitted_and_filled(&collect_order_events(&mut receiver));
10347        let ancestry_range: (i64, i64) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10348            "SELECT height_start, height_end FROM {schema}.execution_verification_decision \
10349             WHERE decision_class = 'finality' AND read_class = 'numbered_block' \
10350               AND height_end > height_start"
10351        )))
10352        .fetch_one(&admin_pool)
10353        .await
10354        .unwrap();
10355        assert_eq!(
10356            ancestry_range,
10357            ((FIXTURE_BLOCK + 1) as i64, (FIXTURE_BLOCK + 2) as i64)
10358        );
10359
10360        sqlx::query(sqlx::AssertSqlSafe(format!(
10361            "UPDATE {schema}.execution_intent SET fill_emitted = FALSE, active = TRUE"
10362        )))
10363        .execute(&admin_pool)
10364        .await
10365        .unwrap();
10366        let database = client.cache.database.as_ref().unwrap().clone();
10367        let payload_keys = client.payload_keys.clone();
10368        let restart_config = client.config.clone();
10369        drop(client);
10370        let (mut restarted, _) = swap_client_with_cache(restart_config);
10371        restarted.cache.database = Some(database);
10372        restarted.payload_keys = payload_keys;
10373        restarted.signer = Some(Arc::new(
10374            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
10375        ));
10376        let mut restart_receiver = start_with_events(&mut restarted);
10377
10378        restarted.reconcile_unresolved_execution().await.unwrap();
10379
10380        let events = collect_order_events(&mut restart_receiver);
10381        let (fill_emitted, active): (bool, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10382            "SELECT fill_emitted, active FROM {schema}.execution_intent"
10383        )))
10384        .fetch_one(&admin_pool)
10385        .await
10386        .unwrap();
10387        assert_eq!(events.len(), 1, "was: {events:?}");
10388        assert!(matches!(&events[0], OrderEventAny::Filled(_)));
10389        assert!(fill_emitted);
10390        assert!(!active);
10391
10392        drop_execution_schema(&admin_pool, &schema).await;
10393    }
10394
10395    #[tokio::test]
10396    async fn finalized_swap_ignores_unrelated_swap_logs() {
10397        let min_amount_out = expected_min_amount_out(50);
10398        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10399        let receipt = finalized_swap_receipt_with_unrelated_swap(expected_hash);
10400        let state = finalized_swap_rpc_state(expected_hash, min_amount_out)
10401            .with_response("eth_getTransactionReceipt", &receipt);
10402        let Some((admin_pool, schema, mut client, _, _)) =
10403            swap_client_with_database("execution_submit_unrelated_log_test", state).await
10404        else {
10405            return;
10406        };
10407        let order = test_market_sell_order(test_pool().instrument_id);
10408        let mut receiver = start_with_events(&mut client);
10409
10410        client.submit_order(submit_order_cmd(&order)).unwrap();
10411        await_pending_tasks(&client).await;
10412
10413        let events = collect_order_events(&mut receiver);
10414        assert_swap_submitted_and_filled(&events);
10415
10416        drop_execution_schema(&admin_pool, &schema).await;
10417    }
10418
10419    #[tokio::test]
10420    async fn prepare_swap_buy_accepts_quote_spend_exact_boundary() {
10421        let amount_in = expected_buy_amount_in();
10422        let min_amount_out = expected_buy_min_amount_out(50);
10423        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10424        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10425        let max_amount = amount_in.to_string();
10426        let Some((admin_pool, schema, client, _, cache)) = swap_client_with_database_config(
10427            "execution_prepare_buy_test",
10428            state,
10429            move |http_rpc_url| {
10430                let mut config = buy_test_config(http_rpc_url);
10431                config.quote_spend_limits.as_mut().unwrap()[0].max_amount = max_amount;
10432                config
10433            },
10434        )
10435        .await
10436        else {
10437            return;
10438        };
10439        let order = test_market_buy_order(test_pool().instrument_id);
10440        cache
10441            .borrow_mut()
10442            .add_order(order.clone(), None, None, true)
10443            .unwrap();
10444
10445        let plan = client
10446            .prepare_swap(&submit_order_cmd(&order), &order)
10447            .unwrap();
10448
10449        assert_eq!(plan.token_in, USDC_ADDRESS);
10450        assert_eq!(plan.token_out, WETH_ADDRESS);
10451        assert_eq!(plan.amount_in, amount_in);
10452        assert_eq!(plan.min_amount_out, min_amount_out);
10453        assert_ne!(plan.token_in, WETH_ADDRESS);
10454
10455        drop_execution_schema(&admin_pool, &schema).await;
10456    }
10457
10458    #[tokio::test]
10459    async fn submit_order_broadcasts_buy_swap() {
10460        let amount_in = expected_buy_amount_in();
10461        let min_amount_out = expected_buy_min_amount_out(50);
10462        let (expected_hash, expected_raw) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10463        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10464        let Some((admin_pool, schema, mut client, state, cache)) =
10465            swap_client_with_buy_database("execution_submit_buy_success_test", state).await
10466        else {
10467            return;
10468        };
10469        let order = test_market_buy_order(test_pool().instrument_id);
10470        cache
10471            .borrow_mut()
10472            .add_order(order.clone(), None, None, true)
10473            .unwrap();
10474        let mut receiver = start_with_events(&mut client);
10475
10476        client.submit_order(submit_order_cmd(&order)).unwrap();
10477        await_pending_tasks(&client).await;
10478
10479        let events = collect_order_events(&mut receiver);
10480        assert_swap_submitted_and_filled(&events);
10481        let broadcasts: Vec<_> = state
10482            .recorded_requests()
10483            .into_iter()
10484            .filter(|request| request["method"] == "eth_sendRawTransaction")
10485            .collect();
10486        assert_eq!(broadcasts.len(), 1);
10487        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
10488
10489        drop_execution_schema(&admin_pool, &schema).await;
10490    }
10491
10492    #[tokio::test]
10493    async fn finalized_buy_swap_emits_fill_from_output_leg() {
10494        let amount_in = expected_buy_amount_in();
10495        let min_amount_out = expected_buy_min_amount_out(50);
10496        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10497        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10498        let Some((admin_pool, schema, mut client, state, cache)) =
10499            swap_client_with_buy_database("execution_submit_buy_fill_test", state).await
10500        else {
10501            return;
10502        };
10503        let order = test_market_buy_order(test_pool().instrument_id);
10504        cache
10505            .borrow_mut()
10506            .add_order(order.clone(), None, None, true)
10507            .unwrap();
10508        let mut receiver = start_with_events(&mut client);
10509        let plan = client
10510            .prepare_swap(&submit_order_cmd(&order), &order)
10511            .unwrap();
10512
10513        execute_swap(
10514            plan,
10515            client.transaction_executor().unwrap(),
10516            client.emitter.clone(),
10517            client.transaction_limits.max_quote_age_blocks,
10518            client.transaction_limits.deadline_seconds,
10519        )
10520        .await
10521        .unwrap();
10522
10523        let mut order_events = Vec::new();
10524
10525        while let Ok(event) = receiver.try_recv() {
10526            if let ExecutionEvent::Order(event) = event {
10527                order_events.push(event);
10528            }
10529        }
10530        assert_eq!(order_events.len(), 2, "was: {order_events:?}");
10531        assert!(matches!(&order_events[0], OrderEventAny::Submitted(_)));
10532        let OrderEventAny::Filled(fill) = &order_events[1] else {
10533            panic!("expected OrderFilled, was {:?}", order_events[1]);
10534        };
10535        let expected_commission = Money::from_u256(
10536            U256::from(50_112_u64) * U256::from(100_000_000_u64),
10537            test_pool().chain.native_currency(),
10538        )
10539        .unwrap();
10540        assert_eq!(fill.client_order_id, order.client_order_id());
10541        assert_eq!(fill.venue_order_id.as_str(), expected_hash.to_string());
10542        assert_eq!(fill.order_side, OrderSide::Buy);
10543        assert_eq!(fill.last_qty, Quantity::from("0.001"));
10544        assert_eq!(fill.currency.code, "USDC@ARBITRUM");
10545        assert_eq!(fill.commission, Some(expected_commission));
10546        assert_eq!(fill.liquidity_side, LiquiditySide::Taker);
10547        assert_eq!(
10548            Money::from_decimal(
10549                fill.last_qty.as_decimal() * fill.last_px.as_decimal(),
10550                fill.currency,
10551            )
10552            .unwrap(),
10553            Money::from_u256(amount_in, fill.currency).unwrap()
10554        );
10555
10556        let (fill_emitted, active): (bool, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
10557            "SELECT fill_emitted, active FROM {schema}.execution_intent"
10558        )))
10559        .fetch_one(&admin_pool)
10560        .await
10561        .unwrap();
10562        assert!(fill_emitted);
10563        assert!(!active);
10564
10565        let database = client.cache.database.as_ref().unwrap().clone();
10566        let payload_keys = client.payload_keys.clone();
10567        let restart_config = client.config.clone();
10568        drop(client);
10569        let (mut restarted, _) = swap_client_with_cache(restart_config);
10570        restarted.cache.database = Some(database);
10571        restarted.payload_keys = payload_keys;
10572        restarted.signer = Some(Arc::new(
10573            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
10574        ));
10575        let mut restart_receiver = start_with_events(&mut restarted);
10576        restarted.reconcile_unresolved_execution().await.unwrap();
10577        restarted.reconcile_unresolved_execution().await.unwrap();
10578        assert!(collect_order_events(&mut restart_receiver).is_empty());
10579        assert_eq!(
10580            state
10581                .recorded_requests()
10582                .iter()
10583                .filter(|request| request["method"] == "eth_sendRawTransaction")
10584                .count(),
10585            1
10586        );
10587
10588        drop_execution_schema(&admin_pool, &schema).await;
10589    }
10590
10591    #[tokio::test]
10592    async fn finalized_buy_swap_cancels_remainder_when_output_is_short() {
10593        let amount_in = expected_buy_amount_in();
10594        let min_amount_out = expected_buy_min_amount_out(50);
10595        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10596        let short_base_out = min_amount_out;
10597        let mut state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10598        state = state.with_response(
10599            "eth_getTransactionReceipt",
10600            &finalized_buy_swap_receipt_with_base_out(expected_hash, amount_in, short_base_out),
10601        );
10602        let Some((admin_pool, schema, mut client, _, cache)) =
10603            swap_client_with_buy_database("execution_submit_buy_short_fill_test", state).await
10604        else {
10605            return;
10606        };
10607        let order = test_market_buy_order(test_pool().instrument_id);
10608        cache
10609            .borrow_mut()
10610            .add_order(order.clone(), None, None, true)
10611            .unwrap();
10612        let mut receiver = start_with_events(&mut client);
10613        let plan = client
10614            .prepare_swap(&submit_order_cmd(&order), &order)
10615            .unwrap();
10616
10617        execute_swap(
10618            plan,
10619            client.transaction_executor().unwrap(),
10620            client.emitter.clone(),
10621            client.transaction_limits.max_quote_age_blocks,
10622            client.transaction_limits.deadline_seconds,
10623        )
10624        .await
10625        .unwrap();
10626
10627        let events = collect_order_events(&mut receiver);
10628        assert_eq!(events.len(), 3, "was: {events:?}");
10629        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
10630        let OrderEventAny::Filled(fill) = &events[1] else {
10631            panic!("expected OrderFilled, was {:?}", events[1]);
10632        };
10633        let expected_qty = raw_amount_to_quantity(short_base_out, 18).unwrap();
10634        assert_eq!(fill.order_side, OrderSide::Buy);
10635        assert_eq!(fill.last_qty, expected_qty);
10636        assert!(fill.last_qty < order.quantity());
10637        let OrderEventAny::Canceled(canceled) = &events[2] else {
10638            panic!("expected OrderCanceled, was {:?}", events[2]);
10639        };
10640        assert_eq!(canceled.client_order_id, order.client_order_id());
10641        assert_eq!(
10642            canceled.venue_order_id.as_ref().map(VenueOrderId::as_str),
10643            Some(expected_hash.to_string().as_str())
10644        );
10645
10646        drop_execution_schema(&admin_pool, &schema).await;
10647    }
10648
10649    #[tokio::test]
10650    async fn finalized_buy_swap_reports_full_output_when_above_order_quantity() {
10651        let amount_in = expected_buy_amount_in();
10652        let min_amount_out = expected_buy_min_amount_out(50);
10653        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10654        let overshoot_base_out = expected_buy_base_amount() * U256::from(2) + U256::from(44);
10655        let mut state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10656        state = state.with_response(
10657            "eth_getTransactionReceipt",
10658            &finalized_buy_swap_receipt_with_base_out(expected_hash, amount_in, overshoot_base_out),
10659        );
10660        let Some((admin_pool, schema, mut client, _, cache)) =
10661            swap_client_with_buy_database("execution_submit_buy_overshoot_fill_test", state).await
10662        else {
10663            return;
10664        };
10665        let order = test_market_buy_order(test_pool().instrument_id);
10666        cache
10667            .borrow_mut()
10668            .add_order(order.clone(), None, None, true)
10669            .unwrap();
10670        let mut receiver = start_with_events(&mut client);
10671        let plan = client
10672            .prepare_swap(&submit_order_cmd(&order), &order)
10673            .unwrap();
10674
10675        execute_swap(
10676            plan,
10677            client.transaction_executor().unwrap(),
10678            client.emitter.clone(),
10679            client.transaction_limits.max_quote_age_blocks,
10680            client.transaction_limits.deadline_seconds,
10681        )
10682        .await
10683        .unwrap();
10684
10685        let events = collect_order_events(&mut receiver);
10686        assert_eq!(events.len(), 2, "was: {events:?}");
10687        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
10688        let OrderEventAny::Filled(fill) = &events[1] else {
10689            panic!("expected OrderFilled, was {:?}", events[1]);
10690        };
10691        let expected_qty = raw_amount_to_quantity(overshoot_base_out, 18).unwrap();
10692        assert_eq!(fill.order_side, OrderSide::Buy);
10693        assert_eq!(fill.last_qty, expected_qty);
10694        assert!(fill.last_qty > order.quantity());
10695        assert_eq!(
10696            Money::from_decimal(
10697                fill.last_qty.as_decimal() * fill.last_px.as_decimal(),
10698                fill.currency,
10699            )
10700            .unwrap(),
10701            Money::from_u256(amount_in, fill.currency).unwrap()
10702        );
10703
10704        drop_execution_schema(&admin_pool, &schema).await;
10705    }
10706
10707    #[tokio::test]
10708    async fn finalized_buy_swap_quarantines_sell_oriented_log() {
10709        let amount_in = expected_buy_amount_in();
10710        let min_amount_out = expected_buy_min_amount_out(50);
10711        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10712        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in)
10713            .with_response(
10714                "eth_getTransactionReceipt",
10715                &finalized_swap_receipt(expected_hash),
10716            );
10717        let Some((admin_pool, schema, mut client, _, cache)) =
10718            swap_client_with_buy_database("execution_submit_buy_sell_log_test", state).await
10719        else {
10720            return;
10721        };
10722        let order = test_market_buy_order(test_pool().instrument_id);
10723        cache
10724            .borrow_mut()
10725            .add_order(order.clone(), None, None, true)
10726            .unwrap();
10727        let mut receiver = start_with_events(&mut client);
10728        let plan = client
10729            .prepare_swap(&submit_order_cmd(&order), &order)
10730            .unwrap();
10731
10732        let error = execute_swap(
10733            plan,
10734            client.transaction_executor().unwrap(),
10735            client.emitter.clone(),
10736            client.transaction_limits.max_quote_age_blocks,
10737            client.transaction_limits.deadline_seconds,
10738        )
10739        .await
10740        .unwrap_err();
10741
10742        let events = collect_order_events(&mut receiver);
10743        assert_swap_quarantined_without_terminal_event(&events);
10744        assert!(
10745            error
10746                .to_string()
10747                .contains("does not match the persisted amount")
10748                || error.to_string().contains("is not a BUY output"),
10749            "was: {error}"
10750        );
10751        assert!(client.in_flight.lock().is_some());
10752
10753        drop_execution_schema(&admin_pool, &schema).await;
10754    }
10755
10756    #[tokio::test]
10757    async fn submit_order_applies_buy_slippage_to_base_output() {
10758        let amount_in = expected_buy_amount_in();
10759        let min_amount_out = expected_buy_min_amount_out(200);
10760        let (expected_hash, expected_raw) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10761        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in);
10762        let Some((admin_pool, schema, mut client, state, cache)) =
10763            swap_client_with_buy_database("execution_submit_buy_slippage_test", state).await
10764        else {
10765            return;
10766        };
10767        let order = test_market_buy_order(test_pool().instrument_id);
10768        cache
10769            .borrow_mut()
10770            .add_order(order.clone(), None, None, true)
10771            .unwrap();
10772        let mut cmd = submit_order_cmd(&order);
10773        cmd.params = Some(serde_json::from_str(r#"{"slippage_bps": 200}"#).unwrap());
10774        let mut receiver = start_with_events(&mut client);
10775
10776        client.submit_order(cmd).unwrap();
10777        await_pending_tasks(&client).await;
10778
10779        let events = collect_order_events(&mut receiver);
10780        assert_swap_submitted_and_filled(&events);
10781        let broadcasts: Vec<_> = state
10782            .recorded_requests()
10783            .into_iter()
10784            .filter(|request| request["method"] == "eth_sendRawTransaction")
10785            .collect();
10786        assert_eq!(broadcasts.len(), 1);
10787        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
10788
10789        drop_execution_schema(&admin_pool, &schema).await;
10790    }
10791
10792    #[tokio::test]
10793    async fn submit_order_denies_buy_on_insufficient_quote_balance() {
10794        let amount_in = expected_buy_amount_in();
10795        let min_amount_out = expected_buy_min_amount_out(50);
10796        let (expected_hash, _) = expected_buy_swap_tx(min_amount_out, amount_in).await;
10797        let state = finalized_buy_swap_rpc_state(expected_hash, min_amount_out, amount_in)
10798            .with_call_response(BALANCE_OF_SELECTOR, CALL_ZERO);
10799        let Some((admin_pool, schema, mut client, _, cache)) =
10800            swap_client_with_buy_database("execution_submit_buy_balance_test", state).await
10801        else {
10802            return;
10803        };
10804        let order = test_market_buy_order(test_pool().instrument_id);
10805        cache
10806            .borrow_mut()
10807            .add_order(order.clone(), None, None, true)
10808            .unwrap();
10809        let mut receiver = start_with_events(&mut client);
10810
10811        client.submit_order(submit_order_cmd(&order)).unwrap();
10812        await_pending_tasks(&client).await;
10813
10814        let events = collect_order_events(&mut receiver);
10815        assert_eq!(events.len(), 1);
10816        let OrderEventAny::Denied(denied) = &events[0] else {
10817            panic!("expected OrderDenied, was {:?}", events[0]);
10818        };
10819        assert!(
10820            denied.reason.contains("is below the swap amount"),
10821            "was: {}",
10822            denied.reason
10823        );
10824
10825        drop_execution_schema(&admin_pool, &schema).await;
10826    }
10827
10828    #[tokio::test]
10829    async fn finalized_swap_without_log_stays_quarantined() {
10830        let state = swap_rpc_state()
10831            .await
10832            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS);
10833        let Some((admin_pool, schema, mut client, _, _)) =
10834            swap_client_with_database("execution_submit_missing_log_test", state).await
10835        else {
10836            return;
10837        };
10838        let order = test_market_sell_order(test_pool().instrument_id);
10839        let mut receiver = start_with_events(&mut client);
10840
10841        client.submit_order(submit_order_cmd(&order)).unwrap();
10842        await_pending_tasks(&client).await;
10843
10844        let events = collect_order_events(&mut receiver);
10845        let (status, terminal_emitted, active): (String, bool, bool) =
10846            sqlx::query_as(sqlx::AssertSqlSafe(format!(
10847                "SELECT status, terminal_emitted, active FROM {schema}.execution_intent"
10848            )))
10849            .fetch_one(&admin_pool)
10850            .await
10851            .unwrap();
10852
10853        assert_swap_quarantined_without_terminal_event(&events);
10854        assert_eq!(status, "broadcast");
10855        assert!(!terminal_emitted);
10856        assert!(active);
10857        assert!(client.in_flight.lock().is_some());
10858
10859        drop_execution_schema(&admin_pool, &schema).await;
10860    }
10861
10862    #[tokio::test]
10863    async fn finalized_swap_refresh_failure_stays_owned_for_reconciliation() {
10864        let min_amount_out = expected_min_amount_out(50);
10865        let (expected_hash, _) = expected_swap_tx(min_amount_out).await;
10866        let state = finalized_swap_rpc_state(expected_hash, min_amount_out).with_response_sequence(
10867            "eth_getBalance",
10868            &[
10869                GET_BALANCE,
10870                GET_BALANCE,
10871                GET_BALANCE,
10872                RPC_METHOD_NOT_FOUND,
10873                RPC_METHOD_NOT_FOUND,
10874                RPC_METHOD_NOT_FOUND,
10875            ],
10876        );
10877        let Some((admin_pool, schema, mut client, _state, _)) =
10878            swap_client_with_database("execution_submit_refresh_fail_test", state).await
10879        else {
10880            return;
10881        };
10882        let order = test_market_sell_order(test_pool().instrument_id);
10883        let mut receiver = start_with_events(&mut client);
10884        let plan = client
10885            .prepare_swap(&submit_order_cmd(&order), &order)
10886            .unwrap();
10887
10888        let error = execute_swap(
10889            plan,
10890            client.transaction_executor().unwrap(),
10891            client.emitter.clone(),
10892            client.transaction_limits.max_quote_age_blocks,
10893            client.transaction_limits.deadline_seconds,
10894        )
10895        .await
10896        .unwrap_err();
10897        let events = collect_order_events(&mut receiver);
10898        let (status, fill_emitted, active): (String, bool, bool) =
10899            sqlx::query_as(sqlx::AssertSqlSafe(format!(
10900                "SELECT status, fill_emitted, active FROM {schema}.execution_intent"
10901            )))
10902            .fetch_one(&admin_pool)
10903            .await
10904            .unwrap();
10905
10906        assert!(
10907            error
10908                .to_string()
10909                .contains("finalized native balance verification is locally invalid"),
10910            "was: {error}"
10911        );
10912        assert_eq!(events.len(), 1, "was: {events:?}");
10913        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
10914        assert_eq!(status, "broadcast");
10915        assert!(!fill_emitted);
10916        assert!(active);
10917        assert!(client.in_flight.lock().is_some());
10918
10919        drop_execution_schema(&admin_pool, &schema).await;
10920    }
10921
10922    #[tokio::test]
10923    async fn submit_order_denies_router_factory_mismatch_before_signing() {
10924        let state = swap_rpc_state()
10925            .await
10926            .with_call_response(FACTORY_SELECTOR, CALL_ZERO);
10927        let Some((admin_pool, schema, mut client, state, _)) =
10928            swap_client_with_database("execution_submit_factory_test", state).await
10929        else {
10930            return;
10931        };
10932        let order = test_market_sell_order(test_pool().instrument_id);
10933        let mut receiver = start_with_events(&mut client);
10934
10935        client.submit_order(submit_order_cmd(&order)).unwrap();
10936        await_pending_tasks(&client).await;
10937
10938        let events = collect_order_events(&mut receiver);
10939        assert_eq!(events.len(), 1);
10940        let OrderEventAny::Denied(denied) = &events[0] else {
10941            panic!("expected OrderDenied, was {:?}", events[0]);
10942        };
10943        assert!(
10944            denied
10945                .reason
10946                .contains("swap deployment manifest verification disagreed"),
10947            "was: {}",
10948            denied.reason
10949        );
10950        let requests = state.recorded_requests();
10951        assert!(
10952            requests
10953                .iter()
10954                .all(|request| request["method"] != "eth_getTransactionCount")
10955        );
10956        assert!(
10957            requests
10958                .iter()
10959                .all(|request| request["method"] != "eth_sendRawTransaction")
10960        );
10961
10962        drop_execution_schema(&admin_pool, &schema).await;
10963    }
10964
10965    #[tokio::test]
10966    async fn submit_order_denies_router_weth_mismatch_before_signing() {
10967        let state = swap_rpc_state()
10968            .await
10969            .with_call_response(WETH9_SELECTOR, CALL_ZERO);
10970        let Some((admin_pool, schema, mut client, state, _)) =
10971            swap_client_with_database("execution_submit_weth_test", state).await
10972        else {
10973            return;
10974        };
10975        let order = test_market_sell_order(test_pool().instrument_id);
10976        let mut receiver = start_with_events(&mut client);
10977
10978        client.submit_order(submit_order_cmd(&order)).unwrap();
10979        await_pending_tasks(&client).await;
10980
10981        let events = collect_order_events(&mut receiver);
10982        assert_eq!(events.len(), 1);
10983        let OrderEventAny::Denied(denied) = &events[0] else {
10984            panic!("expected OrderDenied, was {:?}", events[0]);
10985        };
10986        assert!(
10987            denied
10988                .reason
10989                .contains("swap deployment manifest verification disagreed"),
10990            "was: {}",
10991            denied.reason
10992        );
10993        let requests = state.recorded_requests();
10994        assert!(
10995            requests
10996                .iter()
10997                .all(|request| request["method"] != "eth_getTransactionCount")
10998        );
10999        assert!(
11000            requests
11001                .iter()
11002                .all(|request| request["method"] != "eth_sendRawTransaction")
11003        );
11004
11005        drop_execution_schema(&admin_pool, &schema).await;
11006    }
11007
11008    #[tokio::test]
11009    async fn submit_order_denies_factory_pool_mismatch_before_signing() {
11010        let state = swap_rpc_state()
11011            .await
11012            .with_call_response(GET_POOL_SELECTOR, CALL_ZERO);
11013        let Some((admin_pool, schema, mut client, state, _)) =
11014            swap_client_with_database("execution_submit_pool_identity_test", state).await
11015        else {
11016            return;
11017        };
11018        let order = test_market_sell_order(test_pool().instrument_id);
11019        let mut receiver = start_with_events(&mut client);
11020
11021        client.submit_order(submit_order_cmd(&order)).unwrap();
11022        await_pending_tasks(&client).await;
11023
11024        let events = collect_order_events(&mut receiver);
11025        assert_eq!(events.len(), 1);
11026        let OrderEventAny::Denied(denied) = &events[0] else {
11027            panic!("expected OrderDenied, was {:?}", events[0]);
11028        };
11029        assert!(
11030            denied
11031                .reason
11032                .contains("swap deployment manifest verification disagreed"),
11033            "was: {}",
11034            denied.reason
11035        );
11036        let requests = state.recorded_requests();
11037        assert!(
11038            requests
11039                .iter()
11040                .all(|request| request["method"] != "eth_getTransactionCount")
11041        );
11042        assert!(
11043            requests
11044                .iter()
11045                .all(|request| request["method"] != "eth_sendRawTransaction")
11046        );
11047
11048        drop_execution_schema(&admin_pool, &schema).await;
11049    }
11050
11051    #[tokio::test]
11052    async fn submit_order_denies_cached_token_decimal_mismatch_before_signing() {
11053        let state = swap_rpc_state().await.with_contract_call_response(
11054            WETH,
11055            DECIMALS_SELECTOR,
11056            CALL_DECIMALS_6,
11057        );
11058        let Some((admin_pool, schema, mut client, state, _)) =
11059            swap_client_with_database("execution_submit_decimals_test", state).await
11060        else {
11061            return;
11062        };
11063        let order = test_market_sell_order(test_pool().instrument_id);
11064        let mut receiver = start_with_events(&mut client);
11065
11066        client.submit_order(submit_order_cmd(&order)).unwrap();
11067        await_pending_tasks(&client).await;
11068
11069        let events = collect_order_events(&mut receiver);
11070        assert_eq!(events.len(), 1);
11071        let OrderEventAny::Denied(denied) = &events[0] else {
11072            panic!("expected OrderDenied, was {:?}", events[0]);
11073        };
11074        assert!(
11075            denied
11076                .reason
11077                .contains("swap deployment manifest verification disagreed"),
11078            "was: {}",
11079            denied.reason
11080        );
11081        let requests = state.recorded_requests();
11082        assert!(
11083            requests
11084                .iter()
11085                .all(|request| request["method"] != "eth_getTransactionCount")
11086        );
11087        assert!(
11088            requests
11089                .iter()
11090                .all(|request| request["method"] != "eth_sendRawTransaction")
11091        );
11092
11093        drop_execution_schema(&admin_pool, &schema).await;
11094    }
11095
11096    #[tokio::test]
11097    async fn submit_order_denies_on_insufficient_router_allowance() {
11098        let state = swap_rpc_state()
11099            .await
11100            .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO);
11101        let Some((admin_pool, schema, mut client, state, _)) =
11102            swap_client_with_database("execution_submit_allowance_test", state).await
11103        else {
11104            return;
11105        };
11106        let order = test_market_sell_order(test_pool().instrument_id);
11107        let mut receiver = start_with_events(&mut client);
11108
11109        client.submit_order(submit_order_cmd(&order)).unwrap();
11110        await_pending_tasks(&client).await;
11111
11112        let events = collect_order_events(&mut receiver);
11113        assert_eq!(events.len(), 1);
11114        let OrderEventAny::Denied(denied) = &events[0] else {
11115            panic!("expected OrderDenied, was {:?}", events[0]);
11116        };
11117        assert!(
11118            denied.reason.contains("below the swap amount"),
11119            "was: {}",
11120            denied.reason
11121        );
11122        let requests = state.recorded_requests();
11123        assert!(
11124            requests
11125                .iter()
11126                .all(|request| request["method"] != "eth_sendRawTransaction"),
11127            "no broadcast may follow a pre-trade denial"
11128        );
11129        let row_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11130            "SELECT COUNT(*) FROM {schema}.execution_intent"
11131        )))
11132        .fetch_one(&admin_pool)
11133        .await
11134        .unwrap();
11135        assert_eq!(row_count, 0);
11136        assert!(client.in_flight.lock().is_none());
11137
11138        drop_execution_schema(&admin_pool, &schema).await;
11139    }
11140
11141    #[tokio::test]
11142    async fn submit_order_denies_on_insufficient_input_balance() {
11143        let state = swap_rpc_state()
11144            .await
11145            .with_call_response(BALANCE_OF_SELECTOR, CALL_ZERO);
11146        let Some((admin_pool, schema, mut client, _, _)) =
11147            swap_client_with_database("execution_submit_balance_test", state).await
11148        else {
11149            return;
11150        };
11151        let order = test_market_sell_order(test_pool().instrument_id);
11152        let mut receiver = start_with_events(&mut client);
11153
11154        client.submit_order(submit_order_cmd(&order)).unwrap();
11155        await_pending_tasks(&client).await;
11156
11157        let events = collect_order_events(&mut receiver);
11158        assert_eq!(events.len(), 1);
11159        let OrderEventAny::Denied(denied) = &events[0] else {
11160            panic!("expected OrderDenied, was {:?}", events[0]);
11161        };
11162        assert!(
11163            denied.reason.contains("is below the swap amount"),
11164            "was: {}",
11165            denied.reason
11166        );
11167
11168        drop_execution_schema(&admin_pool, &schema).await;
11169    }
11170
11171    #[tokio::test]
11172    async fn submit_order_denies_on_insufficient_native_balance() {
11173        let state = swap_rpc_state()
11174            .await
11175            .with_response("eth_getBalance", GET_BALANCE_INSUFFICIENT);
11176        let Some((admin_pool, schema, mut client, state, _)) =
11177            swap_client_with_database("execution_submit_native_balance_test", state).await
11178        else {
11179            return;
11180        };
11181        let order = test_market_sell_order(test_pool().instrument_id);
11182        let mut receiver = start_with_events(&mut client);
11183
11184        client.submit_order(submit_order_cmd(&order)).unwrap();
11185        await_pending_tasks(&client).await;
11186
11187        let events = collect_order_events(&mut receiver);
11188        assert_eq!(events.len(), 1);
11189        let OrderEventAny::Denied(denied) = &events[0] else {
11190            panic!("expected OrderDenied, was {:?}", events[0]);
11191        };
11192        assert!(
11193            denied.reason.contains("below maximum transaction cost"),
11194            "was: {}",
11195            denied.reason
11196        );
11197        assert!(
11198            state
11199                .recorded_requests()
11200                .iter()
11201                .all(|request| request["method"] != "eth_sendRawTransaction"),
11202            "no broadcast may follow an insufficient native balance"
11203        );
11204        let (row_count, status): (i64, Option<String>) = sqlx::query_as(sqlx::AssertSqlSafe(
11205            format!("SELECT COUNT(*), MAX(status) FROM {schema}.execution_intent"),
11206        ))
11207        .fetch_one(&admin_pool)
11208        .await
11209        .unwrap();
11210        assert_eq!(row_count, 1);
11211        assert_eq!(status.as_deref(), Some("recoverable"));
11212        assert!(client.in_flight.lock().is_none());
11213
11214        drop_execution_schema(&admin_pool, &schema).await;
11215    }
11216
11217    #[tokio::test]
11218    async fn submit_order_denies_on_stale_quote() {
11219        let Some((admin_pool, schema, mut client, state, cache)) =
11220            swap_client_with_database("execution_submit_stale_quote_test", swap_rpc_state().await)
11221                .await
11222        else {
11223            return;
11224        };
11225        let pool = test_pool();
11226        cache
11227            .borrow_mut()
11228            .add_pool_profiler(test_profiler(&pool, FIXTURE_BLOCK - 101))
11229            .unwrap();
11230        let order = test_market_sell_order(pool.instrument_id);
11231        let mut receiver = start_with_events(&mut client);
11232
11233        client.submit_order(submit_order_cmd(&order)).unwrap();
11234        await_pending_tasks(&client).await;
11235
11236        let events = collect_order_events(&mut receiver);
11237        assert_eq!(events.len(), 1);
11238        let OrderEventAny::Denied(denied) = &events[0] else {
11239            panic!("expected OrderDenied, was {:?}", events[0]);
11240        };
11241        assert!(
11242            denied.reason.contains("Stale quote"),
11243            "was: {}",
11244            denied.reason
11245        );
11246        let requests = state.recorded_requests();
11247        assert!(
11248            requests
11249                .iter()
11250                .all(|request| request["method"] != "eth_sendRawTransaction"),
11251            "no broadcast may follow a pre-trade denial"
11252        );
11253
11254        drop_execution_schema(&admin_pool, &schema).await;
11255    }
11256
11257    #[tokio::test]
11258    async fn submit_order_denies_quote_ahead_of_chain_head() {
11259        let Some((admin_pool, schema, mut client, state, cache)) =
11260            swap_client_with_database("execution_submit_ahead_quote_test", swap_rpc_state().await)
11261                .await
11262        else {
11263            return;
11264        };
11265        let pool = test_pool();
11266        cache
11267            .borrow_mut()
11268            .add_pool_profiler(test_profiler(&pool, FIXTURE_BLOCK + 1))
11269            .unwrap();
11270        let order = test_market_sell_order(pool.instrument_id);
11271        let mut receiver = start_with_events(&mut client);
11272
11273        client.submit_order(submit_order_cmd(&order)).unwrap();
11274        await_pending_tasks(&client).await;
11275
11276        let events = collect_order_events(&mut receiver);
11277        assert_eq!(events.len(), 1);
11278        let OrderEventAny::Denied(denied) = &events[0] else {
11279            panic!("expected OrderDenied, was {:?}", events[0]);
11280        };
11281        assert!(
11282            denied.reason.contains("is ahead of the latest block"),
11283            "was: {}",
11284            denied.reason
11285        );
11286        let requests = state.recorded_requests();
11287        assert!(
11288            requests
11289                .iter()
11290                .all(|request| request["method"] != "eth_sendRawTransaction"),
11291            "no broadcast may follow a pre-trade denial"
11292        );
11293
11294        drop_execution_schema(&admin_pool, &schema).await;
11295    }
11296
11297    #[tokio::test]
11298    async fn submit_order_denies_on_deadline_overflow() {
11299        let Some((admin_pool, schema, mut client, state, _)) = swap_client_with_database(
11300            "execution_submit_deadline_overflow_test",
11301            swap_rpc_state().await,
11302        )
11303        .await
11304        else {
11305            return;
11306        };
11307        client.transaction_limits.deadline_seconds = u64::MAX;
11308        let order = test_market_sell_order(test_pool().instrument_id);
11309        let mut receiver = start_with_events(&mut client);
11310
11311        client.submit_order(submit_order_cmd(&order)).unwrap();
11312        await_pending_tasks(&client).await;
11313
11314        let events = collect_order_events(&mut receiver);
11315        assert_eq!(events.len(), 1);
11316        let OrderEventAny::Denied(denied) = &events[0] else {
11317            panic!("expected OrderDenied, was {:?}", events[0]);
11318        };
11319        assert!(
11320            denied.reason.contains("deadline overflow"),
11321            "was: {}",
11322            denied.reason
11323        );
11324        let requests = state.recorded_requests();
11325        assert!(
11326            requests
11327                .iter()
11328                .all(|request| request["method"] != "eth_sendRawTransaction"),
11329            "no broadcast may follow a pre-trade denial"
11330        );
11331        assert!(client.in_flight.lock().is_none());
11332
11333        drop_execution_schema(&admin_pool, &schema).await;
11334    }
11335
11336    #[tokio::test]
11337    async fn submit_order_reconciles_node_rejection_to_finalized_receipt() {
11338        let state = swap_rpc_state()
11339            .await
11340            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION_REJECTED);
11341        let Some((admin_pool, schema, mut client, _state, _)) =
11342            swap_client_with_database("execution_submit_node_rejected_test", state).await
11343        else {
11344            return;
11345        };
11346        let order = test_market_sell_order(test_pool().instrument_id);
11347        let mut receiver = start_with_events(&mut client);
11348
11349        client.submit_order(submit_order_cmd(&order)).unwrap();
11350        await_pending_tasks(&client).await;
11351
11352        let events = collect_order_events(&mut receiver);
11353        assert_swap_submitted_and_filled(&events);
11354        let (purpose, status, client_order_id): (String, String, Option<String>) =
11355            sqlx::query_as(sqlx::AssertSqlSafe(format!(
11356                "SELECT purpose, status, client_order_id FROM {schema}.execution_intent"
11357            )))
11358            .fetch_one(&admin_pool)
11359            .await
11360            .unwrap();
11361        assert_eq!(purpose, "swap");
11362        assert_eq!(status, "finalized");
11363        assert_eq!(
11364            client_order_id.as_deref(),
11365            Some(order.client_order_id().as_str())
11366        );
11367        assert!(client.in_flight.lock().is_none());
11368
11369        drop_execution_schema(&admin_pool, &schema).await;
11370    }
11371
11372    #[tokio::test]
11373    async fn submit_order_acknowledges_uncertain_nonce_too_low() {
11374        let state = swap_rpc_state()
11375            .await
11376            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION_NONCE_TOO_LOW);
11377        let Some((admin_pool, schema, mut client, _state, _)) =
11378            swap_client_with_database("execution_submit_nonce_too_low_test", state).await
11379        else {
11380            return;
11381        };
11382        let order = test_market_sell_order(test_pool().instrument_id);
11383        let mut receiver = start_with_events(&mut client);
11384
11385        client.submit_order(submit_order_cmd(&order)).unwrap();
11386        await_pending_tasks(&client).await;
11387
11388        let events = collect_order_events(&mut receiver);
11389        assert_swap_submitted_and_filled(&events);
11390        let (purpose, status, client_order_id): (String, String, Option<String>) =
11391            sqlx::query_as(sqlx::AssertSqlSafe(format!(
11392                "SELECT purpose, status, client_order_id FROM {schema}.execution_intent"
11393            )))
11394            .fetch_one(&admin_pool)
11395            .await
11396            .unwrap();
11397        assert_eq!(purpose, "swap");
11398        assert_eq!(status, "finalized");
11399        assert_eq!(
11400            client_order_id.as_deref(),
11401            Some(order.client_order_id().as_str())
11402        );
11403        assert!(client.in_flight.lock().is_none());
11404
11405        drop_execution_schema(&admin_pool, &schema).await;
11406    }
11407
11408    #[tokio::test]
11409    async fn submit_order_rejected_on_reverted_receipt() {
11410        let expected_min_out = expected_min_amount_out(50);
11411        let (expected_hash, _) = expected_swap_tx(expected_min_out).await;
11412        let block = finalized_swap_block(expected_hash, expected_min_out);
11413        let receipt = receipt_with_transaction_hash(RECEIPT_REVERTED, expected_hash);
11414        let state = with_finalized_identity(
11415            swap_rpc_state()
11416                .await
11417                .with_response("eth_getTransactionReceipt", &receipt),
11418            &block,
11419            &receipt,
11420        );
11421        let Some((admin_pool, schema, mut client, _state, _)) =
11422            swap_client_with_database("execution_submit_reverted_test", state).await
11423        else {
11424            return;
11425        };
11426        let order = test_market_sell_order(test_pool().instrument_id);
11427        let mut receiver = start_with_events(&mut client);
11428        client.submit_order(submit_order_cmd(&order)).unwrap();
11429        await_pending_tasks(&client).await;
11430
11431        let events = collect_order_events(&mut receiver);
11432        assert_eq!(events.len(), 2);
11433        assert!(
11434            matches!(&events[0], OrderEventAny::Submitted(_)),
11435            "was: {:?}",
11436            events[0]
11437        );
11438        let OrderEventAny::Rejected(rejected) = &events[1] else {
11439            panic!("expected OrderRejected, was {:?}", events[1]);
11440        };
11441        assert!(
11442            rejected.reason.contains("reverted on-chain"),
11443            "was: {}",
11444            rejected.reason
11445        );
11446
11447        let record = client
11448            .cache
11449            .get_execution_transaction(42161, &expected_hash.to_string())
11450            .await
11451            .unwrap()
11452            .unwrap();
11453        assert_eq!(record.purpose, "swap");
11454        assert_eq!(record.status, "reverted");
11455        assert_eq!(
11456            record.client_order_id.as_deref(),
11457            Some(order.client_order_id().as_str())
11458        );
11459        assert!(client.in_flight.lock().is_none());
11460
11461        drop_execution_schema(&admin_pool, &schema).await;
11462    }
11463
11464    #[tokio::test]
11465    async fn submit_order_acknowledges_ambiguous_broadcast() {
11466        // A response the client cannot parse classifies as an ambiguous broadcast failure:
11467        // the transaction may be live, so the durable intent remains submitted and occupied
11468        let state = swap_rpc_state()
11469            .await
11470            .with_response("eth_sendRawTransaction", "not json");
11471        let Some((admin_pool, schema, mut client, _state, _)) =
11472            swap_client_with_database("execution_submit_ambiguous_test", state).await
11473        else {
11474            return;
11475        };
11476        let order = test_market_sell_order(test_pool().instrument_id);
11477        let mut receiver = start_with_events(&mut client);
11478
11479        client.submit_order(submit_order_cmd(&order)).unwrap();
11480        await_pending_tasks(&client).await;
11481
11482        let events = collect_order_events(&mut receiver);
11483        assert_swap_submitted_and_filled(&events);
11484
11485        let record = client
11486            .cache
11487            .get_execution_transaction(
11488                42161,
11489                &expected_swap_tx(expected_min_amount_out(50))
11490                    .await
11491                    .0
11492                    .to_string(),
11493            )
11494            .await
11495            .unwrap()
11496            .unwrap();
11497        assert_eq!(record.purpose, "swap");
11498        assert_eq!(record.status, "finalized");
11499        assert!(client.in_flight.lock().is_none());
11500
11501        drop_execution_schema(&admin_pool, &schema).await;
11502    }
11503
11504    #[tokio::test]
11505    async fn submit_order_acknowledges_broadcast_hash_mismatch() {
11506        // The static fixture's hash differs from the locally signed hash, so acceptance of the
11507        // signed transaction is unverified until the independent receipt reaches finality
11508        let state = swap_rpc_state_for_mismatch().await;
11509        let Some((admin_pool, schema, mut client, _state, _)) =
11510            swap_client_with_database("execution_submit_hash_mismatch_test", state).await
11511        else {
11512            return;
11513        };
11514        let order = test_market_sell_order(test_pool().instrument_id);
11515        let mut receiver = start_with_events(&mut client);
11516
11517        client.submit_order(submit_order_cmd(&order)).unwrap();
11518        await_pending_tasks(&client).await;
11519
11520        let events = collect_order_events(&mut receiver);
11521        assert_swap_submitted_and_filled(&events);
11522
11523        let record = client
11524            .cache
11525            .get_execution_transaction(
11526                42161,
11527                &expected_swap_tx(expected_min_amount_out(50))
11528                    .await
11529                    .0
11530                    .to_string(),
11531            )
11532            .await
11533            .unwrap()
11534            .unwrap();
11535        assert_eq!(record.purpose, "swap");
11536        assert_eq!(record.status, "finalized");
11537        assert!(client.in_flight.lock().is_none());
11538
11539        drop_execution_schema(&admin_pool, &schema).await;
11540    }
11541
11542    #[tokio::test]
11543    async fn submit_order_persists_authenticated_envelope_before_broadcast() {
11544        let state = swap_rpc_state().await;
11545        let Some((admin_pool, schema, mut client, state, _)) =
11546            swap_client_with_database("protected_submit_test", state).await
11547        else {
11548            return;
11549        };
11550        let order = test_market_sell_order(test_pool().instrument_id);
11551        let mut receiver = start_with_events(&mut client);
11552
11553        client.submit_order(submit_order_cmd(&order)).unwrap();
11554        await_pending_tasks(&client).await;
11555
11556        let events = collect_order_events(&mut receiver);
11557        assert_swap_submitted_and_filled(&events);
11558        let representations: Vec<(bool, bool)> = sqlx::query_as(sqlx::AssertSqlSafe(format!(
11559            "SELECT raw_transaction IS NULL, sealed_transaction IS NOT NULL \
11560             FROM {schema}.execution_transaction_hash WHERE payload_expected"
11561        )))
11562        .fetch_all(&admin_pool)
11563        .await
11564        .unwrap();
11565        let broadcasts = state
11566            .recorded_requests()
11567            .into_iter()
11568            .filter(|request| request["method"] == "eth_sendRawTransaction")
11569            .count();
11570        assert_eq!(representations, vec![(true, true)]);
11571        assert_eq!(broadcasts, 1);
11572
11573        drop_execution_schema(&admin_pool, &schema).await;
11574    }
11575
11576    #[tokio::test]
11577    async fn protected_persistence_failure_prevents_broadcast_and_acknowledgment() {
11578        let state = swap_rpc_state().await;
11579        let Some((admin_pool, schema, mut client, state, _)) =
11580            swap_client_with_database("protected_persist_failure_test", state).await
11581        else {
11582            return;
11583        };
11584
11585        for statement in [
11586            format!(
11587                "CREATE FUNCTION {schema}.reject_protected_payload() RETURNS trigger \
11588                 LANGUAGE plpgsql AS 'BEGIN RAISE EXCEPTION ''test payload rejection''; END'"
11589            ),
11590            format!(
11591                "CREATE TRIGGER reject_protected_payload BEFORE INSERT ON \
11592                 {schema}.execution_transaction_hash FOR EACH ROW \
11593                 EXECUTE FUNCTION {schema}.reject_protected_payload()"
11594            ),
11595        ] {
11596            sqlx::query(sqlx::AssertSqlSafe(statement))
11597                .execute(&admin_pool)
11598                .await
11599                .unwrap();
11600        }
11601        let order = test_market_sell_order(test_pool().instrument_id);
11602        let mut receiver = start_with_events(&mut client);
11603
11604        client.submit_order(submit_order_cmd(&order)).unwrap();
11605        await_pending_tasks(&client).await;
11606
11607        let events = collect_order_events(&mut receiver);
11608        assert!(
11609            events
11610                .iter()
11611                .all(|event| !matches!(event, OrderEventAny::Submitted(_)))
11612        );
11613        let broadcasts = state
11614            .recorded_requests()
11615            .into_iter()
11616            .filter(|request| request["method"] == "eth_sendRawTransaction")
11617            .count();
11618        let payload_rows: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11619            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
11620        )))
11621        .fetch_one(&admin_pool)
11622        .await
11623        .unwrap();
11624        assert_eq!(broadcasts, 0);
11625        assert_eq!(payload_rows, 0);
11626
11627        drop_execution_schema(&admin_pool, &schema).await;
11628    }
11629
11630    #[tokio::test]
11631    async fn submit_order_reservation_failure_denies_without_broadcast_and_releases_slot() {
11632        let Some((admin_pool, schema, mut client, state, cache)) =
11633            swap_client_with_database("execution_submit_persist_fail_test", swap_rpc_state().await)
11634                .await
11635        else {
11636            return;
11637        };
11638        sqlx::query(sqlx::AssertSqlSafe(format!(
11639            "DROP TABLE {schema}.execution_intent CASCADE"
11640        )))
11641        .execute(&admin_pool)
11642        .await
11643        .unwrap();
11644        let pool = test_pool();
11645        let first = test_market_sell_order(pool.instrument_id);
11646        let second = market_sell_order_with_id(pool.instrument_id, "O-SWAP-002");
11647        cache
11648            .borrow_mut()
11649            .add_order(second.clone(), None, None, false)
11650            .unwrap();
11651        let mut receiver = start_with_events(&mut client);
11652
11653        client.submit_order(submit_order_cmd(&first)).unwrap();
11654        await_pending_tasks(&client).await;
11655
11656        let events = collect_order_events(&mut receiver);
11657        assert_eq!(events.len(), 1);
11658        let OrderEventAny::Denied(denied) = &events[0] else {
11659            panic!("expected OrderDenied, was {:?}", events[0]);
11660        };
11661        assert!(
11662            denied
11663                .reason
11664                .contains("Execution intent reservation failed before commit"),
11665            "was: {}",
11666            denied.reason
11667        );
11668        client.submit_order(submit_order_cmd(&second)).unwrap();
11669        await_pending_tasks(&client).await;
11670        let retry_events = collect_order_events(&mut receiver);
11671        assert_eq!(retry_events.len(), 1);
11672        let OrderEventAny::Denied(retry_denied) = &retry_events[0] else {
11673            panic!("expected OrderDenied, was {:?}", retry_events[0]);
11674        };
11675        assert_eq!(
11676            retry_denied.reason,
11677            "Execution intent reservation failed before commit"
11678        );
11679        let broadcasts = state
11680            .recorded_requests()
11681            .into_iter()
11682            .filter(|request| request["method"] == "eth_sendRawTransaction")
11683            .count();
11684        assert_eq!(broadcasts, 0);
11685        assert!(client.in_flight.lock().is_none());
11686
11687        drop_execution_schema(&admin_pool, &schema).await;
11688    }
11689
11690    #[tokio::test]
11691    async fn submit_order_reservation_commit_failure_keeps_preparing_slot() {
11692        let Some((admin_pool, schema, mut client, state, cache)) = swap_client_with_database(
11693            "execution_submit_reservation_commit_fail_test",
11694            swap_rpc_state().await,
11695        )
11696        .await
11697        else {
11698            return;
11699        };
11700        install_reservation_commit_rejection(&admin_pool, &schema).await;
11701        let pool = test_pool();
11702        let first = test_market_sell_order(pool.instrument_id);
11703        let second = market_sell_order_with_id(pool.instrument_id, "O-SWAP-002");
11704        cache
11705            .borrow_mut()
11706            .add_order(second.clone(), None, None, false)
11707            .unwrap();
11708        let mut receiver = start_with_events(&mut client);
11709
11710        client.submit_order(submit_order_cmd(&first)).unwrap();
11711        await_pending_tasks(&client).await;
11712        client.submit_order(submit_order_cmd(&second)).unwrap();
11713        await_pending_tasks(&client).await;
11714
11715        let events = collect_order_events(&mut receiver);
11716        let submitted = events
11717            .iter()
11718            .filter(|event| matches!(event, OrderEventAny::Submitted(_)))
11719            .count();
11720        let denied_commit = events
11721            .iter()
11722            .filter(|event| {
11723                matches!(event, OrderEventAny::Denied(denied) if denied.reason == "Execution intent reservation commit outcome is unknown; reconciliation is required")
11724            })
11725            .count();
11726        let denied_in_flight = events
11727            .iter()
11728            .filter(|event| {
11729                matches!(event, OrderEventAny::Denied(denied) if denied.reason.contains("at most one transaction can be in flight"))
11730            })
11731            .count();
11732        let requests = state.recorded_requests();
11733        let intent_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11734            "SELECT COUNT(*) FROM {schema}.execution_intent"
11735        )))
11736        .fetch_one(&admin_pool)
11737        .await
11738        .unwrap();
11739        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11740            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
11741        )))
11742        .fetch_one(&admin_pool)
11743        .await
11744        .unwrap();
11745
11746        assert_eq!(submitted, 0, "was: {events:?}");
11747        assert_eq!(denied_commit, 1, "was: {events:?}");
11748        assert_eq!(denied_in_flight, 1, "was: {events:?}");
11749        assert!(matches!(
11750            *client.in_flight.lock(),
11751            Some(InFlightSlot::Preparing(TransactionPurpose::Swap))
11752        ));
11753        assert_eq!(intent_count, 0);
11754        assert_eq!(signed_count, 0);
11755        assert!(
11756            requests
11757                .iter()
11758                .all(|request| request["method"] != "eth_getTransactionCount")
11759        );
11760        assert!(
11761            requests
11762                .iter()
11763                .all(|request| request["method"] != "eth_sendRawTransaction")
11764        );
11765
11766        drop_execution_schema(&admin_pool, &schema).await;
11767    }
11768
11769    #[tokio::test]
11770    async fn protected_payload_migration_failure_keeps_plaintext_and_blocks_ready() {
11771        let Some((admin_pool, schema, client, _)) = execution_client_with_unprotected_database(
11772            "protected_payload_migration_failure",
11773            execution_rpc_state(),
11774        )
11775        .await
11776        else {
11777            return;
11778        };
11779        let database = client.cache.database.as_ref().unwrap();
11780        let (intent, _) = persist_invalid_test_swap(database, None).await;
11781        let keys = payload_test_keys([0x31; 32], vec![], "migration-failure");
11782        let error = database
11783            .ensure_execution_payload_storage(&keys)
11784            .await
11785            .unwrap_err();
11786
11787        assert!(
11788            error
11789                .to_string()
11790                .contains("failed to authenticate execution payload")
11791        );
11792        let row = database
11793            .get_execution_transaction_hashes(intent.id)
11794            .await
11795            .unwrap()
11796            .pop()
11797            .unwrap();
11798        let operation: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11799            "SELECT operation FROM {schema}.execution_payload_state"
11800        )))
11801        .fetch_one(&admin_pool)
11802        .await
11803        .unwrap();
11804        assert_eq!(operation, "migrate");
11805        assert!(row.raw_transaction.is_some());
11806        assert!(row.sealed_transaction.is_none());
11807
11808        drop_execution_schema(&admin_pool, &schema).await;
11809    }
11810
11811    #[tokio::test]
11812    async fn protected_payload_migration_restart_restore_rewrap_and_rollback() {
11813        let Some((admin_pool, pg_config)) =
11814            connect_test_postgres("protected payload lifecycle").await
11815        else {
11816            return;
11817        };
11818        let schema = format!("protected_payload_lifecycle_{}", std::process::id());
11819        setup_execution_schema(&admin_pool, &schema).await;
11820        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
11821        let options = options.options([("search_path", schema.clone())]);
11822        let database = connect_test_database(options.clone()).await.unwrap();
11823        database
11824            .ensure_execution_transaction_schema()
11825            .await
11826            .unwrap();
11827        let intent = reserve_test_wrap_intent(&database).await;
11828        database
11829            .assign_execution_intent_nonce(intent.id, 7)
11830            .await
11831            .unwrap();
11832        let transaction = build_eip1559_transaction(
11833            42161,
11834            7,
11835            78_000,
11836            130_000_000,
11837            10_000_000,
11838            WETH_ADDRESS,
11839            U256::from(1_u64),
11840            Bytes::from(hex::decode("d0e30db0").unwrap()),
11841        );
11842        let (transaction_hash, raw_transaction) = sign_eip1559_transaction(
11843            transaction,
11844            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
11845        )
11846        .await
11847        .unwrap();
11848        database
11849            .add_execution_transaction_hash(
11850                intent.id,
11851                42161,
11852                &transaction_hash.to_string(),
11853                &raw_transaction,
11854            )
11855            .await
11856            .unwrap();
11857        let keys = payload_test_keys([0x41; 32], vec![], "restore-a");
11858
11859        database
11860            .ensure_execution_payload_storage(&keys)
11861            .await
11862            .unwrap();
11863        let operation: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11864            "SELECT operation FROM {schema}.execution_payload_state"
11865        )))
11866        .fetch_one(&admin_pool)
11867        .await
11868        .unwrap();
11869        assert_eq!(operation, "ready");
11870        drop(database);
11871
11872        let restarted = connect_test_database(options).await.unwrap();
11873        restarted
11874            .ensure_execution_payload_storage(&keys)
11875            .await
11876            .unwrap();
11877        let row = restarted
11878            .get_execution_transaction_hashes(intent.id)
11879            .await
11880            .unwrap()
11881            .pop()
11882            .unwrap();
11883        assert!(row.raw_transaction.is_none());
11884        let sealed_transaction = row.sealed_transaction.clone().unwrap();
11885        let stored_intent = restarted.get_execution_intent(intent.id).await.unwrap();
11886        let context = payload_context(&stored_intent, &row, keys.deployment_id()).unwrap();
11887        let alternate_envelope = keys.seal(&raw_transaction, &context).unwrap();
11888        assert_ne!(alternate_envelope, sealed_transaction);
11889        let repeated = restarted
11890            .add_execution_transaction_envelope(
11891                intent.id,
11892                42161,
11893                &transaction_hash.to_string(),
11894                &alternate_envelope,
11895            )
11896            .await
11897            .unwrap();
11898        let check = restarted
11899            .check_execution_payload_storage(Some(&keys), None, 1)
11900            .await
11901            .unwrap();
11902        assert_eq!(
11903            repeated.sealed_transaction,
11904            Some(sealed_transaction.clone())
11905        );
11906        assert_eq!(check.plaintext_rows, 0);
11907        assert_eq!(check.original_rows, 1);
11908        assert_eq!(check.replacement_rows, 0);
11909        assert_eq!(check.authenticated_rows, 1);
11910        assert!(!check.read_roles.is_empty());
11911
11912        sqlx::query(sqlx::AssertSqlSafe(format!(
11913            "UPDATE {schema}.execution_payload_key_state SET seals = 4294967295"
11914        )))
11915        .execute(&admin_pool)
11916        .await
11917        .unwrap();
11918        let exhausted = restarted
11919            .reserve_execution_payload_seal(&keys)
11920            .await
11921            .unwrap_err();
11922        assert!(exhausted.to_string().contains("seal limit"));
11923        let seals: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
11924            "SELECT seals FROM {schema}.execution_payload_key_state"
11925        )))
11926        .fetch_one(&admin_pool)
11927        .await
11928        .unwrap();
11929        assert_eq!(seals, 4_294_967_295);
11930        sqlx::query(sqlx::AssertSqlSafe(format!(
11931            "UPDATE {schema}.execution_payload_key_state SET seals = 1"
11932        )))
11933        .execute(&admin_pool)
11934        .await
11935        .unwrap();
11936
11937        let missing_key = restarted
11938            .check_execution_payload_storage(None, None, 1)
11939            .await
11940            .unwrap_err();
11941        assert!(
11942            missing_key
11943                .to_string()
11944                .contains("no payload key is configured")
11945        );
11946        let restored_elsewhere = payload_test_keys([0x41; 32], vec![], "restore-b");
11947        let wrong_context = restarted
11948            .ensure_execution_payload_storage(&restored_elsewhere)
11949            .await
11950            .unwrap_err();
11951        assert!(wrong_context.to_string().contains("deployment ID"));
11952
11953        sqlx::query(sqlx::AssertSqlSafe(format!(
11954            "UPDATE {schema}.execution_transaction_hash \
11955             SET sealed_transaction = set_byte(sealed_transaction, octet_length(sealed_transaction) - 1, \
11956                 get_byte(sealed_transaction, octet_length(sealed_transaction) - 1) # 1)"
11957        )))
11958        .execute(&admin_pool)
11959        .await
11960        .unwrap();
11961        assert!(
11962            restarted
11963                .check_execution_payload_storage(Some(&keys), None, 1)
11964                .await
11965                .is_err()
11966        );
11967        sqlx::query(sqlx::AssertSqlSafe(format!(
11968            "UPDATE {schema}.execution_transaction_hash SET sealed_transaction = $1"
11969        )))
11970        .bind(&sealed_transaction)
11971        .execute(&admin_pool)
11972        .await
11973        .unwrap();
11974
11975        for statement in [
11976            format!(
11977                "ALTER TABLE {schema}.execution_transaction_hash \
11978                 DROP CONSTRAINT execution_transaction_payload_protected_check"
11979            ),
11980            format!("UPDATE {schema}.execution_transaction_hash SET sealed_transaction = NULL"),
11981        ] {
11982            sqlx::query(sqlx::AssertSqlSafe(statement))
11983                .execute(&admin_pool)
11984                .await
11985                .unwrap();
11986        }
11987        assert!(
11988            restarted
11989                .check_execution_payload_storage(Some(&keys), None, 1)
11990                .await
11991                .is_err()
11992        );
11993        sqlx::query(sqlx::AssertSqlSafe(format!(
11994            "UPDATE {schema}.execution_transaction_hash SET sealed_transaction = $1"
11995        )))
11996        .bind(&sealed_transaction)
11997        .execute(&admin_pool)
11998        .await
11999        .unwrap();
12000        sqlx::query(sqlx::AssertSqlSafe(format!(
12001            "ALTER TABLE {schema}.execution_transaction_hash \
12002             ADD CONSTRAINT execution_transaction_payload_protected_check CHECK ( \
12003                 (payload_expected AND raw_transaction IS NULL AND sealed_transaction IS NOT NULL) \
12004                 OR (NOT payload_expected AND raw_transaction IS NULL AND sealed_transaction IS NULL) \
12005             )"
12006        )))
12007        .execute(&admin_pool)
12008        .await
12009        .unwrap();
12010
12011        let rotated = payload_test_keys([0x52; 32], vec![[0x41; 32]], "restore-a");
12012        restarted
12013            .rewrap_execution_payload_storage(&rotated, 1)
12014            .await
12015            .unwrap();
12016        let rotated_check = restarted
12017            .check_execution_payload_storage(Some(&rotated), None, 1)
12018            .await
12019            .unwrap();
12020        assert_eq!(rotated_check.authenticated_rows, 1);
12021        assert_eq!(rotated_check.key_ids.len(), 1);
12022
12023        restarted
12024            .rollback_execution_payload_storage(&rotated, 1)
12025            .await
12026            .unwrap();
12027        let rolled_back = restarted
12028            .get_execution_transaction_hashes(intent.id)
12029            .await
12030            .unwrap()
12031            .pop()
12032            .unwrap();
12033        assert_eq!(
12034            rolled_back.raw_transaction.as_deref(),
12035            Some(raw_transaction.as_slice())
12036        );
12037        assert!(rolled_back.sealed_transaction.is_none());
12038        let legacy_check = restarted
12039            .check_execution_payload_storage(None, None, 1)
12040            .await
12041            .unwrap();
12042        assert!(!legacy_check.protected);
12043        assert_eq!(legacy_check.plaintext_rows, 1);
12044        assert_eq!(legacy_check.authenticated_rows, 1);
12045
12046        drop_execution_schema(&admin_pool, &schema).await;
12047    }
12048
12049    #[tokio::test]
12050    async fn protected_payload_storage_authenticates_multiple_execution_identities() {
12051        let Some((admin_pool, pg_config)) =
12052            connect_test_postgres("protected payload multiple identities").await
12053        else {
12054            return;
12055        };
12056        let schema = format!("protected_payload_identities_{}", std::process::id());
12057        setup_execution_schema(&admin_pool, &schema).await;
12058        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
12059        let database = connect_test_database(options.options([("search_path", schema.clone())]))
12060            .await
12061            .unwrap();
12062        database
12063            .ensure_execution_transaction_schema()
12064            .await
12065            .unwrap();
12066
12067        let private_keys = [
12068            TEST_PRIVATE_KEY,
12069            "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d",
12070        ];
12071
12072        for (index, private_key) in private_keys.into_iter().enumerate() {
12073            let signer = PrivateKeySigner::from_str(private_key).unwrap();
12074            let nonce = 7 + u64::try_from(index).unwrap();
12075            let intent =
12076                reserve_test_wrap_intent_for_wallet(&database, &signer.address().to_string()).await;
12077            database
12078                .assign_execution_intent_nonce(intent.id, nonce)
12079                .await
12080                .unwrap();
12081            let transaction = build_eip1559_transaction(
12082                42161,
12083                nonce,
12084                78_000,
12085                130_000_000,
12086                10_000_000,
12087                WETH_ADDRESS,
12088                U256::from(1_u64),
12089                Bytes::from(hex::decode("d0e30db0").unwrap()),
12090            );
12091            let (transaction_hash, raw_transaction) =
12092                sign_eip1559_transaction(transaction, &signer)
12093                    .await
12094                    .unwrap();
12095            database
12096                .add_execution_transaction_hash(
12097                    intent.id,
12098                    42161,
12099                    &transaction_hash.to_string(),
12100                    &raw_transaction,
12101                )
12102                .await
12103                .unwrap();
12104        }
12105
12106        let keys = payload_test_keys([0x61; 32], vec![], "multiple-identities");
12107        database
12108            .ensure_execution_payload_storage(&keys)
12109            .await
12110            .unwrap();
12111        let lease = database
12112            .require_execution_payload_storage(
12113                &keys,
12114                PayloadPolicy {
12115                    chain_id: 42161,
12116                    signer: Address::from_str(WALLET).unwrap(),
12117                    gas_limit: 1_000_000,
12118                    max_fee_per_gas: 1_000_000_000,
12119                },
12120                1,
12121            )
12122            .await
12123            .unwrap();
12124        drop(lease);
12125        let check = database
12126            .check_execution_payload_storage(Some(&keys), None, 1)
12127            .await
12128            .unwrap();
12129
12130        assert!(check.protected);
12131        assert_eq!(check.plaintext_rows, 0);
12132        assert_eq!(check.original_rows, 2);
12133        assert_eq!(check.replacement_rows, 0);
12134        assert_eq!(check.authenticated_rows, 2);
12135        assert_eq!(check.key_ids.len(), 1);
12136
12137        drop_execution_schema(&admin_pool, &schema).await;
12138    }
12139
12140    #[rstest]
12141    #[case::finalized(TransactionStatus::Finalized)]
12142    #[case::reverted(TransactionStatus::Reverted)]
12143    #[tokio::test]
12144    async fn protected_payload_storage_ignores_current_policy_for_released_terminal_history(
12145        #[case] status: TransactionStatus,
12146    ) {
12147        let Some((admin_pool, pg_config)) =
12148            connect_test_postgres("protected payload terminal history").await
12149        else {
12150            return;
12151        };
12152        let schema = format!(
12153            "protected_payload_terminal_{}_{}",
12154            status.as_str(),
12155            std::process::id()
12156        );
12157        setup_execution_schema(&admin_pool, &schema).await;
12158        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
12159        let database = connect_test_database(options.options([("search_path", schema.clone())]))
12160            .await
12161            .unwrap();
12162        database
12163            .ensure_execution_transaction_schema()
12164            .await
12165            .unwrap();
12166        let (intent, transaction_hash, _) = persist_test_wrap_broadcast(&database, None).await;
12167        database
12168            .record_execution_status(
12169                intent.id,
12170                &transaction_hash.to_string(),
12171                status,
12172                None,
12173                None,
12174                None,
12175                None,
12176                None,
12177            )
12178            .await
12179            .unwrap();
12180        database
12181            .mark_execution_event_emitted(intent.id, "terminal")
12182            .await
12183            .unwrap();
12184        let keys = payload_test_keys([0x62; 32], vec![], "terminal-history");
12185        database
12186            .ensure_execution_payload_storage(&keys)
12187            .await
12188            .unwrap();
12189
12190        let lease = database
12191            .require_execution_payload_storage(
12192                &keys,
12193                PayloadPolicy {
12194                    chain_id: 42161,
12195                    signer: Address::from_str(WALLET).unwrap(),
12196                    gas_limit: 1,
12197                    max_fee_per_gas: 1,
12198                },
12199                1,
12200            )
12201            .await
12202            .unwrap();
12203        drop(lease);
12204        let check = database
12205            .check_execution_payload_storage(Some(&keys), None, 1)
12206            .await
12207            .unwrap();
12208        let active_intent = reserve_test_wrap_intent(&database).await;
12209        database
12210            .assign_execution_intent_nonce(active_intent.id, 8)
12211            .await
12212            .unwrap();
12213        let active_intent = database
12214            .get_execution_intent(active_intent.id)
12215            .await
12216            .unwrap();
12217        let active_transaction = build_eip1559_transaction(
12218            42161,
12219            8,
12220            78_000,
12221            130_000_000,
12222            10_000_000,
12223            WETH_ADDRESS,
12224            U256::from(1_u64),
12225            Bytes::from(hex::decode("d0e30db0").unwrap()),
12226        );
12227        let (active_hash, active_raw_transaction) = sign_eip1559_transaction(
12228            active_transaction,
12229            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
12230        )
12231        .await
12232        .unwrap();
12233        persist_test_payload(
12234            &database,
12235            Some(&keys),
12236            &active_intent,
12237            active_hash,
12238            &active_raw_transaction,
12239        )
12240        .await;
12241        let active_error = match database
12242            .require_execution_payload_storage(
12243                &keys,
12244                PayloadPolicy {
12245                    chain_id: 42161,
12246                    signer: Address::from_str(WALLET).unwrap(),
12247                    gas_limit: 1,
12248                    max_fee_per_gas: 1,
12249                },
12250                1,
12251            )
12252            .await
12253        {
12254            Ok(_) => panic!("active execution payload unexpectedly passed current policy"),
12255            Err(e) => e,
12256        };
12257        let active_error = format!("{active_error:#}");
12258
12259        assert!(check.protected);
12260        assert_eq!(check.authenticated_rows, 1);
12261        assert!(
12262            active_error.contains(&format!(
12263                "execution intent {} transaction {active_hash} violates current execution policy",
12264                active_intent.id
12265            )),
12266            "was: {active_error}"
12267        );
12268        assert!(
12269            active_error.contains("gas limit 78000 exceeds configured ceiling 1"),
12270            "was: {active_error}"
12271        );
12272
12273        drop_execution_schema(&admin_pool, &schema).await;
12274    }
12275
12276    #[allow(unsafe_code)] // env-var mutation uses the test client's dedicated signer variable
12277    #[tokio::test]
12278    async fn rollback_blocks_execution_until_protection_and_full_check_succeed() {
12279        let state = ready_rpc_state();
12280        let Some((admin_pool, schema, mut client, state)) =
12281            execution_client_with_database("payload_rollback_reactivation", state).await
12282        else {
12283            return;
12284        };
12285        // SAFETY: this test binary owns the dedicated test signer variable
12286        unsafe { std::env::set_var("BLOCKCHAIN_TEST_PRIVATE_KEY", TEST_PRIVATE_KEY) };
12287        client.disconnect().await.unwrap();
12288        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
12289        replace_exec_event_sender(sender);
12290        client.start().unwrap();
12291
12292        client.rollback_payload_storage(1).await.unwrap();
12293        let unprotected = client.check_payload_storage(1).await.unwrap();
12294        let error = client.connect().await.unwrap_err();
12295
12296        assert!(!unprotected.protected);
12297        assert_eq!(unprotected.plaintext_rows, 0);
12298        assert_eq!(unprotected.authenticated_rows, 0);
12299        assert!(
12300            error
12301                .to_string()
12302                .contains("Postgres execution requires protected payload storage"),
12303            "was: {error}"
12304        );
12305        assert!(client.signer.is_none());
12306        assert!(state.recorded_requests().is_empty());
12307
12308        client.protect_payload_storage().await.unwrap();
12309        let protected = client.check_payload_storage(1).await.unwrap();
12310        assert!(protected.protected);
12311        assert_eq!(protected.plaintext_rows, 0);
12312        assert_eq!(protected.authenticated_rows, 0);
12313
12314        client.connect().await.unwrap();
12315
12316        assert!(client.is_connected());
12317        assert!(client.transaction_executor().is_ok());
12318        assert!(!state.recorded_requests().is_empty());
12319
12320        drop(client);
12321        drop_execution_schema(&admin_pool, &schema).await;
12322    }
12323
12324    #[rstest]
12325    #[case::active_key(true)]
12326    #[case::deployment_identity(false)]
12327    #[tokio::test]
12328    async fn postgres_connect_rejects_missing_payload_identity_before_rpc(
12329        #[case] remove_active_key: bool,
12330    ) {
12331        let test_name = if remove_active_key {
12332            "payload_connect_missing_active_key"
12333        } else {
12334            "payload_connect_missing_deployment"
12335        };
12336        let Some((admin_pool, schema, mut client, state)) =
12337            execution_client_with_database(test_name, ready_rpc_state()).await
12338        else {
12339            return;
12340        };
12341        client.disconnect().await.unwrap();
12342        client.payload_keys = None;
12343        if remove_active_key {
12344            client.config.payload_key_env = None;
12345            client.config.payload_deployment_id = None;
12346        } else {
12347            client.config.payload_deployment_id = None;
12348        }
12349
12350        let error = client.connect().await.unwrap_err();
12351
12352        assert!(
12353            error.to_string().contains(if remove_active_key {
12354                "Postgres execution requires an active payload key and deployment identity"
12355            } else {
12356                "Payload deployment ID is required"
12357            }),
12358            "was: {error}"
12359        );
12360        assert!(client.signer.is_none());
12361        assert!(client.payload_keys.is_none());
12362        assert!(state.recorded_requests().is_empty());
12363
12364        drop(client);
12365        drop_execution_schema(&admin_pool, &schema).await;
12366    }
12367
12368    #[tokio::test]
12369    async fn postgres_connect_rejects_missing_envelope_key_before_rpc() {
12370        let Some((admin_pool, schema, mut client, state)) = execution_client_with_database(
12371            "payload_connect_missing_envelope_key",
12372            ready_rpc_state(),
12373        )
12374        .await
12375        else {
12376            return;
12377        };
12378        let database = client.cache.database.as_ref().unwrap().clone();
12379        persist_test_wrap_broadcast(&database, client.payload_keys.as_deref()).await;
12380        client.disconnect().await.unwrap();
12381        client.payload_keys = None;
12382        let keys = set_test_payload_key(&mut client, [0xb6; 32], &schema);
12383        sqlx::query(sqlx::AssertSqlSafe(format!(
12384            "UPDATE {schema}.execution_payload_state SET active_key_id = $1 \
12385             WHERE component = 'signed_transactions'"
12386        )))
12387        .bind(keys.active_key_id().as_slice())
12388        .execute(&admin_pool)
12389        .await
12390        .unwrap();
12391
12392        let error = client.connect().await.unwrap_err();
12393
12394        assert!(
12395            error
12396                .to_string()
12397                .contains("Stored execution payload requires unavailable key"),
12398            "was: {error}"
12399        );
12400        assert!(client.signer.is_none());
12401        assert!(client.payload_keys.is_none());
12402        assert!(state.recorded_requests().is_empty());
12403
12404        drop(client);
12405        drop_execution_schema(&admin_pool, &schema).await;
12406    }
12407
12408    #[tokio::test]
12409    async fn payload_action_lease_blocks_rewrap_transition_until_release() {
12410        let Some((admin_pool, schema, client, _)) = execution_client_with_unprotected_database(
12411            "payload_action_lease",
12412            execution_rpc_state(),
12413        )
12414        .await
12415        else {
12416            return;
12417        };
12418        let database = client.cache.database.as_ref().unwrap();
12419        let keys = payload_test_keys([0x71; 32], vec![], "action-lease");
12420        database
12421            .ensure_execution_payload_storage(&keys)
12422            .await
12423            .unwrap();
12424        let lease = database
12425            .acquire_execution_payload_lease(&keys)
12426            .await
12427            .unwrap();
12428        let rotated = payload_test_keys([0x72; 32], vec![[0x71; 32]], "action-lease");
12429        let mut operation = Box::pin(database.rewrap_execution_payload_storage(&rotated, 1));
12430
12431        assert!(
12432            tokio::time::timeout(Duration::from_millis(50), &mut operation)
12433                .await
12434                .is_err()
12435        );
12436        let state: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
12437            "SELECT operation FROM {schema}.execution_payload_state"
12438        )))
12439        .fetch_one(&admin_pool)
12440        .await
12441        .unwrap();
12442        assert_eq!(state, "ready");
12443
12444        drop(lease);
12445        tokio::time::timeout(Duration::from_secs(2), operation)
12446            .await
12447            .unwrap()
12448            .unwrap();
12449        let state: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
12450            "SELECT operation FROM {schema}.execution_payload_state"
12451        )))
12452        .fetch_one(&admin_pool)
12453        .await
12454        .unwrap();
12455        assert_eq!(state, "ready");
12456
12457        drop_execution_schema(&admin_pool, &schema).await;
12458    }
12459
12460    #[tokio::test]
12461    async fn payload_infrastructure_checks_are_scoped_to_the_execution_schema() {
12462        let Some((admin_pool, pg_config)) = connect_test_postgres("payload schema isolation").await
12463        else {
12464            return;
12465        };
12466        let schema_a = format!("payload_schema_a_{}", std::process::id());
12467        let schema_b = format!("payload_schema_b_{}", std::process::id());
12468        setup_execution_schema(&admin_pool, &schema_a).await;
12469        setup_execution_schema(&admin_pool, &schema_b).await;
12470        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
12471        let database_a =
12472            connect_test_database(options.clone().options([("search_path", schema_a.clone())]))
12473                .await
12474                .unwrap();
12475        let database_b =
12476            connect_test_database(options.options([("search_path", schema_b.clone())]))
12477                .await
12478                .unwrap();
12479        database_a
12480            .ensure_execution_transaction_schema()
12481            .await
12482            .unwrap();
12483        database_b
12484            .ensure_execution_transaction_schema()
12485            .await
12486            .unwrap();
12487        let keys_a = payload_test_keys([0x91; 32], vec![], "schema-a");
12488        let keys_b = payload_test_keys([0x92; 32], vec![], "schema-b");
12489
12490        database_a
12491            .ensure_execution_payload_storage(&keys_a)
12492            .await
12493            .unwrap();
12494        database_b
12495            .ensure_execution_payload_storage(&keys_b)
12496            .await
12497            .unwrap();
12498
12499        for statement in [
12500            format!(
12501                "DROP TRIGGER execution_transaction_payload_fence ON \
12502                 {schema_a}.execution_transaction_hash"
12503            ),
12504            format!(
12505                "ALTER TABLE {schema_a}.execution_transaction_hash \
12506                 DROP CONSTRAINT execution_transaction_payload_protected_check"
12507            ),
12508        ] {
12509            sqlx::query(sqlx::AssertSqlSafe(statement))
12510                .execute(&admin_pool)
12511                .await
12512                .unwrap();
12513        }
12514
12515        let error = database_a
12516            .ensure_execution_payload_storage(&keys_a)
12517            .await
12518            .unwrap_err();
12519
12520        assert!(
12521            error
12522                .to_string()
12523                .contains("without its write fence or constraint"),
12524            "was: {error}"
12525        );
12526
12527        drop_execution_schema(&admin_pool, &schema_a).await;
12528        drop_execution_schema(&admin_pool, &schema_b).await;
12529    }
12530
12531    #[tokio::test]
12532    async fn execution_fresh_schema_preserves_nullable_wallet_address() {
12533        let Some((admin_pool, _)) = connect_test_postgres("fresh execution schema").await else {
12534            return;
12535        };
12536        let schema = format!("execution_fresh_test_{}", std::process::id());
12537        let mut transaction = admin_pool.begin().await.unwrap();
12538        sqlx::query(sqlx::AssertSqlSafe(format!("CREATE SCHEMA {schema}")))
12539            .execute(&mut *transaction)
12540            .await
12541            .unwrap();
12542        sqlx::query(sqlx::AssertSqlSafe(format!(
12543            "SET LOCAL search_path TO {schema}"
12544        )))
12545        .execute(&mut *transaction)
12546        .await
12547        .unwrap();
12548        sqlx::query("CREATE TABLE chain (chain_id INTEGER PRIMARY KEY)")
12549            .execute(&mut *transaction)
12550            .await
12551            .unwrap();
12552        sqlx::query("INSERT INTO chain (chain_id) VALUES (42161)")
12553            .execute(&mut *transaction)
12554            .await
12555            .unwrap();
12556        sqlx::query(sqlx::AssertSqlSafe(execution_transaction_create_sql()))
12557            .execute(&mut *transaction)
12558            .await
12559            .unwrap();
12560        sqlx::query(
12561            "INSERT INTO execution_transaction \
12562             (chain_id, nonce, transaction_hash, purpose, status) \
12563             VALUES (42161, 7, '0xfresh-legacy', 'wrap', 'rejected')",
12564        )
12565        .execute(&mut *transaction)
12566        .await
12567        .unwrap();
12568
12569        let is_nullable: String = sqlx::query_scalar(
12570            "SELECT is_nullable FROM information_schema.columns \
12571             WHERE table_schema = $1 AND table_name = 'execution_transaction' \
12572             AND column_name = 'wallet_address'",
12573        )
12574        .bind(&schema)
12575        .fetch_one(&mut *transaction)
12576        .await
12577        .unwrap();
12578        let wallet_address: Option<String> = sqlx::query_scalar(
12579            "SELECT wallet_address FROM execution_transaction \
12580             WHERE transaction_hash = '0xfresh-legacy'",
12581        )
12582        .fetch_one(&mut *transaction)
12583        .await
12584        .unwrap();
12585
12586        assert_eq!(is_nullable, "YES");
12587        assert_eq!(wallet_address, None);
12588        transaction.rollback().await.unwrap();
12589    }
12590
12591    #[tokio::test]
12592    async fn execution_schema_migration_preserves_existing_rows() {
12593        let Some((admin_pool, pg_config)) =
12594            connect_test_postgres("execution schema migration").await
12595        else {
12596            return;
12597        };
12598        let schema = format!("execution_migration_test_{}", std::process::id());
12599        setup_execution_schema(&admin_pool, &schema).await;
12600        sqlx::query(sqlx::AssertSqlSafe(format!(
12601            "INSERT INTO {schema}.execution_transaction \
12602             (chain_id, nonce, transaction_hash, purpose, status) \
12603             VALUES (42161, 7, '0xlegacy', 'wrap', 'rejected')"
12604        )))
12605        .execute(&admin_pool)
12606        .await
12607        .unwrap();
12608
12609        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
12610        let db_options = db_options.options([("search_path", schema.clone())]);
12611        let database = connect_test_database(db_options).await.unwrap();
12612        database
12613            .ensure_execution_transaction_schema()
12614            .await
12615            .unwrap();
12616        let legacy = database
12617            .get_execution_transaction(42161, "0xlegacy")
12618            .await
12619            .unwrap()
12620            .unwrap();
12621        assert_eq!(legacy.purpose, "wrap");
12622        assert_eq!(legacy.status, "rejected");
12623        assert_eq!(legacy.client_order_id, None);
12624        assert_eq!(legacy.wallet_address, None);
12625        let is_nullable: String = sqlx::query_scalar(
12626            "SELECT is_nullable FROM information_schema.columns \
12627             WHERE table_schema = $1 AND table_name = 'execution_transaction' \
12628             AND column_name = 'wallet_address'",
12629        )
12630        .bind(&schema)
12631        .fetch_one(&admin_pool)
12632        .await
12633        .unwrap();
12634        let fence_error = database
12635            .add_execution_transaction(
12636                42161,
12637                WALLET,
12638                8,
12639                "0xswap",
12640                "swap",
12641                "pending",
12642                Some("O-SWAP-001"),
12643            )
12644            .await
12645            .err()
12646            .unwrap();
12647        assert!(
12648            fence_error
12649                .to_string()
12650                .contains("Legacy execution writer refused"),
12651            "was: {fence_error}"
12652        );
12653        assert_eq!(is_nullable, "YES");
12654
12655        drop_execution_schema(&admin_pool, &schema).await;
12656    }
12657
12658    #[tokio::test]
12659    async fn execution_schema_migration_drops_legacy_wallet_not_null() {
12660        let Some((admin_pool, pg_config)) =
12661            connect_test_postgres("legacy wallet address schema migration").await
12662        else {
12663            return;
12664        };
12665        let schema = format!("execution_wallet_migration_test_{}", std::process::id());
12666        setup_execution_schema(&admin_pool, &schema).await;
12667        sqlx::query(sqlx::AssertSqlSafe(format!(
12668            "ALTER TABLE {schema}.execution_transaction \
12669             ADD COLUMN wallet_address TEXT NOT NULL"
12670        )))
12671        .execute(&admin_pool)
12672        .await
12673        .unwrap();
12674        sqlx::query(sqlx::AssertSqlSafe(format!(
12675            "INSERT INTO {schema}.execution_transaction \
12676             (chain_id, wallet_address, nonce, transaction_hash, purpose, status) \
12677             VALUES (42161, '{WALLET}', 7, '0xlegacy-wallet', 'wrap', 'rejected')"
12678        )))
12679        .execute(&admin_pool)
12680        .await
12681        .unwrap();
12682
12683        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
12684        let db_options = db_options.options([("search_path", schema.clone())]);
12685        let database = connect_test_database(db_options).await.unwrap();
12686        database
12687            .ensure_execution_transaction_schema()
12688            .await
12689            .unwrap();
12690        let legacy = database
12691            .get_execution_transaction(42161, "0xlegacy-wallet")
12692            .await
12693            .unwrap()
12694            .unwrap();
12695        let is_nullable: String = sqlx::query_scalar(
12696            "SELECT is_nullable FROM information_schema.columns \
12697             WHERE table_schema = $1 AND table_name = 'execution_transaction' \
12698             AND column_name = 'wallet_address'",
12699        )
12700        .bind(&schema)
12701        .fetch_one(&admin_pool)
12702        .await
12703        .unwrap();
12704
12705        assert_eq!(legacy.wallet_address.as_deref(), Some(WALLET));
12706        assert_eq!(is_nullable, "YES");
12707        drop_execution_schema(&admin_pool, &schema).await;
12708    }
12709
12710    #[tokio::test]
12711    async fn execution_schema_migration_refuses_unresolved_legacy_rows() {
12712        let Some((admin_pool, pg_config)) =
12713            connect_test_postgres("unsafe execution schema migration").await
12714        else {
12715            return;
12716        };
12717        let schema = format!("execution_unsafe_migration_test_{}", std::process::id());
12718        setup_execution_schema(&admin_pool, &schema).await;
12719        sqlx::query(sqlx::AssertSqlSafe(format!(
12720            "INSERT INTO {schema}.execution_transaction \
12721             (chain_id, nonce, transaction_hash, purpose, status) \
12722             VALUES (42161, 7, '0xunresolved', 'wrap', 'pending')"
12723        )))
12724        .execute(&admin_pool)
12725        .await
12726        .unwrap();
12727        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
12728        let db_options = db_options.options([("search_path", schema.clone())]);
12729        let database = connect_test_database(db_options).await.unwrap();
12730
12731        let error = database
12732            .ensure_execution_transaction_schema()
12733            .await
12734            .unwrap_err();
12735        let legacy_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
12736            "SELECT COUNT(*) FROM {schema}.execution_transaction \
12737             WHERE transaction_hash = '0xunresolved' AND status = 'pending'"
12738        )))
12739        .fetch_one(&admin_pool)
12740        .await
12741        .unwrap();
12742        let v2_table: Option<String> = sqlx::query_scalar("SELECT to_regclass($1)::TEXT")
12743            .bind(format!("{schema}.execution_intent"))
12744            .fetch_one(&admin_pool)
12745            .await
12746            .unwrap();
12747
12748        assert!(
12749            error
12750                .to_string()
12751                .contains("Cannot safely migrate 1 unresolved execution schema version 1"),
12752            "was: {error}"
12753        );
12754        assert_eq!(legacy_count, 1);
12755        assert_eq!(v2_table, None);
12756
12757        drop_execution_schema(&admin_pool, &schema).await;
12758    }
12759
12760    #[rstest]
12761    fn receipt_max_polls_derives_from_timeout() {
12762        assert_eq!(receipt_max_polls(0), 1);
12763        assert_eq!(receipt_max_polls(1), 1);
12764        assert_eq!(receipt_max_polls(60), 60);
12765        assert_eq!(receipt_max_polls(u64::MAX), u32::MAX);
12766        assert_eq!(receipt_timeout(0), Duration::from_secs(1));
12767        assert_eq!(receipt_timeout(60), Duration::from_secs(60));
12768        assert_eq!(
12769            receipt_timeout(u64::MAX),
12770            Duration::from_secs(u64::from(u32::MAX))
12771        );
12772    }
12773
12774    #[rstest]
12775    fn submit_order_errors_when_order_not_cached() {
12776        let client = swap_client_with_cache(test_config("http://127.0.0.1:1".to_string())).0;
12777        let mut cmd = submit_order_cmd(&test_market_sell_order(test_pool().instrument_id));
12778        cmd.client_order_id = ClientOrderId::from("O-UNKNOWN");
12779
12780        let error = client.submit_order(cmd).unwrap_err();
12781
12782        assert!(!error.to_string().is_empty());
12783    }
12784
12785    #[tokio::test]
12786    async fn submit_order_denies_pool_fee_above_uint24() {
12787        let cache = Rc::new(RefCell::new(Cache::default()));
12788        let mut pool = test_pool();
12789        pool.fee = Some(16_777_216); // 2^24, above the uint24 calldata range
12790        cache.borrow_mut().add_pool(pool.clone()).unwrap();
12791        let order = test_market_sell_order(pool.instrument_id);
12792        cache
12793            .borrow_mut()
12794            .add_order(order.clone(), None, None, false)
12795            .unwrap();
12796        let core = ExecutionClientCore::new(
12797            TraderId::from("TRADER-001"),
12798            ClientId::from("BLOCKCHAIN-001"),
12799            *BLOCKCHAIN_VENUE,
12800            OmsType::Netting,
12801            AccountId::from("BLOCKCHAIN-001"),
12802            AccountType::Wallet,
12803            None,
12804            cache,
12805        );
12806        let mut client =
12807            BlockchainExecutionClient::new(core, test_config("http://127.0.0.1:1".to_string()))
12808                .unwrap();
12809        let mut receiver = start_with_events(&mut client);
12810
12811        client.submit_order(submit_order_cmd(&order)).unwrap();
12812
12813        let events = collect_order_events(&mut receiver);
12814        assert_eq!(events.len(), 1);
12815        let OrderEventAny::Denied(denied) = &events[0] else {
12816            panic!("expected OrderDenied, was {:?}", events[0]);
12817        };
12818        assert!(
12819            denied.reason.contains("exceeds uint24"),
12820            "was: {}",
12821            denied.reason
12822        );
12823    }
12824
12825    #[tokio::test]
12826    async fn submit_order_denies_uninitialized_profiler() {
12827        let cache = Rc::new(RefCell::new(Cache::default()));
12828        let pool = test_pool();
12829        cache.borrow_mut().add_pool(pool.clone()).unwrap();
12830        let order = test_market_sell_order(pool.instrument_id);
12831        cache
12832            .borrow_mut()
12833            .add_order(order.clone(), None, None, false)
12834            .unwrap();
12835        cache
12836            .borrow_mut()
12837            .add_pool_profiler(PoolProfiler::new(Arc::new(pool)))
12838            .unwrap();
12839        let core = ExecutionClientCore::new(
12840            TraderId::from("TRADER-001"),
12841            ClientId::from("BLOCKCHAIN-001"),
12842            *BLOCKCHAIN_VENUE,
12843            OmsType::Netting,
12844            AccountId::from("BLOCKCHAIN-001"),
12845            AccountType::Wallet,
12846            None,
12847            cache,
12848        );
12849        let mut client =
12850            BlockchainExecutionClient::new(core, test_config("http://127.0.0.1:1".to_string()))
12851                .unwrap();
12852        let mut receiver = start_with_events(&mut client);
12853
12854        client.submit_order(submit_order_cmd(&order)).unwrap();
12855
12856        let events = collect_order_events(&mut receiver);
12857        assert_eq!(events.len(), 1);
12858        let OrderEventAny::Denied(denied) = &events[0] else {
12859            panic!("expected OrderDenied, was {:?}", events[0]);
12860        };
12861        assert!(
12862            denied.reason.contains("is not initialized"),
12863            "was: {}",
12864            denied.reason
12865        );
12866    }
12867
12868    #[tokio::test]
12869    async fn submit_order_denies_when_quote_cannot_fill_order() {
12870        let cache = Rc::new(RefCell::new(Cache::default()));
12871        let pool = test_pool();
12872        cache.borrow_mut().add_pool(pool.clone()).unwrap();
12873        let order = test_market_sell_order(pool.instrument_id);
12874        cache
12875            .borrow_mut()
12876            .add_order(order.clone(), None, None, false)
12877            .unwrap();
12878        // A narrow one-unit-of-liquidity position cannot fill the order
12879        cache
12880            .borrow_mut()
12881            .add_pool_profiler(test_profiler_with_range(
12882                &pool,
12883                FIXTURE_BLOCK,
12884                FIXTURE_BLOCK_HASH,
12885                U160::from(1u128 << 96),
12886                -10,
12887                10,
12888                1,
12889            ))
12890            .unwrap();
12891        let core = ExecutionClientCore::new(
12892            TraderId::from("TRADER-001"),
12893            ClientId::from("BLOCKCHAIN-001"),
12894            *BLOCKCHAIN_VENUE,
12895            OmsType::Netting,
12896            AccountId::from("BLOCKCHAIN-001"),
12897            AccountType::Wallet,
12898            None,
12899            cache,
12900        );
12901        let mut client =
12902            BlockchainExecutionClient::new(core, test_config("http://127.0.0.1:1".to_string()))
12903                .unwrap();
12904        let mut receiver = start_with_events(&mut client);
12905
12906        client.submit_order(submit_order_cmd(&order)).unwrap();
12907
12908        let events = collect_order_events(&mut receiver);
12909        assert_eq!(events.len(), 1);
12910        let OrderEventAny::Denied(denied) = &events[0] else {
12911            panic!("expected OrderDenied, was {:?}", events[0]);
12912        };
12913        assert!(
12914            denied.reason.contains("cannot fill the order"),
12915            "was: {}",
12916            denied.reason
12917        );
12918    }
12919
12920    #[tokio::test]
12921    async fn submit_order_applies_slippage_param_override_at_ceiling() {
12922        let Some((admin_pool, schema, mut client, state, _)) = swap_client_with_database(
12923            "execution_submit_slippage_override_test",
12924            swap_rpc_state_with_min_amount_out(expected_min_amount_out(200)).await,
12925        )
12926        .await
12927        else {
12928            return;
12929        };
12930        let order = test_market_sell_order(test_pool().instrument_id);
12931        let mut cmd = submit_order_cmd(&order);
12932        // Exactly at the configured ceiling (200 bps): accepted, not denied
12933        cmd.params = Some(serde_json::from_str(r#"{"slippage_bps": 200}"#).unwrap());
12934        let mut receiver = start_with_events(&mut client);
12935        let expected_min_out = expected_min_amount_out(200);
12936
12937        client.submit_order(cmd).unwrap();
12938        await_pending_tasks(&client).await;
12939
12940        let events = collect_order_events(&mut receiver);
12941        assert_swap_submitted_and_filled(&events);
12942
12943        let (_, expected_raw) = expected_swap_tx(expected_min_out).await;
12944        let broadcasts: Vec<_> = state
12945            .recorded_requests()
12946            .into_iter()
12947            .filter(|request| request["method"] == "eth_sendRawTransaction")
12948            .collect();
12949        assert_eq!(broadcasts.len(), 1);
12950        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
12951
12952        drop_execution_schema(&admin_pool, &schema).await;
12953    }
12954
12955    #[tokio::test]
12956    async fn submit_order_accepts_quote_fresh_at_max_age_boundary() {
12957        let min_amount_out = expected_min_amount_out(50);
12958        let (tx_hash, _) = expected_swap_tx(min_amount_out).await;
12959        let head = finalized_swap_block(tx_hash, min_amount_out);
12960        let state = swap_rpc_state()
12961            .await
12962            .with_response("eth_getBlockByNumber", &head)
12963            .with_parameter_response("eth_getBlockByNumber", FIXTURE_BLOCK_PARAM, BLOCK_BY_NUMBER);
12964        let Some((admin_pool, schema, mut client, state, cache)) =
12965            swap_client_with_database_config(
12966                "execution_submit_fresh_boundary_test",
12967                state,
12968                |http_rpc_url| {
12969                    let mut config = test_config(http_rpc_url);
12970                    config.max_quote_age_blocks = Some(1);
12971                    config
12972                },
12973            )
12974            .await
12975        else {
12976            return;
12977        };
12978        let pool = test_pool();
12979        cache
12980            .borrow_mut()
12981            .add_pool_profiler(test_profiler_at_block(
12982                &pool,
12983                FIXTURE_BLOCK,
12984                FIXTURE_BLOCK_HASH,
12985            ))
12986            .unwrap();
12987        let order = test_market_sell_order(pool.instrument_id);
12988        let mut receiver = start_with_events(&mut client);
12989
12990        client.submit_order(submit_order_cmd(&order)).unwrap();
12991        await_pending_tasks(&client).await;
12992
12993        let events = collect_order_events(&mut receiver);
12994        assert_eq!(events.len(), 1, "was: {events:?}");
12995        assert!(matches!(&events[0], OrderEventAny::Submitted(_)));
12996        assert_eq!(
12997            state
12998                .recorded_requests()
12999                .iter()
13000                .filter(|request| request["method"] == "eth_sendRawTransaction")
13001                .count(),
13002            1
13003        );
13004
13005        drop_execution_schema(&admin_pool, &schema).await;
13006    }
13007
13008    #[tokio::test]
13009    async fn submit_order_sells_base_token_from_token1_position() {
13010        // A pool with the token order reversed relative to the convention: USDC is token0
13011        // and WETH is token1, so the base token (WETH, by token priority) sits in the
13012        // token1 position and the swap quotes zero_for_one = false
13013        let chain = Arc::new(chains::ARBITRUM.clone());
13014        let dex = Arc::clone(&UNISWAP_V3.dex);
13015        let usdc = Token::new(
13016            Arc::clone(&chain),
13017            address!("af88d065e77c8cC2239327C5EDb3A432268e5831"),
13018            "USD Coin".to_string(),
13019            "USDC".to_string(),
13020            6,
13021        );
13022        let weth = Token::new(
13023            Arc::clone(&chain),
13024            address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
13025            "Wrapped Ether".to_string(),
13026            "WETH".to_string(),
13027            18,
13028        );
13029        let pool = Pool::new(
13030            chain,
13031            dex,
13032            address!("C6962004f452bE9203591991D15f6b388e09E8D0"),
13033            PoolIdentifier::from_address(address!("C6962004f452bE9203591991D15f6b388e09E8D0")),
13034            55_000_000,
13035            usdc,
13036            weth,
13037            Some(500),
13038            Some(10),
13039            UnixNanos::default(),
13040        );
13041
13042        let cache = Rc::new(RefCell::new(Cache::default()));
13043        cache.borrow_mut().add_pool(pool.clone()).unwrap();
13044        let order = test_market_sell_order(pool.instrument_id);
13045        cache
13046            .borrow_mut()
13047            .add_order(order.clone(), None, None, false)
13048            .unwrap();
13049        // Asymmetric price so the zero_for_one direction changes the quote
13050        cache
13051            .borrow_mut()
13052            .add_pool_profiler(test_profiler_with_state(
13053                &pool,
13054                FIXTURE_BLOCK,
13055                U160::from(2u128 << 96),
13056                TEST_LIQUIDITY,
13057            ))
13058            .unwrap();
13059
13060        let (admin_pool, pg_config) = match connect_test_postgres("orientation").await {
13061            Some(setup) => setup,
13062            None => return,
13063        };
13064        let schema = format!("execution_submit_orientation_test_{}", std::process::id());
13065        setup_execution_schema(&admin_pool, &schema).await;
13066        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
13067        let db_options = db_options.options([("search_path", schema.clone())]);
13068        let database = connect_test_database(db_options).await.unwrap();
13069
13070        let state = swap_rpc_state()
13071            .await
13072            .with_call_response(POOL_TOKEN0_SELECTOR, CALL_USDC)
13073            .with_call_response(POOL_TOKEN1_SELECTOR, CALL_WETH)
13074            .with_response("eth_getTransactionReceipt", RECEIPT_NULL);
13075        let addr = start_mock_rpc_server(state.clone()).await;
13076        let core = ExecutionClientCore::new(
13077            TraderId::from("TRADER-001"),
13078            ClientId::from("BLOCKCHAIN-001"),
13079            *BLOCKCHAIN_VENUE,
13080            OmsType::Netting,
13081            AccountId::from("BLOCKCHAIN-001"),
13082            AccountType::Wallet,
13083            None,
13084            cache,
13085        );
13086        let mut config = test_config(format!("http://{addr}"));
13087        let result = |response: &str| {
13088            serde_json::from_str::<serde_json::Value>(response).unwrap()["result"]
13089                .as_str()
13090                .unwrap()
13091                .to_string()
13092        };
13093        {
13094            let verification = config.verification.as_mut().unwrap();
13095            let pool_identity = &mut verification.deployment_manifest.pools[0];
13096            pool_identity.token0 = USDC.to_string();
13097            pool_identity.token1 = WETH.to_string();
13098            let pool_contract = verification
13099                .deployment_manifest
13100                .contracts
13101                .iter_mut()
13102                .find(|contract| contract.role == BlockchainContractRole::Pool)
13103                .unwrap();
13104
13105            for probe in &mut pool_contract.probes {
13106                if probe.call_data.starts_with(POOL_TOKEN0_SELECTOR) {
13107                    probe.expected_output = result(CALL_USDC);
13108                } else if probe.call_data.starts_with(POOL_TOKEN1_SELECTOR) {
13109                    probe.expected_output = result(CALL_WETH);
13110                }
13111            }
13112        }
13113        refresh_test_manifest_digest(&mut config);
13114        let mut client = BlockchainExecutionClient::new(core, config).unwrap();
13115        client.cache.database = Some(database);
13116        client
13117            .cache
13118            .ensure_execution_transaction_schema()
13119            .await
13120            .unwrap();
13121        protect_test_storage(&mut client, &schema).await;
13122        initialize_test_verification_ledger(&client).await;
13123        client.signer = Some(Arc::new(
13124            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
13125        ));
13126        client.core.set_connected();
13127        let mut receiver = start_with_events(&mut client);
13128
13129        let profiler = test_profiler_with_state(
13130            &pool,
13131            FIXTURE_BLOCK,
13132            U160::from(2u128 << 96),
13133            TEST_LIQUIDITY,
13134        );
13135        let quote = profiler
13136            .swap_exact_in(U256::from(1_000_000_000_000_000u64), false, None)
13137            .unwrap();
13138        let quoted = exact_output_amount(&quote, false).unwrap();
13139        let expected_min_out = derive_min_amount_out(quoted, 50).unwrap();
13140        let wrong_direction_quote = profiler
13141            .swap_exact_in(U256::from(1_000_000_000_000_000u64), true, None)
13142            .unwrap();
13143        let wrong_direction_out = exact_output_amount(&wrong_direction_quote, true).unwrap();
13144        assert_ne!(
13145            quoted, wrong_direction_out,
13146            "the asymmetric price must make the quote direction observable"
13147        );
13148        assert_ne!(
13149            expected_min_out,
13150            expected_min_amount_out(50),
13151            "the profiler quote must remain distinct from the independent quote fixture"
13152        );
13153
13154        client.submit_order(submit_order_cmd(&order)).unwrap();
13155        await_pending_tasks(&client).await;
13156
13157        let events = collect_order_events(&mut receiver);
13158        assert_eq!(events.len(), 1);
13159        assert!(
13160            matches!(&events[0], OrderEventAny::Submitted(_)),
13161            "was: {:?}",
13162            events[0]
13163        );
13164
13165        let (_, expected_raw) = expected_swap_tx(expected_min_amount_out(50)).await;
13166        let broadcasts: Vec<_> = state
13167            .recorded_requests()
13168            .into_iter()
13169            .filter(|request| request["method"] == "eth_sendRawTransaction")
13170            .collect();
13171        assert_eq!(broadcasts.len(), 1);
13172        assert_eq!(broadcasts[0]["params"][0].as_str().unwrap(), expected_raw);
13173
13174        drop_execution_schema(&admin_pool, &schema).await;
13175    }
13176
13177    #[tokio::test]
13178    async fn submit_order_denies_on_chain_mismatch() {
13179        let state = swap_rpc_state()
13180            .await
13181            .with_response("eth_chainId", CHAIN_ID_ETHEREUM);
13182        let Some((admin_pool, schema, mut client, state, _)) =
13183            swap_client_with_database("execution_submit_chain_mismatch_test", state).await
13184        else {
13185            return;
13186        };
13187        let order = test_market_sell_order(test_pool().instrument_id);
13188        let mut receiver = start_with_events(&mut client);
13189
13190        client.submit_order(submit_order_cmd(&order)).unwrap();
13191        await_pending_tasks(&client).await;
13192
13193        let events = collect_order_events(&mut receiver);
13194        assert_eq!(events.len(), 1);
13195        let OrderEventAny::Denied(denied) = &events[0] else {
13196            panic!("expected OrderDenied, was {:?}", events[0]);
13197        };
13198        assert!(
13199            denied
13200                .reason
13201                .contains("pre-sign chain ID verification disagreed"),
13202            "was: {}",
13203            denied.reason
13204        );
13205        let requests = state.recorded_requests();
13206        assert!(
13207            requests
13208                .iter()
13209                .all(|request| request["method"] != "eth_sendRawTransaction"),
13210            "no broadcast may follow a chain mismatch"
13211        );
13212        assert!(client.in_flight.lock().is_none());
13213
13214        drop_execution_schema(&admin_pool, &schema).await;
13215    }
13216
13217    #[tokio::test]
13218    async fn submit_order_finality_timeout_marks_dropped_and_keeps_ownership() {
13219        let receipt_release = Arc::new(tokio::sync::Semaphore::new(0));
13220        let state = swap_rpc_state()
13221            .await
13222            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
13223            .with_response_release("eth_getTransactionReceipt", Arc::clone(&receipt_release));
13224        let Some((admin_pool, schema, mut client, state, _)) =
13225            swap_client_with_database("execution_submit_inclusion_timeout_test", state).await
13226        else {
13227            return;
13228        };
13229        client.transaction_limits.receipt_timeout_secs = 1;
13230        let order = test_market_sell_order(test_pool().instrument_id);
13231        let mut receiver = start_with_events(&mut client);
13232
13233        client.submit_order(submit_order_cmd(&order)).unwrap();
13234        await_recorded_requests(&state, "eth_getTransactionReceipt", 3).await;
13235        tokio::time::timeout(Duration::from_secs(3), await_pending_tasks(&client))
13236            .await
13237            .unwrap();
13238        receipt_release.add_permits(3);
13239
13240        // Broadcast acceptance was observed, so the order is submitted; the unobserved
13241        // inclusion justifies no further event
13242        let events = collect_order_events(&mut receiver);
13243        assert_eq!(events.len(), 1);
13244        assert!(
13245            matches!(&events[0], OrderEventAny::Submitted(_)),
13246            "was: {:?}",
13247            events[0]
13248        );
13249
13250        let record = client
13251            .cache
13252            .get_execution_transaction(
13253                42161,
13254                &expected_swap_tx(expected_min_amount_out(50))
13255                    .await
13256                    .0
13257                    .to_string(),
13258            )
13259            .await
13260            .unwrap()
13261            .unwrap();
13262        assert_eq!(record.status, "dropped");
13263        assert!(client.in_flight.lock().is_some());
13264
13265        drop_execution_schema(&admin_pool, &schema).await;
13266    }
13267
13268    #[tokio::test]
13269    async fn included_receipt_finality_timeout_marks_dropped_and_keeps_ownership() {
13270        let state = execution_rpc_state()
13271            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
13272            .with_response("eth_estimateGas", ESTIMATE_GAS)
13273            .with_response("eth_call", CALL_BALANCE)
13274            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS)
13275            .with_parameter_response("eth_getBlockByNumber", "finalized", BLOCK_BY_NUMBER)
13276            .with_send_raw_transaction_echo();
13277        let Some((admin_pool, schema, mut client, _)) =
13278            execution_client_with_database("execution_included_timeout_test", state).await
13279        else {
13280            return;
13281        };
13282        client.transaction_limits.receipt_timeout_secs = 1;
13283
13284        let error = client
13285            .wrap(U256::from(1_000_000_000_000_000_u64))
13286            .await
13287            .unwrap_err();
13288        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
13289            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
13290        )))
13291        .fetch_all(&admin_pool)
13292        .await
13293        .unwrap();
13294
13295        assert!(
13296            error.to_string().contains("Timed out awaiting finality"),
13297            "was: {error}"
13298        );
13299        assert_eq!(transitions, ["prepared", "signed", "broadcast", "dropped"]);
13300        assert!(client.in_flight.lock().is_some());
13301
13302        drop_execution_schema(&admin_pool, &schema).await;
13303    }
13304
13305    #[tokio::test]
13306    async fn submit_order_single_in_flight_rejects_concurrent_swap() {
13307        let broadcast_release = Arc::new(tokio::sync::Semaphore::new(0));
13308        let state = swap_rpc_state()
13309            .await
13310            .with_response_release("eth_sendRawTransaction", Arc::clone(&broadcast_release));
13311        let Some((admin_pool, schema, mut client, state, cache)) =
13312            swap_client_with_database("execution_submit_concurrent_test", state).await
13313        else {
13314            return;
13315        };
13316        let pool = test_pool();
13317        let first = test_market_sell_order(pool.instrument_id);
13318        let second = OrderTestBuilder::new(OrderType::Market)
13319            .trader_id(TraderId::from("TRADER-001"))
13320            .strategy_id(StrategyId::from("S-001"))
13321            .instrument_id(pool.instrument_id)
13322            .client_order_id(ClientOrderId::from("O-SWAP-002"))
13323            .side(OrderSide::Sell)
13324            .quantity(Quantity::from("0.001"))
13325            .build();
13326        cache
13327            .borrow_mut()
13328            .add_order(second.clone(), None, None, false)
13329            .unwrap();
13330        let mut receiver = start_with_events(&mut client);
13331
13332        client.submit_order(submit_order_cmd(&first)).unwrap();
13333        await_recorded_requests(&state, "eth_sendRawTransaction", 1).await;
13334        client.submit_order(submit_order_cmd(&second)).unwrap();
13335        let event = tokio::time::timeout(TEST_TIMEOUT, receiver.recv())
13336            .await
13337            .unwrap()
13338            .unwrap();
13339        let ExecutionEvent::Order(OrderEventAny::Denied(denied)) = event else {
13340            panic!("expected OrderDenied, was {event:?}");
13341        };
13342        assert_eq!(denied.client_order_id, second.client_order_id());
13343        assert!(
13344            denied
13345                .reason
13346                .contains("at most one transaction can be in flight"),
13347            "was: {}",
13348            denied.reason
13349        );
13350        broadcast_release.add_permits(1);
13351        await_pending_tasks(&client).await;
13352
13353        let events = collect_order_events(&mut receiver);
13354        assert_swap_submitted_and_filled(&events);
13355
13356        let broadcasts = state
13357            .recorded_requests()
13358            .into_iter()
13359            .filter(|request| request["method"] == "eth_sendRawTransaction")
13360            .count();
13361        assert_eq!(broadcasts, 1);
13362        let row_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
13363            "SELECT COUNT(*) FROM {schema}.execution_intent"
13364        )))
13365        .fetch_one(&admin_pool)
13366        .await
13367        .unwrap();
13368        assert_eq!(row_count, 1);
13369        assert!(client.in_flight.lock().is_none());
13370
13371        drop_execution_schema(&admin_pool, &schema).await;
13372    }
13373
13374    #[tokio::test]
13375    async fn preflight_ready_when_all_checks_pass() {
13376        let (client, state) = client_with_mock_rpc(ready_rpc_state()).await;
13377        let pool = test_pool();
13378
13379        let report = client.preflight(&pool.instrument_id).await.unwrap();
13380
13381        assert!(report.ready, "issues: {:?}", report.issues);
13382        assert!(report.issues.is_empty());
13383        assert_eq!(report.expected_chain_id, 42161);
13384        assert_eq!(report.actual_chain_id, 42161);
13385        assert!(report.chain_id_matches);
13386        assert_eq!(
13387            report.pool.address,
13388            address!("C6962004f452bE9203591991D15f6b388e09E8D0")
13389        );
13390        assert!(report.pool.has_deployed_code);
13391        assert_eq!(report.pool.fee, Some(500));
13392        assert_eq!(
13393            report.pool.base_token,
13394            address!("82aF49447D8a07e3bd95BD0d56f35241523fBab1")
13395        );
13396        assert_eq!(
13397            report.pool.quote_token,
13398            address!("af88d065e77c8cC2239327C5EDb3A432268e5831")
13399        );
13400        assert_eq!(report.routers.len(), 1);
13401        assert!(report.routers[0].has_deployed_code);
13402        assert_eq!(report.tokens.len(), 2);
13403        assert_eq!(
13404            report.tokens[0].wallet_balance,
13405            U256::from(500_000_000_000_000_000u64)
13406        );
13407        assert_eq!(
13408            report.tokens[0].router_allowances,
13409            vec![(
13410                address!("E592427A0AEce92De3Edee1F18E0157C05861564"),
13411                U256::from(1_000_000_000_000_000_000u64)
13412            )]
13413        );
13414        assert_eq!(
13415            report.native_balance_wei,
13416            U256::from(1_000_000_000_000_000_000u64)
13417        );
13418        assert_eq!(report.base_fee_per_gas_wei, 100_000_000);
13419        assert_eq!(report.max_priority_fee_per_gas_wei, 10_000_000);
13420        assert_eq!(report.derived_max_fee_per_gas_wei, 130_000_000);
13421        assert!(report.fee_within_ceiling);
13422
13423        let requests = state.recorded_requests();
13424        for method in ["eth_getCode", "eth_call", "eth_getBalance"] {
13425            let matching: Vec<_> = requests
13426                .iter()
13427                .filter(|request| request["method"] == method)
13428                .collect();
13429            assert!(!matching.is_empty(), "method {method}");
13430            assert!(
13431                matching
13432                    .iter()
13433                    .all(|request| request["params"][1] == "latest"),
13434                "method {method}: {matching:?}"
13435            );
13436        }
13437    }
13438
13439    #[tokio::test]
13440    async fn preflight_not_ready_without_pool_fee() {
13441        let addr = start_mock_rpc_server(ready_rpc_state()).await;
13442        let mut pool = test_pool();
13443        pool.fee = None;
13444        let client = test_client_from_config(test_config(format!("http://{addr}")), pool.clone());
13445
13446        let report = client.preflight(&pool.instrument_id).await.unwrap();
13447
13448        assert!(!report.ready);
13449        assert_eq!(report.pool.fee, None);
13450        assert_eq!(report.issues, vec!["Pool fee tier is missing"]);
13451    }
13452
13453    #[tokio::test]
13454    async fn preflight_not_ready_on_wrong_chain() {
13455        let state = ready_rpc_state().with_response("eth_chainId", CHAIN_ID_ETHEREUM);
13456        let (client, _) = client_with_mock_rpc(state).await;
13457        let pool = test_pool();
13458
13459        let report = client.preflight(&pool.instrument_id).await.unwrap();
13460
13461        assert!(!report.ready);
13462        assert!(!report.chain_id_matches);
13463        assert!(
13464            report
13465                .issues
13466                .iter()
13467                .any(|issue| issue.contains("Chain ID mismatch"))
13468        );
13469    }
13470
13471    #[tokio::test]
13472    async fn preflight_not_ready_without_deployed_code() {
13473        let state = ready_rpc_state().with_response("eth_getCode", GET_CODE_EMPTY);
13474        let (client, _) = client_with_mock_rpc(state).await;
13475        let pool = test_pool();
13476
13477        let report = client.preflight(&pool.instrument_id).await.unwrap();
13478
13479        assert!(!report.ready);
13480        assert!(!report.pool.has_deployed_code);
13481        assert!(!report.routers[0].has_deployed_code);
13482        assert!(report.tokens.iter().all(|t| !t.has_deployed_code));
13483        assert!(
13484            report
13485                .issues
13486                .iter()
13487                .any(|issue| issue.contains("No deployed bytecode at router address"))
13488        );
13489    }
13490
13491    #[tokio::test]
13492    async fn preflight_not_ready_with_zero_balances_and_allowance() {
13493        let state = ready_rpc_state()
13494            .with_response("eth_getBalance", GET_BALANCE_ZERO)
13495            .with_call_response(BALANCE_OF_SELECTOR, CALL_ZERO)
13496            .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO);
13497        let (client, _) = client_with_mock_rpc(state).await;
13498        let pool = test_pool();
13499
13500        let report = client.preflight(&pool.instrument_id).await.unwrap();
13501
13502        assert!(!report.ready);
13503        assert!(
13504            report
13505                .issues
13506                .iter()
13507                .any(|issue| issue.contains("Native currency balance is zero"))
13508        );
13509        assert!(
13510            report
13511                .issues
13512                .iter()
13513                .any(|issue| issue.contains("balance is zero"))
13514        );
13515        assert!(
13516            report
13517                .issues
13518                .iter()
13519                .any(|issue| issue.contains("No router allowance"))
13520        );
13521    }
13522
13523    #[tokio::test]
13524    async fn preflight_not_ready_when_fees_exceed_ceiling() {
13525        let addr = start_mock_rpc_server(ready_rpc_state()).await;
13526        let mut config = test_config(format!("http://{addr}"));
13527        config.max_fee_per_gas_wei = 1;
13528        let pool = test_pool();
13529        let client = test_client_from_config(config, pool.clone());
13530
13531        let report = client.preflight(&pool.instrument_id).await.unwrap();
13532
13533        assert!(!report.ready);
13534        assert!(!report.fee_within_ceiling);
13535        assert_eq!(report.derived_max_fee_per_gas_wei, 130_000_000);
13536        assert!(
13537            report
13538                .issues
13539                .iter()
13540                .any(|issue| issue.contains("exceeds ceiling"))
13541        );
13542    }
13543
13544    #[rstest]
13545    fn resolve_pool_rejects_unknown_pool() {
13546        let client = test_client("http://127.0.0.1:1".to_string());
13547        let unknown: InstrumentId = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45.Arbitrum:UniswapV3"
13548            .parse()
13549            .unwrap();
13550
13551        let error = client.resolve_pool(&unknown).unwrap_err();
13552
13553        assert!(error.to_string().contains("Unknown pool"), "was: {error}");
13554    }
13555
13556    #[rstest]
13557    fn resolve_pool_rejects_mismatched_chain() {
13558        let client = test_client("http://127.0.0.1:1".to_string());
13559        let ethereum_pool: InstrumentId =
13560            "0xC6962004f452bE9203591991D15f6b388e09E8D0.Ethereum:UniswapV3"
13561                .parse()
13562                .unwrap();
13563
13564        let error = client.resolve_pool(&ethereum_pool).unwrap_err();
13565
13566        assert!(
13567            error
13568                .to_string()
13569                .contains("does not match the client chain"),
13570            "was: {error}"
13571        );
13572    }
13573
13574    #[rstest]
13575    fn resolve_pool_rejects_unsupported_dex() {
13576        let client = test_client("http://127.0.0.1:1".to_string());
13577        let v4_pool: InstrumentId = "0xC6962004f452bE9203591991D15f6b388e09E8D0.Arbitrum:UniswapV4"
13578            .parse()
13579            .unwrap();
13580
13581        let error = client.resolve_pool(&v4_pool).unwrap_err();
13582
13583        assert!(
13584            error.to_string().contains("only UniswapV3 is supported"),
13585            "was: {error}"
13586        );
13587    }
13588
13589    #[rstest]
13590    fn resolve_pool_rejects_pool_id_identifier() {
13591        let client = test_client("http://127.0.0.1:1".to_string());
13592        let pool_id: InstrumentId =
13593            "0x0000000000000000000000000000000000000000000000000000000000000000.Arbitrum:UniswapV3"
13594                .parse()
13595                .unwrap();
13596
13597        let error = client.resolve_pool(&pool_id).unwrap_err();
13598
13599        assert!(
13600            error
13601                .to_string()
13602                .contains("only address identifiers are supported"),
13603            "was: {error}"
13604        );
13605    }
13606
13607    #[rstest]
13608    fn resolve_pool_rejects_ambiguous_token_priority() {
13609        let chain = Arc::new(chains::ARBITRUM.clone());
13610        let dex = Arc::clone(&UNISWAP_V3.dex);
13611        let token_a = Token::new(
13612            Arc::clone(&chain),
13613            address!("1111111111111111111111111111111111111111"),
13614            "Token A".to_string(),
13615            "TOKA".to_string(),
13616            18,
13617        );
13618        let token_b = Token::new(
13619            Arc::clone(&chain),
13620            address!("2222222222222222222222222222222222222222"),
13621            "Token B".to_string(),
13622            "TOKB".to_string(),
13623            18,
13624        );
13625        let pool = Pool::new(
13626            chain,
13627            dex,
13628            address!("3333333333333333333333333333333333333333"),
13629            PoolIdentifier::from_address(address!("3333333333333333333333333333333333333333")),
13630            55_000_000,
13631            token_a,
13632            token_b,
13633            Some(500),
13634            Some(10),
13635            UnixNanos::default(),
13636        );
13637        let client =
13638            test_client_from_config(test_config("http://127.0.0.1:1".to_string()), pool.clone());
13639
13640        let error = client.resolve_pool(&pool.instrument_id).unwrap_err();
13641
13642        assert!(error.to_string().contains("ambiguous"), "was: {error}");
13643    }
13644
13645    #[rstest]
13646    fn new_parses_pair_specific_quote_spend_limits_with_distinct_precisions() {
13647        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13648        config.quote_spend_limits = Some(vec![
13649            quote_spend_limit(WETH, USDC, 18, &U256::MAX.to_string()),
13650            quote_spend_limit(USDC, WETH, 6, "1000000000"),
13651        ]);
13652
13653        let client = test_client_from_config(config, test_pool());
13654        let sell_ceiling = client
13655            .transaction_limits
13656            .quote_spend_limits
13657            .get(&(WETH_ADDRESS, USDC_ADDRESS))
13658            .unwrap();
13659        let buy_ceiling = client
13660            .transaction_limits
13661            .quote_spend_limits
13662            .get(&(USDC_ADDRESS, WETH_ADDRESS))
13663            .unwrap();
13664
13665        assert_eq!(sell_ceiling.spend_token, WETH_ADDRESS);
13666        assert_eq!(sell_ceiling.spend_token_decimals, 18);
13667        assert_eq!(sell_ceiling.max_amount, U256::MAX);
13668        assert_eq!(buy_ceiling.spend_token, USDC_ADDRESS);
13669        assert_eq!(buy_ceiling.spend_token_decimals, 6);
13670        assert_eq!(buy_ceiling.max_amount, U256::from(1_000_000_000u64));
13671    }
13672
13673    #[rstest]
13674    fn new_rejects_quote_spend_limit_token_pair_mismatch() {
13675        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13676        config.quote_spend_limits.as_mut().unwrap()[0].spend_token = WETH.to_string();
13677
13678        let error = test_client_result(config, test_pool()).unwrap_err();
13679
13680        assert!(
13681            error
13682                .to_string()
13683                .contains("`spend_token` must match `token_in`"),
13684            "was: {error}"
13685        );
13686    }
13687
13688    #[rstest]
13689    fn new_rejects_quote_spend_limit_pair_outside_allowlist() {
13690        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13691        config.quote_spend_limits = Some(vec![quote_spend_limit(
13692            USDC,
13693            "0x1111111111111111111111111111111111111111",
13694            6,
13695            "1000000000",
13696        )]);
13697
13698        let error = test_client_result(config, test_pool()).unwrap_err();
13699
13700        assert!(
13701            error
13702                .to_string()
13703                .contains("is not in the `allowed_token_pairs` allowlist"),
13704            "was: {error}"
13705        );
13706    }
13707
13708    #[rstest]
13709    fn new_rejects_duplicate_quote_spend_pairs() {
13710        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13711        config.quote_spend_limits = Some(vec![
13712            quote_spend_limit(USDC, WETH, 6, "1000000000"),
13713            quote_spend_limit(USDC, WETH, 6, "2000000000"),
13714        ]);
13715
13716        let error = test_client_result(config, test_pool()).unwrap_err();
13717
13718        assert!(
13719            error
13720                .to_string()
13721                .contains("Duplicate quote spend limit for token pair"),
13722            "was: {error}"
13723        );
13724    }
13725
13726    #[rstest]
13727    #[case::empty("")]
13728    #[case::signed("-1")]
13729    #[case::fractional("1.5")]
13730    #[case::hexadecimal("0x10")]
13731    #[case::overflow(
13732        "115792089237316195423570985008687907853269984665640564039457584007913129639936"
13733    )]
13734    fn new_rejects_invalid_quote_spend_max_amount(#[case] max_amount: &str) {
13735        let mut config = buy_test_config("http://127.0.0.1:1".to_string());
13736        config.quote_spend_limits.as_mut().unwrap()[0].max_amount = max_amount.to_string();
13737
13738        let error = test_client_result(config, test_pool()).unwrap_err();
13739
13740        assert!(
13741            error.to_string().contains("Quote spend limit `max_amount`"),
13742            "was: {error}"
13743        );
13744    }
13745
13746    #[rstest]
13747    #[case::allowed_token_pairs("allowed_token_pairs")]
13748    #[case::slippage_bps("slippage_bps")]
13749    #[case::max_slippage_bps("max_slippage_bps")]
13750    #[case::max_order_amount("max_order_amount")]
13751    #[case::deadline_seconds("deadline_seconds")]
13752    #[case::max_quote_age_blocks("max_quote_age_blocks")]
13753    #[case::receipt_timeout_secs("receipt_timeout_secs")]
13754    fn new_rejects_each_missing_transaction_limit(#[case] missing: &str) {
13755        let mut config = test_config("http://127.0.0.1:1".to_string());
13756        match missing {
13757            "allowed_token_pairs" => config.allowed_token_pairs = None,
13758            "slippage_bps" => config.slippage_bps = None,
13759            "max_slippage_bps" => config.max_slippage_bps = None,
13760            "max_order_amount" => config.max_order_amount = None,
13761            "deadline_seconds" => config.deadline_seconds = None,
13762            "max_quote_age_blocks" => config.max_quote_age_blocks = None,
13763            "receipt_timeout_secs" => config.receipt_timeout_secs = None,
13764            _ => unreachable!(),
13765        }
13766
13767        let error = test_client_result(config, test_pool()).unwrap_err();
13768
13769        assert_eq!(
13770            error.to_string(),
13771            "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"
13772        );
13773    }
13774
13775    #[rstest]
13776    fn new_rejects_empty_router_allowlist() {
13777        let mut config = test_config("http://127.0.0.1:1".to_string());
13778        config.router_addresses = Vec::new();
13779
13780        let error = test_client_result(config, test_pool()).unwrap_err();
13781
13782        assert!(
13783            error.to_string().contains("at least one router address"),
13784            "was: {error}"
13785        );
13786    }
13787
13788    #[tokio::test]
13789    async fn wrap_refuses_without_durable_store() {
13790        let (mut client, _) = client_with_mock_rpc(ready_rpc_state()).await;
13791        client.core.set_connected();
13792
13793        let error = client.wrap(U256::from(1_000u64)).await.unwrap_err();
13794
13795        assert!(
13796            error.to_string().contains("No durable store configured"),
13797            "was: {error}"
13798        );
13799    }
13800
13801    #[tokio::test]
13802    async fn approve_rejects_router_outside_allowlist() {
13803        let (mut client, state) = client_with_mock_rpc(ready_rpc_state()).await;
13804
13805        let error = client
13806            .approve(
13807                WETH_ADDRESS,
13808                U256::from(1_000u64),
13809                address!("68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"),
13810            )
13811            .await
13812            .err()
13813            .unwrap();
13814
13815        assert!(
13816            error
13817                .to_string()
13818                .contains("not in the configured `router_addresses` allowlist"),
13819            "was: {error}"
13820        );
13821        assert!(state.recorded_requests().is_empty());
13822    }
13823
13824    #[tokio::test]
13825    async fn approve_rejects_token_outside_input_allowlist() {
13826        let (mut client, state) = client_with_mock_rpc(ready_rpc_state()).await;
13827
13828        let error = client
13829            .approve(USDC_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
13830            .await
13831            .unwrap_err();
13832
13833        assert!(
13834            error
13835                .to_string()
13836                .contains("is not an input token in the configured `allowed_token_pairs`"),
13837            "was: {error}"
13838        );
13839        assert!(state.recorded_requests().is_empty());
13840    }
13841
13842    #[tokio::test]
13843    async fn in_flight_guard_rejects_second_transaction() {
13844        let (mut client, _) = client_with_mock_rpc(ready_rpc_state()).await;
13845        client.core.set_connected();
13846        *client.in_flight.lock() = Some(InFlightSlot::AwaitingFinality(InFlightTransaction {
13847            intent_id: 1,
13848            nonce: 7,
13849            tx_hash: B256::ZERO,
13850            purpose: TransactionPurpose::Wrap,
13851        }));
13852
13853        let error = client.wrap(U256::from(1_000u64)).await.unwrap_err();
13854
13855        assert!(
13856            error.to_string().contains("still awaiting finality"),
13857            "was: {error}"
13858        );
13859    }
13860
13861    #[tokio::test]
13862    async fn wrap_rejects_zero_amount() {
13863        let (mut client, _) = client_with_mock_rpc(ready_rpc_state()).await;
13864
13865        let error = client.wrap(U256::ZERO).await.unwrap_err();
13866
13867        assert!(
13868            error.to_string().contains("Wrap amount must be positive"),
13869            "was: {error}"
13870        );
13871    }
13872
13873    #[tokio::test]
13874    async fn wrap_rejects_code_free_target_before_broadcast() {
13875        let state = execution_rpc_state().with_response("eth_getCode", GET_CODE_EMPTY);
13876        let Some((admin_pool, schema, mut client, state)) =
13877            execution_client_with_database("execution_wrap_code_free_test", state).await
13878        else {
13879            return;
13880        };
13881
13882        let error = client
13883            .wrap(U256::from(1_000_000_000_000_000u64))
13884            .await
13885            .unwrap_err();
13886
13887        assert!(
13888            error
13889                .to_string()
13890                .contains("pre-sign deployment manifest verification disagreed"),
13891            "was: {error}"
13892        );
13893        assert!(client.in_flight.lock().is_none());
13894        let requests = state.recorded_requests();
13895        assert_eq!(
13896            requests
13897                .iter()
13898                .filter(|request| request["method"] == "eth_getCode")
13899                .count(),
13900            3
13901        );
13902        assert!(
13903            requests
13904                .iter()
13905                .all(|request| request["method"] != "eth_sendRawTransaction")
13906        );
13907
13908        drop_execution_schema(&admin_pool, &schema).await;
13909    }
13910
13911    #[tokio::test]
13912    async fn wrap_rejects_unrelated_target_before_broadcast() {
13913        let state = execution_rpc_state().with_response("eth_call", CALL_EMPTY);
13914        let Some((admin_pool, schema, mut client, state)) =
13915            execution_client_with_database("execution_wrap_unrelated_test", state).await
13916        else {
13917            return;
13918        };
13919
13920        let error = client
13921            .wrap(U256::from(1_000_000_000_000_000u64))
13922            .await
13923            .unwrap_err();
13924
13925        assert!(
13926            error
13927                .to_string()
13928                .contains("pre-sign wrapped token probe verification is unavailable"),
13929            "was: {error}"
13930        );
13931        assert!(client.in_flight.lock().is_none());
13932        let requests = state.recorded_requests();
13933        assert!(
13934            requests
13935                .iter()
13936                .all(|request| request["method"] != "eth_sendRawTransaction")
13937        );
13938
13939        drop_execution_schema(&admin_pool, &schema).await;
13940    }
13941
13942    #[tokio::test]
13943    async fn wrap_rejects_included_transaction_without_balance_delta() {
13944        let state = broadcast_rpc_state().with_response_sequence("eth_call", &[CALL_BALANCE; 9]);
13945        let Some((admin_pool, schema, mut client, state)) =
13946            execution_client_with_database("execution_wrap_no_delta_test", state).await
13947        else {
13948            return;
13949        };
13950
13951        let error = client
13952            .wrap(U256::from(1_000_000_000_000_000u64))
13953            .await
13954            .unwrap_err();
13955
13956        assert!(
13957            error.to_string().contains("did not increase"),
13958            "was: {error}"
13959        );
13960        let in_flight = awaiting_in_flight(&client);
13961        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
13962        assert_eq!(
13963            execution_intent_markers(&admin_pool, &schema).await,
13964            vec![("wrap".into(), "broadcast".into(), false, true)]
13965        );
13966        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
13967            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
13968        )))
13969        .fetch_one(&admin_pool)
13970        .await
13971        .unwrap();
13972        assert_eq!(nonce_state, (7, 0));
13973        let broadcasts = state
13974            .recorded_requests()
13975            .into_iter()
13976            .filter(|request| request["method"] == "eth_sendRawTransaction")
13977            .count();
13978        assert_eq!(broadcasts, 1);
13979
13980        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000u64)).await;
13981        let block = finalized_wrap_block(expected_hash);
13982        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
13983        let restart_state = with_finalized_identity(
13984            execution_rpc_state()
13985                .with_response("eth_getTransactionReceipt", &receipt)
13986                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
13987                .with_response_sequence("eth_call", &[CALL_BALANCE; 6]),
13988            &block,
13989            &receipt,
13990        );
13991        let addr = start_mock_rpc_server(restart_state).await;
13992        let error = later_reconnect(client, format!("http://{addr}")).await;
13993        assert!(
13994            error.to_string().contains("did not increase"),
13995            "was: {error}"
13996        );
13997        assert_eq!(
13998            execution_intent_markers(&admin_pool, &schema).await,
13999            vec![("wrap".into(), "broadcast".into(), false, true)]
14000        );
14001        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
14002            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
14003        )))
14004        .fetch_one(&admin_pool)
14005        .await
14006        .unwrap();
14007        assert_eq!(nonce_state, (7, 0));
14008
14009        drop_execution_schema(&admin_pool, &schema).await;
14010    }
14011
14012    #[tokio::test]
14013    async fn wrap_reports_inclusion_when_postcondition_read_fails() {
14014        let state = broadcast_rpc_state().with_response_sequence(
14015            "eth_call",
14016            &[
14017                CALL_BALANCE,
14018                CALL_BALANCE,
14019                CALL_BALANCE,
14020                CALL_BALANCE,
14021                CALL_BALANCE,
14022                CALL_BALANCE,
14023                RPC_METHOD_NOT_FOUND,
14024                RPC_METHOD_NOT_FOUND,
14025                RPC_METHOD_NOT_FOUND,
14026            ],
14027        );
14028        let Some((admin_pool, schema, mut client, _)) =
14029            execution_client_with_database("execution_wrap_postcondition_rpc_test", state).await
14030        else {
14031            return;
14032        };
14033
14034        let error = client
14035            .wrap(U256::from(1_000_000_000_000_000u64))
14036            .await
14037            .unwrap_err();
14038
14039        let message = error.to_string();
14040        assert!(
14041            message.contains("failed to verify WETH balance after included transaction 0x"),
14042            "was: {message}"
14043        );
14044        assert!(message.contains("at block 30346561"), "was: {message}");
14045        let in_flight = awaiting_in_flight(&client);
14046        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
14047        assert_eq!(
14048            execution_intent_markers(&admin_pool, &schema).await,
14049            vec![("wrap".into(), "broadcast".into(), false, true)]
14050        );
14051
14052        drop_execution_schema(&admin_pool, &schema).await;
14053    }
14054
14055    #[tokio::test]
14056    async fn approve_rejects_false_return_before_broadcast() {
14057        let state = execution_rpc_state().with_response("eth_call", CALL_ZERO);
14058        let Some((admin_pool, schema, mut client, state)) =
14059            execution_client_with_database("execution_approve_false_test", state).await
14060        else {
14061            return;
14062        };
14063
14064        let error = client
14065            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14066            .await
14067            .unwrap_err();
14068
14069        assert!(error.to_string().contains("returned false"), "was: {error}");
14070        assert!(client.in_flight.lock().is_none());
14071        let requests = state.recorded_requests();
14072        let approval_calls = requests
14073            .iter()
14074            .filter(|request| {
14075                request["method"] == "eth_call"
14076                    && request["params"][0]["data"]
14077                        .as_str()
14078                        .is_some_and(|data| data.starts_with("0x095ea7b3"))
14079            })
14080            .collect::<Vec<_>>();
14081        assert_eq!(approval_calls.len(), 3);
14082        for request in approval_calls {
14083            assert_eq!(
14084                request["params"][0]["from"]
14085                    .as_str()
14086                    .unwrap()
14087                    .parse::<Address>()
14088                    .unwrap(),
14089                WALLET.parse::<Address>().unwrap()
14090            );
14091            assert_eq!(request["params"][1], FIXTURE_BLOCK_PARAM);
14092        }
14093        assert!(
14094            requests
14095                .iter()
14096                .all(|request| request["method"] != "eth_getTransactionCount")
14097        );
14098        assert!(
14099            requests
14100                .iter()
14101                .all(|request| request["method"] != "eth_sendRawTransaction")
14102        );
14103
14104        drop_execution_schema(&admin_pool, &schema).await;
14105    }
14106
14107    #[tokio::test]
14108    async fn approve_rejects_router_with_wrong_factory_before_signing() {
14109        let state = ready_rpc_state().with_call_response(FACTORY_SELECTOR, CALL_ZERO);
14110        let Some((admin_pool, schema, mut client, state)) =
14111            execution_client_with_database("execution_approve_factory_test", state).await
14112        else {
14113            return;
14114        };
14115
14116        let error = client
14117            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14118            .await
14119            .unwrap_err();
14120
14121        assert!(
14122            error
14123                .to_string()
14124                .contains("pre-sign deployment manifest verification disagreed"),
14125            "was: {error}"
14126        );
14127        let requests = state.recorded_requests();
14128        assert!(
14129            requests
14130                .iter()
14131                .all(|request| request["method"] != "eth_getTransactionCount")
14132        );
14133        assert!(
14134            requests
14135                .iter()
14136                .all(|request| request["method"] != "eth_sendRawTransaction")
14137        );
14138
14139        drop_execution_schema(&admin_pool, &schema).await;
14140    }
14141
14142    #[tokio::test]
14143    async fn approve_rejects_router_with_wrong_weth_before_signing() {
14144        let state = ready_rpc_state().with_call_response(WETH9_SELECTOR, CALL_ZERO);
14145        let Some((admin_pool, schema, mut client, state)) =
14146            execution_client_with_database("execution_approve_weth_test", state).await
14147        else {
14148            return;
14149        };
14150
14151        let error = client
14152            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14153            .await
14154            .unwrap_err();
14155
14156        assert!(
14157            error
14158                .to_string()
14159                .contains("pre-sign deployment manifest verification disagreed"),
14160            "was: {error}"
14161        );
14162        let requests = state.recorded_requests();
14163        assert!(
14164            requests
14165                .iter()
14166                .all(|request| request["method"] != "eth_getTransactionCount")
14167        );
14168        assert!(
14169            requests
14170                .iter()
14171                .all(|request| request["method"] != "eth_sendRawTransaction")
14172        );
14173
14174        drop_execution_schema(&admin_pool, &schema).await;
14175    }
14176
14177    #[tokio::test]
14178    async fn approve_rejects_nonzero_to_nonzero_transition_before_signing() {
14179        let state = ready_rpc_state();
14180        let Some((admin_pool, schema, mut client, state)) =
14181            execution_client_with_database("execution_approve_nonzero_test", state).await
14182        else {
14183            return;
14184        };
14185
14186        let error = client
14187            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14188            .await
14189            .unwrap_err();
14190
14191        assert!(
14192            error.to_string().contains("approve zero before setting"),
14193            "was: {error}"
14194        );
14195        let requests = state.recorded_requests();
14196        assert!(
14197            requests
14198                .iter()
14199                .all(|request| request["method"] != "eth_getTransactionCount")
14200        );
14201        assert!(
14202            requests
14203                .iter()
14204                .all(|request| request["method"] != "eth_sendRawTransaction")
14205        );
14206
14207        drop_execution_schema(&admin_pool, &schema).await;
14208    }
14209
14210    #[tokio::test]
14211    async fn approve_zero_revokes_under_unlimited_policy() {
14212        let state = broadcast_rpc_state()
14213            .with_response("eth_call", CALL_BOOL_TRUE)
14214            .with_call_response_sequence(
14215                ALLOWANCE_SELECTOR,
14216                &[
14217                    CALL_ALLOWANCE,
14218                    CALL_ALLOWANCE,
14219                    CALL_ALLOWANCE,
14220                    CALL_ZERO,
14221                    CALL_ZERO,
14222                    CALL_ZERO,
14223                ],
14224            );
14225        let Some((admin_pool, schema, mut client, state)) =
14226            execution_client_with_database("execution_approve_revoke_test", state).await
14227        else {
14228            return;
14229        };
14230        client.config.unlimited_approval = true;
14231        client.transaction_limits.receipt_timeout_secs = TEST_TIMEOUT.as_secs();
14232
14233        let tx_hash = client
14234            .approve(WETH_ADDRESS, U256::ZERO, ROUTER_ADDRESS)
14235            .await
14236            .unwrap();
14237
14238        assert_eq!(tx_hash, expected_approve_tx_hash(U256::ZERO).await);
14239        let approve_data = state
14240            .recorded_requests()
14241            .into_iter()
14242            .find_map(|request| {
14243                (request["method"] == "eth_estimateGas")
14244                    .then(|| request["params"][0]["data"].as_str().map(str::to_owned))
14245                    .flatten()
14246            })
14247            .unwrap();
14248        assert!(approve_data.starts_with("0x095ea7b3"));
14249        assert!(approve_data.ends_with(&"0".repeat(64)));
14250        assert_eq!(
14251            state
14252                .recorded_requests()
14253                .iter()
14254                .filter(|request| {
14255                    request["method"] == "eth_call"
14256                        && request["params"][0]["data"]
14257                            .as_str()
14258                            .is_some_and(|data| data.starts_with(FACTORY_SELECTOR))
14259                })
14260                .count(),
14261            12
14262        );
14263        assert_eq!(
14264            execution_intent_markers(&admin_pool, &schema).await,
14265            vec![("approve".into(), "finalized".into(), true, false)]
14266        );
14267
14268        drop_execution_schema(&admin_pool, &schema).await;
14269    }
14270
14271    #[tokio::test]
14272    async fn approve_accepts_empty_return_with_sufficient_allowance() {
14273        let state = broadcast_rpc_state()
14274            .with_response("eth_call", CALL_EMPTY)
14275            .with_call_response_sequence(
14276                ALLOWANCE_SELECTOR,
14277                &[
14278                    CALL_ZERO,
14279                    CALL_ZERO,
14280                    CALL_ZERO,
14281                    CALL_ALLOWANCE_1000,
14282                    CALL_ALLOWANCE_1000,
14283                    CALL_ALLOWANCE_1000,
14284                ],
14285            );
14286        let Some((admin_pool, schema, mut client, _)) =
14287            execution_client_with_database("execution_approve_empty_test", state).await
14288        else {
14289            return;
14290        };
14291
14292        let tx_hash = client
14293            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14294            .await
14295            .unwrap();
14296
14297        let record = client
14298            .cache
14299            .get_execution_transaction(42161, &tx_hash.to_string())
14300            .await
14301            .unwrap()
14302            .unwrap();
14303        assert_eq!(record.purpose, "approve");
14304        assert_eq!(record.status, "finalized");
14305        assert!(client.in_flight.lock().is_none());
14306        assert_eq!(
14307            execution_intent_markers(&admin_pool, &schema).await,
14308            vec![("approve".into(), "finalized".into(), true, false)]
14309        );
14310
14311        drop_execution_schema(&admin_pool, &schema).await;
14312    }
14313
14314    #[tokio::test]
14315    async fn approve_rejects_empty_return_with_insufficient_allowance() {
14316        let state = broadcast_rpc_state()
14317            .with_response("eth_call", CALL_EMPTY)
14318            .with_call_response_sequence(ALLOWANCE_SELECTOR, &[CALL_ZERO; 6]);
14319        let Some((admin_pool, schema, mut client, _)) =
14320            execution_client_with_database("execution_approve_insufficient_test", state).await
14321        else {
14322            return;
14323        };
14324
14325        let error = client
14326            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14327            .await
14328            .unwrap_err();
14329
14330        assert!(
14331            error
14332                .to_string()
14333                .contains("does not equal the requested amount"),
14334            "was: {error}"
14335        );
14336        let in_flight = awaiting_in_flight(&client);
14337        assert_eq!(in_flight.purpose, TransactionPurpose::Approve);
14338        assert_eq!(
14339            execution_intent_markers(&admin_pool, &schema).await,
14340            vec![("approve".into(), "broadcast".into(), false, true)]
14341        );
14342        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
14343            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
14344        )))
14345        .fetch_one(&admin_pool)
14346        .await
14347        .unwrap();
14348        assert_eq!(nonce_state, (7, 0));
14349
14350        let expected_hash = expected_approve_tx_hash(U256::from(1_000u64)).await;
14351        let block = finalized_approve_block(expected_hash, U256::from(1_000u64));
14352        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
14353        let restart_state = with_finalized_identity(
14354            execution_rpc_state()
14355                .with_response("eth_getTransactionReceipt", &receipt)
14356                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
14357                .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO),
14358            &block,
14359            &receipt,
14360        );
14361        let addr = start_mock_rpc_server(restart_state).await;
14362        let error = later_reconnect(client, format!("http://{addr}")).await;
14363        assert!(
14364            error
14365                .to_string()
14366                .contains("does not equal the requested amount"),
14367            "was: {error}"
14368        );
14369        assert_eq!(
14370            execution_intent_markers(&admin_pool, &schema).await,
14371            vec![("approve".into(), "broadcast".into(), false, true)]
14372        );
14373        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
14374            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
14375        )))
14376        .fetch_one(&admin_pool)
14377        .await
14378        .unwrap();
14379        assert_eq!(nonce_state, (7, 0));
14380
14381        drop_execution_schema(&admin_pool, &schema).await;
14382    }
14383
14384    #[tokio::test]
14385    async fn approve_reports_inclusion_when_postcondition_read_fails() {
14386        let state = broadcast_rpc_state()
14387            .with_response("eth_call", CALL_BOOL_TRUE)
14388            .with_call_response_sequence(
14389                ALLOWANCE_SELECTOR,
14390                &[
14391                    CALL_ZERO,
14392                    CALL_ZERO,
14393                    CALL_ZERO,
14394                    RPC_METHOD_NOT_FOUND,
14395                    RPC_METHOD_NOT_FOUND,
14396                    RPC_METHOD_NOT_FOUND,
14397                ],
14398            );
14399        let Some((admin_pool, schema, mut client, _)) =
14400            execution_client_with_database("execution_approve_postcondition_rpc_test", state).await
14401        else {
14402            return;
14403        };
14404
14405        let error = client
14406            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
14407            .await
14408            .unwrap_err();
14409
14410        let message = error.to_string();
14411        assert!(
14412            message.contains("failed to verify router allowance after included transaction 0x"),
14413            "was: {message}"
14414        );
14415        assert!(message.contains("at block 30346561"), "was: {message}");
14416        let in_flight = awaiting_in_flight(&client);
14417        assert_eq!(in_flight.purpose, TransactionPurpose::Approve);
14418        assert_eq!(
14419            execution_intent_markers(&admin_pool, &schema).await,
14420            vec![("approve".into(), "broadcast".into(), false, true)]
14421        );
14422
14423        drop_execution_schema(&admin_pool, &schema).await;
14424    }
14425
14426    #[tokio::test]
14427    async fn wallet_balance_refresh_replaces_complete_snapshot_with_exact_precision() {
14428        let state = execution_rpc_state()
14429            .with_response_sequence("eth_getBalance", &[GET_BALANCE, GET_BALANCE_ZERO])
14430            .with_response_sequence(
14431                "eth_call",
14432                &[
14433                    CALL_BALANCE_WETH,
14434                    CALL_BALANCE_USDC,
14435                    CALL_BALANCE_WETH_UPDATED,
14436                    CALL_BALANCE_USDC_UPDATED,
14437                ],
14438            );
14439        let (mut client, _, _) =
14440            client_with_token_mock_rpc(state, "BLOCKCHAIN_TEST_BALANCE_REPLACE").await;
14441        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14442        replace_exec_event_sender(sender);
14443        client.start().unwrap();
14444
14445        client.refresh_wallet_balances().await.unwrap();
14446        let balances = client.wallet_balance.lock().as_account_balances().unwrap();
14447
14448        assert_eq!(balances.len(), 3);
14449        assert_eq!(balances[0].currency.code, "ETH");
14450        assert_eq!(balances[0].currency.name, "Ethereum");
14451        assert_eq!(balances[0].currency.precision, 18);
14452        assert_eq!(balances[0].total.raw(), 1_000_000_000_000_000_000);
14453        assert_eq!(balances[0].free, balances[0].total);
14454        assert_eq!(balances[0].locked, Money::zero(balances[0].currency));
14455        assert_eq!(balances[1].currency.code, "WETH@ARBITRUM");
14456        assert_eq!(balances[1].currency.name, "Wrapped Ether");
14457        assert_eq!(balances[1].currency.precision, 18);
14458        assert_eq!(balances[1].total.raw(), 1_234_567_890_123_456_789);
14459        assert_eq!(balances[1].free, balances[1].total);
14460        assert_eq!(balances[1].locked, Money::zero(balances[1].currency));
14461        assert_eq!(balances[2].currency.code, "USDC@ARBITRUM");
14462        assert_eq!(balances[2].currency.name, "USD Coin");
14463        assert_eq!(balances[2].currency.precision, 6);
14464        assert_eq!(balances[2].total.raw(), 9_876_543_210_000_000_000);
14465        assert_eq!(balances[2].free, balances[2].total);
14466        assert_eq!(balances[2].locked, Money::zero(balances[2].currency));
14467
14468        client.refresh_wallet_balances().await.unwrap();
14469        let balances = client.wallet_balance.lock().as_account_balances().unwrap();
14470
14471        assert_eq!(balances.len(), 3);
14472        assert_eq!(client.wallet_balance.lock().token_balances.len(), 2);
14473        assert_eq!(balances[0].total.raw(), 0);
14474        assert_eq!(balances[1].total.raw(), 2_000_000_000_000_000_000);
14475        assert_eq!(balances[2].total.raw(), 12_345_670_000_000_000);
14476    }
14477
14478    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14479    #[tokio::test]
14480    async fn failed_connect_refresh_retains_snapshot_and_publishes_nothing() {
14481        let state = execution_rpc_state()
14482            .with_response_sequence("eth_getBalance", &[GET_BALANCE, GET_BALANCE_ZERO])
14483            .with_response_sequence(
14484                "eth_call",
14485                &[
14486                    CALL_BALANCE_WETH,
14487                    CALL_BALANCE_USDC,
14488                    CALL_BALANCE_WETH_UPDATED,
14489                    RPC_METHOD_NOT_FOUND,
14490                ],
14491            );
14492        let (mut client, _, _) =
14493            client_with_token_mock_rpc(state, "BLOCKCHAIN_TEST_BALANCE_ATOMIC").await;
14494        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
14495        replace_exec_event_sender(sender);
14496        client.start().unwrap();
14497        client.refresh_wallet_balances().await.unwrap();
14498        let retained = client.wallet_balance.lock().as_account_balances().unwrap();
14499        receiver.try_recv().unwrap();
14500        // SAFETY: this variable name is unique to this test across the test binary
14501        unsafe { std::env::set_var("BLOCKCHAIN_TEST_BALANCE_ATOMIC", TEST_PRIVATE_KEY) };
14502
14503        let error = client.connect().await.unwrap_err();
14504        let failed_address = Address::from_str(USDC).unwrap();
14505
14506        assert!(
14507            error.to_string().contains(&format!(
14508                "failed to fetch token balance for {failed_address}"
14509            )),
14510            "was: {error}"
14511        );
14512        assert!(!client.is_connected());
14513        assert!(client.signer.is_none());
14514        assert_eq!(
14515            client.wallet_balance.lock().as_account_balances().unwrap(),
14516            retained
14517        );
14518        assert!(matches!(
14519            receiver.try_recv(),
14520            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
14521        ));
14522    }
14523
14524    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14525    #[tokio::test]
14526    async fn failed_connect_publication_retains_snapshot() {
14527        let state = execution_rpc_state()
14528            .with_response_sequence("eth_getBalance", &[GET_BALANCE, GET_BALANCE_ZERO])
14529            .with_response_sequence(
14530                "eth_call",
14531                &[
14532                    CALL_BALANCE_WETH,
14533                    CALL_BALANCE_USDC,
14534                    CALL_BALANCE_WETH_UPDATED,
14535                    CALL_BALANCE_USDC_UPDATED,
14536                ],
14537            );
14538        let (mut client, _, _) =
14539            client_with_token_mock_rpc(state, "BLOCKCHAIN_TEST_BALANCE_PUBLICATION").await;
14540        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
14541        replace_exec_event_sender(sender);
14542        client.start().unwrap();
14543        client.refresh_wallet_balances().await.unwrap();
14544        let retained = client.wallet_balance.lock().as_account_balances().unwrap();
14545        receiver.try_recv().unwrap();
14546        drop(receiver);
14547        // SAFETY: this variable name is unique to this test across the test binary
14548        unsafe { std::env::set_var("BLOCKCHAIN_TEST_BALANCE_PUBLICATION", TEST_PRIVATE_KEY) };
14549
14550        let error = client.connect().await.unwrap_err();
14551
14552        assert!(
14553            error.to_string().contains("Failed to send account state"),
14554            "was: {error}"
14555        );
14556        assert!(!client.is_connected());
14557        assert!(client.signer.is_none());
14558        assert_eq!(
14559            client.wallet_balance.lock().as_account_balances().unwrap(),
14560            retained
14561        );
14562    }
14563
14564    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14565    #[tokio::test]
14566    async fn connect_and_repeated_query_publish_wallet_account_state() {
14567        let state = execution_rpc_state()
14568            .with_response_sequence("eth_call", &[CALL_BALANCE_WETH, CALL_BALANCE_USDC]);
14569        let (mut client, state, cache) =
14570            client_with_token_mock_rpc(state, "BLOCKCHAIN_TEST_ACCOUNT_STATE").await;
14571        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
14572        replace_exec_event_sender(sender);
14573        client.start().unwrap();
14574        // SAFETY: this variable name is unique to this test across the test binary
14575        unsafe { std::env::set_var("BLOCKCHAIN_TEST_ACCOUNT_STATE", TEST_PRIVATE_KEY) };
14576
14577        client.connect().await.unwrap();
14578
14579        let ExecutionEvent::Account(connected) = receiver.try_recv().unwrap() else {
14580            panic!("expected account state event")
14581        };
14582        assert_eq!(connected.account_id, AccountId::from("BLOCKCHAIN-001"));
14583        assert_eq!(connected.account_type, AccountType::Wallet);
14584        assert_eq!(connected.base_currency, None);
14585        assert_eq!(connected.balances.len(), 3);
14586        assert!(connected.margins.is_empty());
14587        assert!(connected.is_reported);
14588        cache.borrow_mut().update_account_state(&connected).unwrap();
14589
14590        let account = client.get_account().unwrap();
14591        assert!(matches!(account, AccountAny::Wallet(_)));
14592        assert_eq!(account.id(), AccountId::from("BLOCKCHAIN-001"));
14593        assert_eq!(account.last_event(), Some(connected.clone()));
14594
14595        let requests_before = state.recorded_requests().len();
14596        let query = || {
14597            QueryAccount::new(
14598                TraderId::from("TRADER-001"),
14599                Some(ClientId::from("BLOCKCHAIN-001")),
14600                AccountId::from("BLOCKCHAIN-001"),
14601                UUID4::new(),
14602                UnixNanos::default(),
14603                None,
14604                None,
14605            )
14606        };
14607        client.query_account(query()).unwrap();
14608        client.query_account(query()).unwrap();
14609
14610        let ExecutionEvent::Account(first_query) = receiver.try_recv().unwrap() else {
14611            panic!("expected first query account state event")
14612        };
14613        let ExecutionEvent::Account(second_query) = receiver.try_recv().unwrap() else {
14614            panic!("expected second query account state event")
14615        };
14616        assert!(connected.has_same_balances_and_margins(&first_query));
14617        assert!(first_query.has_same_balances_and_margins(&second_query));
14618        assert_eq!(first_query.account_id, connected.account_id);
14619        assert_eq!(first_query.account_type, connected.account_type);
14620        assert_eq!(first_query.base_currency, connected.base_currency);
14621        assert_eq!(first_query.is_reported, connected.is_reported);
14622        assert_ne!(first_query.event_id, second_query.event_id);
14623        assert_eq!(state.recorded_requests().len(), requests_before);
14624
14625        client.stop().unwrap();
14626        assert!(client.core.is_stopped());
14627        assert!(!client.is_connected());
14628        assert!(client.signer.is_none());
14629    }
14630
14631    #[tokio::test]
14632    async fn connect_rejects_on_chain_mismatch() {
14633        let state = ready_rpc_state().with_response("eth_chainId", CHAIN_ID_ETHEREUM);
14634        let (mut client, _) = client_with_mock_rpc(state).await;
14635
14636        let error = client.connect().await.unwrap_err();
14637
14638        assert!(
14639            error
14640                .to_string()
14641                .contains("Blockchain chain ID verification disagreed"),
14642            "was: {error}"
14643        );
14644    }
14645
14646    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14647    #[tokio::test]
14648    async fn connect_rejects_on_signer_wallet_mismatch() {
14649        let addr = start_mock_rpc_server(ready_rpc_state()).await;
14650        let config = test_config_with_signer_env(
14651            format!("http://{addr}"),
14652            "BLOCKCHAIN_TEST_PRIVATE_KEY_MISMATCH",
14653        );
14654        let mut client = test_client_from_config(config, test_pool());
14655        // Anvil development key #1 derives a different address than the configured wallet
14656        // SAFETY: this variable name is unique to this test across the test binary
14657        unsafe {
14658            std::env::set_var(
14659                "BLOCKCHAIN_TEST_PRIVATE_KEY_MISMATCH",
14660                "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d",
14661            );
14662        };
14663
14664        let error = client.connect().await.unwrap_err();
14665
14666        assert!(
14667            error
14668                .to_string()
14669                .contains("does not match configured wallet address"),
14670            "was: {error}"
14671        );
14672    }
14673
14674    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14675    #[tokio::test]
14676    async fn connect_rejects_missing_trace_capability_before_signer_load() {
14677        let state = ready_rpc_state().with_parameter_response(
14678            "debug_traceTransaction",
14679            &B256::ZERO.to_string(),
14680            RPC_METHOD_NOT_FOUND,
14681        );
14682        let addr = start_mock_rpc_server(state.clone()).await;
14683        let config = test_config_with_signer_env(
14684            format!("http://{addr}"),
14685            "BLOCKCHAIN_TEST_TRACE_CAPABILITY",
14686        );
14687        let mut client = test_client_from_config(config, test_pool());
14688        // SAFETY: this variable name is unique to this test across the test binary
14689        unsafe { std::env::set_var("BLOCKCHAIN_TEST_TRACE_CAPABILITY", TEST_PRIVATE_KEY) };
14690
14691        let error = client.connect().await.unwrap_err();
14692
14693        assert!(
14694            error
14695                .to_string()
14696                .contains("Blockchain call trace capability verification is locally invalid"),
14697            "was: {error}"
14698        );
14699        assert!(client.signer.is_none());
14700        assert!(
14701            state
14702                .recorded_requests()
14703                .iter()
14704                .all(|request| request["method"] != "eth_getBalance")
14705        );
14706    }
14707
14708    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14709    #[tokio::test]
14710    async fn connect_initializes_signer_from_env() {
14711        let addr = start_mock_rpc_server(ready_rpc_state()).await;
14712        let config =
14713            test_config_with_signer_env(format!("http://{addr}"), "BLOCKCHAIN_TEST_PRIVATE_KEY_OK");
14714        let mut client = test_client_from_config(config, test_pool());
14715        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14716        replace_exec_event_sender(sender);
14717        client.start().unwrap();
14718        // SAFETY: this variable name is unique to this test across the test binary
14719        unsafe { std::env::set_var("BLOCKCHAIN_TEST_PRIVATE_KEY_OK", TEST_PRIVATE_KEY) };
14720
14721        client.connect().await.unwrap();
14722
14723        let signer = client.signer.as_ref().unwrap();
14724        assert_eq!(
14725            signer.address(),
14726            address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266")
14727        );
14728    }
14729
14730    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14731    #[tokio::test]
14732    async fn reconnect_resumes_at_the_durable_finalized_tip() {
14733        let Some((admin_pool, pg_config)) =
14734            connect_test_postgres("verification ledger resume").await
14735        else {
14736            return;
14737        };
14738        let schema = format!("verification_ledger_resume_{}", std::process::id());
14739        setup_execution_schema(&admin_pool, &schema).await;
14740        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
14741        let options = options.options([("search_path", schema.clone())]);
14742        let database = connect_test_database(options).await.unwrap();
14743        database
14744            .ensure_execution_transaction_schema()
14745            .await
14746            .unwrap();
14747
14748        let state = ready_rpc_state();
14749        let addr = start_mock_rpc_server(state.clone()).await;
14750        let config = test_config_with_signer_env(
14751            format!("http://{addr}"),
14752            "BLOCKCHAIN_TEST_VERIFICATION_RESUME",
14753        );
14754        let mut client = test_client_from_config(config, test_pool());
14755        client.cache.database = Some(database);
14756        protect_test_storage(&mut client, &schema).await;
14757        let finalized_headers = [
14758            ExecutionVerifiedHeader {
14759                number: FIXTURE_BLOCK,
14760                hash: FIXTURE_BLOCK_HASH.to_string(),
14761                parent_hash: "0x0000000000000000000000000000000000000000000000000000000000000001"
14762                    .to_string(),
14763                timestamp: FIXTURE_BLOCK_TIMESTAMP,
14764                base_fee_per_gas: Some(100_000_000),
14765            },
14766            ExecutionVerifiedHeader {
14767                number: FIXTURE_BLOCK + 1,
14768                hash: B256::from([0x22; 32]).to_string(),
14769                parent_hash: FIXTURE_BLOCK_HASH.to_string(),
14770                timestamp: FIXTURE_BLOCK_TIMESTAMP + 1,
14771                base_fee_per_gas: Some(100_000_000),
14772            },
14773            ExecutionVerifiedHeader {
14774                number: FIXTURE_BLOCK + 2,
14775                hash: B256::from([0x33; 32]).to_string(),
14776                parent_hash: B256::from([0x22; 32]).to_string(),
14777                timestamp: FIXTURE_BLOCK_TIMESTAMP + 2,
14778                base_fee_per_gas: Some(100_000_000),
14779            },
14780        ];
14781        initialize_test_verification_ledger_with_headers(&client, &finalized_headers).await;
14782        let verification = client.config.verification.as_ref().unwrap();
14783        let position = client
14784            .cache
14785            .database
14786            .as_ref()
14787            .unwrap()
14788            .load_execution_verification_position(
14789                42_161,
14790                WALLET,
14791                &verification.manifest_version,
14792                &verification.manifest_digest,
14793            )
14794            .await
14795            .unwrap()
14796            .unwrap();
14797        let resume = client
14798            .cache
14799            .database
14800            .as_ref()
14801            .unwrap()
14802            .load_execution_verification_resume(
14803                42_161,
14804                WALLET,
14805                &verification.manifest_version,
14806                &verification.manifest_digest,
14807            )
14808            .await
14809            .unwrap()
14810            .unwrap();
14811        assert_eq!(position.next_canonical_nonce, 7);
14812        assert_eq!(position.revision, 0);
14813        assert_eq!(position.finalized_tip, finalized_headers[2]);
14814        assert_eq!(resume.next_canonical_nonce, 7);
14815        assert_eq!(resume.revision, 0);
14816        assert_eq!(resume.finalized_headers, finalized_headers);
14817
14818        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14819        replace_exec_event_sender(sender);
14820        client.start().unwrap();
14821        // SAFETY: this variable name is unique to this test across the test binary
14822        unsafe { std::env::set_var("BLOCKCHAIN_TEST_VERIFICATION_RESUME", TEST_PRIVATE_KEY) };
14823
14824        client.connect().await.unwrap();
14825
14826        let skipped_height = format!("0x{:x}", FIXTURE_BLOCK + 1);
14827        assert!(client.is_connected());
14828        assert!(state.recorded_requests().iter().all(|request| {
14829            request["method"] != "eth_getBlockByNumber"
14830                || request["params"][0].as_str() != Some(&skipped_height)
14831        }));
14832        let header_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
14833            "SELECT COUNT(*) FROM {schema}.execution_verified_finalized_header"
14834        )))
14835        .fetch_one(&admin_pool)
14836        .await
14837        .unwrap();
14838        assert_eq!(header_count, 3);
14839
14840        drop(client);
14841        drop_execution_schema(&admin_pool, &schema).await;
14842    }
14843
14844    #[tokio::test]
14845    async fn disconnect_revokes_signer_and_blocks_execution() {
14846        let (mut client, state) = client_with_mock_rpc(ready_rpc_state()).await;
14847        client.core.set_connected();
14848        client.signer = Some(Arc::new(
14849            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
14850        ));
14851
14852        client.disconnect().await.unwrap();
14853        let error = client.wrap(U256::from(1_000u64)).await.unwrap_err();
14854
14855        assert!(!client.is_connected());
14856        assert!(client.signer.is_none());
14857        assert!(
14858            error.to_string().contains("is not connected"),
14859            "was: {error}"
14860        );
14861        assert!(state.recorded_requests().is_empty());
14862    }
14863
14864    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14865    #[tokio::test]
14866    async fn connect_releases_stale_preparing_claim_after_tasks_finish() {
14867        let addr = start_mock_rpc_server(ready_rpc_state()).await;
14868        let config = test_config_with_signer_env(
14869            format!("http://{addr}"),
14870            "BLOCKCHAIN_TEST_RECONNECT_CLAIM",
14871        );
14872        let mut client = test_client_from_config(config, test_pool());
14873        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14874        replace_exec_event_sender(sender);
14875        client.start().unwrap();
14876        // SAFETY: this variable name is unique to this test across the test binary
14877        unsafe { std::env::set_var("BLOCKCHAIN_TEST_RECONNECT_CLAIM", TEST_PRIVATE_KEY) };
14878        *client.in_flight.lock() = Some(InFlightSlot::Preparing(TransactionPurpose::Swap));
14879        client
14880            .pending_tasks
14881            .spawn(async {})
14882            .expect("stale task spawn");
14883
14884        client.connect().await.unwrap();
14885
14886        assert!(client.in_flight.lock().is_none());
14887    }
14888
14889    #[allow(unsafe_code)] // env-var mutation in tests; unique var names avoid cross-test races
14890    #[tokio::test]
14891    async fn reconnect_after_aborted_submission_releases_preparing_claim() {
14892        // The swap task blocks in its first RPC; disconnect aborts it mid-preparation, and the
14893        // following connect awaits termination and releases the stale claim
14894        let state = ready_rpc_state().with_sleep("eth_getBlockByNumber", Duration::from_secs(30));
14895        let Some((admin_pool, schema, mut client, state, _)) =
14896            swap_client_with_database("execution_reconnect_claim_test", state).await
14897        else {
14898            return;
14899        };
14900        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
14901        replace_exec_event_sender(sender);
14902        client.start().unwrap();
14903        // SAFETY: this variable name is unique to this test across the test binary
14904        unsafe { std::env::set_var("BLOCKCHAIN_TEST_PRIVATE_KEY", TEST_PRIVATE_KEY) };
14905
14906        let order = test_market_sell_order(test_pool().instrument_id);
14907        client.submit_order(submit_order_cmd(&order)).unwrap();
14908        await_recorded_requests(&state, "eth_getBlockByNumber", 1).await;
14909        assert!(client.in_flight.lock().is_some());
14910
14911        client.disconnect().await.unwrap();
14912        let ready_addr = start_mock_rpc_server(ready_rpc_state()).await;
14913        let ready = test_client(format!("http://{ready_addr}"));
14914        client.http_rpc_client = ready.http_rpc_client;
14915        client.verification = ready.verification;
14916        client.connect().await.unwrap();
14917
14918        assert!(client.in_flight.lock().is_none());
14919
14920        drop_execution_schema(&admin_pool, &schema).await;
14921    }
14922
14923    #[tokio::test]
14924    async fn poll_for_receipt_returns_none_after_exhaustion() {
14925        let state = ready_rpc_state().with_response("eth_getTransactionReceipt", RECEIPT_NULL);
14926        let (client, state) = client_with_mock_rpc(state).await;
14927
14928        let receipt = poll_for_receipt(&client.http_rpc_client, &B256::ZERO, 3, Duration::ZERO)
14929            .await
14930            .unwrap();
14931
14932        assert!(receipt.is_none());
14933        let requests = state.recorded_requests();
14934        assert_eq!(requests.len(), 3);
14935    }
14936
14937    #[tokio::test]
14938    async fn poll_for_receipt_returns_last_error_when_every_poll_fails() {
14939        let state =
14940            ready_rpc_state().with_response("eth_getTransactionReceipt", RPC_METHOD_NOT_FOUND);
14941        let (client, state) = client_with_mock_rpc(state).await;
14942
14943        let error = poll_for_receipt(&client.http_rpc_client, &B256::ZERO, 3, Duration::ZERO)
14944            .await
14945            .unwrap_err();
14946
14947        assert_eq!(
14948            error.to_string(),
14949            "eth_getTransactionReceipt RPC error -32601"
14950        );
14951        let requests = state.recorded_requests();
14952        assert_eq!(requests.len(), 3);
14953    }
14954
14955    #[tokio::test]
14956    async fn poll_for_receipt_returns_none_after_pending_then_errors() {
14957        let state = ready_rpc_state().with_response_sequence(
14958            "eth_getTransactionReceipt",
14959            &[RECEIPT_NULL, RPC_METHOD_NOT_FOUND, RPC_METHOD_NOT_FOUND],
14960        );
14961        let (client, state) = client_with_mock_rpc(state).await;
14962
14963        let receipt = poll_for_receipt(&client.http_rpc_client, &B256::ZERO, 3, Duration::ZERO)
14964            .await
14965            .unwrap();
14966
14967        assert!(receipt.is_none());
14968        let requests = state.recorded_requests();
14969        assert_eq!(requests.len(), 3);
14970    }
14971
14972    #[tokio::test]
14973    async fn cancellation_during_persistence_keeps_in_flight_slot() {
14974        let Some((admin_pool, pg_config)) = connect_test_postgres("persistence cancellation").await
14975        else {
14976            return;
14977        };
14978
14979        let schema = format!("execution_persist_cancel_test_{}", std::process::id());
14980        setup_execution_schema(&admin_pool, &schema).await;
14981
14982        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
14983        let db_options = db_options.options([("search_path", schema.clone())]);
14984        let database = connect_test_database(db_options).await.unwrap();
14985
14986        let state = signing_rpc_state();
14987        let addr = start_mock_rpc_server(state.clone()).await;
14988
14989        let mut client = test_client(format!("http://{addr}"));
14990        client.cache.database = Some(database);
14991        // Mirror the connect-time migration: tests create the pre-submission table shape
14992        client
14993            .cache
14994            .ensure_execution_transaction_schema()
14995            .await
14996            .unwrap();
14997        protect_test_storage(&mut client, &schema).await;
14998        initialize_test_verification_ledger(&client).await;
14999        client.signer = Some(Arc::new(
15000            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
15001        ));
15002        client.core.set_connected();
15003
15004        let advisory_lock = i64::from(std::process::id());
15005
15006        for statement in [
15007            format!(
15008                "CREATE FUNCTION {schema}.block_execution_hash_insert() RETURNS trigger \
15009                 LANGUAGE plpgsql AS 'BEGIN PERFORM pg_advisory_xact_lock({advisory_lock}); \
15010                 RETURN NEW; END'"
15011            ),
15012            format!(
15013                "CREATE TRIGGER block_execution_hash_insert BEFORE INSERT ON \
15014                 {schema}.execution_transaction_hash FOR EACH ROW EXECUTE FUNCTION \
15015                 {schema}.block_execution_hash_insert()"
15016            ),
15017        ] {
15018            sqlx::query(sqlx::AssertSqlSafe(statement))
15019                .execute(&admin_pool)
15020                .await
15021                .unwrap();
15022        }
15023        let mut lock_transaction = admin_pool.begin().await.unwrap();
15024        sqlx::query("SELECT pg_advisory_xact_lock($1)")
15025            .bind(advisory_lock)
15026            .execute(&mut *lock_transaction)
15027            .await
15028            .unwrap();
15029
15030        let value = U256::from(1_000_000_000_000_000u64);
15031        let in_flight = Arc::clone(&client.in_flight);
15032        let mut wrap = Box::pin(client.wrap(value));
15033        tokio::time::timeout(Duration::from_secs(2), async {
15034            loop {
15035                tokio::select! {
15036                    result = &mut wrap => {
15037                        panic!("persistence completed while the table was locked: {result:?}")
15038                    }
15039                    () = tokio::time::sleep(Duration::from_millis(1)) => {}
15040                }
15041
15042                if matches!(*in_flight.lock(), Some(InFlightSlot::AwaitingFinality(_))) {
15043                    break;
15044                }
15045            }
15046        })
15047        .await
15048        .unwrap();
15049        drop(wrap);
15050        lock_transaction.rollback().await.unwrap();
15051
15052        let slot = *client.in_flight.lock();
15053        let second_error = client
15054            .wrap(U256::from(2_000_000_000_000_000u64))
15055            .await
15056            .unwrap_err();
15057        let broadcasts = state
15058            .recorded_requests()
15059            .into_iter()
15060            .filter(|request| request["method"] == "eth_sendRawTransaction")
15061            .count();
15062        let status: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15063            "SELECT status FROM {schema}.execution_intent"
15064        )))
15065        .fetch_one(&admin_pool)
15066        .await
15067        .unwrap();
15068
15069        assert!(matches!(slot, Some(InFlightSlot::AwaitingFinality(_))));
15070        assert_eq!(status, "prepared");
15071        assert!(
15072            second_error.to_string().contains("awaiting finality"),
15073            "was: {second_error}"
15074        );
15075        assert_eq!(broadcasts, 0);
15076
15077        drop_execution_schema(&admin_pool, &schema).await;
15078    }
15079
15080    #[tokio::test]
15081    async fn clock_error_releases_preparing_slot_and_allows_retry() {
15082        let state = broadcast_rpc_state().with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
15083
15084        let Some((admin_pool, schema, client, state)) =
15085            execution_client_with_database("execution_clock_error_test", state).await
15086        else {
15087            return;
15088        };
15089
15090        let executor = client.transaction_executor().unwrap();
15091        let value = U256::from(1_000_000_000_000_000u64);
15092        let input = Bytes::from(WETH9::depositCall {}.abi_encode());
15093        let authorization = TransactionAuthorization::Wrap { weth: WETH_ADDRESS };
15094
15095        let error = executor
15096            .transact(
15097                UNIX_EPOCH - Duration::from_secs(1),
15098                WETH_ADDRESS,
15099                value,
15100                input.clone(),
15101                TransactionPurpose::Wrap,
15102                None,
15103                authorization,
15104            )
15105            .await
15106            .unwrap_err();
15107        let slot_after_error = *client.in_flight.lock();
15108        let requests_after_error = state.recorded_requests();
15109        let intent_count_after_error: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15110            "SELECT COUNT(*) FROM {schema}.execution_intent"
15111        )))
15112        .fetch_one(&admin_pool)
15113        .await
15114        .unwrap();
15115        let retry = executor
15116            .transact(
15117                SystemTime::now(),
15118                WETH_ADDRESS,
15119                value,
15120                input,
15121                TransactionPurpose::Wrap,
15122                None,
15123                authorization,
15124            )
15125            .await;
15126        let slot_after_retry = *client.in_flight.lock();
15127        let requests_after_retry = state.recorded_requests();
15128        let intent_count_after_retry: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15129            "SELECT COUNT(*) FROM {schema}.execution_intent"
15130        )))
15131        .fetch_one(&admin_pool)
15132        .await
15133        .unwrap();
15134        let expected_hash = expected_wrap_tx_hash(value).await;
15135
15136        drop_execution_schema(&admin_pool, &schema).await;
15137
15138        assert_eq!(
15139            error.to_string(),
15140            "Trusted host clock precedes the Unix epoch"
15141        );
15142        assert!(slot_after_error.is_none(), "was: {slot_after_error:?}");
15143        assert!(
15144            requests_after_error.is_empty(),
15145            "was: {requests_after_error:?}"
15146        );
15147        assert_eq!(intent_count_after_error, 0);
15148        let included = retry.unwrap();
15149        assert_eq!(included.nonce, 7);
15150        assert_eq!(included.tx_hash, expected_hash);
15151        assert!(matches!(
15152            slot_after_retry,
15153            Some(InFlightSlot::AwaitingFinality(_))
15154        ));
15155        assert_eq!(intent_count_after_retry, 1);
15156        assert_eq!(
15157            requests_after_retry
15158                .iter()
15159                .filter(|request| request["method"] == "eth_sendRawTransaction")
15160                .count(),
15161            1
15162        );
15163    }
15164
15165    #[tokio::test]
15166    async fn reservation_failure_releases_preparing_slot() {
15167        let state = signing_rpc_state();
15168        let Some((admin_pool, schema, mut client, state)) =
15169            execution_client_with_database("execution_reservation_fail_test", state).await
15170        else {
15171            return;
15172        };
15173        sqlx::query(sqlx::AssertSqlSafe(format!(
15174            "DROP TABLE {schema}.execution_intent CASCADE"
15175        )))
15176        .execute(&admin_pool)
15177        .await
15178        .unwrap();
15179
15180        let error = client
15181            .wrap(U256::from(1_000_000_000_000_000u64))
15182            .await
15183            .unwrap_err();
15184        let retry_error = client
15185            .wrap(U256::from(2_000_000_000_000_000u64))
15186            .await
15187            .unwrap_err();
15188        let broadcasts = state
15189            .recorded_requests()
15190            .into_iter()
15191            .filter(|request| request["method"] == "eth_sendRawTransaction")
15192            .count();
15193
15194        assert_eq!(
15195            error.to_string(),
15196            "Execution intent reservation failed before commit"
15197        );
15198        assert!(reservation_failure_proven_not_committed(&error));
15199        assert_eq!(
15200            retry_error.to_string(),
15201            "Execution intent reservation failed before commit"
15202        );
15203        assert_eq!(broadcasts, 0);
15204        assert!(client.in_flight.lock().is_none());
15205
15206        drop_execution_schema(&admin_pool, &schema).await;
15207    }
15208
15209    #[tokio::test]
15210    async fn reservation_commit_failure_keeps_preparing_slot() {
15211        let state = signing_rpc_state();
15212        let Some((admin_pool, schema, mut client, state)) =
15213            execution_client_with_database("execution_reservation_commit_fail_test", state).await
15214        else {
15215            return;
15216        };
15217        install_reservation_commit_rejection(&admin_pool, &schema).await;
15218
15219        let error = client
15220            .wrap(U256::from(1_000_000_000_000_000u64))
15221            .await
15222            .unwrap_err();
15223        let slot = *client.in_flight.lock();
15224        let second_error = client
15225            .wrap(U256::from(2_000_000_000_000_000u64))
15226            .await
15227            .unwrap_err();
15228        let requests = state.recorded_requests();
15229        let intent_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15230            "SELECT COUNT(*) FROM {schema}.execution_intent"
15231        )))
15232        .fetch_one(&admin_pool)
15233        .await
15234        .unwrap();
15235        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15236            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
15237        )))
15238        .fetch_one(&admin_pool)
15239        .await
15240        .unwrap();
15241
15242        assert_eq!(
15243            error.to_string(),
15244            "Execution intent reservation commit outcome is unknown; reconciliation is required"
15245        );
15246        assert!(!reservation_failure_proven_not_committed(&error));
15247        assert!(matches!(
15248            slot,
15249            Some(InFlightSlot::Preparing(TransactionPurpose::Wrap))
15250        ));
15251        assert!(
15252            second_error.to_string().contains("being prepared"),
15253            "was: {second_error}"
15254        );
15255        assert_eq!(intent_count, 0);
15256        assert_eq!(signed_count, 0);
15257        assert!(
15258            requests
15259                .iter()
15260                .all(|request| request["method"] != "eth_getTransactionCount")
15261        );
15262        assert!(
15263            requests
15264                .iter()
15265                .all(|request| request["method"] != "eth_sendRawTransaction")
15266        );
15267
15268        drop_execution_schema(&admin_pool, &schema).await;
15269    }
15270
15271    #[tokio::test]
15272    async fn persistence_failure_keeps_unbroadcast_slot() {
15273        let state = signing_rpc_state();
15274        let Some((admin_pool, schema, mut client, state)) =
15275            execution_client_with_database("execution_persist_fail_test", state).await
15276        else {
15277            return;
15278        };
15279        sqlx::query(sqlx::AssertSqlSafe(format!(
15280            "ALTER TABLE {schema}.execution_transaction_hash \
15281             ADD CONSTRAINT execution_hash_reject CHECK (FALSE)"
15282        )))
15283        .execute(&admin_pool)
15284        .await
15285        .unwrap();
15286
15287        let value = U256::from(1_000_000_000_000_000u64);
15288        let error = client.wrap(value).await.unwrap_err();
15289        let in_flight = awaiting_in_flight(&client);
15290        let second_error = client
15291            .wrap(U256::from(2_000_000_000_000_000u64))
15292            .await
15293            .unwrap_err();
15294        let broadcasts = state
15295            .recorded_requests()
15296            .into_iter()
15297            .filter(|request| request["method"] == "eth_sendRawTransaction")
15298            .count();
15299        let expected_hash = expected_wrap_tx_hash(value).await;
15300
15301        let error_message = error.to_string();
15302        assert!(error_message.starts_with(&format!(
15303            "Failed to persist transaction {expected_hash}: Failed to persist signed transaction"
15304        )), "was: {error_message}");
15305        assert!(
15306            error_message.ends_with("the in-flight slot stays occupied"),
15307            "was: {error_message}"
15308        );
15309        assert_eq!(in_flight.nonce, 7);
15310        assert_eq!(in_flight.tx_hash, expected_hash);
15311        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15312        assert!(
15313            second_error.to_string().contains("still awaiting finality"),
15314            "was: {second_error}"
15315        );
15316        assert_eq!(broadcasts, 0);
15317
15318        drop_execution_schema(&admin_pool, &schema).await;
15319    }
15320
15321    #[tokio::test]
15322    async fn cancellation_after_dispatch_keeps_record_and_in_flight_slot() {
15323        let state = signing_rpc_state().with_sleep(
15324            "eth_sendRawTransaction",
15325            Duration::from_secs(EXECUTION_RPC_TIMEOUT_SECS + 2),
15326        );
15327        let Some((admin_pool, schema, mut client, state)) =
15328            execution_client_with_database("execution_cancel_test", state).await
15329        else {
15330            return;
15331        };
15332
15333        let mut wrap = Box::pin(client.wrap(U256::from(1_000_000_000_000_000u64)));
15334        tokio::select! {
15335            result = &mut wrap => panic!("broadcast completed before cancellation: {result:?}"),
15336            () = await_recorded_requests(&state, "eth_sendRawTransaction", 1) => {}
15337        }
15338        drop(wrap);
15339
15340        let in_flight = awaiting_in_flight(&client);
15341        let error = client
15342            .wrap(U256::from(2_000_000_000_000_000u64))
15343            .await
15344            .unwrap_err();
15345        let record = client
15346            .cache
15347            .get_execution_transaction(42161, &in_flight.tx_hash.to_string())
15348            .await
15349            .unwrap()
15350            .unwrap();
15351        let broadcasts = state
15352            .recorded_requests()
15353            .into_iter()
15354            .filter(|request| request["method"] == "eth_sendRawTransaction")
15355            .count();
15356
15357        assert!(
15358            error.to_string().contains("still awaiting finality"),
15359            "was: {error}"
15360        );
15361        assert_eq!(record.nonce, 7);
15362        assert_eq!(record.purpose, "wrap");
15363        assert_eq!(record.status, "broadcast");
15364        assert_eq!(broadcasts, 1);
15365
15366        drop_execution_schema(&admin_pool, &schema).await;
15367    }
15368
15369    #[tokio::test]
15370    async fn cancellation_during_receipt_polling_keeps_record_and_in_flight_slot() {
15371        let state = signing_rpc_state()
15372            .with_send_raw_transaction_echo()
15373            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS)
15374            .with_sleep(
15375                "eth_getTransactionReceipt",
15376                Duration::from_secs(EXECUTION_RPC_TIMEOUT_SECS + 2),
15377            );
15378        let Some((admin_pool, schema, mut client, state)) =
15379            execution_client_with_database("execution_receipt_cancel_test", state).await
15380        else {
15381            return;
15382        };
15383
15384        let mut wrap = Box::pin(client.wrap(U256::from(1_000_000_000_000_000u64)));
15385        tokio::select! {
15386            result = &mut wrap => panic!("receipt polling completed before cancellation: {result:?}"),
15387            () = await_recorded_requests(&state, "eth_getTransactionReceipt", 3) => {}
15388        }
15389        drop(wrap);
15390
15391        let in_flight = awaiting_in_flight(&client);
15392        let second_error = client
15393            .wrap(U256::from(2_000_000_000_000_000u64))
15394            .await
15395            .unwrap_err();
15396        let record = client
15397            .cache
15398            .get_execution_transaction(42161, &in_flight.tx_hash.to_string())
15399            .await
15400            .unwrap()
15401            .unwrap();
15402        let requests = state.recorded_requests();
15403
15404        assert_eq!(in_flight.nonce, 7);
15405        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15406        assert!(
15407            second_error.to_string().contains("still awaiting finality"),
15408            "was: {second_error}"
15409        );
15410        assert_eq!(record.nonce, 7);
15411        assert_eq!(record.transaction_hash, in_flight.tx_hash.to_string());
15412        assert_eq!(record.purpose, "wrap");
15413        assert_eq!(record.status, "broadcast");
15414        assert_eq!(
15415            requests
15416                .iter()
15417                .filter(|request| request["method"] == "eth_sendRawTransaction")
15418                .count(),
15419            1
15420        );
15421        assert_eq!(
15422            requests
15423                .iter()
15424                .filter(|request| request["method"] == "eth_getTransactionReceipt")
15425                .count(),
15426            3
15427        );
15428
15429        drop_execution_schema(&admin_pool, &schema).await;
15430    }
15431
15432    #[tokio::test]
15433    async fn rejected_broadcast_stays_dropped_and_occupied() {
15434        let state = signing_rpc_state()
15435            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION_REJECTED)
15436            .with_response("eth_getTransactionReceipt", RECEIPT_NULL);
15437        let Some((admin_pool, schema, mut client, state)) =
15438            execution_client_with_database("execution_rejected_test", state).await
15439        else {
15440            return;
15441        };
15442
15443        let error = client
15444            .wrap(U256::from(1_000_000_000_000_000u64))
15445            .await
15446            .unwrap_err();
15447        let (purpose, status): (String, String) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
15448            "SELECT purpose, status FROM {schema}.execution_intent"
15449        )))
15450        .fetch_one(&admin_pool)
15451        .await
15452        .unwrap();
15453        let broadcasts = state
15454            .recorded_requests()
15455            .into_iter()
15456            .filter(|request| request["method"] == "eth_sendRawTransaction")
15457            .count();
15458
15459        assert!(
15460            error.to_string().contains("Timed out awaiting finality"),
15461            "was: {error}"
15462        );
15463        assert!(client.in_flight.lock().is_some());
15464        assert_eq!(purpose, "wrap");
15465        assert_eq!(status, "dropped");
15466        assert_eq!(broadcasts, 1);
15467
15468        drop_execution_schema(&admin_pool, &schema).await;
15469    }
15470
15471    #[tokio::test]
15472    async fn legacy_table_loss_does_not_release_rejected_broadcast() {
15473        let state = signing_rpc_state()
15474            .with_response("eth_sendRawTransaction", SEND_RAW_TRANSACTION_REJECTED)
15475            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
15476            .with_sleep("eth_sendRawTransaction", Duration::from_secs(1));
15477        let Some((admin_pool, schema, mut client, state)) =
15478            execution_client_with_database("execution_rejected_update_test", state).await
15479        else {
15480            return;
15481        };
15482
15483        let mut wrap = Box::pin(client.wrap(U256::from(1_000_000_000_000_000u64)));
15484        tokio::select! {
15485            result = &mut wrap => panic!("broadcast completed before database failure: {result:?}"),
15486            () = await_recorded_requests(&state, "eth_sendRawTransaction", 1) => {}
15487        }
15488        sqlx::query(sqlx::AssertSqlSafe(format!(
15489            "DROP TABLE {schema}.execution_transaction"
15490        )))
15491        .execute(&admin_pool)
15492        .await
15493        .unwrap();
15494
15495        let error = wrap.await.unwrap_err();
15496
15497        assert!(
15498            error.to_string().contains("Timed out awaiting finality"),
15499            "was: {error}"
15500        );
15501        let in_flight = awaiting_in_flight(&client);
15502        assert_eq!(in_flight.nonce, 7);
15503        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15504
15505        drop_execution_schema(&admin_pool, &schema).await;
15506    }
15507
15508    #[tokio::test]
15509    async fn finalized_receipt_keeps_slot_when_status_update_fails() {
15510        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000u64)).await;
15511        let block = finalized_wrap_block(expected_hash);
15512        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
15513        let state = with_finalized_identity(
15514            signing_rpc_state()
15515                .with_send_raw_transaction_echo()
15516                .with_response("eth_getTransactionReceipt", &receipt)
15517                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
15518                .with_call_response_sequence(
15519                    BALANCE_OF_SELECTOR,
15520                    &[
15521                        CALL_BALANCE,
15522                        CALL_BALANCE,
15523                        CALL_BALANCE,
15524                        CALL_BALANCE,
15525                        CALL_BALANCE,
15526                        CALL_BALANCE,
15527                        CALL_BALANCE_AFTER_WRAP,
15528                        CALL_BALANCE_AFTER_WRAP,
15529                        CALL_BALANCE_AFTER_WRAP,
15530                    ],
15531                ),
15532            &block,
15533            &receipt,
15534        );
15535        let Some((admin_pool, schema, mut client, state)) =
15536            execution_client_with_database("execution_finalized_update_test", state).await
15537        else {
15538            return;
15539        };
15540
15541        for statement in [
15542            format!(
15543                "CREATE FUNCTION {schema}.reject_finalized_status() RETURNS trigger \
15544                 LANGUAGE plpgsql AS 'BEGIN IF NEW.status = ''finalized'' THEN \
15545                 RAISE EXCEPTION ''test finalized status rejection''; END IF; \
15546                 RETURN NEW; END'"
15547            ),
15548            format!(
15549                "CREATE TRIGGER reject_finalized_status BEFORE UPDATE ON \
15550                 {schema}.execution_transaction_hash FOR EACH ROW \
15551                 EXECUTE FUNCTION {schema}.reject_finalized_status()"
15552            ),
15553        ] {
15554            sqlx::query(sqlx::AssertSqlSafe(statement))
15555                .execute(&admin_pool)
15556                .await
15557                .unwrap();
15558        }
15559
15560        let error = client
15561            .wrap(U256::from(1_000_000_000_000_000u64))
15562            .await
15563            .unwrap_err();
15564        let in_flight = awaiting_in_flight(&client);
15565        let requests = state.recorded_requests();
15566
15567        assert!(
15568            error
15569                .to_string()
15570                .contains("test finalized status rejection"),
15571            "was: {error}"
15572        );
15573        assert_eq!(in_flight.nonce, 7);
15574        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15575        assert_eq!(
15576            requests
15577                .iter()
15578                .filter(|request| request["method"] == "eth_sendRawTransaction")
15579                .count(),
15580            1
15581        );
15582        assert_eq!(
15583            requests
15584                .iter()
15585                .filter(|request| request["method"] == "eth_getTransactionReceipt")
15586                .count(),
15587            3
15588        );
15589
15590        drop_execution_schema(&admin_pool, &schema).await;
15591    }
15592
15593    #[tokio::test]
15594    async fn broadcast_timeout_marks_dropped_and_keeps_ownership() {
15595        let state = signing_rpc_state()
15596            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
15597            .with_sleep(
15598                "eth_sendRawTransaction",
15599                Duration::from_secs(EXECUTION_RPC_TIMEOUT_SECS + 2),
15600            );
15601        let Some((admin_pool, schema, mut client, _)) =
15602            execution_client_with_database("execution_timeout_test", state).await
15603        else {
15604            return;
15605        };
15606
15607        let error = client
15608            .wrap(U256::from(1_000_000_000_000_000u64))
15609            .await
15610            .unwrap_err();
15611
15612        assert!(
15613            error.to_string().contains("Timed out awaiting finality"),
15614            "was: {error}"
15615        );
15616        let in_flight = awaiting_in_flight(&client);
15617        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
15618        assert_eq!(in_flight.nonce, 7);
15619
15620        // The persisted record stays active for reconciliation instead of rebroadcasting.
15621        let record = client
15622            .cache
15623            .get_execution_transaction(42161, &in_flight.tx_hash.to_string())
15624            .await
15625            .unwrap()
15626            .unwrap();
15627        assert_eq!(record.status, "dropped");
15628
15629        drop_execution_schema(&admin_pool, &schema).await;
15630    }
15631
15632    #[tokio::test]
15633    async fn restart_reconciles_dropped_transaction_without_rebroadcast() {
15634        let initial_state = broadcast_rpc_state()
15635            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
15636            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
15637        let Some((admin_pool, schema, mut first_client, _)) =
15638            execution_client_with_database("execution_restart_test", initial_state).await
15639        else {
15640            return;
15641        };
15642        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
15643        let error = first_client
15644            .wrap(U256::from(1_000_000_000_000_000_u64))
15645            .await
15646            .unwrap_err();
15647        assert!(
15648            error.to_string().contains("Timed out awaiting finality"),
15649            "was: {error}"
15650        );
15651        let database = first_client.cache.database.as_ref().unwrap().clone();
15652        let payload_keys = first_client.payload_keys.clone();
15653        drop(first_client);
15654
15655        let block = finalized_wrap_block(expected_hash);
15656        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
15657        let restart_state = with_finalized_identity(
15658            execution_rpc_state()
15659                .with_response("eth_getTransactionReceipt", &receipt)
15660                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
15661                .with_response_sequence(
15662                    "eth_call",
15663                    &[
15664                        CALL_BALANCE,
15665                        CALL_BALANCE,
15666                        CALL_BALANCE,
15667                        CALL_BALANCE_AFTER_WRAP,
15668                        CALL_BALANCE_AFTER_WRAP,
15669                        CALL_BALANCE_AFTER_WRAP,
15670                    ],
15671                ),
15672            &block,
15673            &receipt,
15674        );
15675        let addr = start_mock_rpc_server(restart_state.clone()).await;
15676        let mut restarted = test_client(format!("http://{addr}"));
15677        restarted.cache.database = Some(database);
15678        restarted.payload_keys = payload_keys;
15679        restarted.signer = Some(Arc::new(
15680            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
15681        ));
15682
15683        restarted.reconcile_unresolved_execution().await.unwrap();
15684        restarted.reconcile_unresolved_execution().await.unwrap();
15685
15686        let record = restarted
15687            .cache
15688            .get_execution_transaction(42161, &expected_hash.to_string())
15689            .await
15690            .unwrap()
15691            .unwrap();
15692        let requests = restart_state.recorded_requests();
15693        assert_eq!(record.status, "finalized");
15694        assert!(restarted.in_flight.lock().is_none());
15695        assert_eq!(
15696            requests
15697                .iter()
15698                .filter(|request| request["method"] == "eth_getTransactionReceipt")
15699                .count(),
15700            6
15701        );
15702        assert_eq!(
15703            requests
15704                .iter()
15705                .filter(|request| {
15706                    request["method"] == "eth_call"
15707                        && request["params"][0]["data"]
15708                            .as_str()
15709                            .is_some_and(|data| data.starts_with(BALANCE_OF_SELECTOR))
15710                })
15711                .count(),
15712            6
15713        );
15714        assert_eq!(
15715            requests
15716                .iter()
15717                .filter(|request| request["method"] == "eth_sendRawTransaction")
15718                .count(),
15719            0
15720        );
15721
15722        drop_execution_schema(&admin_pool, &schema).await;
15723    }
15724
15725    fn migration_test_intent(id: i64) -> ExecutionIntentRow {
15726        ExecutionIntentRow {
15727            id,
15728            schema_version: crate::execution::transaction::EXECUTION_SCHEMA_VERSION,
15729            chain_id: 42_161,
15730            wallet_address: WALLET.to_string(),
15731            nonce: None,
15732            purpose: "wrap".to_string(),
15733            status: "prepared".to_string(),
15734            client_order_id: None,
15735            trader_id: None,
15736            strategy_id: None,
15737            account_id: None,
15738            instrument_id: None,
15739            pool_address: None,
15740            transaction_to: WETH.to_string(),
15741            transaction_input: "0xd0e30db0".to_string(),
15742            transaction_value: "1".to_string(),
15743            amount_in: None,
15744            created_block: FIXTURE_BLOCK,
15745            acknowledgement_emitted: false,
15746            fill_emitted: false,
15747            terminal_emitted: false,
15748            active: true,
15749        }
15750    }
15751
15752    fn migration_nonce_verification() -> Verified<u64> {
15753        Verified {
15754            value: 7,
15755            read: crate::rpc::verification::VerificationRead::TransactionCount,
15756            provider_ids: [
15757                "authoritative".to_string(),
15758                "verifier-a".to_string(),
15759                "verifier-b".to_string(),
15760            ],
15761            normalized_value_digest: keccak256(7_u64.to_be_bytes()),
15762        }
15763    }
15764
15765    fn migration_finalized_header() -> VerifiedBlockHeader {
15766        VerifiedBlockHeader {
15767            number: FIXTURE_BLOCK,
15768            hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
15769            parent_hash: B256::from_str(
15770                "0x0000000000000000000000000000000000000000000000000000000000000001",
15771            )
15772            .unwrap(),
15773            timestamp: FIXTURE_BLOCK_TIMESTAMP,
15774            base_fee_per_gas: Some(100_000_000),
15775        }
15776    }
15777
15778    #[tokio::test]
15779    async fn verification_migration_recovers_prepared_unassigned_intent() {
15780        let client = test_client("http://127.0.0.1:1".to_string());
15781        let snapshot = ExecutionVerificationMigrationSnapshot {
15782            intents: vec![migration_test_intent(1)],
15783            hashes: Vec::new(),
15784        };
15785        let finalized = migration_finalized_header();
15786        let migration = client
15787            .build_execution_verification_migration(
15788                snapshot,
15789                finalized,
15790                &[finalized],
15791                &migration_nonce_verification(),
15792            )
15793            .await
15794            .unwrap();
15795
15796        assert_eq!(migration.records.len(), 1);
15797        let record = &migration.records[0];
15798        assert_eq!(record.intent_id, 1);
15799        assert_eq!(record.nonce, None);
15800        assert_eq!(record.transaction_hash, None);
15801        assert!(record.recover_prepared);
15802        assert_eq!(record.decisions.len(), 1);
15803    }
15804
15805    #[tokio::test]
15806    async fn verification_migration_rejects_inconsistent_released_history() {
15807        let client = test_client("http://127.0.0.1:1".to_string());
15808        let finalized = migration_finalized_header();
15809        let nonce_verification = migration_nonce_verification();
15810        let mut missing_marker = migration_test_intent(1);
15811        missing_marker.active = false;
15812        missing_marker.status = "finalized".to_string();
15813        missing_marker.nonce = Some(6);
15814        let error = client
15815            .build_execution_verification_migration(
15816                ExecutionVerificationMigrationSnapshot {
15817                    intents: vec![missing_marker],
15818                    hashes: Vec::new(),
15819                },
15820                finalized,
15821                &[finalized],
15822                &nonce_verification,
15823            )
15824            .await
15825            .err()
15826            .unwrap();
15827        assert!(
15828            error.to_string().contains("has no durable event marker"),
15829            "was: {error}"
15830        );
15831
15832        let mut first = migration_test_intent(1);
15833        first.active = false;
15834        first.status = "recoverable".to_string();
15835        first.nonce = Some(6);
15836        let mut second = first.clone();
15837        second.id = 2;
15838        let error = client
15839            .build_execution_verification_migration(
15840                ExecutionVerificationMigrationSnapshot {
15841                    intents: vec![first, second],
15842                    hashes: Vec::new(),
15843                },
15844                finalized,
15845                &[finalized],
15846                &nonce_verification,
15847            )
15848            .await
15849            .err()
15850            .unwrap();
15851        assert!(
15852            error
15853                .to_string()
15854                .contains("duplicate signer nonce ownership"),
15855            "was: {error}"
15856        );
15857    }
15858
15859    #[tokio::test]
15860    async fn verification_migration_reconstructs_consumed_active_intent() {
15861        let expected_hash = expected_wrap_tx_hash(U256::from(1u64)).await;
15862        let mut block_value: serde_json::Value =
15863            serde_json::from_str(&finalized_wrap_block(expected_hash)).unwrap();
15864        block_value["result"]["transactions"][0]["value"] = serde_json::json!("0x1");
15865        let block = block_value.to_string();
15866        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
15867        let state = with_finalized_identity(
15868            execution_rpc_state()
15869                .with_response("eth_getTransactionCount", TRANSACTION_COUNT_NEXT)
15870                .with_response("eth_getTransactionReceipt", &receipt)
15871                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block),
15872            &block,
15873            &receipt,
15874        );
15875        let Some((admin_pool, pg_config)) =
15876            connect_test_postgres("verification_migration_reconstructs_consumed_active_intent")
15877                .await
15878        else {
15879            return;
15880        };
15881        let schema = format!(
15882            "verification_migration_reconstructs_consumed_active_intent_{}",
15883            std::process::id()
15884        );
15885        setup_execution_schema(&admin_pool, &schema).await;
15886        let options: sqlx::postgres::PgConnectOptions = pg_config.into();
15887        let database = connect_test_database(options.options([("search_path", schema.clone())]))
15888            .await
15889            .unwrap();
15890        let addr = start_mock_rpc_server(state).await;
15891        let (mut client, _) = swap_client_with_cache(test_config(format!("http://{addr}")));
15892        client.cache.database = Some(database.clone());
15893        client
15894            .cache
15895            .ensure_execution_transaction_schema()
15896            .await
15897            .unwrap();
15898        let (intent, persisted_hash, _) = persist_test_wrap_broadcast(&database, None).await;
15899        protect_test_storage(&mut client, &schema).await;
15900        assert_eq!(persisted_hash, expected_hash);
15901
15902        let snapshot = database
15903            .load_execution_verification_migration_snapshot(42_161, WALLET)
15904            .await
15905            .unwrap();
15906        let nonce_verification = required_verification(
15907            client
15908                .verification
15909                .verify_transaction_count(&Address::from_str(WALLET).unwrap(), FIXTURE_BLOCK + 1)
15910                .await,
15911            "test migration nonce",
15912        )
15913        .unwrap();
15914        let headers = [
15915            VerifiedBlockHeader {
15916                number: FIXTURE_BLOCK,
15917                hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
15918                parent_hash: B256::from_str(
15919                    "0x0000000000000000000000000000000000000000000000000000000000000001",
15920                )
15921                .unwrap(),
15922                timestamp: FIXTURE_BLOCK_TIMESTAMP,
15923                base_fee_per_gas: Some(100_000_000),
15924            },
15925            VerifiedBlockHeader {
15926                number: FIXTURE_BLOCK + 1,
15927                hash: B256::from([0x22; 32]),
15928                parent_hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
15929                timestamp: FIXTURE_BLOCK_TIMESTAMP + 1,
15930                base_fee_per_gas: Some(100_000_000),
15931            },
15932        ];
15933        let migration = client
15934            .build_execution_verification_migration(
15935                snapshot,
15936                headers[1],
15937                &headers,
15938                &nonce_verification,
15939            )
15940            .await
15941            .unwrap();
15942        let finalized_headers = headers
15943            .iter()
15944            .map(|header| ExecutionVerifiedHeader {
15945                number: header.number,
15946                hash: header.hash.to_string(),
15947                parent_hash: header.parent_hash.to_string(),
15948                timestamp: header.timestamp,
15949                base_fee_per_gas: header.base_fee_per_gas,
15950            })
15951            .collect::<Vec<_>>();
15952        let decisions = [verification_decision(
15953            &nonce_verification,
15954            Some(FIXTURE_BLOCK + 1),
15955            Some(FIXTURE_BLOCK + 1),
15956        )];
15957
15958        initialize_test_verification_migration(
15959            &client,
15960            &finalized_headers,
15961            8,
15962            &decisions,
15963            &migration,
15964        )
15965        .await;
15966
15967        let migrated = database.get_execution_intent(intent.id).await.unwrap();
15968        let resume = database
15969            .load_execution_verification_resume(
15970                42_161,
15971                WALLET,
15972                &client
15973                    .config
15974                    .verification
15975                    .as_ref()
15976                    .unwrap()
15977                    .manifest_version,
15978                &client.config.verification.as_ref().unwrap().manifest_digest,
15979            )
15980            .await
15981            .unwrap()
15982            .unwrap();
15983        let evidence: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
15984            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
15985             WHERE intent_id = $1 AND decision_class = 'migration'"
15986        )))
15987        .bind(intent.id)
15988        .fetch_one(&admin_pool)
15989        .await
15990        .unwrap();
15991
15992        assert_eq!(migrated.status, "finalized");
15993        assert!(migrated.active);
15994        assert_eq!(resume.next_canonical_nonce, 8);
15995        assert!(evidence >= 5);
15996
15997        drop_execution_schema(&admin_pool, &schema).await;
15998    }
15999
16000    #[tokio::test]
16001    async fn verification_resume_accepts_one_consumed_owned_nonce() {
16002        let Some((admin_pool, schema, client, _)) = execution_client_with_database(
16003            "verification_resume_owned_nonce_test",
16004            ready_rpc_state(),
16005        )
16006        .await
16007        else {
16008            return;
16009        };
16010        let database = client.cache.database.as_ref().unwrap();
16011        persist_test_wrap_broadcast(database, client.payload_keys.as_deref()).await;
16012        let resume = database
16013            .load_execution_verification_resume(
16014                42_161,
16015                WALLET,
16016                &client
16017                    .config
16018                    .verification
16019                    .as_ref()
16020                    .unwrap()
16021                    .manifest_version,
16022                &client.config.verification.as_ref().unwrap().manifest_digest,
16023            )
16024            .await
16025            .unwrap()
16026            .unwrap();
16027
16028        ensure_test_verification_ledger(&client, &resume.finalized_headers, 7, 8)
16029            .await
16030            .unwrap();
16031
16032        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
16033            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
16034        )))
16035        .fetch_one(&admin_pool)
16036        .await
16037        .unwrap();
16038        assert_eq!(nonce_state, (7, 0));
16039
16040        drop_execution_schema(&admin_pool, &schema).await;
16041    }
16042
16043    #[tokio::test]
16044    async fn verification_resume_rejects_unowned_nonce_advance() {
16045        for (test_name, mutation, observed_canonical_nonce) in [
16046            ("verification_resume_no_active_test", "no_active", 8),
16047            ("verification_resume_excess_test", "unchanged", 9),
16048            ("verification_resume_signed_test", "signed", 8),
16049            ("verification_resume_prepared_test", "prepared", 8),
16050            (
16051                "verification_resume_missing_payload_test",
16052                "missing_payload",
16053                8,
16054            ),
16055        ] {
16056            let Some((admin_pool, schema, client, _)) =
16057                execution_client_with_database(test_name, ready_rpc_state()).await
16058            else {
16059                return;
16060            };
16061            let database = client.cache.database.as_ref().unwrap();
16062            let (intent, _, _) =
16063                persist_test_wrap_broadcast(database, client.payload_keys.as_deref()).await;
16064
16065            match mutation {
16066                "no_active" => {
16067                    sqlx::query(sqlx::AssertSqlSafe(format!(
16068                        "UPDATE {schema}.execution_intent SET active = FALSE WHERE id = $1"
16069                    )))
16070                    .bind(intent.id)
16071                    .execute(&admin_pool)
16072                    .await
16073                    .unwrap();
16074                }
16075                "signed" => {
16076                    sqlx::query(sqlx::AssertSqlSafe(format!(
16077                        "UPDATE {schema}.execution_intent SET status = 'signed' WHERE id = $1"
16078                    )))
16079                    .bind(intent.id)
16080                    .execute(&admin_pool)
16081                    .await
16082                    .unwrap();
16083                    sqlx::query(sqlx::AssertSqlSafe(format!(
16084                        "UPDATE {schema}.execution_transaction_hash SET status = 'signed' \
16085                         WHERE intent_id = $1"
16086                    )))
16087                    .bind(intent.id)
16088                    .execute(&admin_pool)
16089                    .await
16090                    .unwrap();
16091                }
16092                "prepared" => {
16093                    sqlx::query(sqlx::AssertSqlSafe(format!(
16094                        "UPDATE {schema}.execution_intent \
16095                         SET nonce = NULL, status = 'prepared' WHERE id = $1"
16096                    )))
16097                    .bind(intent.id)
16098                    .execute(&admin_pool)
16099                    .await
16100                    .unwrap();
16101                    sqlx::query(sqlx::AssertSqlSafe(format!(
16102                        "UPDATE {schema}.execution_transaction_hash SET current = FALSE \
16103                         WHERE intent_id = $1"
16104                    )))
16105                    .bind(intent.id)
16106                    .execute(&admin_pool)
16107                    .await
16108                    .unwrap();
16109                }
16110                "missing_payload" => {
16111                    sqlx::query(sqlx::AssertSqlSafe(format!(
16112                        "UPDATE {schema}.execution_transaction_hash \
16113                         SET payload_expected = FALSE, sealed_transaction = NULL \
16114                         WHERE intent_id = $1"
16115                    )))
16116                    .bind(intent.id)
16117                    .execute(&admin_pool)
16118                    .await
16119                    .unwrap();
16120                }
16121                "unchanged" => {}
16122                _ => unreachable!(),
16123            }
16124            let resume = database
16125                .load_execution_verification_resume(
16126                    42_161,
16127                    WALLET,
16128                    &client
16129                        .config
16130                        .verification
16131                        .as_ref()
16132                        .unwrap()
16133                        .manifest_version,
16134                    &client.config.verification.as_ref().unwrap().manifest_digest,
16135                )
16136                .await
16137                .unwrap()
16138                .unwrap();
16139
16140            let error = ensure_test_verification_ledger(
16141                &client,
16142                &resume.finalized_headers,
16143                7,
16144                observed_canonical_nonce,
16145            )
16146            .await
16147            .unwrap_err();
16148
16149            assert!(
16150                error
16151                    .to_string()
16152                    .contains(if observed_canonical_nonce == 9 {
16153                        "outside the owned recovery range"
16154                    } else {
16155                        "without"
16156                    }),
16157                "{mutation}: {error}"
16158            );
16159            let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
16160                "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
16161            )))
16162            .fetch_one(&admin_pool)
16163            .await
16164            .unwrap();
16165            assert_eq!(nonce_state, (7, 0), "{mutation}");
16166
16167            drop_execution_schema(&admin_pool, &schema).await;
16168        }
16169    }
16170
16171    #[tokio::test]
16172    async fn restart_marks_prepared_intent_recoverable_without_broadcast() {
16173        let Some((admin_pool, schema, client, state)) =
16174            execution_client_with_database("execution_prepared_restart_test", ready_rpc_state())
16175                .await
16176        else {
16177            return;
16178        };
16179        let database = client.cache.database.as_ref().unwrap();
16180        let intent = reserve_test_wrap_intent(database).await;
16181        *client.in_flight.lock() = Some(InFlightSlot::Preparing(TransactionPurpose::Wrap));
16182
16183        client.reconcile_unresolved_execution().await.unwrap();
16184
16185        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
16186            "SELECT status, active FROM {schema}.execution_intent WHERE id = {}",
16187            intent.id
16188        )))
16189        .fetch_one(&admin_pool)
16190        .await
16191        .unwrap();
16192        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16193            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
16194        )))
16195        .fetch_all(&admin_pool)
16196        .await
16197        .unwrap();
16198
16199        assert_eq!(status, "recoverable");
16200        assert!(!active);
16201        assert_eq!(transitions, ["prepared", "recoverable"]);
16202        assert!(client.in_flight.lock().is_none());
16203        assert!(
16204            state
16205                .recorded_requests()
16206                .iter()
16207                .all(|request| request["method"] != "eth_sendRawTransaction")
16208        );
16209
16210        drop_execution_schema(&admin_pool, &schema).await;
16211    }
16212
16213    #[tokio::test]
16214    async fn protected_restart_authenticates_envelope_before_recovery() {
16215        let initial_state = broadcast_rpc_state()
16216            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16217            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
16218        let Some((admin_pool, schema, mut first_client, _)) =
16219            execution_client_with_database("protected_restart_test", initial_state).await
16220        else {
16221            return;
16222        };
16223        let database = first_client.cache.database.as_ref().unwrap().clone();
16224        let value = U256::from(1_000_000_000_000_000_u64);
16225        let expected_hash = expected_wrap_tx_hash(value).await;
16226
16227        let error = first_client.wrap(value).await.unwrap_err();
16228
16229        assert!(error.to_string().contains("Timed out awaiting finality"));
16230        let intent = database
16231            .get_active_execution_intent(42161, WALLET)
16232            .await
16233            .unwrap()
16234            .unwrap();
16235        let payload = database
16236            .get_execution_transaction_hashes(intent.id)
16237            .await
16238            .unwrap()
16239            .pop()
16240            .unwrap();
16241        assert!(payload.raw_transaction.is_none());
16242        assert!(payload.sealed_transaction.is_some());
16243        let keys = first_client.payload_keys.take().unwrap();
16244        drop(first_client);
16245
16246        let block = finalized_wrap_block(expected_hash);
16247        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
16248        let restart_state = with_finalized_identity(
16249            execution_rpc_state()
16250                .with_response("eth_getTransactionReceipt", &receipt)
16251                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
16252                .with_response_sequence(
16253                    "eth_call",
16254                    &[
16255                        CALL_BALANCE,
16256                        CALL_BALANCE,
16257                        CALL_BALANCE,
16258                        CALL_BALANCE_AFTER_WRAP,
16259                        CALL_BALANCE_AFTER_WRAP,
16260                        CALL_BALANCE_AFTER_WRAP,
16261                    ],
16262                ),
16263            &block,
16264            &receipt,
16265        );
16266        let addr = start_mock_rpc_server(restart_state.clone()).await;
16267        let mut restarted = test_client(format!("http://{addr}"));
16268        restarted.cache.database = Some(database);
16269        restarted.payload_keys = Some(keys);
16270        restarted.signer = Some(Arc::new(
16271            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16272        ));
16273
16274        restarted.reconcile_unresolved_execution().await.unwrap();
16275
16276        let record = restarted
16277            .cache
16278            .get_execution_transaction(42161, &expected_hash.to_string())
16279            .await
16280            .unwrap()
16281            .unwrap();
16282        let requests = restart_state.recorded_requests();
16283        assert_eq!(record.status, "finalized");
16284        assert!(restarted.in_flight.lock().is_none());
16285        assert_eq!(
16286            requests
16287                .iter()
16288                .filter(|request| request["method"] == "eth_sendRawTransaction")
16289                .count(),
16290            0
16291        );
16292
16293        drop_execution_schema(&admin_pool, &schema).await;
16294    }
16295
16296    #[tokio::test]
16297    async fn active_intent_reconciliation_waits_for_reservation_fence() {
16298        let Some((admin_pool, schema, client, _)) = execution_client_with_database(
16299            "execution_active_intent_reservation_fence_test",
16300            ready_rpc_state(),
16301        )
16302        .await
16303        else {
16304            return;
16305        };
16306        let database = client.cache.database.as_ref().unwrap().clone();
16307        let lock = PgAdvisoryLock::new(format!(
16308            "nautilus:blockchain:execution:42161:{}",
16309            WALLET.to_ascii_lowercase()
16310        ));
16311        let PgAdvisoryLockKey::BigInt(lock_key) = lock.key() else {
16312            unreachable!("string advisory locks use the 64-bit key space");
16313        };
16314        let mut reservation = admin_pool.begin().await.unwrap();
16315        sqlx::query("SELECT pg_advisory_xact_lock($1)")
16316            .bind(*lock_key)
16317            .execute(&mut *reservation)
16318            .await
16319            .unwrap();
16320        sqlx::query(sqlx::AssertSqlSafe(format!(
16321            "INSERT INTO {schema}.execution_intent (\
16322                schema_version, chain_id, wallet_address, purpose, status, transaction_to, \
16323                transaction_input, transaction_value, created_block\
16324             ) VALUES (2, $1, $2, 'wrap', 'prepared', $3, '0xd0e30db0', '1', $4)"
16325        )))
16326        .bind(42161_i32)
16327        .bind(WALLET)
16328        .bind(WETH_ADDRESS.to_string())
16329        .bind(i64::try_from(FIXTURE_BLOCK).unwrap())
16330        .execute(&mut *reservation)
16331        .await
16332        .unwrap();
16333
16334        let mut reconciliation = Box::pin(database.get_active_execution_intent(42161, WALLET));
16335        assert!(
16336            tokio::time::timeout(Duration::from_millis(100), &mut reconciliation)
16337                .await
16338                .is_err(),
16339            "reconciliation did not wait for the reservation fence"
16340        );
16341
16342        reservation.commit().await.unwrap();
16343        let intent = tokio::time::timeout(Duration::from_secs(2), reconciliation)
16344            .await
16345            .unwrap()
16346            .unwrap()
16347            .unwrap();
16348
16349        assert_eq!(intent.chain_id, 42161);
16350        assert_eq!(intent.wallet_address, WALLET);
16351        assert_eq!(intent.purpose, "wrap");
16352        assert_eq!(intent.status, "prepared");
16353        assert!(intent.active);
16354
16355        drop_execution_schema(&admin_pool, &schema).await;
16356    }
16357
16358    #[tokio::test]
16359    async fn restart_keeps_unbroadcast_signed_intent_reserved() {
16360        let Some((admin_pool, schema, client, state)) =
16361            execution_client_with_database("execution_signed_restart_test", ready_rpc_state())
16362                .await
16363        else {
16364            return;
16365        };
16366        let database = client.cache.database.as_ref().unwrap();
16367        let intent = reserve_test_wrap_intent(database).await;
16368        let transaction = build_eip1559_transaction(
16369            42161,
16370            7,
16371            78_000,
16372            130_000_000,
16373            10_000_000,
16374            WETH_ADDRESS,
16375            U256::from(1u64),
16376            Bytes::from(nautilus_core::hex::decode("d0e30db0").unwrap()),
16377        );
16378        let (tx_hash, raw_transaction) = sign_eip1559_transaction(
16379            transaction,
16380            &PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16381        )
16382        .await
16383        .unwrap();
16384        database
16385            .assign_execution_intent_nonce(intent.id, 7)
16386            .await
16387            .unwrap();
16388        let intent = database.get_execution_intent(intent.id).await.unwrap();
16389        persist_test_payload(
16390            database,
16391            client.payload_keys.as_deref(),
16392            &intent,
16393            tx_hash,
16394            &raw_transaction,
16395        )
16396        .await;
16397
16398        let error = client.reconcile_unresolved_execution().await.unwrap_err();
16399
16400        assert!(
16401            error
16402                .to_string()
16403                .contains("was not authorized for broadcast"),
16404            "was: {error}"
16405        );
16406        let recovery = recovering_in_flight(&client);
16407        assert_eq!(recovery.intent_id, intent.id);
16408        assert_eq!(recovery.nonce, 7);
16409        assert_eq!(recovery.purpose, TransactionPurpose::Wrap);
16410        assert_eq!(
16411            execution_intent_markers(&admin_pool, &schema).await,
16412            vec![("wrap".into(), "signed".into(), false, true)]
16413        );
16414        assert!(
16415            state
16416                .recorded_requests()
16417                .iter()
16418                .all(|request| request["method"] != "eth_sendRawTransaction")
16419        );
16420
16421        drop_execution_schema(&admin_pool, &schema).await;
16422    }
16423
16424    #[tokio::test]
16425    async fn restart_quarantines_legacy_recoverable_signed_intent() {
16426        let Some((admin_pool, schema, client, state)) = execution_client_with_database(
16427            "execution_legacy_recoverable_restart_test",
16428            ready_rpc_state(),
16429        )
16430        .await
16431        else {
16432            return;
16433        };
16434        let database = client.cache.database.as_ref().unwrap();
16435        let intent = reserve_test_wrap_intent(database).await;
16436        let tx_hash = B256::from([0x55; 32]);
16437        database
16438            .assign_execution_intent_nonce(intent.id, 7)
16439            .await
16440            .unwrap();
16441        let intent = database.get_execution_intent(intent.id).await.unwrap();
16442        persist_test_payload(
16443            database,
16444            client.payload_keys.as_deref(),
16445            &intent,
16446            tx_hash,
16447            &[0x01, 0x02, 0x03],
16448        )
16449        .await;
16450        sqlx::query(sqlx::AssertSqlSafe(format!(
16451            "UPDATE {schema}.execution_intent SET status = 'recoverable', active = FALSE WHERE id = {}",
16452            intent.id
16453        )))
16454        .execute(&admin_pool)
16455        .await
16456        .unwrap();
16457
16458        let error = client.reconcile_unresolved_execution().await.unwrap_err();
16459
16460        assert!(
16461            error
16462                .to_string()
16463                .contains("retains signed transaction bytes"),
16464            "was: {error}"
16465        );
16466        assert!(client.in_flight.lock().is_none());
16467        assert!(
16468            state
16469                .recorded_requests()
16470                .iter()
16471                .all(|request| request["method"] != "eth_sendRawTransaction")
16472        );
16473
16474        drop_execution_schema(&admin_pool, &schema).await;
16475    }
16476
16477    #[rstest]
16478    #[case::current("execution_invalid_signed_restart_test", false, "broadcast")]
16479    #[case::historical("execution_invalid_historical_restart_test", true, "replaced")]
16480    #[tokio::test]
16481    async fn restart_rejects_invalid_signed_bytes_before_recovery_effects(
16482        #[case] test_name: &str,
16483        #[case] historical: bool,
16484        #[case] expected_status: &str,
16485    ) {
16486        let Some((admin_pool, schema, first_client, state, _)) =
16487            swap_client_with_database(test_name, ready_rpc_state()).await
16488        else {
16489            return;
16490        };
16491        let database = first_client.cache.database.as_ref().unwrap().clone();
16492        let (intent, _) =
16493            persist_invalid_test_swap(&database, first_client.payload_keys.as_deref()).await;
16494
16495        if historical {
16496            sqlx::query(sqlx::AssertSqlSafe(format!(
16497                "UPDATE {schema}.execution_transaction_hash \
16498                 SET current = FALSE, status = 'replaced' WHERE intent_id = $1"
16499            )))
16500            .bind(intent.id)
16501            .execute(&admin_pool)
16502            .await
16503            .unwrap();
16504            sqlx::query(sqlx::AssertSqlSafe(format!(
16505                "INSERT INTO {schema}.execution_transaction_hash (\
16506                     intent_id, chain_id, transaction_hash, payload_expected, status, current\
16507                 ) VALUES ($1, 42161, $2, FALSE, 'replaced', TRUE)"
16508            )))
16509            .bind(intent.id)
16510            .bind(B256::from([0x44; 32]).to_string())
16511            .execute(&admin_pool)
16512            .await
16513            .unwrap();
16514            sqlx::query(sqlx::AssertSqlSafe(format!(
16515                "UPDATE {schema}.execution_intent SET status = 'replaced' WHERE id = $1"
16516            )))
16517            .bind(intent.id)
16518            .execute(&admin_pool)
16519            .await
16520            .unwrap();
16521        }
16522        let transitions_before: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16523            "SELECT COUNT(*) FROM {schema}.execution_transaction_transition"
16524        )))
16525        .fetch_one(&admin_pool)
16526        .await
16527        .unwrap();
16528        let config = first_client.config.clone();
16529        let payload_keys = first_client.payload_keys.clone();
16530        drop(first_client);
16531
16532        let (mut restarted, _) = swap_client_with_cache(config);
16533        restarted.cache.database = Some(database);
16534        restarted.payload_keys = payload_keys;
16535        restarted.signer = Some(Arc::new(
16536            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16537        ));
16538        let mut receiver = start_with_events(&mut restarted);
16539
16540        let error = restarted
16541            .reconcile_unresolved_execution()
16542            .await
16543            .unwrap_err();
16544
16545        let recovery = recovering_in_flight(&restarted);
16546        let (status, acknowledgement_emitted, active): (String, bool, bool) =
16547            sqlx::query_as(sqlx::AssertSqlSafe(format!(
16548                "SELECT status, acknowledgement_emitted, active FROM {schema}.execution_intent"
16549            )))
16550            .fetch_one(&admin_pool)
16551            .await
16552            .unwrap();
16553        let transitions_after: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16554            "SELECT COUNT(*) FROM {schema}.execution_transaction_transition"
16555        )))
16556        .fetch_one(&admin_pool)
16557        .await
16558        .unwrap();
16559
16560        assert!(
16561            error
16562                .to_string()
16563                .contains("is not a complete EIP-2718 envelope"),
16564            "was: {error}"
16565        );
16566        assert_eq!(recovery.intent_id, intent.id);
16567        assert_eq!(recovery.nonce, 7);
16568        assert_eq!(recovery.purpose, TransactionPurpose::Swap);
16569        assert_eq!(status, expected_status);
16570        assert!(!acknowledgement_emitted);
16571        assert!(active);
16572        assert_eq!(transitions_after, transitions_before);
16573        assert!(collect_order_events(&mut receiver).is_empty());
16574        assert!(
16575            state
16576                .recorded_requests()
16577                .iter()
16578                .all(|request| request["method"] != "eth_sendRawTransaction")
16579        );
16580
16581        drop_execution_schema(&admin_pool, &schema).await;
16582    }
16583
16584    #[tokio::test]
16585    async fn restart_rebroadcasts_only_durably_authorized_bytes() {
16586        let Some((admin_pool, schema, first_client, _)) =
16587            execution_client_with_database("execution_broadcast_restart_test", ready_rpc_state())
16588                .await
16589        else {
16590            return;
16591        };
16592        let database = first_client.cache.database.as_ref().unwrap().clone();
16593        let (_, _, raw_tx) =
16594            persist_test_wrap_broadcast(&database, first_client.payload_keys.as_deref()).await;
16595        let payload_keys = first_client.payload_keys.clone();
16596        drop(first_client);
16597
16598        let restart_state = execution_rpc_state()
16599            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
16600            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16601            .with_response("eth_call", CALL_EMPTY)
16602            .with_send_raw_transaction_echo();
16603        let addr = start_mock_rpc_server(restart_state.clone()).await;
16604        let mut restarted = test_client(format!("http://{addr}"));
16605        restarted.cache.database = Some(database);
16606        restarted.payload_keys = payload_keys;
16607        restarted.signer = Some(Arc::new(
16608            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16609        ));
16610
16611        restarted.reconcile_unresolved_execution().await.unwrap();
16612
16613        let broadcasts = restart_state
16614            .recorded_requests()
16615            .into_iter()
16616            .filter(|request| request["method"] == "eth_sendRawTransaction")
16617            .collect::<Vec<_>>();
16618        assert_eq!(broadcasts.len(), 1);
16619        assert_eq!(broadcasts[0]["params"][0], hex::encode_prefixed(&raw_tx));
16620        assert_eq!(
16621            execution_intent_markers(&admin_pool, &schema).await,
16622            vec![("wrap".into(), "dropped".into(), false, true)]
16623        );
16624
16625        drop_execution_schema(&admin_pool, &schema).await;
16626    }
16627
16628    #[tokio::test]
16629    async fn restart_suppresses_rebroadcast_when_canonical_nonce_advanced() {
16630        let Some((admin_pool, schema, first_client, _)) = execution_client_with_database(
16631            "execution_rebroadcast_nonce_advanced_test",
16632            ready_rpc_state(),
16633        )
16634        .await
16635        else {
16636            return;
16637        };
16638        let database = first_client.cache.database.as_ref().unwrap().clone();
16639        let (intent, _, _) =
16640            persist_test_wrap_broadcast(&database, first_client.payload_keys.as_deref()).await;
16641        let payload_keys = first_client.payload_keys.clone();
16642        drop(first_client);
16643
16644        let mut empty_block: serde_json::Value =
16645            serde_json::from_str(&replacement_head_block(B256::from([0x44; 32]))).unwrap();
16646        empty_block["result"]["transactions"] = serde_json::json!([]);
16647        let empty_block = empty_block.to_string();
16648        let restart_state = execution_rpc_state()
16649            .with_response("eth_getTransactionCount", TRANSACTION_COUNT_NEXT)
16650            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16651            .with_response("eth_call", CALL_EMPTY)
16652            .with_parameter_response("eth_getBlockByNumber", "0x1cf0d40", &empty_block)
16653            .with_send_raw_transaction_echo();
16654        let addr = start_mock_rpc_server(restart_state.clone()).await;
16655        let mut restarted = test_client(format!("http://{addr}"));
16656        restarted.cache.database = Some(database);
16657        restarted.payload_keys = payload_keys;
16658        restarted.signer = Some(Arc::new(
16659            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16660        ));
16661
16662        let error = restarted
16663            .reconcile_unresolved_execution()
16664            .await
16665            .unwrap_err();
16666
16667        let requests = restart_state.recorded_requests();
16668        assert!(
16669            requests
16670                .iter()
16671                .all(|request| request["method"] != "eth_sendRawTransaction")
16672        );
16673        assert!(requests.iter().all(|request| {
16674            request["method"] != "eth_call" || request["params"][0]["data"] != "0xd0e30db0"
16675        }));
16676        let decision_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16677            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
16678             WHERE intent_id = $1 AND decision_class = 'rebroadcast'"
16679        )))
16680        .bind(intent.id)
16681        .fetch_one(&admin_pool)
16682        .await
16683        .unwrap();
16684        assert!(
16685            error
16686                .to_string()
16687                .contains("without an authenticated signer transaction"),
16688            "was: {error}"
16689        );
16690        assert_eq!(decision_count, 6);
16691        let replacement_decision_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16692            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
16693                 WHERE intent_id = $1 AND decision_class = 'replacement_scan'"
16694        )))
16695        .bind(intent.id)
16696        .fetch_one(&admin_pool)
16697        .await
16698        .unwrap();
16699        assert_eq!(replacement_decision_count, 2);
16700        let nonce_state = sqlx::query_as::<_, (i64, i64)>(sqlx::AssertSqlSafe(format!(
16701            "SELECT next_canonical_nonce, revision FROM {schema}.execution_verification_nonce"
16702        )))
16703        .fetch_one(&admin_pool)
16704        .await
16705        .unwrap();
16706        assert_eq!(nonce_state, (7, 0));
16707
16708        drop_execution_schema(&admin_pool, &schema).await;
16709    }
16710
16711    #[tokio::test]
16712    async fn restart_suppresses_rebroadcast_when_receipt_exists() {
16713        let Some((admin_pool, schema, first_client, _)) = execution_client_with_database(
16714            "execution_rebroadcast_receipt_present_test",
16715            ready_rpc_state(),
16716        )
16717        .await
16718        else {
16719            return;
16720        };
16721        let database = first_client.cache.database.as_ref().unwrap().clone();
16722        let (intent, _, _) =
16723            persist_test_wrap_broadcast(&database, first_client.payload_keys.as_deref()).await;
16724        let payload_keys = first_client.payload_keys.clone();
16725        drop(first_client);
16726
16727        let restart_state = execution_rpc_state()
16728            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
16729            .with_response("eth_getTransactionReceipt", RECEIPT_SUCCESS)
16730            .with_response("eth_call", CALL_EMPTY)
16731            .with_send_raw_transaction_echo();
16732        let addr = start_mock_rpc_server(restart_state.clone()).await;
16733        let mut restarted = test_client(format!("http://{addr}"));
16734        restarted.cache.database = Some(database);
16735        restarted.payload_keys = payload_keys;
16736        restarted.signer = Some(Arc::new(
16737            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16738        ));
16739
16740        let error = restarted
16741            .reconcile_unresolved_execution()
16742            .await
16743            .unwrap_err();
16744
16745        assert!(
16746            error
16747                .to_string()
16748                .contains("finalized transaction verification is locally invalid"),
16749            "was: {error}"
16750        );
16751        let requests = restart_state.recorded_requests();
16752        assert!(
16753            requests
16754                .iter()
16755                .all(|request| request["method"] != "eth_sendRawTransaction")
16756        );
16757        assert!(requests.iter().all(|request| {
16758            request["method"] != "eth_call" || request["params"][0]["data"] != "0xd0e30db0"
16759        }));
16760        let decision_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16761            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
16762             WHERE intent_id = $1 AND decision_class = 'rebroadcast'"
16763        )))
16764        .bind(intent.id)
16765        .fetch_one(&admin_pool)
16766        .await
16767        .unwrap();
16768        assert_eq!(decision_count, 6);
16769
16770        drop_execution_schema(&admin_pool, &schema).await;
16771    }
16772
16773    #[rstest]
16774    #[case("execution_rebroadcast_false_test", CALL_ZERO)]
16775    #[case("execution_rebroadcast_revert_test", CALL_REVERTED)]
16776    #[tokio::test]
16777    async fn restart_suppresses_rebroadcast_when_simulation_denies(
16778        #[case] test_name: &str,
16779        #[case] simulation_response: &str,
16780    ) {
16781        let Some((admin_pool, schema, first_client, _)) =
16782            execution_client_with_database(test_name, ready_rpc_state()).await
16783        else {
16784            return;
16785        };
16786        let database = first_client.cache.database.as_ref().unwrap().clone();
16787        let (intent, _, _) =
16788            persist_test_wrap_broadcast(&database, first_client.payload_keys.as_deref()).await;
16789        let payload_keys = first_client.payload_keys.clone();
16790        drop(first_client);
16791
16792        let restart_state = execution_rpc_state()
16793            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
16794            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16795            .with_response("eth_call", simulation_response)
16796            .with_send_raw_transaction_echo();
16797        let addr = start_mock_rpc_server(restart_state.clone()).await;
16798        let mut restarted = test_client(format!("http://{addr}"));
16799        restarted.cache.database = Some(database);
16800        restarted.payload_keys = payload_keys;
16801        restarted.signer = Some(Arc::new(
16802            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16803        ));
16804
16805        restarted.reconcile_unresolved_execution().await.unwrap();
16806
16807        let requests = restart_state.recorded_requests();
16808        assert!(
16809            requests
16810                .iter()
16811                .all(|request| request["method"] != "eth_sendRawTransaction")
16812        );
16813        let simulation_calls = requests
16814            .iter()
16815            .filter(|request| {
16816                request["method"] == "eth_call"
16817                    && request["params"][0]["data"] == "0xd0e30db0"
16818                    && request["params"][1] == FIXTURE_BLOCK_PARAM
16819            })
16820            .count();
16821        assert_eq!(simulation_calls, 3);
16822        let decision_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16823            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
16824             WHERE intent_id = $1 AND decision_class = 'rebroadcast'"
16825        )))
16826        .bind(intent.id)
16827        .fetch_one(&admin_pool)
16828        .await
16829        .unwrap();
16830        assert_eq!(decision_count, 7);
16831
16832        drop_execution_schema(&admin_pool, &schema).await;
16833    }
16834
16835    #[tokio::test]
16836    async fn restart_wrap_identity_mismatch_keeps_signer_ownership() {
16837        let initial_state = broadcast_rpc_state()
16838            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16839            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
16840        let Some((admin_pool, schema, mut first_client, _)) =
16841            execution_client_with_database("execution_restart_mismatch_test", initial_state).await
16842        else {
16843            return;
16844        };
16845        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
16846        let error = first_client
16847            .wrap(U256::from(1_000_000_000_000_000_u64))
16848            .await
16849            .unwrap_err();
16850        assert!(
16851            error.to_string().contains("Timed out awaiting finality"),
16852            "was: {error}"
16853        );
16854        let database = first_client.cache.database.as_ref().unwrap().clone();
16855        let payload_keys = first_client.payload_keys.clone();
16856        drop(first_client);
16857
16858        // The finalized transaction carries no value, so it cannot be the persisted wrap
16859        let mismatched_block = serde_json::json!({
16860            "jsonrpc": "2.0",
16861            "id": 1,
16862            "result": {
16863                "number": "0x1cf0d41",
16864                "hash": "0x2222222222222222222222222222222222222222222222222222222222222222",
16865                "parentHash": FIXTURE_BLOCK_HASH,
16866                "timestamp": "0x69044a21",
16867                "baseFeePerGas": "0x5f5e100",
16868                "transactions": [{
16869                    "hash": expected_hash.to_string(),
16870                    "from": WALLET,
16871                    "nonce": "0x7",
16872                    "chainId": "0xa4b1",
16873                    "type": "0x2",
16874                    "to": WETH,
16875                    "input": "0xd0e30db0",
16876                    "value": "0x0",
16877                    "gas": "0x130b0",
16878                    "maxFeePerGas": "0x7bfa480",
16879                    "maxPriorityFeePerGas": "0x989680"
16880                }]
16881            }
16882        })
16883        .to_string();
16884        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
16885        let restart_state = with_finalized_identity(
16886            execution_rpc_state()
16887                .with_response("eth_getTransactionReceipt", &receipt)
16888                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &mismatched_block),
16889            &mismatched_block,
16890            &receipt,
16891        );
16892        let addr = start_mock_rpc_server(restart_state.clone()).await;
16893        let mut restarted = test_client(format!("http://{addr}"));
16894        restarted.cache.database = Some(database);
16895        restarted.payload_keys = payload_keys;
16896        restarted.signer = Some(Arc::new(
16897            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16898        ));
16899
16900        let error = restarted
16901            .reconcile_unresolved_execution()
16902            .await
16903            .unwrap_err();
16904
16905        assert!(
16906            error
16907                .to_string()
16908                .contains("finalized transaction identity mismatch"),
16909            "was: {error}"
16910        );
16911        let in_flight = awaiting_in_flight(&restarted);
16912        assert_eq!(in_flight.nonce, 7);
16913        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
16914        assert_eq!(in_flight.tx_hash, expected_hash);
16915        let requests = restart_state.recorded_requests();
16916        assert!(
16917            requests.iter().all(|request| {
16918                request["method"] != "eth_call"
16919                    || !request["params"][0]["data"]
16920                        .as_str()
16921                        .is_some_and(|data| data.starts_with(BALANCE_OF_SELECTOR))
16922            }),
16923            "the postcondition must not run when call identity is unproven"
16924        );
16925        assert!(
16926            requests
16927                .iter()
16928                .all(|request| request["method"] != "eth_sendRawTransaction")
16929        );
16930        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
16931            "SELECT status, active FROM {schema}.execution_intent"
16932        )))
16933        .fetch_one(&admin_pool)
16934        .await
16935        .unwrap();
16936        assert_eq!(status, "dropped");
16937        assert!(active);
16938
16939        let database = restarted.cache.database.as_ref().unwrap().clone();
16940        let payload_keys = restarted.payload_keys.clone();
16941        drop(restarted);
16942        let mut second = test_client(format!("http://{addr}"));
16943        second.cache.database = Some(database);
16944        second.payload_keys = payload_keys;
16945        second.signer = Some(Arc::new(
16946            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
16947        ));
16948        let error = second.reconcile_unresolved_execution().await.unwrap_err();
16949        assert!(
16950            error
16951                .to_string()
16952                .contains("finalized transaction identity mismatch"),
16953            "was: {error}"
16954        );
16955        let active: bool = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
16956            "SELECT active FROM {schema}.execution_intent"
16957        )))
16958        .fetch_one(&admin_pool)
16959        .await
16960        .unwrap();
16961        assert!(active);
16962
16963        drop_execution_schema(&admin_pool, &schema).await;
16964    }
16965
16966    #[tokio::test]
16967    async fn restart_wrap_postcondition_failure_keeps_signer_ownership() {
16968        let initial_state = broadcast_rpc_state()
16969            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
16970            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
16971        let Some((admin_pool, schema, mut first_client, _)) =
16972            execution_client_with_database("execution_restart_postcondition_test", initial_state)
16973                .await
16974        else {
16975            return;
16976        };
16977        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
16978        let error = first_client
16979            .wrap(U256::from(1_000_000_000_000_000_u64))
16980            .await
16981            .unwrap_err();
16982        assert!(
16983            error.to_string().contains("Timed out awaiting finality"),
16984            "was: {error}"
16985        );
16986        let database = first_client.cache.database.as_ref().unwrap().clone();
16987        let payload_keys = first_client.payload_keys.clone();
16988        drop(first_client);
16989
16990        // Call identity matches, but the wrapped balance does not increase
16991        let failing_wrap_state = || {
16992            let block = finalized_wrap_block(expected_hash);
16993            let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
16994            with_finalized_identity(
16995                execution_rpc_state()
16996                    .with_response("eth_getTransactionReceipt", &receipt)
16997                    .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
16998                    .with_response_sequence("eth_call", &[CALL_BALANCE; 6]),
16999                &block,
17000                &receipt,
17001            )
17002        };
17003        let restart_state = failing_wrap_state();
17004        let addr = start_mock_rpc_server(restart_state.clone()).await;
17005        let mut restarted = test_client(format!("http://{addr}"));
17006        restarted.cache.database = Some(database);
17007        restarted.payload_keys = payload_keys;
17008        restarted.signer = Some(Arc::new(
17009            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17010        ));
17011
17012        let error = restarted
17013            .reconcile_unresolved_execution()
17014            .await
17015            .unwrap_err();
17016
17017        assert!(
17018            error.to_string().contains("did not increase by"),
17019            "was: {error}"
17020        );
17021        let in_flight = awaiting_in_flight(&restarted);
17022        assert_eq!(in_flight.nonce, 7);
17023        assert_eq!(in_flight.purpose, TransactionPurpose::Wrap);
17024        assert!(
17025            restart_state
17026                .recorded_requests()
17027                .iter()
17028                .all(|request| request["method"] != "eth_sendRawTransaction")
17029        );
17030        assert_eq!(
17031            execution_intent_markers(&admin_pool, &schema).await,
17032            vec![("wrap".into(), "dropped".into(), false, true)]
17033        );
17034
17035        let addr = start_mock_rpc_server(failing_wrap_state()).await;
17036        let error = later_reconnect(restarted, format!("http://{addr}")).await;
17037        assert!(
17038            error.to_string().contains("did not increase by"),
17039            "was: {error}"
17040        );
17041        assert_eq!(
17042            execution_intent_markers(&admin_pool, &schema).await,
17043            vec![("wrap".into(), "dropped".into(), false, true)]
17044        );
17045
17046        drop_execution_schema(&admin_pool, &schema).await;
17047    }
17048
17049    #[tokio::test]
17050    async fn restart_wrap_revert_marks_terminal_and_releases() {
17051        let initial_state = broadcast_rpc_state()
17052            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
17053            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
17054        let Some((admin_pool, schema, mut first_client, _)) =
17055            execution_client_with_database("execution_restart_wrap_revert_test", initial_state)
17056                .await
17057        else {
17058            return;
17059        };
17060        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
17061        let error = first_client
17062            .wrap(U256::from(1_000_000_000_000_000_u64))
17063            .await
17064            .unwrap_err();
17065        assert!(
17066            error.to_string().contains("Timed out awaiting finality"),
17067            "was: {error}"
17068        );
17069        let database = first_client.cache.database.as_ref().unwrap().clone();
17070        let payload_keys = first_client.payload_keys.clone();
17071        drop(first_client);
17072
17073        let block = finalized_wrap_block(expected_hash);
17074        let receipt = receipt_with_transaction_hash(RECEIPT_REVERTED, expected_hash);
17075        let restart_state = with_finalized_identity(
17076            execution_rpc_state()
17077                .with_response("eth_getTransactionReceipt", &receipt)
17078                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block),
17079            &block,
17080            &receipt,
17081        );
17082        let addr = start_mock_rpc_server(restart_state.clone()).await;
17083        let mut restarted = test_client(format!("http://{addr}"));
17084        restarted.cache.database = Some(database);
17085        restarted.payload_keys = payload_keys;
17086        restarted.signer = Some(Arc::new(
17087            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17088        ));
17089
17090        restarted.reconcile_unresolved_execution().await.unwrap();
17091
17092        assert!(restarted.in_flight.lock().is_none());
17093        assert!(
17094            restart_state
17095                .recorded_requests()
17096                .iter()
17097                .all(|request| request["method"] != "eth_sendRawTransaction")
17098        );
17099        assert_eq!(
17100            execution_intent_markers(&admin_pool, &schema).await,
17101            vec![("wrap".into(), "reverted".into(), true, false)]
17102        );
17103
17104        drop_execution_schema(&admin_pool, &schema).await;
17105    }
17106
17107    #[tokio::test]
17108    async fn restart_quarantines_unretained_same_nonce_wrap_replacement() {
17109        let initial_state = broadcast_rpc_state()
17110            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
17111            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE);
17112        let Some((admin_pool, schema, mut first_client, _)) =
17113            execution_client_with_database("execution_restart_replacement_test", initial_state)
17114                .await
17115        else {
17116            return;
17117        };
17118        let original_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000_u64)).await;
17119        let error = first_client
17120            .wrap(U256::from(1_000_000_000_000_000_u64))
17121            .await
17122            .unwrap_err();
17123        assert!(
17124            error.to_string().contains("Timed out awaiting finality"),
17125            "was: {error}"
17126        );
17127        let database = first_client.cache.database.as_ref().unwrap().clone();
17128        let payload_keys = first_client.payload_keys.clone();
17129        drop(first_client);
17130
17131        // Matching call fields do not authenticate an unknown same-nonce payload.
17132        let replacement_hash = B256::from([0x44; 32]);
17133        let restart_state = execution_rpc_state()
17134            .with_response("eth_getTransactionCount", TRANSACTION_COUNT_NEXT)
17135            .with_response_sequence("eth_call", &[CALL_BALANCE, CALL_BALANCE_AFTER_WRAP])
17136            .with_response_sequence(
17137                "eth_getTransactionReceipt",
17138                &[RECEIPT_NULL, RECEIPT_NULL, RECEIPT_NULL],
17139            )
17140            .with_parameter_response(
17141                "eth_getBlockByNumber",
17142                "0x1cf0d40",
17143                &replacement_head_block(replacement_hash),
17144            )
17145            .with_parameter_response(
17146                "eth_getBlockByNumber",
17147                "0x1cf0d41",
17148                &finalized_wrap_block(replacement_hash),
17149            );
17150        let addr = start_mock_rpc_server(restart_state.clone()).await;
17151        let mut restarted = test_client(format!("http://{addr}"));
17152        restarted.cache.database = Some(database);
17153        restarted.payload_keys = payload_keys;
17154        restarted.signer = Some(Arc::new(
17155            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17156        ));
17157        restarted.transaction_limits.receipt_timeout_secs = 2;
17158
17159        let error = restarted
17160            .reconcile_unresolved_execution()
17161            .await
17162            .unwrap_err();
17163
17164        let hashes: Vec<(String, String, bool)> = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17165            "SELECT transaction_hash, status, current FROM \
17166                 {schema}.execution_transaction_hash ORDER BY id"
17167        )))
17168        .fetch_all(&admin_pool)
17169        .await
17170        .unwrap();
17171        let requests = restart_state.recorded_requests();
17172
17173        assert!(
17174            error
17175                .to_string()
17176                .contains("has no authenticated retained payload"),
17177            "was: {error}"
17178        );
17179        assert_eq!(
17180            hashes,
17181            [(original_hash.to_string(), "dropped".to_string(), true)]
17182        );
17183        assert!(restarted.in_flight.lock().is_some());
17184        assert_eq!(
17185            execution_intent_markers(&admin_pool, &schema).await,
17186            vec![("wrap".into(), "dropped".into(), false, true)]
17187        );
17188        assert_eq!(
17189            requests
17190                .iter()
17191                .filter(|request| request["method"] == "eth_getTransactionReceipt")
17192                .count(),
17193            3
17194        );
17195        assert!(requests.iter().all(|request| {
17196            request["method"] != "eth_call" || request["params"][0]["data"] != "0xd0e30db0"
17197        }));
17198        assert!(
17199            requests
17200                .iter()
17201                .all(|request| request["method"] != "eth_sendRawTransaction")
17202        );
17203
17204        drop_execution_schema(&admin_pool, &schema).await;
17205    }
17206
17207    #[tokio::test]
17208    async fn replacement_scan_accepts_only_an_authenticated_retained_payload() {
17209        let expected_hash = expected_wrap_tx_hash(U256::from(1_u64)).await;
17210        let mut replacement_block: serde_json::Value =
17211            serde_json::from_str(&replacement_head_block(expected_hash)).unwrap();
17212        replacement_block["result"]["transactions"][1]["value"] = serde_json::json!("0x1");
17213        let replacement_block = replacement_block.to_string();
17214        let state = execution_rpc_state().with_parameter_response(
17215            "eth_getBlockByNumber",
17216            "0x1cf0d40",
17217            &replacement_block,
17218        );
17219        let Some((admin_pool, schema, client, _)) =
17220            execution_client_with_database("replacement_scan_authenticated", state).await
17221        else {
17222            return;
17223        };
17224        let database = client.cache.database.as_ref().unwrap();
17225        let (intent, persisted_hash, persisted_raw) =
17226            persist_test_wrap_broadcast(database, client.payload_keys.as_deref()).await;
17227        assert_eq!(persisted_hash, expected_hash);
17228        let authenticated_payloads = HashMap::from([(expected_hash, persisted_raw.clone())]);
17229        let head = VerifiedBlockHeader {
17230            number: FIXTURE_BLOCK,
17231            hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
17232            parent_hash: B256::from_str(
17233                "0x0000000000000000000000000000000000000000000000000000000000000001",
17234            )
17235            .unwrap(),
17236            timestamp: FIXTURE_BLOCK_TIMESTAMP,
17237            base_fee_per_gas: Some(100_000_000),
17238        };
17239
17240        let matched = client
17241            .transaction_executor()
17242            .unwrap()
17243            .scan_canonical_replacement(&intent, 7, head, &authenticated_payloads)
17244            .await
17245            .unwrap()
17246            .unwrap();
17247
17248        assert_eq!(matched, (expected_hash, persisted_raw));
17249        let cursor: (i64, String) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17250            "SELECT finalized_cursor_number, finalized_cursor_hash \
17251             FROM {schema}.execution_replacement_scan WHERE intent_id = $1"
17252        )))
17253        .bind(intent.id)
17254        .fetch_one(&admin_pool)
17255        .await
17256        .unwrap();
17257        assert_eq!(
17258            cursor,
17259            (FIXTURE_BLOCK as i64, FIXTURE_BLOCK_HASH.to_string())
17260        );
17261        let evidence_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17262            "SELECT COUNT(*) FROM {schema}.execution_verification_decision \
17263             WHERE intent_id = $1 AND decision_class = 'replacement_scan'"
17264        )))
17265        .bind(intent.id)
17266        .fetch_one(&admin_pool)
17267        .await
17268        .unwrap();
17269        assert_eq!(evidence_count, 2);
17270
17271        drop_execution_schema(&admin_pool, &schema).await;
17272    }
17273
17274    #[tokio::test]
17275    async fn restart_reconciles_finalized_approve_after_validation() {
17276        let initial_state = broadcast_rpc_state()
17277            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
17278            .with_response("eth_call", CALL_BOOL_TRUE)
17279            .with_call_response_sequence(ALLOWANCE_SELECTOR, &[CALL_ZERO; 3])
17280            .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO);
17281        let Some((admin_pool, schema, mut first_client, _)) =
17282            execution_client_with_database("execution_restart_approve_test", initial_state).await
17283        else {
17284            return;
17285        };
17286        let expected_hash = expected_approve_tx_hash(U256::from(1_000u64)).await;
17287        let error = first_client
17288            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
17289            .await
17290            .unwrap_err();
17291        assert!(
17292            error.to_string().contains("Timed out awaiting finality"),
17293            "was: {error}"
17294        );
17295        let database = first_client.cache.database.as_ref().unwrap().clone();
17296        let payload_keys = first_client.payload_keys.clone();
17297        drop(first_client);
17298
17299        let block = finalized_approve_block(expected_hash, U256::from(1_000u64));
17300        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
17301        let restart_state = with_finalized_identity(
17302            execution_rpc_state()
17303                .with_response("eth_getTransactionReceipt", &receipt)
17304                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
17305                .with_call_response(ALLOWANCE_SELECTOR, CALL_ALLOWANCE_1000),
17306            &block,
17307            &receipt,
17308        );
17309        let addr = start_mock_rpc_server(restart_state.clone()).await;
17310        let mut restarted = test_client(format!("http://{addr}"));
17311        restarted.cache.database = Some(database);
17312        restarted.payload_keys = payload_keys;
17313        restarted.signer = Some(Arc::new(
17314            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17315        ));
17316
17317        restarted.reconcile_unresolved_execution().await.unwrap();
17318
17319        let record = restarted
17320            .cache
17321            .get_execution_transaction(42161, &expected_hash.to_string())
17322            .await
17323            .unwrap()
17324            .unwrap();
17325        let requests = restart_state.recorded_requests();
17326        assert_eq!(record.status, "finalized");
17327        assert_eq!(record.purpose, "approve");
17328        assert!(restarted.in_flight.lock().is_none());
17329        assert_eq!(
17330            execution_intent_markers(&admin_pool, &schema).await,
17331            vec![("approve".into(), "finalized".into(), true, false)]
17332        );
17333        assert_eq!(
17334            requests
17335                .iter()
17336                .filter(|request| {
17337                    request["method"] == "eth_call"
17338                        && request["params"][0]["data"]
17339                            .as_str()
17340                            .is_some_and(|data| data.starts_with(ALLOWANCE_SELECTOR))
17341                })
17342                .count(),
17343            3
17344        );
17345        assert_eq!(
17346            requests
17347                .iter()
17348                .filter(|request| request["method"] == "eth_sendRawTransaction")
17349                .count(),
17350            0
17351        );
17352
17353        drop_execution_schema(&admin_pool, &schema).await;
17354    }
17355
17356    #[tokio::test]
17357    async fn restart_approve_postcondition_failure_keeps_signer_ownership() {
17358        let initial_state = broadcast_rpc_state()
17359            .with_response("eth_getTransactionReceipt", RECEIPT_NULL)
17360            .with_response("eth_call", CALL_BOOL_TRUE)
17361            .with_call_response_sequence(ALLOWANCE_SELECTOR, &[CALL_ZERO; 3])
17362            .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO);
17363        let Some((admin_pool, schema, mut first_client, _)) =
17364            execution_client_with_database("execution_restart_approve_post_test", initial_state)
17365                .await
17366        else {
17367            return;
17368        };
17369        let expected_hash = expected_approve_tx_hash(U256::from(1_000u64)).await;
17370        let error = first_client
17371            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
17372            .await
17373            .unwrap_err();
17374        assert!(
17375            error.to_string().contains("Timed out awaiting finality"),
17376            "was: {error}"
17377        );
17378        let database = first_client.cache.database.as_ref().unwrap().clone();
17379        let payload_keys = first_client.payload_keys.clone();
17380        drop(first_client);
17381
17382        // Call identity matches, but the allowance does not equal the approved amount
17383        let block = finalized_approve_block(expected_hash, U256::from(1_000u64));
17384        let receipt = receipt_with_transaction_hash(RECEIPT_SUCCESS, expected_hash);
17385        let restart_state = with_finalized_identity(
17386            execution_rpc_state()
17387                .with_response("eth_getTransactionReceipt", &receipt)
17388                .with_parameter_response("eth_getBlockByNumber", "0x1cf0d41", &block)
17389                .with_call_response(ALLOWANCE_SELECTOR, CALL_ZERO),
17390            &block,
17391            &receipt,
17392        );
17393        let addr = start_mock_rpc_server(restart_state.clone()).await;
17394        let mut restarted = test_client(format!("http://{addr}"));
17395        restarted.cache.database = Some(database);
17396        restarted.payload_keys = payload_keys;
17397        restarted.signer = Some(Arc::new(
17398            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
17399        ));
17400
17401        let error = restarted
17402            .reconcile_unresolved_execution()
17403            .await
17404            .unwrap_err();
17405
17406        assert!(
17407            error
17408                .to_string()
17409                .contains("does not equal the requested amount"),
17410            "was: {error}"
17411        );
17412        let in_flight = awaiting_in_flight(&restarted);
17413        assert_eq!(in_flight.nonce, 7);
17414        assert_eq!(in_flight.purpose, TransactionPurpose::Approve);
17415        assert!(
17416            restart_state
17417                .recorded_requests()
17418                .iter()
17419                .all(|request| request["method"] != "eth_sendRawTransaction")
17420        );
17421        assert_eq!(
17422            execution_intent_markers(&admin_pool, &schema).await,
17423            vec![("approve".into(), "dropped".into(), false, true)]
17424        );
17425
17426        let error = later_reconnect(restarted, format!("http://{addr}")).await;
17427        assert!(
17428            error
17429                .to_string()
17430                .contains("does not equal the requested amount"),
17431            "was: {error}"
17432        );
17433        assert_eq!(
17434            execution_intent_markers(&admin_pool, &schema).await,
17435            vec![("approve".into(), "dropped".into(), false, true)]
17436        );
17437
17438        drop_execution_schema(&admin_pool, &schema).await;
17439    }
17440
17441    #[tokio::test]
17442    async fn disappearing_unfinalized_receipt_drops_without_committing_inclusion() {
17443        let state = execution_rpc_state()
17444            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
17445            .with_response("eth_estimateGas", ESTIMATE_GAS)
17446            .with_response("eth_call", CALL_BALANCE)
17447            .with_response_sequence(
17448                "eth_getTransactionReceipt",
17449                &[
17450                    RECEIPT_SUCCESS,
17451                    RECEIPT_SUCCESS,
17452                    RECEIPT_SUCCESS,
17453                    RECEIPT_NULL,
17454                    RECEIPT_NULL,
17455                    RECEIPT_NULL,
17456                ],
17457            )
17458            .with_parameter_response("eth_getBlockByNumber", "finalized", BLOCK_BY_NUMBER)
17459            .with_send_raw_transaction_echo();
17460        let Some((admin_pool, schema, mut client, _)) =
17461            execution_client_with_database("execution_receipt_disappeared_test", state).await
17462        else {
17463            return;
17464        };
17465        client.transaction_limits.receipt_timeout_secs = 2;
17466
17467        let error = client
17468            .wrap(U256::from(1_000_000_000_000_000_u64))
17469            .await
17470            .unwrap_err();
17471        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17472            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
17473        )))
17474        .fetch_all(&admin_pool)
17475        .await
17476        .unwrap();
17477
17478        assert!(
17479            error.to_string().contains("Timed out awaiting finality"),
17480            "was: {error}"
17481        );
17482        assert_eq!(transitions, ["prepared", "signed", "broadcast", "dropped"]);
17483        assert!(client.in_flight.lock().is_some());
17484
17485        drop_execution_schema(&admin_pool, &schema).await;
17486    }
17487
17488    #[tokio::test]
17489    async fn changed_unfinalized_block_drops_without_committing_inclusion() {
17490        let changed_block = serde_json::json!({
17491            "jsonrpc": "2.0",
17492            "id": 1,
17493            "result": {
17494                "number": "0x1cf0d41",
17495                "hash": "0x4444444444444444444444444444444444444444444444444444444444444444",
17496                "parentHash": FIXTURE_BLOCK_HASH,
17497                "timestamp": "0x69044a21",
17498                "baseFeePerGas": "0x5f5e100",
17499                "transactions": []
17500            }
17501        })
17502        .to_string();
17503        let state = execution_rpc_state()
17504            .with_response("eth_getTransactionCount", TRANSACTION_COUNT)
17505            .with_response("eth_estimateGas", ESTIMATE_GAS)
17506            .with_response("eth_call", CALL_BALANCE)
17507            .with_response_sequence(
17508                "eth_getTransactionReceipt",
17509                &[
17510                    RECEIPT_SUCCESS,
17511                    RECEIPT_SUCCESS,
17512                    RECEIPT_SUCCESS,
17513                    RECEIPT_SUCCESS,
17514                    RECEIPT_SUCCESS,
17515                    RECEIPT_SUCCESS,
17516                ],
17517            )
17518            .with_parameter_response_sequence(
17519                "eth_getBlockByNumber",
17520                "0x1cf0d41",
17521                &[
17522                    BLOCK_CANONICAL,
17523                    BLOCK_CANONICAL,
17524                    BLOCK_CANONICAL,
17525                    &changed_block,
17526                    &changed_block,
17527                    &changed_block,
17528                ],
17529            )
17530            .with_parameter_response("eth_getBlockByNumber", "finalized", BLOCK_BY_NUMBER)
17531            .with_send_raw_transaction_echo();
17532        let Some((admin_pool, schema, mut client, _)) =
17533            execution_client_with_database("execution_reorg_test", state).await
17534        else {
17535            return;
17536        };
17537        client.transaction_limits.receipt_timeout_secs = 2;
17538
17539        let error = client
17540            .wrap(U256::from(1_000_000_000_000_000_u64))
17541            .await
17542            .unwrap_err();
17543        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17544            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
17545        )))
17546        .fetch_all(&admin_pool)
17547        .await
17548        .unwrap();
17549
17550        assert!(
17551            error.to_string().contains("Timed out awaiting finality"),
17552            "was: {error}"
17553        );
17554        assert_eq!(transitions, ["prepared", "signed", "broadcast", "dropped"]);
17555        assert!(client.in_flight.lock().is_some());
17556
17557        drop_execution_schema(&admin_pool, &schema).await;
17558    }
17559
17560    #[tokio::test]
17561    async fn pre_sign_pending_nonce_drift_blocks_wrap_before_signature() {
17562        let state = execution_rpc_state()
17563            .with_response_sequence(
17564                "eth_getTransactionCount",
17565                &[
17566                    TRANSACTION_COUNT,
17567                    TRANSACTION_COUNT,
17568                    TRANSACTION_COUNT,
17569                    TRANSACTION_COUNT_NEXT,
17570                    TRANSACTION_COUNT_NEXT,
17571                    TRANSACTION_COUNT_NEXT,
17572                ],
17573            )
17574            .with_response("eth_estimateGas", ESTIMATE_GAS)
17575            .with_call_response(BALANCE_OF_SELECTOR, CALL_BALANCE)
17576            .with_send_raw_transaction_echo();
17577        let Some((admin_pool, schema, mut client, state)) =
17578            execution_client_with_database("pre_sign_pending_nonce_drift", state).await
17579        else {
17580            return;
17581        };
17582
17583        let error = client
17584            .wrap(U256::from(1_000_000_000_000_000_u64))
17585            .await
17586            .unwrap_err();
17587        let signed_count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17588            "SELECT COUNT(*) FROM {schema}.execution_transaction_hash"
17589        )))
17590        .fetch_one(&admin_pool)
17591        .await
17592        .unwrap();
17593
17594        assert!(
17595            error
17596                .to_string()
17597                .contains("Pending nonce does not match the verified canonical nonce"),
17598            "was: {error}"
17599        );
17600        assert_eq!(signed_count, 0);
17601        assert!(
17602            state
17603                .recorded_requests()
17604                .iter()
17605                .all(|request| request["method"] != "eth_sendRawTransaction")
17606        );
17607        assert!(client.in_flight.lock().is_none());
17608
17609        drop_execution_schema(&admin_pool, &schema).await;
17610    }
17611
17612    #[tokio::test]
17613    async fn unknown_same_nonce_swap_replacement_emits_no_rejection() {
17614        let replacement_hash = B256::from([0x44; 32]);
17615        let replacement_block = replacement_head_block(replacement_hash);
17616        let state = execution_rpc_state()
17617            .with_parameter_response("eth_getBlockByNumber", "0x1cf0d40", &replacement_block)
17618            .with_send_raw_transaction_echo();
17619        let Some((admin_pool, schema, mut client, _, _)) =
17620            swap_client_with_database("unknown_same_nonce_swap_replacement", state).await
17621        else {
17622            return;
17623        };
17624        let mut receiver = start_with_events(&mut client);
17625        let database = client.cache.database.as_ref().unwrap();
17626        let (intent, original_hash, original_payload) =
17627            persist_test_swap_broadcast(database, client.payload_keys.as_deref()).await;
17628        let authenticated_payloads = HashMap::from([(original_hash, original_payload)]);
17629        let head = VerifiedBlockHeader {
17630            number: FIXTURE_BLOCK,
17631            hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
17632            parent_hash: B256::from_str(
17633                "0x0000000000000000000000000000000000000000000000000000000000000001",
17634            )
17635            .unwrap(),
17636            timestamp: FIXTURE_BLOCK_TIMESTAMP,
17637            base_fee_per_gas: Some(100_000_000),
17638        };
17639
17640        let error = client
17641            .transaction_executor()
17642            .unwrap()
17643            .scan_canonical_replacement(&intent, 7, head, &authenticated_payloads)
17644            .await
17645            .unwrap_err();
17646        let events = collect_order_events(&mut receiver);
17647        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17648            "SELECT status, active FROM {schema}.execution_intent"
17649        )))
17650        .fetch_one(&admin_pool)
17651        .await
17652        .unwrap();
17653
17654        assert!(
17655            error
17656                .to_string()
17657                .contains("has no authenticated retained payload"),
17658            "was: {error}"
17659        );
17660        assert!(events.is_empty(), "was: {events:?}");
17661        assert_eq!(status, "broadcast");
17662        assert!(active);
17663
17664        drop_execution_schema(&admin_pool, &schema).await;
17665    }
17666
17667    #[tokio::test]
17668    async fn replacement_scan_rejects_rpc_fields_that_conflict_with_the_payload() {
17669        let expected_hash = expected_wrap_tx_hash(U256::from(1_u64)).await;
17670        let mut replacement_block: serde_json::Value =
17671            serde_json::from_str(&replacement_head_block(expected_hash)).unwrap();
17672        replacement_block["result"]["transactions"][1]["value"] = serde_json::json!("0x2");
17673        let replacement_block = replacement_block.to_string();
17674        let state = execution_rpc_state().with_parameter_response(
17675            "eth_getBlockByNumber",
17676            "0x1cf0d40",
17677            &replacement_block,
17678        );
17679        let Some((admin_pool, schema, client, _)) =
17680            execution_client_with_database("replacement_scan_payload_mismatch", state).await
17681        else {
17682            return;
17683        };
17684        let database = client.cache.database.as_ref().unwrap();
17685        let (intent, persisted_hash, persisted_payload) =
17686            persist_test_wrap_broadcast(database, client.payload_keys.as_deref()).await;
17687        assert_eq!(persisted_hash, expected_hash);
17688        let authenticated_payloads = HashMap::from([(persisted_hash, persisted_payload)]);
17689        let head = VerifiedBlockHeader {
17690            number: FIXTURE_BLOCK,
17691            hash: B256::from_str(FIXTURE_BLOCK_HASH).unwrap(),
17692            parent_hash: B256::from_str(
17693                "0x0000000000000000000000000000000000000000000000000000000000000001",
17694            )
17695            .unwrap(),
17696            timestamp: FIXTURE_BLOCK_TIMESTAMP,
17697            base_fee_per_gas: Some(100_000_000),
17698        };
17699
17700        let error = client
17701            .transaction_executor()
17702            .unwrap()
17703            .scan_canonical_replacement(&intent, 7, head, &authenticated_payloads)
17704            .await
17705            .unwrap_err();
17706        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17707            "SELECT status, active FROM {schema}.execution_intent"
17708        )))
17709        .fetch_one(&admin_pool)
17710        .await
17711        .unwrap();
17712
17713        assert!(
17714            error
17715                .to_string()
17716                .contains("failed authenticated payload validation"),
17717            "was: {error}"
17718        );
17719        assert_eq!(status, "broadcast");
17720        assert!(active);
17721
17722        drop_execution_schema(&admin_pool, &schema).await;
17723    }
17724
17725    #[tokio::test]
17726    async fn execution_transaction_constraints_reject_conflicting_identity() {
17727        const TRANSACTION_HASH: &str = "0xduplicate-transaction-hash";
17728        const OTHER_WALLET: &str = "0x0000000000000000000000000000000000000001";
17729        let Some((admin_pool, schema, client, _)) = execution_client_with_unprotected_database(
17730            "execution_duplicate_record_test",
17731            ready_rpc_state(),
17732        )
17733        .await
17734        else {
17735            return;
17736        };
17737        let database = client.cache.database.as_ref().unwrap();
17738        let operator = database
17739            .reserve_execution_intent(&ExecutionIntentInsert {
17740                chain_id: 42161,
17741                wallet_address: WALLET.to_string(),
17742                purpose: "wrap".to_string(),
17743                client_order_id: None,
17744                trader_id: None,
17745                strategy_id: None,
17746                account_id: None,
17747                instrument_id: None,
17748                pool_address: None,
17749                transaction_to: WETH_ADDRESS.to_string(),
17750                transaction_input: "0xd0e30db0".to_string(),
17751                transaction_value: "1".to_string(),
17752                amount_in: None,
17753                created_block: FIXTURE_BLOCK,
17754            })
17755            .await
17756            .unwrap();
17757        database
17758            .assign_execution_intent_nonce(operator.id, 7)
17759            .await
17760            .unwrap();
17761        database
17762            .add_execution_transaction_hash(operator.id, 42161, TRANSACTION_HASH, &[1, 2, 3])
17763            .await
17764            .unwrap();
17765        database
17766            .add_execution_transaction_hash(operator.id, 42161, TRANSACTION_HASH, &[1, 2, 3])
17767            .await
17768            .unwrap();
17769
17770        let signer_conflict = database
17771            .reserve_execution_intent(&ExecutionIntentInsert {
17772                chain_id: 42161,
17773                wallet_address: WALLET.to_string(),
17774                purpose: "approve".to_string(),
17775                client_order_id: None,
17776                trader_id: None,
17777                strategy_id: None,
17778                account_id: None,
17779                instrument_id: None,
17780                pool_address: None,
17781                transaction_to: ROUTER_ADDRESS.to_string(),
17782                transaction_input: "0x01".to_string(),
17783                transaction_value: "0".to_string(),
17784                amount_in: None,
17785                created_block: FIXTURE_BLOCK,
17786            })
17787            .await
17788            .unwrap_err();
17789        let other = database
17790            .reserve_execution_intent(&ExecutionIntentInsert {
17791                chain_id: 42161,
17792                wallet_address: OTHER_WALLET.to_string(),
17793                purpose: "approve".to_string(),
17794                client_order_id: None,
17795                trader_id: None,
17796                strategy_id: None,
17797                account_id: None,
17798                instrument_id: None,
17799                pool_address: None,
17800                transaction_to: ROUTER_ADDRESS.to_string(),
17801                transaction_input: "0x01".to_string(),
17802                transaction_value: "0".to_string(),
17803                amount_in: None,
17804                created_block: FIXTURE_BLOCK,
17805            })
17806            .await
17807            .unwrap();
17808        database
17809            .assign_execution_intent_nonce(other.id, 7)
17810            .await
17811            .unwrap();
17812        let hash_conflict = database
17813            .add_execution_transaction_hash(other.id, 42161, TRANSACTION_HASH, &[4, 5, 6])
17814            .await
17815            .unwrap_err();
17816
17817        let record = database
17818            .get_execution_transaction(42161, TRANSACTION_HASH)
17819            .await
17820            .unwrap()
17821            .unwrap();
17822        let count: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17823            "SELECT COUNT(*) FROM {schema}.execution_intent"
17824        )))
17825        .fetch_one(&admin_pool)
17826        .await
17827        .unwrap();
17828
17829        assert_eq!(record.wallet_address.as_deref(), Some(WALLET));
17830        assert_eq!(record.nonce, 7);
17831        assert_eq!(record.transaction_hash, TRANSACTION_HASH);
17832        assert_eq!(record.purpose, "wrap");
17833        assert_eq!(record.status, "signed");
17834        assert_eq!(record.client_order_id, None);
17835        assert!(
17836            hash_conflict
17837                .to_string()
17838                .contains("conflicts with its persisted identity"),
17839            "was: {hash_conflict}"
17840        );
17841        assert_eq!(
17842            signer_conflict.to_string(),
17843            "Execution intent reservation failed before commit"
17844        );
17845        assert!(
17846            signer_conflict.chain().any(|cause| cause
17847                .to_string()
17848                .contains("execution_intent_active_signer_key")),
17849            "was: {signer_conflict:#}"
17850        );
17851        assert_eq!(count, 2);
17852
17853        drop_execution_schema(&admin_pool, &schema).await;
17854    }
17855
17856    #[tokio::test]
17857    async fn execution_status_transitions_are_idempotent() {
17858        const TRANSACTION_HASH: &str =
17859            "0x5555555555555555555555555555555555555555555555555555555555555555";
17860        let Some((admin_pool, schema, client, _)) = execution_client_with_unprotected_database(
17861            "execution_transition_test",
17862            ready_rpc_state(),
17863        )
17864        .await
17865        else {
17866            return;
17867        };
17868        let database = client.cache.database.as_ref().unwrap();
17869        let intent = database
17870            .reserve_execution_intent(&ExecutionIntentInsert {
17871                chain_id: 42161,
17872                wallet_address: WALLET.to_string(),
17873                purpose: "wrap".to_string(),
17874                client_order_id: None,
17875                trader_id: None,
17876                strategy_id: None,
17877                account_id: None,
17878                instrument_id: None,
17879                pool_address: None,
17880                transaction_to: WETH_ADDRESS.to_string(),
17881                transaction_input: "0xd0e30db0".to_string(),
17882                transaction_value: "1".to_string(),
17883                amount_in: None,
17884                created_block: FIXTURE_BLOCK,
17885            })
17886            .await
17887            .unwrap();
17888        database
17889            .assign_execution_intent_nonce(intent.id, 7)
17890            .await
17891            .unwrap();
17892        database
17893            .add_execution_transaction_hash(intent.id, 42161, TRANSACTION_HASH, &[1, 2, 3])
17894            .await
17895            .unwrap();
17896
17897        for _ in 0..2 {
17898            database
17899                .record_execution_status(
17900                    intent.id,
17901                    TRANSACTION_HASH,
17902                    TransactionStatus::Broadcast,
17903                    None,
17904                    None,
17905                    None,
17906                    None,
17907                    None,
17908                )
17909                .await
17910                .unwrap();
17911        }
17912
17913        for status in [TransactionStatus::Included, TransactionStatus::Included] {
17914            database
17915                .record_execution_status(
17916                    intent.id,
17917                    TRANSACTION_HASH,
17918                    status,
17919                    Some(FIXTURE_BLOCK + 1),
17920                    Some("0x2222222222222222222222222222222222222222222222222222222222222222"),
17921                    Some(true),
17922                    Some(50_112),
17923                    Some("100000000"),
17924                )
17925                .await
17926                .unwrap();
17927        }
17928
17929        for _ in 0..2 {
17930            database
17931                .record_execution_status(
17932                    intent.id,
17933                    TRANSACTION_HASH,
17934                    TransactionStatus::Finalized,
17935                    Some(FIXTURE_BLOCK + 1),
17936                    Some("0x2222222222222222222222222222222222222222222222222222222222222222"),
17937                    Some(true),
17938                    Some(50_112),
17939                    Some("100000000"),
17940                )
17941                .await
17942                .unwrap();
17943        }
17944
17945        let transitions: Vec<String> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
17946            "SELECT to_status FROM {schema}.execution_transaction_transition ORDER BY id"
17947        )))
17948        .fetch_all(&admin_pool)
17949        .await
17950        .unwrap();
17951        let (status, active): (String, bool) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
17952            "SELECT status, active FROM {schema}.execution_intent"
17953        )))
17954        .fetch_one(&admin_pool)
17955        .await
17956        .unwrap();
17957        let append_only_error = sqlx::query(sqlx::AssertSqlSafe(format!(
17958            "DELETE FROM {schema}.execution_transaction_transition WHERE intent_id = {}",
17959            intent.id
17960        )))
17961        .execute(&admin_pool)
17962        .await
17963        .unwrap_err();
17964
17965        assert_eq!(
17966            transitions,
17967            ["prepared", "signed", "broadcast", "included", "finalized"]
17968        );
17969        assert_eq!(status, "finalized");
17970        assert!(active);
17971        assert!(
17972            append_only_error
17973                .to_string()
17974                .contains("Execution transitions are append-only"),
17975            "was: {append_only_error}"
17976        );
17977
17978        drop_execution_schema(&admin_pool, &schema).await;
17979    }
17980
17981    #[tokio::test]
17982    async fn wrap_then_approve_persists_records_and_clears_in_flight() {
17983        let state = execution_rpc_state()
17984            .with_parameter_response_sequence(
17985                "eth_getBlockByNumber",
17986                "latest",
17987                &[
17988                    BLOCK_BY_NUMBER,
17989                    BLOCK_BY_NUMBER,
17990                    BLOCK_BY_NUMBER,
17991                    BLOCK_FINALIZED,
17992                    BLOCK_FINALIZED,
17993                    BLOCK_FINALIZED,
17994                ],
17995            )
17996            .with_response_sequence(
17997                "eth_call",
17998                &[
17999                    CALL_BALANCE,
18000                    CALL_BALANCE,
18001                    CALL_BALANCE,
18002                    CALL_BALANCE,
18003                    CALL_BALANCE,
18004                    CALL_BALANCE,
18005                    CALL_BALANCE_AFTER_WRAP,
18006                    CALL_BALANCE_AFTER_WRAP,
18007                    CALL_BALANCE_AFTER_WRAP,
18008                    CALL_BOOL_TRUE,
18009                    CALL_BOOL_TRUE,
18010                    CALL_BOOL_TRUE,
18011                ],
18012            )
18013            .with_call_response_sequence(
18014                ALLOWANCE_SELECTOR,
18015                &[
18016                    CALL_ZERO,
18017                    CALL_ZERO,
18018                    CALL_ZERO,
18019                    CALL_ALLOWANCE_MAX,
18020                    CALL_ALLOWANCE_MAX,
18021                    CALL_ALLOWANCE_MAX,
18022                ],
18023            )
18024            .with_response_sequence(
18025                "eth_getTransactionCount",
18026                &[
18027                    TRANSACTION_COUNT,
18028                    TRANSACTION_COUNT,
18029                    TRANSACTION_COUNT,
18030                    TRANSACTION_COUNT,
18031                    TRANSACTION_COUNT,
18032                    TRANSACTION_COUNT,
18033                    TRANSACTION_COUNT_NEXT,
18034                    TRANSACTION_COUNT_NEXT,
18035                    TRANSACTION_COUNT_NEXT,
18036                    TRANSACTION_COUNT_NEXT,
18037                    TRANSACTION_COUNT_NEXT,
18038                    TRANSACTION_COUNT_NEXT,
18039                ],
18040            )
18041            .with_response("eth_estimateGas", ESTIMATE_GAS)
18042            .with_response_sequence(
18043                "eth_getTransactionReceipt",
18044                &[
18045                    RECEIPT_SUCCESS,
18046                    RECEIPT_SUCCESS,
18047                    RECEIPT_SUCCESS,
18048                    RECEIPT_SUCCESS,
18049                    RECEIPT_SUCCESS,
18050                    RECEIPT_SUCCESS,
18051                ],
18052            )
18053            .with_send_raw_transaction_echo();
18054        let Some((admin_pool, schema, mut client, state)) =
18055            execution_client_with_database("execution_client_test", state).await
18056        else {
18057            return;
18058        };
18059        client.config.unlimited_approval = true;
18060        client.transaction_limits.receipt_timeout_secs = 3;
18061
18062        let wrap_hash = client
18063            .wrap(U256::from(1_000_000_000_000_000u64))
18064            .await
18065            .unwrap();
18066
18067        let record = client
18068            .cache
18069            .get_execution_transaction(42161, &wrap_hash.to_string())
18070            .await
18071            .unwrap()
18072            .unwrap();
18073        assert_eq!(record.nonce, 7);
18074        assert_eq!(record.purpose, "wrap");
18075        assert_eq!(record.status, "finalized");
18076        assert_eq!(
18077            execution_intent_markers(&admin_pool, &schema).await,
18078            vec![("wrap".into(), "finalized".into(), true, false)]
18079        );
18080
18081        let approve_hash = client
18082            .approve(WETH_ADDRESS, U256::from(1_000u64), ROUTER_ADDRESS)
18083            .await
18084            .unwrap();
18085
18086        let record = client
18087            .cache
18088            .get_execution_transaction(42161, &approve_hash.to_string())
18089            .await
18090            .unwrap()
18091            .unwrap();
18092        assert_eq!(record.nonce, 8);
18093        assert_eq!(record.purpose, "approve");
18094        assert_eq!(record.status, "finalized");
18095        assert_eq!(
18096            execution_intent_markers(&admin_pool, &schema).await,
18097            vec![
18098                ("wrap".into(), "finalized".into(), true, false),
18099                ("approve".into(), "finalized".into(), true, false),
18100            ]
18101        );
18102
18103        let requests = state.recorded_requests();
18104        let broadcasts: Vec<_> = requests
18105            .iter()
18106            .filter(|request| request["method"] == "eth_sendRawTransaction")
18107            .collect();
18108        assert_eq!(broadcasts.len(), 2);
18109        for broadcast in &broadcasts {
18110            let payload = broadcast["params"][0].as_str().unwrap();
18111            assert!(payload.starts_with("0x02"), "was: {payload}");
18112        }
18113        let broadcast_indexes = requests
18114            .iter()
18115            .enumerate()
18116            .filter_map(|(index, request)| {
18117                (request["method"] == "eth_sendRawTransaction").then_some(index)
18118            })
18119            .collect::<Vec<_>>();
18120
18121        for (index, expected_block) in broadcast_indexes
18122            .into_iter()
18123            .zip([FIXTURE_BLOCK_PARAM, "0x1cf0d42"])
18124        {
18125            let nonce_fence = &requests[index - 6..index];
18126            assert!(nonce_fence[..3].iter().all(|request| {
18127                request["method"] == "eth_getTransactionCount"
18128                    && request["params"][1] == expected_block
18129            }));
18130            assert!(nonce_fence[3..].iter().all(|request| {
18131                request["method"] == "eth_getTransactionCount" && request["params"][1] == "pending"
18132            }));
18133        }
18134        let receipt_polls = requests
18135            .iter()
18136            .filter(|request| request["method"] == "eth_getTransactionReceipt")
18137            .count();
18138        assert_eq!(receipt_polls, 6);
18139        let allowance_calls: Vec<_> = requests
18140            .iter()
18141            .filter(|request| {
18142                request["method"] == "eth_call"
18143                    && request["params"][0]["data"]
18144                        .as_str()
18145                        .is_some_and(|data| data.starts_with(ALLOWANCE_SELECTOR))
18146            })
18147            .collect();
18148        assert_eq!(allowance_calls.len(), 6);
18149        assert!(
18150            allowance_calls[..3]
18151                .iter()
18152                .all(|request| request["params"][1] == "0x1cf0d42")
18153        );
18154        assert!(
18155            allowance_calls[3..]
18156                .iter()
18157                .all(|request| request["params"][1] == "0x1cf0d41")
18158        );
18159
18160        // Unlimited approval policy encoded U256::MAX in the approve calldata
18161        let estimates: Vec<_> = requests
18162            .iter()
18163            .filter(|request| request["method"] == "eth_estimateGas")
18164            .collect();
18165        assert_eq!(estimates.len(), 6);
18166        assert!(estimates[..3].iter().all(|request| {
18167            request["params"].as_array().unwrap().len() == 2
18168                && request["params"][1] == FIXTURE_BLOCK_PARAM
18169        }));
18170        assert!(estimates[3..].iter().all(|request| {
18171            request["params"].as_array().unwrap().len() == 2 && request["params"][1] == "0x1cf0d42"
18172        }));
18173        let approve_data = estimates[3]["params"][0]["data"].as_str().unwrap();
18174        assert!(
18175            approve_data.starts_with("0x095ea7b3"),
18176            "was: {approve_data}"
18177        );
18178        assert!(
18179            approve_data.ends_with(&"f".repeat(64)),
18180            "was: {approve_data}"
18181        );
18182
18183        for selector in [FACTORY_SELECTOR, WETH9_SELECTOR] {
18184            let calls: Vec<_> = requests
18185                .iter()
18186                .filter(|request| {
18187                    request["method"] == "eth_call"
18188                        && request["params"][0]["data"]
18189                            .as_str()
18190                            .is_some_and(|data| data.starts_with(selector))
18191                })
18192                .collect();
18193            assert!(!calls.is_empty(), "selector {selector}");
18194            assert!(
18195                calls.iter().all(|request| request["params"][1]
18196                    .as_str()
18197                    .is_some_and(|block| block.starts_with("0x"))),
18198                "selector {selector}: {calls:?}"
18199            );
18200        }
18201        let latest_blocks = requests
18202            .iter()
18203            .filter(|request| {
18204                request["method"] == "eth_getBlockByNumber"
18205                    && request["params"] == serde_json::json!(["latest", false])
18206            })
18207            .count();
18208        assert_eq!(latest_blocks, 6);
18209
18210        drop_execution_schema(&admin_pool, &schema).await;
18211    }
18212
18213    #[tokio::test]
18214    async fn reverted_receipt_marks_record_reverted_and_errors() {
18215        let state = signing_rpc_state()
18216            .with_response("eth_getTransactionReceipt", RECEIPT_REVERTED)
18217            .with_send_raw_transaction_echo();
18218        let Some((admin_pool, schema, mut client, _)) =
18219            execution_client_with_database("execution_reverted_test", state).await
18220        else {
18221            return;
18222        };
18223
18224        let error = client
18225            .wrap(U256::from(1_000_000_000_000_000u64))
18226            .await
18227            .unwrap_err();
18228
18229        assert!(
18230            error.to_string().contains("reverted on-chain"),
18231            "was: {error}"
18232        );
18233        assert!(client.in_flight.lock().is_none());
18234
18235        let expected_hash = expected_wrap_tx_hash(U256::from(1_000_000_000_000_000u64)).await;
18236
18237        let record = client
18238            .cache
18239            .get_execution_transaction(42161, &expected_hash.to_string())
18240            .await
18241            .unwrap()
18242            .unwrap();
18243        assert_eq!(record.status, "reverted");
18244        assert_eq!(
18245            execution_intent_markers(&admin_pool, &schema).await,
18246            vec![("wrap".into(), "reverted".into(), true, false)]
18247        );
18248
18249        drop_execution_schema(&admin_pool, &schema).await;
18250    }
18251
18252    fn market_sell_order_with_id(instrument_id: InstrumentId, client_order_id: &str) -> OrderAny {
18253        OrderTestBuilder::new(OrderType::Market)
18254            .trader_id(TraderId::from("TRADER-001"))
18255            .strategy_id(StrategyId::from("S-001"))
18256            .instrument_id(instrument_id)
18257            .client_order_id(ClientOrderId::from(client_order_id))
18258            .side(OrderSide::Sell)
18259            .quantity(Quantity::from("0.001"))
18260            .build()
18261    }
18262
18263    fn market_buy_order_with_id(instrument_id: InstrumentId, client_order_id: &str) -> OrderAny {
18264        OrderTestBuilder::new(OrderType::Market)
18265            .trader_id(TraderId::from("TRADER-001"))
18266            .strategy_id(StrategyId::from("S-001"))
18267            .instrument_id(instrument_id)
18268            .client_order_id(ClientOrderId::from(client_order_id))
18269            .side(OrderSide::Buy)
18270            .quantity(Quantity::from("0.001"))
18271            .build()
18272    }
18273
18274    fn submit_order_list_cmd(orders: &[OrderAny]) -> SubmitOrderList {
18275        let order_list = OrderList::new(
18276            OrderListId::from("OL-001"),
18277            orders[0].instrument_id(),
18278            orders[0].strategy_id(),
18279            orders.iter().map(|order| order.client_order_id()).collect(),
18280            UnixNanos::default(),
18281        );
18282        SubmitOrderList::new(
18283            TraderId::from("TRADER-001"),
18284            Some(ClientId::from("BLOCKCHAIN-001")),
18285            orders[0].strategy_id(),
18286            order_list,
18287            orders
18288                .iter()
18289                .map(|order| order.init_event().clone())
18290                .collect(),
18291            None,
18292            None,
18293            None,
18294            UUID4::new(),
18295            UnixNanos::default(),
18296            None,
18297        )
18298    }
18299
18300    fn modify_order_cmd(
18301        instrument_id: InstrumentId,
18302        client_order_id: ClientOrderId,
18303    ) -> ModifyOrder {
18304        ModifyOrder::new(
18305            TraderId::from("TRADER-001"),
18306            Some(ClientId::from("BLOCKCHAIN-001")),
18307            StrategyId::from("S-001"),
18308            instrument_id,
18309            client_order_id,
18310            None,
18311            Some(Quantity::from("0.002")),
18312            None,
18313            None,
18314            UUID4::new(),
18315            UnixNanos::default(),
18316            None,
18317            None,
18318        )
18319    }
18320
18321    fn cancel_order_cmd(
18322        instrument_id: InstrumentId,
18323        client_order_id: ClientOrderId,
18324    ) -> CancelOrder {
18325        CancelOrder::new(
18326            TraderId::from("TRADER-001"),
18327            Some(ClientId::from("BLOCKCHAIN-001")),
18328            StrategyId::from("S-001"),
18329            instrument_id,
18330            client_order_id,
18331            None,
18332            UUID4::new(),
18333            UnixNanos::default(),
18334            None,
18335            None,
18336        )
18337    }
18338
18339    fn cancel_all_orders_cmd(instrument_id: InstrumentId) -> CancelAllOrders {
18340        CancelAllOrders::new(
18341            TraderId::from("TRADER-001"),
18342            Some(ClientId::from("BLOCKCHAIN-001")),
18343            StrategyId::from("S-001"),
18344            instrument_id,
18345            Some(OrderSide::Sell),
18346            UUID4::new(),
18347            UnixNanos::default(),
18348            None,
18349            None,
18350        )
18351    }
18352
18353    fn batch_cancel_orders_cmd(cancels: Vec<CancelOrder>) -> BatchCancelOrders {
18354        BatchCancelOrders::new(
18355            TraderId::from("TRADER-001"),
18356            Some(ClientId::from("BLOCKCHAIN-001")),
18357            StrategyId::from("S-001"),
18358            cancels[0].instrument_id,
18359            cancels,
18360            UUID4::new(),
18361            UnixNanos::default(),
18362            None,
18363            None,
18364        )
18365    }
18366
18367    fn query_order_cmd(instrument_id: InstrumentId, client_order_id: ClientOrderId) -> QueryOrder {
18368        QueryOrder::new(
18369            TraderId::from("TRADER-001"),
18370            Some(ClientId::from("BLOCKCHAIN-001")),
18371            StrategyId::from("S-001"),
18372            instrument_id,
18373            client_order_id,
18374            None,
18375            UUID4::new(),
18376            UnixNanos::default(),
18377            None,
18378            None,
18379        )
18380    }
18381
18382    async fn unsupported_client_with_mock_rpc()
18383    -> (BlockchainExecutionClient, MockRpcState, Rc<RefCell<Cache>>) {
18384        let state = ready_rpc_state();
18385        let addr = start_mock_rpc_server(state.clone()).await;
18386        let (client, cache) = swap_client_with_cache(test_config(format!("http://{addr}")));
18387        (client, state, cache)
18388    }
18389
18390    #[tokio::test]
18391    async fn submit_order_denies_reduce_only_without_side_effects() {
18392        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18393        let order = OrderTestBuilder::new(OrderType::Market)
18394            .trader_id(TraderId::from("TRADER-001"))
18395            .strategy_id(StrategyId::from("S-001"))
18396            .instrument_id(test_pool().instrument_id)
18397            .client_order_id(ClientOrderId::from("O-REDUCE-ONLY"))
18398            .side(OrderSide::Sell)
18399            .quantity(Quantity::from("0.001"))
18400            .reduce_only(true)
18401            .build();
18402        cache
18403            .borrow_mut()
18404            .add_order(order.clone(), None, None, false)
18405            .unwrap();
18406        let mut receiver = start_with_events(&mut client);
18407
18408        client.submit_order(submit_order_cmd(&order)).unwrap();
18409
18410        let events = collect_order_events(&mut receiver);
18411        assert_eq!(events.len(), 1, "was: {events:?}");
18412        let OrderEventAny::Denied(denied) = &events[0] else {
18413            panic!("expected OrderDenied, was {:?}", events[0]);
18414        };
18415        assert_eq!(denied.client_order_id, order.client_order_id());
18416        assert_eq!(denied.reason, "UNSUPPORTED_REDUCE_ONLY");
18417        assert!(state.recorded_requests().is_empty());
18418        assert!(client.in_flight.lock().is_none());
18419    }
18420
18421    #[tokio::test]
18422    async fn submit_order_list_denies_every_order_without_side_effects() {
18423        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18424        let pool = test_pool();
18425        let first = test_market_sell_order(pool.instrument_id);
18426        let second = market_sell_order_with_id(pool.instrument_id, "O-SWAP-002");
18427        cache
18428            .borrow_mut()
18429            .add_order(second.clone(), None, None, false)
18430            .unwrap();
18431        let orders = [first.clone(), second.clone()];
18432        let mut receiver = start_with_events(&mut client);
18433
18434        client
18435            .submit_order_list(submit_order_list_cmd(&orders))
18436            .unwrap();
18437
18438        let events = collect_order_events(&mut receiver);
18439        let mut denied_ids = Vec::new();
18440
18441        for event in &events {
18442            let OrderEventAny::Denied(denied) = event else {
18443                panic!("expected OrderDenied, was {event:?}");
18444            };
18445            assert_eq!(denied.reason, ORDER_LIST_UNSUPPORTED);
18446            denied_ids.push(denied.client_order_id);
18447        }
18448        denied_ids.sort();
18449        assert_eq!(
18450            denied_ids,
18451            [first.client_order_id(), second.client_order_id()]
18452        );
18453        assert!(state.recorded_requests().is_empty());
18454        assert!(client.in_flight.lock().is_none());
18455
18456        for order in &orders {
18457            let cache_ref = cache.borrow();
18458            let cached = cache_ref.order(&order.client_order_id()).unwrap();
18459            assert_eq!(cached.status(), OrderStatus::Initialized);
18460        }
18461    }
18462
18463    #[tokio::test]
18464    async fn modify_order_denies_without_side_effects() {
18465        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18466        let order = test_market_sell_order(test_pool().instrument_id);
18467        let mut receiver = start_with_events(&mut client);
18468
18469        let command = modify_order_cmd(order.instrument_id(), order.client_order_id());
18470        let cause = command.command_id;
18471        client.modify_order(command).unwrap();
18472
18473        let events = collect_order_events(&mut receiver);
18474        assert_eq!(events.len(), 1, "was: {events:?}");
18475
18476        let OrderEventAny::ModifyDenied(rejected) = &events[0] else {
18477            panic!("expected OrderModifyDenied, was {:?}", events[0]);
18478        };
18479
18480        assert_eq!(rejected.causation_id, Some(cause));
18481        assert_eq!(rejected.client_order_id, order.client_order_id());
18482        assert_eq!(rejected.reason, ORDER_MODIFY_UNSUPPORTED);
18483        assert!(state.recorded_requests().is_empty());
18484        assert!(client.in_flight.lock().is_none());
18485        let cache_ref = cache.borrow();
18486        let cached = cache_ref.order(&order.client_order_id()).unwrap();
18487        assert_eq!(cached.status(), OrderStatus::Initialized);
18488    }
18489
18490    #[tokio::test]
18491    async fn cancel_order_denies_without_side_effects() {
18492        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18493        let order = test_market_sell_order(test_pool().instrument_id);
18494        let mut receiver = start_with_events(&mut client);
18495
18496        let command = cancel_order_cmd(order.instrument_id(), order.client_order_id());
18497        let cause = command.command_id;
18498        client.cancel_order(command).unwrap();
18499
18500        let events = collect_order_events(&mut receiver);
18501        assert_eq!(events.len(), 1, "was: {events:?}");
18502
18503        let OrderEventAny::CancelDenied(rejected) = &events[0] else {
18504            panic!("expected OrderCancelDenied, was {:?}", events[0]);
18505        };
18506
18507        assert_eq!(rejected.causation_id, Some(cause));
18508        assert_eq!(rejected.client_order_id, order.client_order_id());
18509        assert_eq!(rejected.reason, ORDER_CANCEL_UNSUPPORTED);
18510        assert!(state.recorded_requests().is_empty());
18511        assert!(client.in_flight.lock().is_none());
18512        let cache_ref = cache.borrow();
18513        let cached = cache_ref.order(&order.client_order_id()).unwrap();
18514        assert_eq!(cached.status(), OrderStatus::Initialized);
18515    }
18516
18517    #[tokio::test]
18518    async fn batch_cancel_orders_denies_each_order_without_side_effects() {
18519        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18520        let pool = test_pool();
18521        let first = test_market_sell_order(pool.instrument_id);
18522        let second = market_sell_order_with_id(pool.instrument_id, "O-SWAP-002");
18523        cache
18524            .borrow_mut()
18525            .add_order(second.clone(), None, None, false)
18526            .unwrap();
18527        let orders = [first.clone(), second.clone()];
18528        let cancels = orders
18529            .iter()
18530            .map(|order| cancel_order_cmd(order.instrument_id(), order.client_order_id()))
18531            .collect::<Vec<_>>();
18532        let causes: std::collections::HashMap<_, _> = cancels
18533            .iter()
18534            .map(|command| (command.client_order_id, command.command_id))
18535            .collect();
18536        let mut receiver = start_with_events(&mut client);
18537
18538        client
18539            .batch_cancel_orders(batch_cancel_orders_cmd(cancels))
18540            .unwrap();
18541
18542        let events = collect_order_events(&mut receiver);
18543        let mut rejected_ids = Vec::new();
18544
18545        for event in &events {
18546            let OrderEventAny::CancelDenied(rejected) = event else {
18547                panic!("expected OrderCancelDenied, was {event:?}");
18548            };
18549
18550            assert_eq!(
18551                rejected.causation_id,
18552                Some(causes[&rejected.client_order_id])
18553            );
18554            assert_eq!(rejected.reason, ORDER_CANCEL_UNSUPPORTED);
18555            rejected_ids.push(rejected.client_order_id);
18556        }
18557        rejected_ids.sort();
18558        assert_eq!(
18559            rejected_ids,
18560            [first.client_order_id(), second.client_order_id()]
18561        );
18562        assert!(state.recorded_requests().is_empty());
18563        assert!(client.in_flight.lock().is_none());
18564    }
18565
18566    #[rstest]
18567    #[case::modify(true)]
18568    #[case::cancel(false)]
18569    #[tokio::test]
18570    async fn command_denial_preserves_cached_owner(
18571        #[case] modify: bool,
18572        #[values(false, true)] cached: bool,
18573    ) {
18574        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18575        let mut order = test_market_sell_order(test_pool().instrument_id);
18576        let venue = VenueOrderId::from("V-OWNER-029");
18577        let account = AccountId::from("BLOCKCHAIN-001");
18578        let accepted = TestOrderEventStubs::accepted(&order, account, venue);
18579        order.apply(accepted.clone()).unwrap();
18580        cache.borrow_mut().update_order(&accepted).unwrap();
18581
18582        let target = if cached {
18583            order.client_order_id()
18584        } else {
18585            ClientOrderId::from("O-UNCACHED")
18586        };
18587
18588        let requester = StrategyId::from("REQUESTER-031");
18589        let explicit_venue = VenueOrderId::from("V-REQUESTER-037");
18590        let command_id = UUID4::new();
18591
18592        let pending = if modify {
18593            let mut event = OrderPendingUpdate::new(
18594                order.trader_id(),
18595                order.strategy_id(),
18596                order.instrument_id(),
18597                order.client_order_id(),
18598                Some(account),
18599                UUID4::new(),
18600                UnixNanos::default(),
18601                UnixNanos::default(),
18602                false,
18603                Some(venue),
18604            );
18605            event.causation_id = Some(command_id);
18606            OrderEventAny::PendingUpdate(event)
18607        } else {
18608            let mut event = OrderPendingCancel::new(
18609                order.trader_id(),
18610                order.strategy_id(),
18611                order.instrument_id(),
18612                order.client_order_id(),
18613                Some(account),
18614                UUID4::new(),
18615                UnixNanos::default(),
18616                UnixNanos::default(),
18617                false,
18618                Some(venue),
18619            );
18620            event.causation_id = Some(command_id);
18621            OrderEventAny::PendingCancel(event)
18622        };
18623
18624        if cached {
18625            cache.borrow_mut().update_order(&pending).unwrap();
18626        }
18627
18628        let mut receiver = start_with_events(&mut client);
18629
18630        if modify {
18631            let mut command = modify_order_cmd(order.instrument_id(), target);
18632            command.strategy_id = requester;
18633            command.venue_order_id = Some(explicit_venue);
18634            command.command_id = command_id;
18635            client.modify_order(command).unwrap();
18636        } else {
18637            let mut command = cancel_order_cmd(order.instrument_id(), target);
18638            command.strategy_id = requester;
18639            command.venue_order_id = Some(explicit_venue);
18640            command.command_id = command_id;
18641            client.cancel_order(command).unwrap();
18642        }
18643
18644        let events = collect_order_events(&mut receiver);
18645        assert_eq!(events.len(), 1);
18646        let event = &events[0];
18647        assert_eq!(
18648            event.strategy_id(),
18649            if cached {
18650                order.strategy_id()
18651            } else {
18652                requester
18653            }
18654        );
18655        assert_eq!(event.client_order_id(), target);
18656        assert_eq!(event.instrument_id(), order.instrument_id());
18657        assert_eq!(
18658            event.venue_order_id(),
18659            Some(if cached { venue } else { explicit_venue })
18660        );
18661
18662        let cause = match event {
18663            OrderEventAny::ModifyDenied(denied) => {
18664                assert!(modify);
18665                denied.causation_id
18666            }
18667            OrderEventAny::CancelDenied(denied) => {
18668                assert!(!modify);
18669                denied.causation_id
18670            }
18671            other => panic!("expected command denial, was {other:?}"),
18672        };
18673
18674        assert_eq!(cause, Some(command_id));
18675
18676        if cached {
18677            cache.borrow_mut().update_order(event).unwrap();
18678            let after = cache.borrow().try_order_owned(&target).unwrap();
18679            assert_eq!(after.status(), OrderStatus::Accepted);
18680            assert_eq!(after.quantity(), order.quantity());
18681            assert_eq!(after.filled_qty(), order.filled_qty());
18682            assert!(!after.has_pending_update_command());
18683            assert!(!after.has_pending_cancel_command());
18684        } else {
18685            assert!(cache.borrow().order_ref(&target).is_none());
18686        }
18687
18688        assert!(state.recorded_requests().is_empty());
18689        assert!(client.in_flight.lock().is_none());
18690    }
18691
18692    #[tokio::test]
18693    async fn cancel_all_and_query_order_log_unsupported_without_side_effects() {
18694        let (mut client, state, cache) = unsupported_client_with_mock_rpc().await;
18695        let order = test_market_sell_order(test_pool().instrument_id);
18696        let mut receiver = start_with_events(&mut client);
18697
18698        client
18699            .cancel_all_orders(cancel_all_orders_cmd(order.instrument_id()))
18700            .unwrap();
18701        client
18702            .query_order(query_order_cmd(
18703                order.instrument_id(),
18704                order.client_order_id(),
18705            ))
18706            .unwrap();
18707
18708        let events = collect_order_events(&mut receiver);
18709        assert!(events.is_empty(), "was: {events:?}");
18710        assert!(state.recorded_requests().is_empty());
18711        assert!(client.in_flight.lock().is_none());
18712        let cache_ref = cache.borrow();
18713        let cached = cache_ref.order(&order.client_order_id()).unwrap();
18714        assert_eq!(cached.status(), OrderStatus::Initialized);
18715    }
18716
18717    #[tokio::test]
18718    async fn unsupported_commands_handle_unknown_orders_without_panic() {
18719        let (mut client, state, _) = unsupported_client_with_mock_rpc().await;
18720        let instrument_id = test_pool().instrument_id;
18721        let unknown = ClientOrderId::from("O-UNKNOWN");
18722        let mut receiver = start_with_events(&mut client);
18723
18724        let modify = modify_order_cmd(instrument_id, unknown);
18725        let cancel = cancel_order_cmd(instrument_id, unknown);
18726        let batch_cancel = cancel_order_cmd(instrument_id, unknown);
18727        let expected = vec![
18728            (
18729                true,
18730                instrument_id,
18731                unknown,
18732                Ustr::from(ORDER_MODIFY_UNSUPPORTED),
18733                Some(modify.command_id),
18734            ),
18735            (
18736                false,
18737                instrument_id,
18738                unknown,
18739                Ustr::from(ORDER_CANCEL_UNSUPPORTED),
18740                Some(cancel.command_id),
18741            ),
18742            (
18743                false,
18744                instrument_id,
18745                unknown,
18746                Ustr::from(ORDER_CANCEL_UNSUPPORTED),
18747                Some(batch_cancel.command_id),
18748            ),
18749        ];
18750        client.modify_order(modify).unwrap();
18751        client.cancel_order(cancel).unwrap();
18752        client
18753            .batch_cancel_orders(batch_cancel_orders_cmd(vec![batch_cancel]))
18754            .unwrap();
18755        client
18756            .query_order(query_order_cmd(instrument_id, unknown))
18757            .unwrap();
18758
18759        let events = collect_order_events(&mut receiver);
18760
18761        let outcomes: Vec<_> = events
18762            .iter()
18763            .map(|event| match event {
18764                OrderEventAny::ModifyDenied(event) => (
18765                    true,
18766                    event.instrument_id,
18767                    event.client_order_id,
18768                    event.reason,
18769                    event.causation_id,
18770                ),
18771                OrderEventAny::CancelDenied(event) => (
18772                    false,
18773                    event.instrument_id,
18774                    event.client_order_id,
18775                    event.reason,
18776                    event.causation_id,
18777                ),
18778                other => panic!("Expected unsupported command denial, was {other:?}"),
18779            })
18780            .collect();
18781
18782        assert_eq!(outcomes, expected);
18783        assert!(state.recorded_requests().is_empty());
18784        assert!(client.in_flight.lock().is_none());
18785    }
18786
18787    #[tokio::test]
18788    async fn report_generators_error_except_mass_status_without_side_effects() {
18789        let (client, state, _) = unsupported_client_with_mock_rpc().await;
18790
18791        let report = client
18792            .generate_order_status_report(&GenerateOrderStatusReport::new(
18793                UUID4::new(),
18794                UnixNanos::default(),
18795                None,
18796                None,
18797                None,
18798                None,
18799                None,
18800            ))
18801            .await
18802            .unwrap_err();
18803        assert_eq!(report.to_string(), VENUE_EXECUTION_REPORTS_UNSUPPORTED);
18804
18805        let reports = client
18806            .generate_order_status_reports(&GenerateOrderStatusReports::new(
18807                UUID4::new(),
18808                UnixNanos::default(),
18809                false,
18810                None,
18811                None,
18812                None,
18813                None,
18814                None,
18815            ))
18816            .await
18817            .unwrap_err();
18818        assert_eq!(reports.to_string(), VENUE_EXECUTION_REPORTS_UNSUPPORTED);
18819
18820        let fills = client
18821            .generate_fill_reports(GenerateFillReports::new(
18822                UUID4::new(),
18823                UnixNanos::default(),
18824                None,
18825                None,
18826                None,
18827                None,
18828                None,
18829                None,
18830            ))
18831            .await
18832            .unwrap_err();
18833        assert_eq!(fills.to_string(), VENUE_EXECUTION_REPORTS_UNSUPPORTED);
18834
18835        let positions = client
18836            .generate_position_status_reports(&GeneratePositionStatusReports::new(
18837                UUID4::new(),
18838                UnixNanos::default(),
18839                None,
18840                None,
18841                None,
18842                None,
18843                None,
18844            ))
18845            .await
18846            .unwrap_err();
18847        assert_eq!(positions.to_string(), VENUE_EXECUTION_REPORTS_UNSUPPORTED);
18848
18849        let mass_status = client.generate_mass_status(None).await.unwrap();
18850        assert!(mass_status.is_none());
18851
18852        let mass_status = client.generate_mass_status(Some(60)).await.unwrap();
18853        assert!(mass_status.is_none());
18854
18855        assert!(state.recorded_requests().is_empty());
18856        assert!(client.in_flight.lock().is_none());
18857    }
18858
18859    async fn connect_test_postgres(
18860        test_name: &str,
18861    ) -> Option<(sqlx::PgPool, PostgresConnectOptions)> {
18862        let pg_config = get_postgres_connect_options(None, None, None, None, None);
18863        let admin_options: sqlx::postgres::PgConnectOptions = pg_config.clone().into();
18864        let admin_pool = match PgPoolOptions::new()
18865            .max_connections(1)
18866            .connect_with(admin_options)
18867            .await
18868        {
18869            Ok(pool) => pool,
18870            Err(e) => {
18871                eprintln!("Postgres unavailable; skipping {test_name} test: {e}");
18872                return None;
18873            }
18874        };
18875
18876        Some((admin_pool, pg_config))
18877    }
18878
18879    async fn execution_client_with_database(
18880        test_name: &str,
18881        state: MockRpcState,
18882    ) -> Option<(
18883        sqlx::PgPool,
18884        String,
18885        BlockchainExecutionClient,
18886        MockRpcState,
18887    )> {
18888        let (admin_pool, schema, mut client, state) =
18889            execution_client_with_unprotected_database(test_name, state).await?;
18890        protect_test_storage(&mut client, &schema).await;
18891        Some((admin_pool, schema, client, state))
18892    }
18893
18894    async fn execution_client_with_unprotected_database(
18895        test_name: &str,
18896        state: MockRpcState,
18897    ) -> Option<(
18898        sqlx::PgPool,
18899        String,
18900        BlockchainExecutionClient,
18901        MockRpcState,
18902    )> {
18903        let (admin_pool, pg_config) = connect_test_postgres(test_name).await?;
18904        let schema = format!("{test_name}_{}", std::process::id());
18905        setup_execution_schema(&admin_pool, &schema).await;
18906
18907        let db_options: sqlx::postgres::PgConnectOptions = pg_config.into();
18908        let db_options = db_options.options([("search_path", schema.clone())]);
18909        let database = connect_test_database(db_options).await.unwrap();
18910        let addr = start_mock_rpc_server(state.clone()).await;
18911        let mut client = test_client(format!("http://{addr}"));
18912        client.cache.database = Some(database);
18913        // Mirror the connect-time migration: tests create the pre-submission table shape
18914        client
18915            .cache
18916            .ensure_execution_transaction_schema()
18917            .await
18918            .unwrap();
18919        initialize_test_verification_ledger(&client).await;
18920        client.signer = Some(Arc::new(
18921            PrivateKeySigner::from_str(TEST_PRIVATE_KEY).unwrap(),
18922        ));
18923        client.core.set_connected();
18924
18925        Some((admin_pool, schema, client, state))
18926    }
18927
18928    async fn install_reservation_commit_rejection(admin_pool: &sqlx::PgPool, schema: &str) {
18929        for statement in [
18930            format!(
18931                "CREATE FUNCTION {schema}.reject_execution_reservation_commit() RETURNS trigger \
18932                 LANGUAGE plpgsql AS 'BEGIN RAISE EXCEPTION ''test reservation commit rejection''; \
18933                 RETURN NEW; END'"
18934            ),
18935            format!(
18936                "CREATE CONSTRAINT TRIGGER reject_execution_reservation_commit AFTER INSERT ON \
18937                 {schema}.execution_transaction_transition DEFERRABLE INITIALLY DEFERRED \
18938                 FOR EACH ROW EXECUTE FUNCTION {schema}.reject_execution_reservation_commit()"
18939            ),
18940        ] {
18941            sqlx::query(sqlx::AssertSqlSafe(statement))
18942                .execute(admin_pool)
18943                .await
18944                .unwrap();
18945        }
18946    }
18947
18948    async fn install_recoverable_commit_rejection(admin_pool: &sqlx::PgPool, schema: &str) {
18949        for statement in [
18950            format!(
18951                "CREATE FUNCTION {schema}.reject_recoverable_commit() RETURNS trigger \
18952                 LANGUAGE plpgsql AS 'BEGIN IF NEW.transition_key = ''recoverable'' THEN \
18953                 RAISE EXCEPTION ''test recoverable commit rejection''; END IF; \
18954                 RETURN NEW; END'"
18955            ),
18956            format!(
18957                "CREATE CONSTRAINT TRIGGER reject_recoverable_commit AFTER INSERT ON \
18958                 {schema}.execution_transaction_transition DEFERRABLE INITIALLY DEFERRED \
18959                 FOR EACH ROW EXECUTE FUNCTION {schema}.reject_recoverable_commit()"
18960            ),
18961        ] {
18962            sqlx::query(sqlx::AssertSqlSafe(statement))
18963                .execute(admin_pool)
18964                .await
18965                .unwrap();
18966        }
18967    }
18968
18969    async fn drop_execution_schema(admin_pool: &sqlx::PgPool, schema: &str) {
18970        sqlx::query(sqlx::AssertSqlSafe(format!("DROP SCHEMA {schema} CASCADE")))
18971            .execute(admin_pool)
18972            .await
18973            .unwrap();
18974    }
18975
18976    async fn setup_execution_schema(admin_pool: &sqlx::PgPool, schema: &str) {
18977        for statement in [
18978            format!("CREATE SCHEMA {schema}"),
18979            format!(
18980                r#"CREATE TABLE {schema}."chain" (chain_id INTEGER PRIMARY KEY, name TEXT NOT NULL)"#
18981            ),
18982            format!(r#"INSERT INTO {schema}."chain" (chain_id, name) VALUES (42161, 'Arbitrum')"#),
18983            format!(
18984                r#"CREATE TABLE {schema}."execution_transaction" (
18985                    id BIGSERIAL PRIMARY KEY,
18986                    chain_id INTEGER NOT NULL REFERENCES {schema}."chain"(chain_id) ON DELETE CASCADE,
18987                    nonce BIGINT NOT NULL,
18988                    transaction_hash TEXT NOT NULL,
18989                    purpose TEXT NOT NULL,
18990                    status TEXT NOT NULL,
18991                    UNIQUE (chain_id, transaction_hash)
18992                )"#
18993            ),
18994        ] {
18995            sqlx::query(sqlx::AssertSqlSafe(statement))
18996                .execute(admin_pool)
18997                .await
18998                .unwrap();
18999        }
19000    }
19001
19002    fn execution_transaction_create_sql() -> &'static str {
19003        const TABLES_SQL: &str = include_str!("../../../../../schema/sql/tables.sql");
19004        const START: &str = "CREATE TABLE IF NOT EXISTS \"execution_transaction\"";
19005        let start = TABLES_SQL
19006            .find(START)
19007            .expect("execution_transaction table is missing from tables.sql");
19008        let statement = &TABLES_SQL[start..];
19009        let end = statement
19010            .find(";\n")
19011            .expect("execution_transaction CREATE TABLE is unterminated")
19012            + 1;
19013        &statement[..end]
19014    }
19015
19016    #[rstest]
19017    #[case(17)]
19018    #[case(18)]
19019    fn closed_pool_position_records_high_precision_quote_pnl(#[case] precision: u8) {
19020        use nautilus_model::{
19021            events::{PositionClosed, PositionEvent, order::spec::OrderFilledSpec},
19022            identifiers::PositionId,
19023            instruments::{CurrencyPair, Instrument},
19024            position::Position,
19025        };
19026        use nautilus_portfolio::Portfolio;
19027
19028        let template = test_pool();
19029
19030        let base = Token::new(
19031            Arc::clone(&template.chain),
19032            Address::from([precision; 20]),
19033            "Portfolio base".into(),
19034            format!("PNLBASE{precision}"),
19035            18,
19036        );
19037
19038        let quote_token = Token::new(
19039            Arc::clone(&template.chain),
19040            Address::from([precision + 50; 20]),
19041            "Portfolio quote".into(),
19042            format!("PNLQUOTE{precision}"),
19043            precision,
19044        );
19045        let address = Address::from([precision + 100; 20]);
19046
19047        let pool = Pool::new(
19048            template.chain,
19049            template.dex,
19050            address,
19051            PoolIdentifier::from_address(address),
19052            1,
19053            base,
19054            quote_token,
19055            Some(500),
19056            Some(10),
19057            UnixNanos::default(),
19058        );
19059        let instrument = CurrencyPair::try_from(&pool).unwrap().into_any();
19060        let quote = instrument.quote_currency();
19061        let position_id = PositionId::new(format!("P-QUOTE{precision}"));
19062        let mut fill = OrderFilledSpec::builder()
19063            .instrument_id(instrument.id())
19064            .position_id(position_id)
19065            .order_side(OrderSide::Buy)
19066            .last_qty(Quantity::from("0.1"))
19067            .last_px(Price::from("1.0000000000000000"))
19068            .currency(quote)
19069            .commission(Money::zero(quote))
19070            .ts_event(UnixNanos::from(1))
19071            .build();
19072        let mut position = Position::new(&instrument, fill.clone());
19073        let cache = Rc::new(RefCell::new(Cache::default()));
19074        cache.borrow_mut().add_instrument(instrument).unwrap();
19075        cache
19076            .borrow_mut()
19077            .add_position(&position, OmsType::Netting)
19078            .unwrap();
19079        fill.event_id = UUID4::new();
19080        fill.trade_id = TradeId::new("CLOSE");
19081        fill.client_order_id = ClientOrderId::new("CLOSE");
19082        fill.order_side = OrderSide::Sell;
19083        fill.last_px = Price::from("1.0000000000000001");
19084        fill.ts_event = UnixNanos::from(2);
19085        position.try_apply(&fill).unwrap();
19086        cache.borrow_mut().update_position(&position).unwrap();
19087
19088        let mut portfolio = Portfolio::new(
19089            Rc::new(RefCell::new(VirtualClock::new())),
19090            Rc::clone(&cache),
19091            None,
19092        );
19093        portfolio.update_position(&PositionEvent::PositionClosed(PositionClosed::create(
19094            &position,
19095            &fill,
19096            UUID4::new(),
19097            UnixNanos::from(3),
19098        )));
19099        let records = portfolio.recorded_realized_pnls();
19100        let analyzer = portfolio.analyzer();
19101        let pnl = position.realized_pnl.unwrap();
19102        assert!(position.is_closed());
19103        assert_eq!(quote.precision, precision);
19104        assert_eq!(quote.code.as_str(), format!("PNLQUOTE{precision}@ARBITRUM"));
19105        assert_eq!(pnl.currency.precision, precision);
19106        assert_eq!(pnl.currency, quote);
19107        assert_eq!(
19108            pnl.as_decimal(),
19109            "0.00000000000000001"
19110                .parse::<rust_decimal::Decimal>()
19111                .unwrap()
19112        );
19113        assert_eq!(
19114            records.get(&quote).unwrap(),
19115            &vec![(position_id, UnixNanos::from(2), 1e-17)]
19116        );
19117        assert_eq!(
19118            analyzer.realized_pnls(Some(&quote)).unwrap(),
19119            &[(position_id, UnixNanos::from(2), 1e-17)]
19120        );
19121    }
19122}