Skip to main content

erpc_sdk/
swap.rs

1//! RPC-backed exact-input quotes for the catalogued EVM constant-product pools.
2//!
3//! The quote path owns request and response validation while delegating HTTP,
4//! timeout, cancellation, and JSON-RPC error handling to the configured
5//! [`crate::HttpJsonRpcTransport`]. Catalog records remain immutable and the
6//! quote result contains only public, decimal-string quantities.
7
8use std::{
9    borrow::Borrow,
10    error::Error,
11    fmt,
12    sync::Arc,
13    time::{SystemTime, UNIX_EPOCH},
14};
15
16use num_bigint::BigUint;
17use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
18use serde_json::{Value, json};
19use tokio_util::sync::CancellationToken;
20
21use crate::{
22    ErpcError, HttpJsonRpcTransport, RequestOptions,
23    dex_catalog::{
24        DEX_CATALOG_CONTENT_DIGEST, DEX_CHAIN_IDS, DexDeployment, NATIVE_WRAP_DEFINITIONS,
25        PoolDefinition, get_dex_deployment, get_pool_definition,
26    },
27    generated::swap_execution_capabilities::{
28        SWAP_EXECUTION_CAPABILITIES_AS_OF_DATE, SWAP_EXECUTION_CAPABILITIES_CONTENT_DIGEST,
29        SWAP_EXECUTION_CAPABILITIES_JSON, SWAP_EXECUTION_FUNCTION_SELECTOR,
30        SWAP_EXECUTION_FUNCTION_SIGNATURE,
31    },
32    token_catalog::{
33        TOKEN_CATALOG_CONTENT_DIGEST, TokenDeployment, TokenRepresentationKind, TokenStandard,
34        TokenStatus, get_token_deployment,
35    },
36};
37
38const SUPPORTED_QUOTE_ADAPTER: &str = "evm-constant-product-v2";
39const UINT256_DECIMAL_MAX_LENGTH: usize = 78;
40const UINT112_MAX_BITS: u64 = 112;
41const UINT32_MAX_BITS: u64 = 32;
42
43const FACTORY_GET_PAIR_SELECTOR: &str = "0xe6a43905";
44const PAIR_FACTORY_SELECTOR: &str = "0xc45a0155";
45const PAIR_TOKEN0_SELECTOR: &str = "0x0dfe1681";
46const PAIR_TOKEN1_SELECTOR: &str = "0xd21220a7";
47const PAIR_GET_RESERVES_SELECTOR: &str = "0x0902f1ac";
48const ROUTER_GET_AMOUNTS_OUT_SELECTOR: &str = "0xd06ca61f";
49const ERC20_ALLOWANCE_SELECTOR: &str = "0xdd62ed3e";
50
51#[derive(Clone, Copy)]
52struct SupportedQuoteCapability {
53    chain_id: &'static str,
54    dex_deployment_id: &'static str,
55    factory_address: &'static str,
56    pool_definition_id: &'static str,
57    pool_address: &'static str,
58    token0_deployment_id: &'static str,
59    token0_address: &'static str,
60    token0_decimals: u8,
61    token0_standard: TokenStandard,
62    token1_deployment_id: &'static str,
63    token1_address: &'static str,
64    token1_decimals: u8,
65    token1_standard: TokenStandard,
66    adapter_kind: &'static str,
67    fee_numerator: &'static str,
68    fee_denominator: &'static str,
69}
70
71// Quote eligibility is a handwritten review boundary. Catalog growth may add
72// lookup, monitoring, or ranking records without granting them RPC quote
73// access.
74const SUPPORTED_QUOTE_CAPABILITIES: &[SupportedQuoteCapability] = &[
75    SupportedQuoteCapability {
76        chain_id: "eip155:1",
77        dex_deployment_id: "dex-deployment-0001",
78        factory_address: "0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f",
79        pool_definition_id: "pool-0001",
80        pool_address: "0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc",
81        token0_deployment_id: "deployment-0008",
82        token0_address: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
83        token0_decimals: 6,
84        token0_standard: TokenStandard::Erc20,
85        token1_deployment_id: "deployment-0002",
86        token1_address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
87        token1_decimals: 18,
88        token1_standard: TokenStandard::Erc20,
89        adapter_kind: SUPPORTED_QUOTE_ADAPTER,
90        fee_numerator: "3",
91        fee_denominator: "1000",
92    },
93    SupportedQuoteCapability {
94        chain_id: "eip155:43114",
95        dex_deployment_id: "dex-deployment-0002",
96        factory_address: "0x9ad6c38be94206ca50bb0d90783181662f0cfa10",
97        pool_definition_id: "pool-0002",
98        pool_address: "0xf4003f4efbe8691b60249e6afbd307abe7758adb",
99        token0_deployment_id: "deployment-0004",
100        token0_address: "0xb31f66aa3c1e785363f0875a1b74e27b85fd66c7",
101        token0_decimals: 18,
102        token0_standard: TokenStandard::Erc20,
103        token1_deployment_id: "deployment-0009",
104        token1_address: "0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e",
105        token1_decimals: 6,
106        token1_standard: TokenStandard::Erc20,
107        adapter_kind: SUPPORTED_QUOTE_ADAPTER,
108        fee_numerator: "3",
109        fee_denominator: "1000",
110    },
111];
112
113/// Fixed domain error codes for exact-input quote validation.
114#[derive(Clone, Copy, Debug, Eq, PartialEq)]
115pub enum SwapQuoteErrorCode {
116    /// The request shape, identifiers, amount, or freshness values are invalid.
117    InvalidArgument,
118    /// The requested chain is not represented by the DEX catalog.
119    UnsupportedChain,
120    /// The requested pool identifier is unknown.
121    UnknownPool,
122    /// The selected pool or token record is on another chain.
123    ChainMismatch,
124    /// A selected pool or DEX record is not active or otherwise valid.
125    InvalidPoolState,
126    /// An input or output token identifier is unknown.
127    UnknownToken,
128    /// A selected token record is not active.
129    TokenNotActive,
130    /// A selected token standard is outside the quote adapter boundary.
131    UnsupportedTokenStandard,
132    /// The selected token or pool is outside the reviewed quote capability.
133    UnsupportedToken,
134    /// The requested pair is not the selected pool pair.
135    PoolTokenMismatch,
136    /// The selected pool adapter cannot produce this quote.
137    UnsupportedAdapter,
138    /// The on-chain factory or pool program identity does not match the catalog.
139    ProgramMismatch,
140    /// The block snapshot is stale, inconsistent, or reorged.
141    StateStale,
142    /// The pool has no usable liquidity for the requested direction.
143    InsufficientLiquidity,
144    /// A checked uint256 calculation or fee configuration is invalid.
145    Arithmetic,
146}
147
148impl SwapQuoteErrorCode {
149    /// Stable spelling for [`Self::InvalidArgument`].
150    pub const SWAP_INVALID_ARGUMENT: Self = Self::InvalidArgument;
151    /// Stable spelling for [`Self::UnsupportedChain`].
152    pub const SWAP_UNSUPPORTED_CHAIN: Self = Self::UnsupportedChain;
153    /// Stable spelling for [`Self::UnknownPool`].
154    pub const SWAP_UNKNOWN_POOL: Self = Self::UnknownPool;
155    /// Stable spelling for [`Self::ChainMismatch`].
156    pub const SWAP_CHAIN_MISMATCH: Self = Self::ChainMismatch;
157    /// Stable spelling for [`Self::InvalidPoolState`].
158    pub const SWAP_INVALID_POOL_STATE: Self = Self::InvalidPoolState;
159    /// Stable spelling for [`Self::UnknownToken`].
160    pub const SWAP_UNKNOWN_TOKEN: Self = Self::UnknownToken;
161    /// Stable spelling for [`Self::TokenNotActive`].
162    pub const SWAP_TOKEN_NOT_ACTIVE: Self = Self::TokenNotActive;
163    /// Stable spelling for [`Self::UnsupportedTokenStandard`].
164    pub const SWAP_UNSUPPORTED_TOKEN_STANDARD: Self = Self::UnsupportedTokenStandard;
165    /// Stable spelling for [`Self::UnsupportedToken`].
166    pub const SWAP_UNSUPPORTED_TOKEN: Self = Self::UnsupportedToken;
167    /// Stable spelling for [`Self::PoolTokenMismatch`].
168    pub const SWAP_POOL_TOKEN_MISMATCH: Self = Self::PoolTokenMismatch;
169    /// Stable spelling for [`Self::UnsupportedAdapter`].
170    pub const SWAP_UNSUPPORTED_ADAPTER: Self = Self::UnsupportedAdapter;
171    /// Stable spelling for [`Self::ProgramMismatch`].
172    pub const SWAP_PROGRAM_MISMATCH: Self = Self::ProgramMismatch;
173    /// Stable spelling for [`Self::StateStale`].
174    pub const SWAP_STATE_STALE: Self = Self::StateStale;
175    /// Stable spelling for [`Self::InsufficientLiquidity`].
176    pub const SWAP_INSUFFICIENT_LIQUIDITY: Self = Self::InsufficientLiquidity;
177    /// Stable spelling for [`Self::Arithmetic`].
178    pub const SWAP_ARITHMETIC: Self = Self::Arithmetic;
179
180    /// Returns the stable wire/error code string.
181    #[must_use]
182    pub const fn as_str(self) -> &'static str {
183        match self {
184            Self::InvalidArgument => "SWAP_INVALID_ARGUMENT",
185            Self::UnsupportedChain => "SWAP_UNSUPPORTED_CHAIN",
186            Self::UnknownPool => "SWAP_UNKNOWN_POOL",
187            Self::ChainMismatch => "SWAP_CHAIN_MISMATCH",
188            Self::InvalidPoolState => "SWAP_INVALID_POOL_STATE",
189            Self::UnknownToken => "SWAP_UNKNOWN_TOKEN",
190            Self::TokenNotActive => "SWAP_TOKEN_NOT_ACTIVE",
191            Self::UnsupportedTokenStandard => "SWAP_UNSUPPORTED_TOKEN_STANDARD",
192            Self::UnsupportedToken => "SWAP_UNSUPPORTED_TOKEN",
193            Self::PoolTokenMismatch => "SWAP_POOL_TOKEN_MISMATCH",
194            Self::UnsupportedAdapter => "SWAP_UNSUPPORTED_ADAPTER",
195            Self::ProgramMismatch => "SWAP_PROGRAM_MISMATCH",
196            Self::StateStale => "SWAP_STATE_STALE",
197            Self::InsufficientLiquidity => "SWAP_INSUFFICIENT_LIQUIDITY",
198            Self::Arithmetic => "SWAP_ARITHMETIC",
199        }
200    }
201
202    const fn message(self) -> &'static str {
203        match self {
204            Self::InvalidArgument => "Swap request is invalid",
205            Self::UnsupportedChain => "Swap chain is unsupported",
206            Self::UnknownPool => "Swap pool is unknown",
207            Self::ChainMismatch => "Swap chain does not match the selected records",
208            Self::InvalidPoolState => "Swap pool state is invalid",
209            Self::UnknownToken => "Swap token is unknown",
210            Self::TokenNotActive => "Swap token is not active",
211            Self::UnsupportedTokenStandard => "Swap token standard is unsupported",
212            Self::UnsupportedToken => "Swap token is unsupported for the selected pool",
213            Self::PoolTokenMismatch => "Swap pool tokens do not match the request",
214            Self::UnsupportedAdapter => "Swap adapter is unsupported",
215            Self::ProgramMismatch => "Swap program does not match the selected records",
216            Self::StateStale => "Swap pool state is stale",
217            Self::InsufficientLiquidity => "Swap pool liquidity is insufficient",
218            Self::Arithmetic => "Swap arithmetic overflowed or produced an invalid result",
219        }
220    }
221}
222
223impl fmt::Display for SwapQuoteErrorCode {
224    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
225        formatter.write_str(self.as_str())
226    }
227}
228
229/// Domain errors produced by quote validation, with upstream errors preserved.
230#[derive(Debug)]
231pub enum SwapQuoteError {
232    /// A deterministic local quote-domain failure.
233    Domain(SwapQuoteErrorCode),
234    /// An existing transport, timeout, cancellation, or JSON-RPC error.
235    Upstream(ErpcError),
236}
237
238impl SwapQuoteError {
239    /// Returns the domain code, or `None` when an upstream error was preserved.
240    #[must_use]
241    pub const fn code(&self) -> Option<SwapQuoteErrorCode> {
242        match self {
243            Self::Domain(code) => Some(*code),
244            Self::Upstream(_) => None,
245        }
246    }
247
248    /// Returns the preserved upstream error when the quote failed in transport.
249    #[must_use]
250    pub const fn upstream(&self) -> Option<&ErpcError> {
251        match self {
252            Self::Domain(_) => None,
253            Self::Upstream(error) => Some(error),
254        }
255    }
256
257    /// Returns the stable code string for a domain error.
258    #[must_use]
259    pub const fn code_string(&self) -> Option<&'static str> {
260        match self {
261            Self::Domain(code) => Some(code.as_str()),
262            Self::Upstream(_) => None,
263        }
264    }
265}
266
267impl fmt::Display for SwapQuoteError {
268    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
269        match self {
270            Self::Domain(code) => formatter.write_str(code.message()),
271            Self::Upstream(error) => error.fmt(formatter),
272        }
273    }
274}
275
276impl Error for SwapQuoteError {
277    fn source(&self) -> Option<&(dyn Error + 'static)> {
278        match self {
279            Self::Domain(_) => None,
280            Self::Upstream(error) => Some(error),
281        }
282    }
283}
284
285impl From<ErpcError> for SwapQuoteError {
286    fn from(error: ErpcError) -> Self {
287        Self::Upstream(error)
288    }
289}
290
291/// Result type for the public swap quote client.
292pub type SwapResult<T> = std::result::Result<T, SwapQuoteError>;
293
294/// Fixed domain error codes for unsigned EVM swap preparation and simulation.
295#[derive(Clone, Copy, Debug, Eq, PartialEq)]
296pub enum SwapExecutionErrorCode {
297    /// The execution request shape or scalar value is invalid.
298    InvalidArgument,
299    /// The selected records do not have an approved execution capability.
300    UnsupportedExecution,
301    /// A reviewed router binding did not match the selected records.
302    ProgramMismatch,
303    /// The caller's current token allowance is below the requested amount.
304    InsufficientAllowance,
305    /// The final router simulation returned a recognized execution revert.
306    SimulationReverted,
307    /// A preflight or final simulation response was malformed or inconsistent.
308    InvalidSimulation,
309}
310
311impl SwapExecutionErrorCode {
312    /// Stable spelling for [`Self::InvalidArgument`].
313    pub const SWAP_EXECUTION_INVALID_ARGUMENT: Self = Self::InvalidArgument;
314    /// Stable spelling for [`Self::UnsupportedExecution`].
315    pub const SWAP_UNSUPPORTED_EXECUTION: Self = Self::UnsupportedExecution;
316    /// Stable spelling for [`Self::ProgramMismatch`].
317    pub const SWAP_PROGRAM_MISMATCH: Self = Self::ProgramMismatch;
318    /// Stable spelling for [`Self::InsufficientAllowance`].
319    pub const SWAP_INSUFFICIENT_ALLOWANCE: Self = Self::InsufficientAllowance;
320    /// Stable spelling for [`Self::SimulationReverted`].
321    pub const SWAP_SIMULATION_REVERTED: Self = Self::SimulationReverted;
322    /// Stable spelling for [`Self::InvalidSimulation`].
323    pub const SWAP_INVALID_SIMULATION: Self = Self::InvalidSimulation;
324
325    /// Returns the stable wire/error code string.
326    #[must_use]
327    pub const fn as_str(self) -> &'static str {
328        match self {
329            Self::InvalidArgument => "SWAP_EXECUTION_INVALID_ARGUMENT",
330            Self::UnsupportedExecution => "SWAP_UNSUPPORTED_EXECUTION",
331            Self::ProgramMismatch => "SWAP_PROGRAM_MISMATCH",
332            Self::InsufficientAllowance => "SWAP_INSUFFICIENT_ALLOWANCE",
333            Self::SimulationReverted => "SWAP_SIMULATION_REVERTED",
334            Self::InvalidSimulation => "SWAP_INVALID_SIMULATION",
335        }
336    }
337
338    const fn message(self) -> &'static str {
339        match self {
340            Self::InvalidArgument => "Swap execution request is invalid",
341            Self::UnsupportedExecution => "Swap execution is unsupported for the selected records",
342            Self::ProgramMismatch => "Swap program does not match the selected records",
343            Self::InsufficientAllowance => "Swap allowance is insufficient",
344            Self::SimulationReverted => "Swap simulation reverted",
345            Self::InvalidSimulation => "Swap simulation result is invalid",
346        }
347    }
348}
349
350impl fmt::Display for SwapExecutionErrorCode {
351    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
352        formatter.write_str(self.as_str())
353    }
354}
355
356/// Errors produced by unsigned EVM swap preparation and simulation.
357///
358/// Quote-domain failures remain available through [`Self::Quote`], while
359/// transport, timeout, cancellation, and non-revert JSON-RPC failures retain
360/// their sanitized SDK error through [`Self::Upstream`].
361#[derive(Debug)]
362pub enum SwapExecutionError {
363    /// A deterministic execution-domain failure.
364    Domain(SwapExecutionErrorCode),
365    /// A quote-domain failure that occurred before router execution reads.
366    Quote(SwapQuoteError),
367    /// An existing transport, timeout, cancellation, or JSON-RPC error.
368    Upstream(ErpcError),
369}
370
371impl SwapExecutionError {
372    /// Returns the execution-domain code, or `None` for a quote or upstream error.
373    #[must_use]
374    pub const fn code(&self) -> Option<SwapExecutionErrorCode> {
375        match self {
376            Self::Domain(code) => Some(*code),
377            Self::Quote(_) | Self::Upstream(_) => None,
378        }
379    }
380
381    /// Returns the nested quote error when quote validation failed.
382    #[must_use]
383    pub const fn quote(&self) -> Option<&SwapQuoteError> {
384        match self {
385            Self::Quote(error) => Some(error),
386            Self::Domain(_) | Self::Upstream(_) => None,
387        }
388    }
389
390    /// Returns the preserved upstream error when transport failed.
391    #[must_use]
392    pub const fn upstream(&self) -> Option<&ErpcError> {
393        match self {
394            Self::Upstream(error) => Some(error),
395            Self::Domain(_) | Self::Quote(_) => None,
396        }
397    }
398
399    /// Returns the stable code string for either execution or quote errors.
400    #[must_use]
401    pub const fn code_string(&self) -> Option<&'static str> {
402        match self {
403            Self::Domain(code) => Some(code.as_str()),
404            Self::Quote(error) => error.code_string(),
405            Self::Upstream(_) => None,
406        }
407    }
408
409    /// Returns the nested quote-domain code when one is present.
410    #[must_use]
411    pub const fn quote_code(&self) -> Option<SwapQuoteErrorCode> {
412        match self {
413            Self::Quote(SwapQuoteError::Domain(code)) => Some(*code),
414            Self::Domain(_) | Self::Quote(SwapQuoteError::Upstream(_)) | Self::Upstream(_) => None,
415        }
416    }
417}
418
419impl fmt::Display for SwapExecutionError {
420    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
421        match self {
422            Self::Domain(code) => formatter.write_str(code.message()),
423            Self::Quote(error) => error.fmt(formatter),
424            Self::Upstream(error) => error.fmt(formatter),
425        }
426    }
427}
428
429impl Error for SwapExecutionError {
430    fn source(&self) -> Option<&(dyn Error + 'static)> {
431        match self {
432            Self::Domain(_) => None,
433            Self::Quote(error) => Some(error),
434            Self::Upstream(error) => Some(error),
435        }
436    }
437}
438
439impl From<SwapQuoteError> for SwapExecutionError {
440    fn from(error: SwapQuoteError) -> Self {
441        match error {
442            SwapQuoteError::Upstream(error) => Self::Upstream(error),
443            SwapQuoteError::Domain(code) => match code {
444                // These quote gates mean the records can be looked up but do
445                // not have an approved execution capability.
446                SwapQuoteErrorCode::UnsupportedAdapter
447                | SwapQuoteErrorCode::UnsupportedToken
448                | SwapQuoteErrorCode::UnsupportedTokenStandard
449                | SwapQuoteErrorCode::UnknownPool => {
450                    Self::Domain(SwapExecutionErrorCode::UnsupportedExecution)
451                }
452                other => Self::Quote(SwapQuoteError::Domain(other)),
453            },
454        }
455    }
456}
457
458/// Result type for unsigned swap preparation and simulation.
459pub type SwapExecutionResult<T> = std::result::Result<T, SwapExecutionError>;
460
461/// Freshness limits for an exact-input quote. Omitted fields use SDK defaults.
462#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
463#[serde(deny_unknown_fields, rename_all = "camelCase")]
464pub struct SwapFreshness {
465    /// Maximum age of the snapshot and final latest block, in seconds (0–86400).
466    #[serde(
467        default,
468        deserialize_with = "deserialize_non_null_u64",
469        skip_serializing_if = "Option::is_none"
470    )]
471    pub max_block_age_seconds: Option<u64>,
472    /// Maximum block distance between the initial and final latest headers (0–1024).
473    #[serde(
474        default,
475        deserialize_with = "deserialize_non_null_u64",
476        skip_serializing_if = "Option::is_none"
477    )]
478    pub max_block_lag: Option<u64>,
479    /// Maximum tolerated future clock skew, in seconds (0–300).
480    #[serde(
481        default,
482        deserialize_with = "deserialize_non_null_u64",
483        skip_serializing_if = "Option::is_none"
484    )]
485    pub max_clock_skew_seconds: Option<u64>,
486}
487
488fn deserialize_non_null_u64<'de, D>(deserializer: D) -> std::result::Result<Option<u64>, D::Error>
489where
490    D: Deserializer<'de>,
491{
492    Option::<u64>::deserialize(deserializer)?
493        .map(Some)
494        .ok_or_else(|| D::Error::custom("freshness values must be integers when present"))
495}
496
497/// Exact-input quote request with the six contract fields.
498#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
499#[serde(deny_unknown_fields, rename_all = "camelCase")]
500pub struct ExactInputQuoteRequest {
501    /// Chain-qualified catalog identifier.
502    pub chain_id: String,
503    /// Opaque catalog pool identifier.
504    pub pool_definition_id: String,
505    /// Opaque input token deployment identifier.
506    pub input_token_deployment_id: String,
507    /// Opaque output token deployment identifier.
508    pub output_token_deployment_id: String,
509    /// Positive canonical decimal amount in base units.
510    pub amount_in: String,
511    /// Optional block freshness limits.
512    #[serde(skip_serializing_if = "Option::is_none")]
513    pub freshness: Option<SwapFreshness>,
514}
515
516/// Alias for callers that prefer the swap-specific request name.
517pub type SwapQuoteRequest = ExactInputQuoteRequest;
518
519/// Request for unsigned ERC20-to-ERC20 preparation or RPC simulation.
520#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
521#[serde(deny_unknown_fields, rename_all = "camelCase")]
522pub struct PrepareExactInputSwapRequest {
523    /// Chain-qualified catalog identifier.
524    pub chain_id: String,
525    /// Opaque catalog pool identifier.
526    pub pool_definition_id: String,
527    /// Opaque input token deployment identifier.
528    pub input_token_deployment_id: String,
529    /// Opaque output token deployment identifier.
530    pub output_token_deployment_id: String,
531    /// Positive canonical decimal amount in base units.
532    pub amount_in: String,
533    /// Optional block freshness limits.
534    #[serde(skip_serializing_if = "Option::is_none")]
535    pub freshness: Option<SwapFreshness>,
536    /// Nonzero EVM address that owns the input tokens.
537    pub sender: String,
538    /// Nonzero EVM address that receives the output tokens.
539    pub recipient: String,
540    /// Slippage tolerance in basis points, from 0 through 9999.
541    pub slippage_bps: u64,
542    /// Positive canonical decimal deadline in seconds.
543    pub deadline: String,
544}
545
546/// Alias for callers that prefer a shorter execution request name.
547pub type ExactInputSwapRequest = PrepareExactInputSwapRequest;
548
549/// One ERC20 deployment and address in an execution path.
550#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
551#[serde(rename_all = "camelCase")]
552pub struct SwapPathEntry {
553    /// Opaque token deployment identifier.
554    pub token_deployment_id: String,
555    /// Lowercase 20-byte EVM token address.
556    pub address: String,
557    /// Token standard discriminator.
558    pub standard: String,
559    /// Catalog representation discriminator.
560    pub representation_kind: String,
561}
562
563/// Alias matching the full exact-input path entry name.
564pub type ExactInputSwapPathEntry = SwapPathEntry;
565
566/// Chain-bound unsigned EVM transaction envelope.
567#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
568#[serde(rename_all = "camelCase")]
569pub struct EvmUnsignedTransaction {
570    /// Transaction envelope discriminator.
571    pub kind: String,
572    /// Canonical CAIP-2 chain identifier.
573    pub chain_id: String,
574    /// Lowercase sender address.
575    pub from: String,
576    /// Lowercase reviewed router address.
577    pub to: String,
578    /// Lowercase ABI calldata.
579    pub data: String,
580    /// Canonical decimal zero value.
581    pub value: String,
582}
583
584/// Allowance requirement attached to a prepared swap.
585#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
586#[serde(rename_all = "camelCase")]
587pub struct SwapAllowance {
588    /// Input token deployment identifier.
589    pub token_deployment_id: String,
590    /// Lowercase input token address.
591    pub token_address: String,
592    /// Lowercase allowance owner address.
593    pub owner: String,
594    /// Lowercase reviewed router spender address.
595    pub spender: String,
596    /// Canonical decimal amount required by the swap.
597    pub required_amount: String,
598}
599
600/// Unsigned ERC20-to-ERC20 router preparation.
601#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
602#[serde(rename_all = "camelCase")]
603pub struct ExactInputSwapPreparation {
604    /// Preparation discriminator.
605    pub preparation_kind: String,
606    /// Reviewed execution capability identifier.
607    pub execution_capability_id: String,
608    /// SHA-256 digest of the canonical runtime capability projection.
609    pub execution_capability_digest: String,
610    /// Fresh quote used to construct the transaction.
611    pub quote: ExactInputQuoteResult,
612    /// Canonical decimal minimum output after slippage.
613    pub minimum_amount_out: String,
614    /// Slippage tolerance in basis points.
615    pub slippage_bps: u64,
616    /// Canonical decimal deadline in seconds.
617    pub deadline: String,
618    /// Lowercase recipient address.
619    pub recipient: String,
620    /// Exactly two entries, input followed by output.
621    pub path: Vec<SwapPathEntry>,
622    /// Chain-bound unsigned transaction envelope.
623    pub transaction: EvmUnsignedTransaction,
624    /// Input allowance requirement for the reviewed router.
625    pub allowance: SwapAllowance,
626}
627
628/// Alias for the preparation result.
629pub type PrepareExactInputSwapResult = ExactInputSwapPreparation;
630
631/// Alias for callers that use the generic preparation name.
632pub type SwapPreparation = ExactInputSwapPreparation;
633
634/// Result of a simulated prepared swap.
635#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
636#[serde(rename_all = "camelCase")]
637pub struct ExactInputSwapSimulation {
638    /// Simulation discriminator.
639    pub simulation_kind: String,
640    /// Fresh unsigned preparation used for this simulation.
641    pub preparation: ExactInputSwapPreparation,
642    /// Block snapshot used for the simulation.
643    pub snapshot: EvmBlockSnapshot,
644    /// Canonical decimal current input-token allowance.
645    pub current_allowance: String,
646    /// Exact simulated amounts, input followed by output.
647    pub amounts: Vec<String>,
648    /// Canonical decimal simulated output amount.
649    pub amount_out: String,
650}
651
652/// Alias for the simulation result.
653pub type SimulateExactInputSwapResult = ExactInputSwapSimulation;
654
655/// Alias for callers that use the generic simulation name.
656pub type SwapSimulation = ExactInputSwapSimulation;
657
658/// Exact-input quote result.
659#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
660#[serde(rename_all = "camelCase")]
661pub struct ExactInputQuoteResult {
662    /// Quote contract discriminator.
663    pub quote_kind: &'static str,
664    /// Chain-qualified catalog identifier.
665    pub chain_id: String,
666    /// Opaque catalog pool identifier.
667    pub pool_definition_id: String,
668    /// Opaque catalog DEX identifier.
669    pub dex_deployment_id: String,
670    /// Catalog adapter kind.
671    pub adapter_kind: String,
672    /// Opaque input token deployment identifier.
673    pub input_token_deployment_id: String,
674    /// Opaque output token deployment identifier.
675    pub output_token_deployment_id: String,
676    /// Canonical decimal input amount.
677    pub amount_in: String,
678    /// Canonical decimal output amount.
679    pub amount_out: String,
680    /// Applied fee fraction.
681    pub fee: QuoteFee,
682    /// Block snapshot used for every pool read.
683    pub snapshot: EvmBlockSnapshot,
684    /// Token catalog content digest.
685    pub token_catalog_digest: &'static str,
686    /// DEX catalog content digest.
687    pub dex_catalog_digest: &'static str,
688}
689
690/// Fee fraction included in an exact-input quote.
691#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
692pub struct QuoteFee {
693    /// Fee numerator.
694    pub numerator: String,
695    /// Fee denominator.
696    pub denominator: String,
697}
698
699/// EVM block snapshot included in an exact-input quote.
700#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
701#[serde(rename_all = "camelCase")]
702pub struct EvmBlockSnapshot {
703    /// Snapshot kind discriminator.
704    pub kind: &'static str,
705    /// Decimal block number.
706    pub block_number: String,
707    /// Lowercase 32-byte block hash.
708    pub block_hash: String,
709    /// Decimal block timestamp.
710    pub block_timestamp: String,
711}
712
713/// Configured RPC-backed swap client.
714#[derive(Clone)]
715pub struct SwapClient {
716    ethereum: Arc<HttpJsonRpcTransport>,
717    avalanche: Arc<HttpJsonRpcTransport>,
718    #[cfg(test)]
719    clock: Option<fn() -> u64>,
720}
721
722impl SwapClient {
723    pub(crate) fn new(
724        ethereum: Arc<HttpJsonRpcTransport>,
725        avalanche: Arc<HttpJsonRpcTransport>,
726    ) -> Self {
727        Self {
728            ethereum,
729            avalanche,
730            #[cfg(test)]
731            clock: None,
732        }
733    }
734
735    /// Executes an exact-input quote through the configured EVM transport.
736    pub async fn quote_exact_input<R>(&self, request: R) -> SwapResult<ExactInputQuoteResult>
737    where
738        R: Borrow<ExactInputQuoteRequest>,
739    {
740        self.quote_exact_input_with(request.borrow(), None).await
741    }
742
743    /// Executes an exact-input quote while observing an optional cancellation token.
744    pub async fn quote_exact_input_with<R>(
745        &self,
746        request: R,
747        cancellation: Option<&CancellationToken>,
748    ) -> SwapResult<ExactInputQuoteResult>
749    where
750        R: Borrow<ExactInputQuoteRequest>,
751    {
752        let request = request.borrow();
753        let normalized = normalize_request(request)?;
754        if normalized.pool.adapter.kind != SUPPORTED_QUOTE_ADAPTER
755            || normalized.dex.adapter_kind != SUPPORTED_QUOTE_ADAPTER
756        {
757            return domain_error(SwapQuoteErrorCode::UnsupportedAdapter);
758        }
759
760        let transport = if normalized.pool.chain_id == chain_id("ethereum") {
761            &self.ethereum
762        } else if normalized.pool.chain_id == chain_id("avalancheC") {
763            &self.avalanche
764        } else {
765            return domain_error(SwapQuoteErrorCode::UnsupportedAdapter);
766        };
767        let options = RequestOptions {
768            cancellation: cancellation.cloned(),
769        };
770        let state = read_evm_state(transport, &normalized, &options, self).await?;
771        assert_freshness(
772            &state.initial,
773            &state.latest_after_reads,
774            &normalized.freshness,
775            self,
776        )?;
777        let calculated = calculate_quote(&normalized, &state)?;
778        Ok(quote_result(&normalized, &state, &calculated))
779    }
780
781    /// Prepares an unsigned ERC20-to-ERC20 router transaction from a fresh
782    /// quote and the reviewed execution capability for the selected pool.
783    ///
784    /// The returned transaction is a chain-bound SDK envelope. It does not
785    /// contain approval calldata, a signature, a nonce, fees, or a send
786    /// operation; the caller's wallet remains responsible for those actions.
787    pub async fn prepare_exact_input_swap<R>(
788        &self,
789        request: R,
790    ) -> SwapExecutionResult<ExactInputSwapPreparation>
791    where
792        R: Borrow<PrepareExactInputSwapRequest>,
793    {
794        self.prepare_exact_input_swap_with(request.borrow(), None)
795            .await
796    }
797
798    /// Prepares an unsigned swap while observing an optional cancellation token.
799    pub async fn prepare_exact_input_swap_with<R>(
800        &self,
801        request: R,
802        cancellation: Option<&CancellationToken>,
803    ) -> SwapExecutionResult<ExactInputSwapPreparation>
804    where
805        R: Borrow<PrepareExactInputSwapRequest>,
806    {
807        // Copy every caller scalar before the first await. This also keeps
808        // interior-mutable callers from changing the request during RPC I/O.
809        let request = request.borrow().clone();
810        let options = RequestOptions {
811            cancellation: cancellation.cloned(),
812        };
813        let prepared = self.prepare_internal(request, &options).await?;
814        Ok(prepared.preparation)
815    }
816
817    /// Simulates a freshly prepared unsigned ERC20-to-ERC20 router call.
818    pub async fn simulate_exact_input_swap<R>(
819        &self,
820        request: R,
821    ) -> SwapExecutionResult<ExactInputSwapSimulation>
822    where
823        R: Borrow<PrepareExactInputSwapRequest>,
824    {
825        self.simulate_exact_input_swap_with(request.borrow(), None)
826            .await
827    }
828
829    /// Simulates a freshly prepared swap while observing an optional
830    /// cancellation token.
831    pub async fn simulate_exact_input_swap_with<R>(
832        &self,
833        request: R,
834        cancellation: Option<&CancellationToken>,
835    ) -> SwapExecutionResult<ExactInputSwapSimulation>
836    where
837        R: Borrow<PrepareExactInputSwapRequest>,
838    {
839        // Keep a caller-owned snapshot for the complete operation, including
840        // the preparation phase and every simulation read.
841        let request = request.borrow().clone();
842        let options = RequestOptions {
843            cancellation: cancellation.cloned(),
844        };
845        let prepared = self.prepare_internal(request, &options).await?;
846        self.simulate_internal(prepared, &options).await
847    }
848
849    #[allow(clippy::too_many_lines)]
850    async fn prepare_internal(
851        &self,
852        request: PrepareExactInputSwapRequest,
853        options: &RequestOptions,
854    ) -> SwapExecutionResult<PreparedExecution> {
855        let scalars = normalize_execution_scalars(&request, self)?;
856        let quote_request = quote_request_from_execution(&request);
857        let normalized = normalize_request(&quote_request).map_err(SwapExecutionError::from)?;
858        let Some(capability) = execution_capability_for(&normalized) else {
859            return execution_domain_error(SwapExecutionErrorCode::UnsupportedExecution);
860        };
861        let transport = if normalized.pool.chain_id == chain_id("ethereum") {
862            &self.ethereum
863        } else if normalized.pool.chain_id == chain_id("avalancheC") {
864            &self.avalanche
865        } else {
866            return execution_domain_error(SwapExecutionErrorCode::UnsupportedExecution);
867        };
868
869        // This is intentionally the existing quote sequence and decoder. A
870        // preparation owns a new quote rather than trusting caller data.
871        let state = read_evm_state(transport, &normalized, options, self)
872            .await
873            .map_err(SwapExecutionError::from)?;
874        assert_freshness(
875            &state.initial,
876            &state.latest_after_reads,
877            &normalized.freshness,
878            self,
879        )
880        .map_err(SwapExecutionError::from)?;
881        let calculated = calculate_quote(&normalized, &state).map_err(SwapExecutionError::from)?;
882        let quote = quote_result(&normalized, &state, &calculated);
883
884        // Deadline comparisons need the quote timestamp and the current
885        // completion clock, so they happen after the quote's 11 reads but
886        // before any router-specific read.
887        ensure_deadline(&scalars, &state.initial.timestamp, self)?;
888        let minimum_amount_out = minimum_amount_out(&quote.amount_out, scalars.slippage_bps)?;
889        let input_address = normalized
890            .input
891            .address
892            .ok_or(SwapExecutionError::Domain(
893                SwapExecutionErrorCode::InvalidSimulation,
894            ))?
895            .to_ascii_lowercase();
896        let output_address = normalized
897            .output
898            .address
899            .ok_or(SwapExecutionError::Domain(
900                SwapExecutionErrorCode::InvalidSimulation,
901            ))?
902            .to_ascii_lowercase();
903        let selector = rpc_selector(&state.initial.hash);
904
905        // Router reads are all pinned to the quote block. They deliberately
906        // remain separate calls so the RPC trace proves the required order.
907        let router_code_raw = execution_rpc_request(
908            transport,
909            "eth_getCode",
910            json!([capability.router_address, selector.clone()]),
911            options,
912        )
913        .await?;
914        let router_code = parse_execution_hex_bytes(&router_code_raw)?;
915        if router_code.len() <= 2 {
916            return execution_invalid_simulation();
917        }
918
919        let router_factory_raw = execution_rpc_request(
920            transport,
921            "eth_call",
922            json!([
923                abi_call(&capability.router_address, PAIR_FACTORY_SELECTOR),
924                selector.clone()
925            ]),
926            options,
927        )
928        .await?;
929        let router_factory = parse_execution_address_word(&router_factory_raw)?;
930        if !router_factory.eq_ignore_ascii_case(&capability.factory_address) {
931            return execution_domain_error(SwapExecutionErrorCode::ProgramMismatch);
932        }
933
934        let router_wrapped_raw = execution_rpc_request(
935            transport,
936            "eth_call",
937            json!([
938                abi_call(
939                    &capability.router_address,
940                    &capability.wrapped_native_function_selector
941                ),
942                selector.clone()
943            ]),
944            options,
945        )
946        .await?;
947        let router_wrapped = parse_execution_address_word(&router_wrapped_raw)?;
948        if !router_wrapped.eq_ignore_ascii_case(&capability.wrapped_native_token_address) {
949            return execution_domain_error(SwapExecutionErrorCode::ProgramMismatch);
950        }
951
952        let amounts_out_data =
953            encode_get_amounts_out(&normalized.amount_in, &input_address, &output_address)?;
954        let router_amounts_raw = execution_rpc_request(
955            transport,
956            "eth_call",
957            json!([
958                abi_call(&capability.router_address, &amounts_out_data),
959                selector.clone()
960            ]),
961            options,
962        )
963        .await?;
964        let (router_amount_in, router_amount_out) = parse_execution_amounts(&router_amounts_raw)?;
965        if router_amount_in != normalized.amount_in
966            || router_amount_out
967                != BigUint::parse_bytes(quote.amount_out.as_bytes(), 10)
968                    .expect("quote amount is canonical")
969        {
970            return execution_invalid_simulation();
971        }
972
973        let latest_after_router_raw = execution_rpc_request(
974            transport,
975            "eth_getBlockByNumber",
976            json!(["latest", false]),
977            options,
978        )
979        .await?;
980        let latest_after_router = parse_execution_block_header(&latest_after_router_raw)?;
981        assert_freshness(
982            &state.initial,
983            &latest_after_router,
984            &normalized.freshness,
985            self,
986        )
987        .map_err(SwapExecutionError::from)?;
988        ensure_deadline(&scalars, &state.initial.timestamp, self)?;
989
990        let data = encode_swap_exact_tokens_for_tokens(
991            &normalized.amount_in,
992            &minimum_amount_out,
993            &input_address,
994            &output_address,
995            &scalars.recipient,
996            &scalars.deadline_value,
997        )?;
998        let preparation = ExactInputSwapPreparation {
999            preparation_kind: "evm-router-v2-exact-input".to_owned(),
1000            execution_capability_id: capability.swap_execution_capability_id,
1001            execution_capability_digest: SWAP_EXECUTION_CAPABILITIES_CONTENT_DIGEST.to_owned(),
1002            quote,
1003            minimum_amount_out: minimum_amount_out.to_str_radix(10),
1004            slippage_bps: scalars.slippage_bps,
1005            deadline: scalars.deadline,
1006            recipient: scalars.recipient.clone(),
1007            path: vec![
1008                SwapPathEntry {
1009                    token_deployment_id: normalized.input.deployment_id.to_owned(),
1010                    address: input_address.clone(),
1011                    standard: "erc20".to_owned(),
1012                    representation_kind: representation_kind_text(
1013                        normalized.input.representation_kind,
1014                    )
1015                    .to_owned(),
1016                },
1017                SwapPathEntry {
1018                    token_deployment_id: normalized.output.deployment_id.to_owned(),
1019                    address: output_address,
1020                    standard: "erc20".to_owned(),
1021                    representation_kind: representation_kind_text(
1022                        normalized.output.representation_kind,
1023                    )
1024                    .to_owned(),
1025                },
1026            ],
1027            transaction: EvmUnsignedTransaction {
1028                kind: "evm-unsigned-transaction".to_owned(),
1029                chain_id: normalized.request.chain_id,
1030                from: scalars.sender.clone(),
1031                to: capability.router_address.clone(),
1032                data,
1033                value: "0".to_owned(),
1034            },
1035            allowance: SwapAllowance {
1036                token_deployment_id: normalized.input.deployment_id.to_owned(),
1037                token_address: input_address,
1038                owner: scalars.sender,
1039                spender: capability.router_address,
1040                required_amount: normalized.amount_in.to_str_radix(10),
1041            },
1042        };
1043        Ok(PreparedExecution {
1044            preparation,
1045            initial: state.initial,
1046            freshness: normalized.freshness,
1047        })
1048    }
1049
1050    async fn simulate_internal(
1051        &self,
1052        prepared: PreparedExecution,
1053        options: &RequestOptions,
1054    ) -> SwapExecutionResult<ExactInputSwapSimulation> {
1055        let preparation = prepared.preparation;
1056        let selected_chain_id = preparation.transaction.chain_id.clone();
1057        let transport = if selected_chain_id == chain_id("ethereum") {
1058            &self.ethereum
1059        } else if selected_chain_id == chain_id("avalancheC") {
1060            &self.avalanche
1061        } else {
1062            return execution_domain_error(SwapExecutionErrorCode::UnsupportedExecution);
1063        };
1064        let amount_in = parse_execution_decimal(&preparation.quote.amount_in)?;
1065        let Ok(quote_amount_out) = parse_execution_decimal(&preparation.quote.amount_out) else {
1066            return execution_invalid_simulation();
1067        };
1068        let token_address = preparation.allowance.token_address.clone();
1069        let allowance_data =
1070            encode_allowance(&preparation.allowance.owner, &preparation.allowance.spender)?;
1071        let selector = rpc_selector(&preparation.quote.snapshot.block_hash);
1072        let allowance_raw = execution_rpc_request(
1073            transport,
1074            "eth_call",
1075            json!([abi_call(&token_address, &allowance_data), selector.clone()]),
1076            options,
1077        )
1078        .await?;
1079        let Ok(current_allowance) = parse_execution_uint_word(&allowance_raw) else {
1080            return execution_domain_error(SwapExecutionErrorCode::InsufficientAllowance);
1081        };
1082        if current_allowance < amount_in {
1083            return execution_domain_error(SwapExecutionErrorCode::InsufficientAllowance);
1084        }
1085
1086        let simulation_call = json!({
1087            "from": preparation.transaction.from,
1088            "to": preparation.transaction.to,
1089            "data": preparation.transaction.data,
1090            "value": "0x0",
1091        });
1092        let simulated_raw = match execution_rpc_request(
1093            transport,
1094            "eth_call",
1095            json!([simulation_call, selector]),
1096            options,
1097        )
1098        .await
1099        {
1100            Ok(value) => value,
1101            Err(SwapExecutionError::Upstream(error)) if is_execution_revert(&error) => {
1102                return execution_domain_error(SwapExecutionErrorCode::SimulationReverted);
1103            }
1104            Err(error) => return Err(error),
1105        };
1106        let (simulated_amount_in, simulated_amount_out, mut invalid_result) =
1107            match parse_execution_amounts(&simulated_raw) {
1108                Ok((amount_in, amount_out)) => (amount_in, amount_out, false),
1109                Err(_) => (BigUint::default(), BigUint::default(), true),
1110            };
1111        let minimum_amount_out =
1112            if let Ok(value) = parse_execution_decimal(&preparation.minimum_amount_out) {
1113                value
1114            } else {
1115                invalid_result = true;
1116                BigUint::default()
1117            };
1118
1119        let latest_raw = execution_rpc_request(
1120            transport,
1121            "eth_getBlockByNumber",
1122            json!(["latest", false]),
1123            options,
1124        )
1125        .await?;
1126        let latest = parse_execution_block_header(&latest_raw)?;
1127        assert_freshness(&prepared.initial, &latest, &prepared.freshness, self)
1128            .map_err(SwapExecutionError::from)?;
1129        let deadline_value = parse_execution_decimal(&preparation.deadline)?;
1130        let now = BigUint::from(now_seconds(self).map_err(SwapExecutionError::from)?);
1131        if deadline_value <= now {
1132            return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1133        }
1134
1135        if invalid_result
1136            || simulated_amount_in != amount_in
1137            || simulated_amount_out != quote_amount_out
1138            || simulated_amount_out < minimum_amount_out
1139        {
1140            return execution_invalid_simulation();
1141        }
1142
1143        let amount_in_text = simulated_amount_in.to_str_radix(10);
1144        let amount_out_text = simulated_amount_out.to_str_radix(10);
1145        Ok(ExactInputSwapSimulation {
1146            simulation_kind: "evm-call".to_owned(),
1147            snapshot: preparation.quote.snapshot.clone(),
1148            current_allowance: current_allowance.to_str_radix(10),
1149            amounts: vec![amount_in_text, amount_out_text.clone()],
1150            amount_out: amount_out_text,
1151            preparation,
1152        })
1153    }
1154
1155    #[cfg(test)]
1156    #[allow(dead_code)]
1157    pub(crate) fn with_clock(mut self, clock: fn() -> u64) -> Self {
1158        self.clock = Some(clock);
1159        self
1160    }
1161}
1162
1163#[derive(Clone)]
1164struct NormalizedFreshness {
1165    block_age_seconds: u64,
1166    block_lag: u64,
1167    clock_skew_seconds: u64,
1168}
1169
1170struct NormalizedRequest {
1171    request: ExactInputQuoteRequest,
1172    amount_in: BigUint,
1173    pool: &'static PoolDefinition,
1174    dex: &'static DexDeployment,
1175    input: &'static TokenDeployment,
1176    output: &'static TokenDeployment,
1177    freshness: NormalizedFreshness,
1178}
1179
1180#[derive(Clone)]
1181struct BlockHeader {
1182    number: BigUint,
1183    hash: String,
1184    timestamp: BigUint,
1185}
1186
1187struct EvmState {
1188    initial: BlockHeader,
1189    latest_after_reads: BlockHeader,
1190    reserve0: BigUint,
1191    reserve1: BigUint,
1192}
1193
1194#[derive(Debug)]
1195struct CalculatedQuote {
1196    amount_out: BigUint,
1197    fee_numerator: BigUint,
1198    fee_denominator: BigUint,
1199}
1200
1201#[allow(clippy::struct_field_names)]
1202#[derive(Clone, Debug, Deserialize)]
1203#[serde(deny_unknown_fields, rename_all = "camelCase")]
1204struct SwapExecutionCapability {
1205    swap_execution_capability_id: String,
1206    chain_id: String,
1207    dex_deployment_id: String,
1208    pool_definition_id: String,
1209    factory_address: String,
1210    router_address: String,
1211    router_kind: String,
1212    adapter_kind: String,
1213    token0_deployment_id: String,
1214    token0_address: String,
1215    token0_standard: String,
1216    token1_deployment_id: String,
1217    token1_address: String,
1218    token1_standard: String,
1219    wrapped_native_token_deployment_id: String,
1220    wrapped_native_token_address: String,
1221    wrapped_native_function_selector: String,
1222    function_kind: String,
1223    function_signature: String,
1224    function_selector: String,
1225    status: String,
1226}
1227
1228#[derive(Clone, Debug)]
1229struct NormalizedExecutionScalars {
1230    sender: String,
1231    recipient: String,
1232    slippage_bps: u64,
1233    deadline: String,
1234    deadline_value: BigUint,
1235}
1236
1237struct PreparedExecution {
1238    preparation: ExactInputSwapPreparation,
1239    initial: BlockHeader,
1240    freshness: NormalizedFreshness,
1241}
1242
1243fn domain_error<T>(code: SwapQuoteErrorCode) -> SwapResult<T> {
1244    Err(SwapQuoteError::Domain(code))
1245}
1246
1247fn execution_domain_error<T>(code: SwapExecutionErrorCode) -> SwapExecutionResult<T> {
1248    Err(SwapExecutionError::Domain(code))
1249}
1250
1251fn execution_invalid_simulation<T>() -> SwapExecutionResult<T> {
1252    execution_domain_error(SwapExecutionErrorCode::InvalidSimulation)
1253}
1254
1255fn normalize_execution_address(value: &str) -> SwapExecutionResult<String> {
1256    if !is_evm_address(value) || value[2..].bytes().all(|byte| byte == b'0') {
1257        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1258    }
1259    Ok(format!("0x{}", value[2..].to_ascii_lowercase()))
1260}
1261
1262fn parse_execution_decimal(value: &str) -> SwapExecutionResult<BigUint> {
1263    if value.is_empty()
1264        || value.len() > UINT256_DECIMAL_MAX_LENGTH
1265        || !value.bytes().all(|byte| byte.is_ascii_digit())
1266        || (value.len() > 1 && value.as_bytes()[0] == b'0')
1267    {
1268        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1269    }
1270    let Some(parsed) = BigUint::parse_bytes(value.as_bytes(), 10) else {
1271        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1272    };
1273    if parsed == BigUint::default() {
1274        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1275    }
1276    if parsed.bits() > 256 {
1277        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1278    }
1279    Ok(parsed)
1280}
1281
1282fn normalize_execution_scalars(
1283    request: &PrepareExactInputSwapRequest,
1284    client: &SwapClient,
1285) -> SwapExecutionResult<NormalizedExecutionScalars> {
1286    let sender = normalize_execution_address(&request.sender)?;
1287    let recipient = normalize_execution_address(&request.recipient)?;
1288    if request.slippage_bps > 9_999 {
1289        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1290    }
1291    let deadline_value = parse_execution_decimal(&request.deadline)?;
1292    let now = BigUint::from(now_seconds(client).map_err(SwapExecutionError::from)?);
1293    if deadline_value <= now {
1294        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1295    }
1296    Ok(NormalizedExecutionScalars {
1297        sender,
1298        recipient,
1299        slippage_bps: request.slippage_bps,
1300        deadline: request.deadline.clone(),
1301        deadline_value,
1302    })
1303}
1304
1305fn generated_execution_capabilities() -> Vec<SwapExecutionCapability> {
1306    let _ = std::hint::black_box(SWAP_EXECUTION_CAPABILITIES_AS_OF_DATE);
1307    serde_json::from_str(SWAP_EXECUTION_CAPABILITIES_JSON)
1308        .expect("generated swap execution capabilities must be valid")
1309}
1310
1311fn execution_capability_for(normalized: &NormalizedRequest) -> Option<SwapExecutionCapability> {
1312    let capability = generated_execution_capabilities()
1313        .into_iter()
1314        .find(|entry| entry.pool_definition_id == normalized.pool.pool_definition_id)?;
1315    let quote_capability = SUPPORTED_QUOTE_CAPABILITIES
1316        .iter()
1317        .find(|entry| entry.pool_definition_id == normalized.pool.pool_definition_id)?;
1318    let wrapped = get_token_deployment(&capability.wrapped_native_token_deployment_id)?;
1319    let native_wrap = NATIVE_WRAP_DEFINITIONS.iter().find(|entry| {
1320        entry.chain_id == capability.chain_id
1321            && entry.wrapped_token_deployment_id == capability.wrapped_native_token_deployment_id
1322    })?;
1323    let input_address = normalized.input.address?;
1324    let output_address = normalized.output.address?;
1325    let token0 = get_token_deployment(&capability.token0_deployment_id)?;
1326    let token1 = get_token_deployment(&capability.token1_deployment_id)?;
1327    let token0_address = token0.address?;
1328    let token1_address = token1.address?;
1329
1330    let rows_match = capability.status == "active"
1331        && capability.chain_id == normalized.pool.chain_id
1332        && capability.dex_deployment_id == normalized.pool.dex_deployment_id
1333        && capability.pool_definition_id == normalized.pool.pool_definition_id
1334        && capability.factory_address == normalized.dex.program_address
1335        && capability.router_address.starts_with("0x")
1336        && is_evm_address(&capability.router_address)
1337        && !capability.router_kind.is_empty()
1338        && capability.adapter_kind == SUPPORTED_QUOTE_ADAPTER
1339        && capability.token0_deployment_id == normalized.pool.token0_deployment_id
1340        && capability
1341            .token0_address
1342            .eq_ignore_ascii_case(token0_address)
1343        && capability.token0_standard == "erc20"
1344        && capability.token1_deployment_id == normalized.pool.token1_deployment_id
1345        && capability
1346            .token1_address
1347            .eq_ignore_ascii_case(token1_address)
1348        && capability.token1_standard == "erc20"
1349        && capability.wrapped_native_token_deployment_id == wrapped.deployment_id
1350        && capability
1351            .wrapped_native_token_address
1352            .eq_ignore_ascii_case(wrapped.address?)
1353        && wrapped.chain_id == normalized.pool.chain_id
1354        && wrapped.standard == TokenStandard::Erc20
1355        && wrapped.status == TokenStatus::Active
1356        && native_wrap.status == "active"
1357        && native_wrap.wrapped_token_deployment_id == capability.wrapped_native_token_deployment_id
1358        && capability
1359            .wrapped_native_function_selector
1360            .starts_with("0x")
1361        && capability.wrapped_native_function_selector.len() == 10
1362        && capability.function_kind == "exact-input-erc20-to-erc20"
1363        && capability.function_signature == SWAP_EXECUTION_FUNCTION_SIGNATURE
1364        && capability.function_selector == SWAP_EXECUTION_FUNCTION_SELECTOR
1365        && capability.router_address.len() == 42
1366        && normalized
1367            .pool
1368            .address
1369            .eq_ignore_ascii_case(quote_capability.pool_address)
1370        && normalized.pool.adapter.kind == quote_capability.adapter_kind
1371        && normalized.pool.adapter.fee_numerator == Some(quote_capability.fee_numerator)
1372        && normalized.pool.adapter.fee_denominator == Some(quote_capability.fee_denominator)
1373        && normalized.dex.dex_deployment_id == quote_capability.dex_deployment_id
1374        && normalized.dex.chain_id == quote_capability.chain_id
1375        && input_address != output_address;
1376    if !rows_match {
1377        return None;
1378    }
1379
1380    // The generated row binds the exact reviewed ordered pair, while the
1381    // quote request may select either direction.
1382    let token_pair_matches = (normalized.input.deployment_id == capability.token0_deployment_id
1383        || normalized.input.deployment_id == capability.token1_deployment_id)
1384        && (normalized.output.deployment_id == capability.token0_deployment_id
1385            || normalized.output.deployment_id == capability.token1_deployment_id);
1386    token_pair_matches.then_some(capability)
1387}
1388
1389fn quote_request_from_execution(request: &PrepareExactInputSwapRequest) -> ExactInputQuoteRequest {
1390    ExactInputQuoteRequest {
1391        chain_id: request.chain_id.clone(),
1392        pool_definition_id: request.pool_definition_id.clone(),
1393        input_token_deployment_id: request.input_token_deployment_id.clone(),
1394        output_token_deployment_id: request.output_token_deployment_id.clone(),
1395        amount_in: request.amount_in.clone(),
1396        freshness: request.freshness.clone(),
1397    }
1398}
1399
1400fn encode_uint256_word(value: &BigUint) -> SwapExecutionResult<String> {
1401    if value.bits() > 256 {
1402        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1403    }
1404    let hex = value.to_str_radix(16);
1405    Ok(format!("{hex:0>64}"))
1406}
1407
1408fn encode_execution_address_argument(address: &str) -> SwapExecutionResult<String> {
1409    if !is_evm_address(address) {
1410        return execution_invalid_simulation();
1411    }
1412    Ok(format!(
1413        "{}{}",
1414        "0".repeat(24),
1415        &address[2..].to_ascii_lowercase()
1416    ))
1417}
1418
1419async fn execution_rpc_request(
1420    transport: &HttpJsonRpcTransport,
1421    method: &str,
1422    params: Value,
1423    options: &RequestOptions,
1424) -> SwapExecutionResult<Value> {
1425    rpc_request(transport, method, params, options)
1426        .await
1427        .map_err(SwapExecutionError::from)
1428}
1429
1430fn parse_execution_hex_bytes(value: &Value) -> SwapExecutionResult<String> {
1431    parse_hex_bytes(value, None, SwapQuoteErrorCode::InvalidPoolState)
1432        .map_err(|_| SwapExecutionError::Domain(SwapExecutionErrorCode::InvalidSimulation))
1433}
1434
1435fn parse_execution_address_word(value: &Value) -> SwapExecutionResult<String> {
1436    let value = parse_execution_hex_bytes_exact(value, 32)?;
1437    let word = &value[2..];
1438    if !word[..24].bytes().all(|byte| byte == b'0') {
1439        return execution_invalid_simulation();
1440    }
1441    Ok(format!("0x{}", &word[24..]))
1442}
1443
1444fn parse_execution_hex_bytes_exact(
1445    value: &Value,
1446    expected_bytes: usize,
1447) -> SwapExecutionResult<String> {
1448    parse_hex_bytes(
1449        value,
1450        Some(expected_bytes),
1451        SwapQuoteErrorCode::InvalidPoolState,
1452    )
1453    .map_err(|_| SwapExecutionError::Domain(SwapExecutionErrorCode::InvalidSimulation))
1454}
1455
1456fn parse_execution_uint_word(value: &Value) -> SwapExecutionResult<BigUint> {
1457    let value = parse_execution_hex_bytes_exact(value, 32)?;
1458    let parsed = BigUint::parse_bytes(value[2..].as_bytes(), 16).ok_or(
1459        SwapExecutionError::Domain(SwapExecutionErrorCode::InvalidSimulation),
1460    )?;
1461    if parsed.bits() > 256 {
1462        return execution_invalid_simulation();
1463    }
1464    Ok(parsed)
1465}
1466
1467fn parse_execution_amounts(value: &Value) -> SwapExecutionResult<(BigUint, BigUint)> {
1468    let value = parse_execution_hex_bytes(value)?;
1469    let payload = &value[2..];
1470    // offset, length, and exactly two 32-byte values; trailing words are not
1471    // accepted because they could change the meaning of the returned array.
1472    if payload.len() != 64 * 4 {
1473        return execution_invalid_simulation();
1474    }
1475    let offset = BigUint::parse_bytes(payload[..64].as_bytes(), 16).ok_or(
1476        SwapExecutionError::Domain(SwapExecutionErrorCode::InvalidSimulation),
1477    )?;
1478    let length = BigUint::parse_bytes(payload[64..128].as_bytes(), 16).ok_or(
1479        SwapExecutionError::Domain(SwapExecutionErrorCode::InvalidSimulation),
1480    )?;
1481    if offset != BigUint::from(32_u8) || length != BigUint::from(2_u8) {
1482        return execution_invalid_simulation();
1483    }
1484    let amount_in = BigUint::parse_bytes(payload[128..192].as_bytes(), 16).ok_or(
1485        SwapExecutionError::Domain(SwapExecutionErrorCode::InvalidSimulation),
1486    )?;
1487    let amount_out = BigUint::parse_bytes(payload[192..256].as_bytes(), 16).ok_or(
1488        SwapExecutionError::Domain(SwapExecutionErrorCode::InvalidSimulation),
1489    )?;
1490    if amount_in.bits() > 256 || amount_out.bits() > 256 {
1491        return execution_invalid_simulation();
1492    }
1493    Ok((amount_in, amount_out))
1494}
1495
1496fn parse_execution_block_header(value: &Value) -> SwapExecutionResult<BlockHeader> {
1497    parse_block_header(value).map_err(SwapExecutionError::from)
1498}
1499
1500fn ensure_deadline(
1501    scalars: &NormalizedExecutionScalars,
1502    quote_timestamp: &BigUint,
1503    client: &SwapClient,
1504) -> SwapExecutionResult<()> {
1505    if scalars.deadline_value <= *quote_timestamp {
1506        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1507    }
1508    let now = BigUint::from(now_seconds(client).map_err(SwapExecutionError::from)?);
1509    if scalars.deadline_value <= now {
1510        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1511    }
1512    Ok(())
1513}
1514
1515fn minimum_amount_out(quote_amount_out: &str, slippage_bps: u64) -> SwapExecutionResult<BigUint> {
1516    let amount_out = BigUint::parse_bytes(quote_amount_out.as_bytes(), 10).ok_or(
1517        SwapExecutionError::Domain(SwapExecutionErrorCode::InvalidSimulation),
1518    )?;
1519    let product = ensure_uint256(
1520        amount_out * BigUint::from(10_000_u64 - slippage_bps),
1521        SwapQuoteErrorCode::Arithmetic,
1522    )
1523    .map_err(SwapExecutionError::from)?;
1524    let minimum = product / BigUint::from(10_000_u64);
1525    if minimum == BigUint::default() {
1526        return execution_domain_error(SwapExecutionErrorCode::InvalidArgument);
1527    }
1528    Ok(minimum)
1529}
1530
1531fn encode_get_amounts_out(
1532    amount_in: &BigUint,
1533    input_address: &str,
1534    output_address: &str,
1535) -> SwapExecutionResult<String> {
1536    Ok(format!(
1537        "{}{}{}{}{}{}",
1538        ROUTER_GET_AMOUNTS_OUT_SELECTOR,
1539        encode_uint256_word(amount_in)?,
1540        encode_uint256_word(&BigUint::from(64_u8))?,
1541        encode_uint256_word(&BigUint::from(2_u8))?,
1542        encode_execution_address_argument(input_address)?,
1543        encode_execution_address_argument(output_address)?,
1544    ))
1545}
1546
1547fn encode_swap_exact_tokens_for_tokens(
1548    amount_in: &BigUint,
1549    minimum_amount_out: &BigUint,
1550    input_address: &str,
1551    output_address: &str,
1552    recipient: &str,
1553    deadline: &BigUint,
1554) -> SwapExecutionResult<String> {
1555    Ok(format!(
1556        "{}{}{}{}{}{}{}{}{}",
1557        SWAP_EXECUTION_FUNCTION_SELECTOR,
1558        encode_uint256_word(amount_in)?,
1559        encode_uint256_word(minimum_amount_out)?,
1560        encode_uint256_word(&BigUint::from(160_u16))?,
1561        encode_execution_address_argument(recipient)?,
1562        encode_uint256_word(deadline)?,
1563        encode_uint256_word(&BigUint::from(2_u8))?,
1564        encode_execution_address_argument(input_address)?,
1565        encode_execution_address_argument(output_address)?,
1566    ))
1567}
1568
1569fn encode_allowance(owner: &str, spender: &str) -> SwapExecutionResult<String> {
1570    Ok(format!(
1571        "{}{}{}",
1572        ERC20_ALLOWANCE_SELECTOR,
1573        encode_execution_address_argument(owner)?,
1574        encode_execution_address_argument(spender)?,
1575    ))
1576}
1577
1578fn representation_kind_text(kind: TokenRepresentationKind) -> &'static str {
1579    match kind {
1580        TokenRepresentationKind::Native => "native",
1581        TokenRepresentationKind::Issued => "issued",
1582        TokenRepresentationKind::Wrapped => "wrapped",
1583        TokenRepresentationKind::Bridged => "bridged",
1584        TokenRepresentationKind::Unclassified => "unclassified",
1585    }
1586}
1587
1588fn is_execution_revert(error: &ErpcError) -> bool {
1589    let ErpcError::JsonRpc {
1590        code,
1591        message,
1592        data: _,
1593    } = error
1594    else {
1595        return false;
1596    };
1597    let message = message.to_ascii_lowercase();
1598    (*code == 3 || *code == -32_000 || *code == -32_015 || *code == -32_603)
1599        && (message.contains("execution reverted")
1600            || message.contains("transaction reverted")
1601            || message.contains("vm execution error")
1602            || message.starts_with("revert"))
1603}
1604
1605fn normalize_request(request: &ExactInputQuoteRequest) -> SwapResult<NormalizedRequest> {
1606    for value in [
1607        request.chain_id.as_str(),
1608        request.pool_definition_id.as_str(),
1609        request.input_token_deployment_id.as_str(),
1610        request.output_token_deployment_id.as_str(),
1611        request.amount_in.as_str(),
1612    ] {
1613        if value.is_empty() || value.trim() != value {
1614            return domain_error(SwapQuoteErrorCode::InvalidArgument);
1615        }
1616    }
1617    for value in [
1618        request.pool_definition_id.as_str(),
1619        request.input_token_deployment_id.as_str(),
1620        request.output_token_deployment_id.as_str(),
1621    ] {
1622        if !is_opaque_id(value) {
1623            return domain_error(SwapQuoteErrorCode::InvalidArgument);
1624        }
1625    }
1626    let freshness = normalize_freshness(request.freshness.as_ref())?;
1627    let amount_in = parse_canonical_decimal(&request.amount_in, true)?;
1628
1629    if !is_known_chain(&request.chain_id) {
1630        return domain_error(SwapQuoteErrorCode::UnsupportedChain);
1631    }
1632    let Some(pool) = get_pool_definition(&request.pool_definition_id) else {
1633        return domain_error(SwapQuoteErrorCode::UnknownPool);
1634    };
1635    if pool.chain_id != request.chain_id {
1636        return domain_error(SwapQuoteErrorCode::ChainMismatch);
1637    }
1638    if pool.status != "active" {
1639        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
1640    }
1641    let Some(dex) = get_dex_deployment(pool.dex_deployment_id) else {
1642        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
1643    };
1644    if dex.status != "active" {
1645        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
1646    }
1647
1648    let Some(input) = get_token_deployment(&request.input_token_deployment_id) else {
1649        return domain_error(SwapQuoteErrorCode::UnknownToken);
1650    };
1651    let Some(output) = get_token_deployment(&request.output_token_deployment_id) else {
1652        return domain_error(SwapQuoteErrorCode::UnknownToken);
1653    };
1654    if input.chain_id != request.chain_id || output.chain_id != request.chain_id {
1655        return domain_error(SwapQuoteErrorCode::ChainMismatch);
1656    }
1657    for token in [input, output] {
1658        if token.status != TokenStatus::Active {
1659            return domain_error(SwapQuoteErrorCode::TokenNotActive);
1660        }
1661    }
1662    // Classic SPL records remain eligible for pair matching so lookup-only
1663    // Solana pools fail at the adapter gate without performing RPC.
1664    for token in [input, output] {
1665        if token.standard != TokenStandard::Erc20 && token.standard != TokenStandard::SplToken {
1666            return domain_error(SwapQuoteErrorCode::UnsupportedTokenStandard);
1667        }
1668    }
1669    if request.input_token_deployment_id == request.output_token_deployment_id {
1670        return domain_error(SwapQuoteErrorCode::PoolTokenMismatch);
1671    }
1672    let (wanted_left, wanted_right) = ordered_pair(
1673        &request.input_token_deployment_id,
1674        &request.output_token_deployment_id,
1675    );
1676    let (actual_left, actual_right) =
1677        ordered_pair(pool.token0_deployment_id, pool.token1_deployment_id);
1678    if wanted_left != actual_left || wanted_right != actual_right {
1679        return domain_error(SwapQuoteErrorCode::PoolTokenMismatch);
1680    }
1681    if pool.adapter.kind != SUPPORTED_QUOTE_ADAPTER || dex.adapter_kind != SUPPORTED_QUOTE_ADAPTER {
1682        return domain_error(SwapQuoteErrorCode::UnsupportedAdapter);
1683    }
1684    if input.standard != TokenStandard::Erc20 || output.standard != TokenStandard::Erc20 {
1685        return domain_error(SwapQuoteErrorCode::UnsupportedTokenStandard);
1686    }
1687    if !matches_supported_quote_capability(pool, dex, input, output) {
1688        return domain_error(SwapQuoteErrorCode::UnsupportedToken);
1689    }
1690
1691    Ok(NormalizedRequest {
1692        request: request.clone(),
1693        amount_in,
1694        pool,
1695        dex,
1696        input,
1697        output,
1698        freshness,
1699    })
1700}
1701
1702fn matches_supported_quote_capability(
1703    pool: &PoolDefinition,
1704    dex: &DexDeployment,
1705    input: &TokenDeployment,
1706    output: &TokenDeployment,
1707) -> bool {
1708    fn matches_token(
1709        token: &TokenDeployment,
1710        chain_id: &str,
1711        deployment_id: &str,
1712        address: &str,
1713        decimals: u8,
1714        standard: TokenStandard,
1715    ) -> bool {
1716        token.chain_id == chain_id
1717            && token.deployment_id == deployment_id
1718            && token.address == Some(address)
1719            && token.decimals == decimals
1720            && token.standard == standard
1721    }
1722
1723    let Some(capability) = SUPPORTED_QUOTE_CAPABILITIES
1724        .iter()
1725        .find(|entry| entry.pool_definition_id == pool.pool_definition_id)
1726    else {
1727        return false;
1728    };
1729
1730    if input.representation_kind == crate::token_catalog::TokenRepresentationKind::Unclassified
1731        || output.representation_kind == crate::token_catalog::TokenRepresentationKind::Unclassified
1732    {
1733        return false;
1734    }
1735
1736    let matches_input = matches_token(
1737        input,
1738        capability.chain_id,
1739        capability.token0_deployment_id,
1740        capability.token0_address,
1741        capability.token0_decimals,
1742        capability.token0_standard,
1743    ) || matches_token(
1744        input,
1745        capability.chain_id,
1746        capability.token1_deployment_id,
1747        capability.token1_address,
1748        capability.token1_decimals,
1749        capability.token1_standard,
1750    );
1751    let matches_output = matches_token(
1752        output,
1753        capability.chain_id,
1754        capability.token0_deployment_id,
1755        capability.token0_address,
1756        capability.token0_decimals,
1757        capability.token0_standard,
1758    ) || matches_token(
1759        output,
1760        capability.chain_id,
1761        capability.token1_deployment_id,
1762        capability.token1_address,
1763        capability.token1_decimals,
1764        capability.token1_standard,
1765    );
1766
1767    pool.chain_id == capability.chain_id
1768        && pool.dex_deployment_id == capability.dex_deployment_id
1769        && pool.address == capability.pool_address
1770        && pool.token0_deployment_id == capability.token0_deployment_id
1771        && pool.token1_deployment_id == capability.token1_deployment_id
1772        && pool.adapter.kind == capability.adapter_kind
1773        && pool.adapter.fee_numerator == Some(capability.fee_numerator)
1774        && pool.adapter.fee_denominator == Some(capability.fee_denominator)
1775        && dex.dex_deployment_id == capability.dex_deployment_id
1776        && dex.chain_id == capability.chain_id
1777        && dex.program_address == capability.factory_address
1778        && dex.adapter_kind == capability.adapter_kind
1779        && matches_input
1780        && matches_output
1781}
1782
1783fn normalize_freshness(value: Option<&SwapFreshness>) -> SwapResult<NormalizedFreshness> {
1784    let defaults = (120, 3, 5);
1785    let values = (
1786        value
1787            .and_then(|freshness| freshness.max_block_age_seconds)
1788            .unwrap_or(defaults.0),
1789        value
1790            .and_then(|freshness| freshness.max_block_lag)
1791            .unwrap_or(defaults.1),
1792        value
1793            .and_then(|freshness| freshness.max_clock_skew_seconds)
1794            .unwrap_or(defaults.2),
1795    );
1796    if values.0 > 86_400 || values.1 > 1_024 || values.2 > 300 {
1797        return domain_error(SwapQuoteErrorCode::InvalidArgument);
1798    }
1799    Ok(NormalizedFreshness {
1800        block_age_seconds: values.0,
1801        block_lag: values.1,
1802        clock_skew_seconds: values.2,
1803    })
1804}
1805
1806fn is_known_chain(chain_id: &str) -> bool {
1807    DEX_CHAIN_IDS
1808        .iter()
1809        .any(|(_, candidate)| *candidate == chain_id)
1810}
1811
1812fn chain_id(name: &str) -> &'static str {
1813    DEX_CHAIN_IDS
1814        .iter()
1815        .find(|(candidate, _)| *candidate == name)
1816        .map_or("", |(_, value)| value)
1817}
1818
1819fn is_opaque_id(value: &str) -> bool {
1820    let mut bytes = value.bytes();
1821    matches!(bytes.next(), Some(b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'))
1822        && bytes
1823            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
1824}
1825
1826fn ordered_pair<'a>(left: &'a str, right: &'a str) -> (&'a str, &'a str) {
1827    if left <= right {
1828        (left, right)
1829    } else {
1830        (right, left)
1831    }
1832}
1833
1834fn ensure_uint256(value: BigUint, code: SwapQuoteErrorCode) -> SwapResult<BigUint> {
1835    if value.bits() > 256 {
1836        return domain_error(code);
1837    }
1838    Ok(value)
1839}
1840
1841fn parse_canonical_decimal(value: &str, positive: bool) -> SwapResult<BigUint> {
1842    if value.is_empty()
1843        || value.len() > UINT256_DECIMAL_MAX_LENGTH
1844        || !value.bytes().all(|byte| byte.is_ascii_digit())
1845        || (value.len() > 1 && value.as_bytes()[0] == b'0')
1846    {
1847        return domain_error(SwapQuoteErrorCode::InvalidArgument);
1848    }
1849    let Some(parsed) = BigUint::parse_bytes(value.as_bytes(), 10) else {
1850        return domain_error(SwapQuoteErrorCode::InvalidArgument);
1851    };
1852    if positive && parsed == BigUint::default() {
1853        return domain_error(SwapQuoteErrorCode::InvalidArgument);
1854    }
1855    ensure_uint256(parsed, SwapQuoteErrorCode::InvalidArgument)
1856}
1857
1858fn parse_decimal_quantity(value: Option<&str>, code: SwapQuoteErrorCode) -> SwapResult<BigUint> {
1859    let Some(value) = value else {
1860        return domain_error(code);
1861    };
1862    if value.is_empty()
1863        || value.len() > UINT256_DECIMAL_MAX_LENGTH
1864        || !value.bytes().all(|byte| byte.is_ascii_digit())
1865        || (value.len() > 1 && value.as_bytes()[0] == b'0')
1866    {
1867        return domain_error(code);
1868    }
1869    let Some(parsed) = BigUint::parse_bytes(value.as_bytes(), 10) else {
1870        return domain_error(code);
1871    };
1872    ensure_uint256(parsed, code)
1873}
1874
1875fn parse_hex_quantity(value: &Value, code: SwapQuoteErrorCode) -> SwapResult<BigUint> {
1876    let Some(value) = value.as_str() else {
1877        return domain_error(code);
1878    };
1879    let bytes = value.as_bytes();
1880    if bytes.len() < 3
1881        || bytes.len() > 66
1882        || bytes[0] != b'0'
1883        || bytes[1] != b'x'
1884        || !bytes[2..].iter().all(u8::is_ascii_hexdigit)
1885        || (bytes[2] == b'0' && bytes.len() > 3)
1886    {
1887        return domain_error(code);
1888    }
1889    let Some(parsed) = BigUint::parse_bytes(&bytes[2..], 16) else {
1890        return domain_error(code);
1891    };
1892    ensure_uint256(parsed, code)
1893}
1894
1895fn parse_hex_bytes(
1896    value: &Value,
1897    expected_bytes: Option<usize>,
1898    code: SwapQuoteErrorCode,
1899) -> SwapResult<String> {
1900    let Some(value) = value.as_str() else {
1901        return domain_error(code);
1902    };
1903    let bytes = value.as_bytes();
1904    if bytes.len() < 2
1905        || bytes[0] != b'0'
1906        || bytes[1] != b'x'
1907        || !bytes[2..].iter().all(u8::is_ascii_hexdigit)
1908        || (bytes.len() - 2) % 2 != 0
1909        || expected_bytes.is_some_and(|expected| bytes.len() != expected * 2 + 2)
1910    {
1911        return domain_error(code);
1912    }
1913    Ok(value.to_ascii_lowercase())
1914}
1915
1916fn parse_block_header(value: &Value) -> SwapResult<BlockHeader> {
1917    let Some(object) = value.as_object() else {
1918        return domain_error(SwapQuoteErrorCode::StateStale);
1919    };
1920    let number = parse_hex_quantity(
1921        object
1922            .get("number")
1923            .ok_or(SwapQuoteError::Domain(SwapQuoteErrorCode::StateStale))?,
1924        SwapQuoteErrorCode::StateStale,
1925    )?;
1926    let hash = parse_hex_bytes(
1927        object
1928            .get("hash")
1929            .ok_or(SwapQuoteError::Domain(SwapQuoteErrorCode::StateStale))?,
1930        Some(32),
1931        SwapQuoteErrorCode::StateStale,
1932    )?;
1933    let timestamp = parse_hex_quantity(
1934        object
1935            .get("timestamp")
1936            .ok_or(SwapQuoteError::Domain(SwapQuoteErrorCode::StateStale))?,
1937        SwapQuoteErrorCode::StateStale,
1938    )?;
1939    Ok(BlockHeader {
1940        number,
1941        hash,
1942        timestamp,
1943    })
1944}
1945
1946fn parse_address_word(value: &Value) -> SwapResult<String> {
1947    let value = parse_hex_bytes(value, Some(32), SwapQuoteErrorCode::InvalidPoolState)?;
1948    let word = &value[2..];
1949    if !word[..24].bytes().all(|byte| byte == b'0') {
1950        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
1951    }
1952    Ok(format!("0x{}", &word[24..]))
1953}
1954
1955fn parse_uint_word(value: &str, maximum_bits: u64) -> SwapResult<BigUint> {
1956    let parsed = BigUint::parse_bytes(value.as_bytes(), 16)
1957        .ok_or(SwapQuoteError::Domain(SwapQuoteErrorCode::InvalidPoolState))?;
1958    if parsed.bits() > maximum_bits {
1959        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
1960    }
1961    Ok(parsed)
1962}
1963
1964fn parse_reserves(value: &Value) -> SwapResult<(BigUint, BigUint)> {
1965    let value = parse_hex_bytes(value, Some(96), SwapQuoteErrorCode::InvalidPoolState)?;
1966    let payload = &value[2..];
1967    let reserve0 = parse_uint_word(&payload[..64], UINT112_MAX_BITS)?;
1968    let reserve1 = parse_uint_word(&payload[64..128], UINT112_MAX_BITS)?;
1969    let _timestamp = parse_uint_word(&payload[128..192], UINT32_MAX_BITS)?;
1970    Ok((reserve0, reserve1))
1971}
1972
1973fn rpc_selector(hash: &str) -> Value {
1974    json!({ "blockHash": hash, "requireCanonical": true })
1975}
1976
1977fn abi_call(to: &str, data: &str) -> Value {
1978    json!({ "to": to, "data": data })
1979}
1980
1981fn encode_address_argument(address: &str) -> SwapResult<String> {
1982    if !is_evm_address(address) {
1983        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
1984    }
1985    Ok(format!(
1986        "{}{}",
1987        "0".repeat(24),
1988        &address[2..].to_ascii_lowercase()
1989    ))
1990}
1991
1992fn is_evm_address(address: &str) -> bool {
1993    let bytes = address.as_bytes();
1994    bytes.len() == 42
1995        && bytes[0] == b'0'
1996        && bytes[1] == b'x'
1997        && bytes[2..].iter().all(u8::is_ascii_hexdigit)
1998}
1999
2000async fn rpc_request(
2001    transport: &HttpJsonRpcTransport,
2002    method: &str,
2003    params: Value,
2004    options: &RequestOptions,
2005) -> SwapResult<Value> {
2006    transport
2007        .request(method, Some(params), options)
2008        .await
2009        .map_err(SwapQuoteError::Upstream)
2010}
2011
2012#[allow(clippy::too_many_lines)]
2013async fn read_evm_state(
2014    transport: &HttpJsonRpcTransport,
2015    normalized: &NormalizedRequest,
2016    options: &RequestOptions,
2017    client: &SwapClient,
2018) -> SwapResult<EvmState> {
2019    let chain_value = rpc_request(transport, "eth_chainId", json!([]), options).await?;
2020    let network_chain_id = parse_hex_quantity(&chain_value, SwapQuoteErrorCode::ChainMismatch)?;
2021    let expected_chain = if normalized.pool.chain_id == chain_id("ethereum") {
2022        1_u32
2023    } else {
2024        43_114_u32
2025    };
2026    if network_chain_id != BigUint::from(expected_chain) {
2027        return domain_error(SwapQuoteErrorCode::ChainMismatch);
2028    }
2029
2030    let initial_value = rpc_request(
2031        transport,
2032        "eth_getBlockByNumber",
2033        json!(["latest", false]),
2034        options,
2035    )
2036    .await?;
2037    let initial = parse_block_header(&initial_value)?;
2038    let selector = rpc_selector(&initial.hash);
2039
2040    // Keep these seven responses opaque until both final headers and freshness
2041    // checks pass. This gives stale/reorg errors precedence over malformed ABI.
2042    let factory_code_raw = rpc_request(
2043        transport,
2044        "eth_getCode",
2045        json!([normalized.dex.program_address, selector.clone()]),
2046        options,
2047    )
2048    .await?;
2049    let pool_code_raw = rpc_request(
2050        transport,
2051        "eth_getCode",
2052        json!([normalized.pool.address, selector.clone()]),
2053        options,
2054    )
2055    .await?;
2056    let Some(token0) = get_token_deployment(normalized.pool.token0_deployment_id) else {
2057        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
2058    };
2059    let Some(token1) = get_token_deployment(normalized.pool.token1_deployment_id) else {
2060        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
2061    };
2062    let (Some(token0_address), Some(token1_address)) = (token0.address, token1.address) else {
2063        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
2064    };
2065    let pair_data = format!(
2066        "{}{}{}",
2067        FACTORY_GET_PAIR_SELECTOR,
2068        encode_address_argument(token0_address)?,
2069        encode_address_argument(token1_address)?,
2070    );
2071    let factory_pair_raw = rpc_request(
2072        transport,
2073        "eth_call",
2074        json!([
2075            abi_call(normalized.dex.program_address, &pair_data),
2076            selector.clone()
2077        ]),
2078        options,
2079    )
2080    .await?;
2081    let pair_factory_raw = rpc_request(
2082        transport,
2083        "eth_call",
2084        json!([
2085            abi_call(normalized.pool.address, PAIR_FACTORY_SELECTOR),
2086            selector.clone()
2087        ]),
2088        options,
2089    )
2090    .await?;
2091    let pair_token0_raw = rpc_request(
2092        transport,
2093        "eth_call",
2094        json!([
2095            abi_call(normalized.pool.address, PAIR_TOKEN0_SELECTOR),
2096            selector.clone()
2097        ]),
2098        options,
2099    )
2100    .await?;
2101    let pair_token1_raw = rpc_request(
2102        transport,
2103        "eth_call",
2104        json!([
2105            abi_call(normalized.pool.address, PAIR_TOKEN1_SELECTOR),
2106            selector.clone()
2107        ]),
2108        options,
2109    )
2110    .await?;
2111    let reserves_raw = rpc_request(
2112        transport,
2113        "eth_call",
2114        json!([
2115            abi_call(normalized.pool.address, PAIR_GET_RESERVES_SELECTOR),
2116            selector
2117        ]),
2118        options,
2119    )
2120    .await?;
2121
2122    let latest_after_reads_value = rpc_request(
2123        transport,
2124        "eth_getBlockByNumber",
2125        json!(["latest", false]),
2126        options,
2127    )
2128    .await?;
2129    let latest_after_reads = parse_block_header(&latest_after_reads_value)?;
2130    let block_number = format!("0x{}", initial.number.to_str_radix(16));
2131    let reread_value = rpc_request(
2132        transport,
2133        "eth_getBlockByNumber",
2134        json!([block_number, false]),
2135        options,
2136    )
2137    .await?;
2138    let reread = parse_block_header(&reread_value)?;
2139    if reread.number != initial.number
2140        || reread.hash != initial.hash
2141        || reread.timestamp != initial.timestamp
2142    {
2143        return domain_error(SwapQuoteErrorCode::StateStale);
2144    }
2145
2146    // Freshness and reorg checks run while all seven state responses are still
2147    // opaque. This preserves deterministic stale precedence over malformed ABI.
2148    assert_freshness(&initial, &latest_after_reads, &normalized.freshness, client)?;
2149
2150    // ABI decoding deliberately starts only after the final header checks.
2151    let factory_code = parse_hex_bytes(
2152        &factory_code_raw,
2153        None,
2154        SwapQuoteErrorCode::InvalidPoolState,
2155    )?;
2156    if factory_code.len() <= 2 {
2157        return domain_error(SwapQuoteErrorCode::ProgramMismatch);
2158    }
2159    let pool_code = parse_hex_bytes(&pool_code_raw, None, SwapQuoteErrorCode::InvalidPoolState)?;
2160    if pool_code.len() <= 2 {
2161        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
2162    }
2163    let factory_pair = parse_address_word(&factory_pair_raw)?;
2164    if !factory_pair.eq_ignore_ascii_case(normalized.pool.address) {
2165        return domain_error(SwapQuoteErrorCode::ProgramMismatch);
2166    }
2167    let pair_factory = parse_address_word(&pair_factory_raw)?;
2168    if !pair_factory.eq_ignore_ascii_case(normalized.dex.program_address) {
2169        return domain_error(SwapQuoteErrorCode::ProgramMismatch);
2170    }
2171    let pair_token0 = parse_address_word(&pair_token0_raw)?;
2172    let pair_token1 = parse_address_word(&pair_token1_raw)?;
2173    if !pair_token0.eq_ignore_ascii_case(token0_address)
2174        || !pair_token1.eq_ignore_ascii_case(token1_address)
2175    {
2176        return domain_error(SwapQuoteErrorCode::PoolTokenMismatch);
2177    }
2178    let (reserve0, reserve1) = parse_reserves(&reserves_raw)?;
2179    Ok(EvmState {
2180        initial,
2181        latest_after_reads,
2182        reserve0,
2183        reserve1,
2184    })
2185}
2186
2187#[cfg(test)]
2188fn now_seconds(client: &SwapClient) -> SwapResult<u64> {
2189    if let Some(clock) = client.clock {
2190        return Ok(clock());
2191    }
2192    SystemTime::now()
2193        .duration_since(UNIX_EPOCH)
2194        .map(|duration| duration.as_secs())
2195        .map_err(|_| SwapQuoteError::Domain(SwapQuoteErrorCode::InvalidArgument))
2196}
2197
2198#[cfg(not(test))]
2199fn now_seconds(_client: &SwapClient) -> SwapResult<u64> {
2200    SystemTime::now()
2201        .duration_since(UNIX_EPOCH)
2202        .map(|duration| duration.as_secs())
2203        .map_err(|_| SwapQuoteError::Domain(SwapQuoteErrorCode::InvalidArgument))
2204}
2205
2206fn assert_freshness(
2207    initial: &BlockHeader,
2208    latest_after_reads: &BlockHeader,
2209    freshness: &NormalizedFreshness,
2210    client: &SwapClient,
2211) -> SwapResult<()> {
2212    let now = BigUint::from(now_seconds(client)?);
2213    let skew = BigUint::from(freshness.clock_skew_seconds);
2214    let max_age = BigUint::from(freshness.block_age_seconds);
2215    for timestamp in [&initial.timestamp, &latest_after_reads.timestamp] {
2216        if *timestamp > now.clone() + skew.clone()
2217            || (now > *timestamp && now.clone() - timestamp > max_age)
2218        {
2219            return domain_error(SwapQuoteErrorCode::StateStale);
2220        }
2221    }
2222    let max_lag = BigUint::from(freshness.block_lag);
2223    if latest_after_reads.number < initial.number
2224        || latest_after_reads.number.clone() - &initial.number > max_lag
2225    {
2226        return domain_error(SwapQuoteErrorCode::StateStale);
2227    }
2228    if latest_after_reads.number == initial.number && latest_after_reads.hash != initial.hash {
2229        return domain_error(SwapQuoteErrorCode::StateStale);
2230    }
2231    if latest_after_reads.number > initial.number
2232        && latest_after_reads.timestamp < initial.timestamp
2233    {
2234        return domain_error(SwapQuoteErrorCode::StateStale);
2235    }
2236    if latest_after_reads.number == initial.number
2237        && latest_after_reads.hash == initial.hash
2238        && latest_after_reads.timestamp != initial.timestamp
2239    {
2240        return domain_error(SwapQuoteErrorCode::StateStale);
2241    }
2242    Ok(())
2243}
2244
2245fn calculate_quote(
2246    normalized: &NormalizedRequest,
2247    state: &EvmState,
2248) -> SwapResult<CalculatedQuote> {
2249    let fee_numerator = parse_decimal_quantity(
2250        normalized.pool.adapter.fee_numerator,
2251        SwapQuoteErrorCode::Arithmetic,
2252    )?;
2253    let fee_denominator = parse_decimal_quantity(
2254        normalized.pool.adapter.fee_denominator,
2255        SwapQuoteErrorCode::Arithmetic,
2256    )?;
2257    if fee_denominator <= fee_numerator {
2258        return domain_error(SwapQuoteErrorCode::Arithmetic);
2259    }
2260    let Some(token0) = get_token_deployment(normalized.pool.token0_deployment_id) else {
2261        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
2262    };
2263    let (Some(token0_address), Some(input_address), Some(output_address)) = (
2264        token0.address,
2265        normalized.input.address,
2266        normalized.output.address,
2267    ) else {
2268        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
2269    };
2270    let input_is_token0 = input_address.eq_ignore_ascii_case(token0_address);
2271    let output_is_token0 = output_address.eq_ignore_ascii_case(token0_address);
2272    if input_is_token0 == output_is_token0 {
2273        return domain_error(SwapQuoteErrorCode::InvalidPoolState);
2274    }
2275    let (reserve_in, reserve_out) = if input_is_token0 {
2276        (&state.reserve0, &state.reserve1)
2277    } else {
2278        (&state.reserve1, &state.reserve0)
2279    };
2280    if reserve_in == &BigUint::default() || reserve_out == &BigUint::default() {
2281        return domain_error(SwapQuoteErrorCode::InsufficientLiquidity);
2282    }
2283
2284    let fee_factor = &fee_denominator - &fee_numerator;
2285    let adjusted = ensure_uint256(
2286        normalized.amount_in.clone() * &fee_factor,
2287        SwapQuoteErrorCode::Arithmetic,
2288    )?;
2289    let reserve_product = ensure_uint256(
2290        reserve_in.clone() * &fee_denominator,
2291        SwapQuoteErrorCode::Arithmetic,
2292    )?;
2293    let denominator = ensure_uint256(reserve_product + &adjusted, SwapQuoteErrorCode::Arithmetic)?;
2294    if denominator == BigUint::default() {
2295        return domain_error(SwapQuoteErrorCode::Arithmetic);
2296    }
2297    let numerator = ensure_uint256(
2298        adjusted.clone() * reserve_out,
2299        SwapQuoteErrorCode::Arithmetic,
2300    )?;
2301    let amount_out = ensure_uint256(numerator / denominator, SwapQuoteErrorCode::Arithmetic)?;
2302    if amount_out == BigUint::default() || amount_out > *reserve_out {
2303        return domain_error(SwapQuoteErrorCode::InsufficientLiquidity);
2304    }
2305    Ok(CalculatedQuote {
2306        amount_out,
2307        fee_numerator,
2308        fee_denominator,
2309    })
2310}
2311
2312fn quote_result(
2313    normalized: &NormalizedRequest,
2314    state: &EvmState,
2315    calculated: &CalculatedQuote,
2316) -> ExactInputQuoteResult {
2317    ExactInputQuoteResult {
2318        quote_kind: "exact-input",
2319        chain_id: normalized.request.chain_id.clone(),
2320        pool_definition_id: normalized.request.pool_definition_id.clone(),
2321        dex_deployment_id: normalized.pool.dex_deployment_id.to_owned(),
2322        adapter_kind: normalized.pool.adapter.kind.to_owned(),
2323        input_token_deployment_id: normalized.request.input_token_deployment_id.clone(),
2324        output_token_deployment_id: normalized.request.output_token_deployment_id.clone(),
2325        amount_in: normalized.amount_in.to_str_radix(10),
2326        amount_out: calculated.amount_out.to_str_radix(10),
2327        fee: QuoteFee {
2328            numerator: calculated.fee_numerator.to_str_radix(10),
2329            denominator: calculated.fee_denominator.to_str_radix(10),
2330        },
2331        snapshot: EvmBlockSnapshot {
2332            kind: "evm-block",
2333            block_number: state.initial.number.to_str_radix(10),
2334            block_hash: state.initial.hash.clone(),
2335            block_timestamp: state.initial.timestamp.to_str_radix(10),
2336        },
2337        token_catalog_digest: TOKEN_CATALOG_CONTENT_DIGEST,
2338        dex_catalog_digest: DEX_CATALOG_CONTENT_DIGEST,
2339    }
2340}
2341
2342#[cfg(test)]
2343mod tests {
2344    use super::*;
2345    use std::{collections::BTreeSet, env, fs, path::Path, time::Duration};
2346
2347    use serde_json::{Map, json};
2348    use tokio::{
2349        io::{AsyncReadExt, AsyncWriteExt},
2350        net::{TcpListener, TcpStream},
2351        task::JoinHandle,
2352    };
2353
2354    use crate::{
2355        dex_catalog::{
2356            DEX_ALIASES, DEX_CATALOG_AS_OF_DATE, DEX_CATALOG_VERSION, DEX_DEPLOYMENTS, DexAlias,
2357            ListPoolDefinitionsOptions, NATIVE_WRAP_DEFINITIONS, NativeWrapDefinition,
2358            POOL_DEFINITIONS, find_pool_definition_by_address, find_pool_definitions_by_pair,
2359            get_dex_deployment, get_native_wrap_definition, get_pool_definition,
2360            list_pool_definitions,
2361        },
2362        token_catalog::{TOKEN_DEPLOYMENTS, TokenRepresentationKind, TokenStandard},
2363    };
2364
2365    #[test]
2366    fn canonical_amount_parser_accepts_large_uint256_text() {
2367        let value = parse_canonical_decimal("9007199254740993", true).expect("valid amount");
2368        assert_eq!(value.to_str_radix(10), "9007199254740993");
2369        assert!(
2370            parse_canonical_decimal(
2371                "115792089237316195423570985008687907853269984665640564039457584007913129639935",
2372                true
2373            )
2374            .is_ok()
2375        );
2376        assert!(parse_canonical_decimal("01", true).is_err());
2377        assert!(parse_canonical_decimal("0", true).is_err());
2378    }
2379
2380    #[test]
2381    fn freshness_deserialization_distinguishes_omitted_and_null_values() {
2382        let omitted: SwapFreshness = serde_json::from_str("{}").expect("omitted defaults");
2383        assert_eq!(omitted, SwapFreshness::default());
2384        assert!(serde_json::from_str::<SwapFreshness>(r#"{"maxBlockAgeSeconds":null}"#).is_err());
2385    }
2386
2387    #[test]
2388    fn abi_words_require_exact_padding_and_width() {
2389        let address = json!(format!("0x{}", "00".repeat(12) + &"11".repeat(20)));
2390        assert_eq!(
2391            parse_address_word(&address).unwrap(),
2392            format!("0x{}", "11".repeat(20))
2393        );
2394        let malformed = json!(format!("0x{}01", "00".repeat(12) + &"11".repeat(20)));
2395        assert!(parse_address_word(&malformed).is_err());
2396    }
2397
2398    #[test]
2399    fn quote_math_checks_each_uint256_intermediate() {
2400        let amount = BigUint::from(1_u32);
2401        let reserve = BigUint::from(1_u32);
2402        let normalized = NormalizedRequest {
2403            request: ExactInputQuoteRequest {
2404                chain_id: chain_id("ethereum").to_owned(),
2405                pool_definition_id: "pool-0001".to_owned(),
2406                input_token_deployment_id: "deployment-0002".to_owned(),
2407                output_token_deployment_id: "deployment-0008".to_owned(),
2408                amount_in: "1".to_owned(),
2409                freshness: None,
2410            },
2411            amount_in: amount.clone(),
2412            pool: get_pool_definition("pool-0001").unwrap(),
2413            dex: get_dex_deployment("dex-deployment-0001").unwrap(),
2414            input: get_token_deployment("deployment-0002").unwrap(),
2415            output: get_token_deployment("deployment-0008").unwrap(),
2416            freshness: NormalizedFreshness {
2417                block_age_seconds: 120,
2418                block_lag: 3,
2419                clock_skew_seconds: 5,
2420            },
2421        };
2422        let state = EvmState {
2423            initial: BlockHeader {
2424                number: BigUint::from(1_u32),
2425                hash: format!("0x{}", "11".repeat(32)),
2426                timestamp: BigUint::from(1_u32),
2427            },
2428            latest_after_reads: BlockHeader {
2429                number: BigUint::from(1_u32),
2430                hash: format!("0x{}", "11".repeat(32)),
2431                timestamp: BigUint::from(1_u32),
2432            },
2433            reserve0: reserve.clone(),
2434            reserve1: reserve,
2435        };
2436        assert_eq!(
2437            calculate_quote(&normalized, &state).unwrap_err().code(),
2438            Some(SwapQuoteErrorCode::InsufficientLiquidity)
2439        );
2440        let overflow = parse_canonical_decimal(
2441            "115792089237316195423570985008687907853269984665640564039457584007913129639935",
2442            true,
2443        )
2444        .unwrap();
2445        let mut overflow_normalized = normalized;
2446        overflow_normalized.amount_in = overflow;
2447        assert_eq!(
2448            calculate_quote(&overflow_normalized, &state)
2449                .unwrap_err()
2450                .code(),
2451            Some(SwapQuoteErrorCode::Arithmetic)
2452        );
2453    }
2454
2455    #[test]
2456    fn quote_capability_requires_the_exact_reviewed_tuple() {
2457        let pool = get_pool_definition("pool-0001").expect("Ethereum seed pool");
2458        let dex = get_dex_deployment("dex-deployment-0001").expect("Ethereum seed DEX");
2459        let input = get_token_deployment("deployment-0002").expect("WETH");
2460        let output = get_token_deployment("deployment-0008").expect("USDC");
2461        assert!(matches_supported_quote_capability(pool, dex, input, output));
2462
2463        let mut unclassified = *input;
2464        unclassified.representation_kind = TokenRepresentationKind::Unclassified;
2465        assert!(!matches_supported_quote_capability(
2466            pool,
2467            dex,
2468            &unclassified,
2469            output
2470        ));
2471
2472        let mut rebound = *output;
2473        rebound.address = Some("0x0000000000000000000000000000000000000001");
2474        assert!(!matches_supported_quote_capability(
2475            pool, dex, input, &rebound
2476        ));
2477    }
2478
2479    fn fixture_value(file_name: &str) -> Value {
2480        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
2481            .join("../..")
2482            .join("registry/fixtures")
2483            .join(file_name);
2484        let source = fs::read_to_string(&path).expect("workspace fixture is readable");
2485        serde_json::from_str(&source).expect("workspace fixture is valid JSON")
2486    }
2487
2488    fn fixed_fixture_clock() -> u64 {
2489        1_789_498_700
2490    }
2491
2492    async fn read_http_json(stream: &mut TcpStream) -> Option<Value> {
2493        let mut bytes = Vec::new();
2494        let mut chunk = [0_u8; 4096];
2495        loop {
2496            let count = stream.read(&mut chunk).await.ok()?;
2497            if count == 0 {
2498                return None;
2499            }
2500            bytes.extend_from_slice(&chunk[..count]);
2501            let header_end = bytes.windows(4).position(|window| window == b"\r\n\r\n")?;
2502            let body_start = header_end + 4;
2503            let headers = String::from_utf8_lossy(&bytes[..header_end]);
2504            let body_length = headers.lines().find_map(|line| {
2505                let (name, value) = line.split_once(':')?;
2506                name.eq_ignore_ascii_case("content-length")
2507                    .then(|| value.trim().parse::<usize>().ok())
2508                    .flatten()
2509            })?;
2510            if bytes.len() < body_start + body_length {
2511                continue;
2512            }
2513            return serde_json::from_slice(&bytes[body_start..body_start + body_length]).ok();
2514        }
2515    }
2516
2517    async fn write_http_json(stream: &mut TcpStream, body: &Value) {
2518        let body = serde_json::to_vec(body).expect("fixture response serializes");
2519        let headers = format!(
2520            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
2521            body.len()
2522        );
2523        stream
2524            .write_all(headers.as_bytes())
2525            .await
2526            .expect("fixture response headers write");
2527        stream
2528            .write_all(&body)
2529            .await
2530            .expect("fixture response body write");
2531    }
2532
2533    async fn write_http_rpc_error(stream: &mut TcpStream, id: &Value, code: i64, message: &str) {
2534        let body = json!({
2535            "jsonrpc": "2.0",
2536            "id": id,
2537            "error": {
2538                "code": code,
2539                "message": message,
2540                "data": "0x",
2541            },
2542        });
2543        let body = serde_json::to_vec(&body).expect("fixture RPC error serializes");
2544        let headers = format!(
2545            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
2546            body.len()
2547        );
2548        stream
2549            .write_all(headers.as_bytes())
2550            .await
2551            .expect("fixture RPC error headers write");
2552        stream
2553            .write_all(&body)
2554            .await
2555            .expect("fixture RPC error body write");
2556    }
2557
2558    async fn start_fixture_server(responses: Vec<Value>) -> (String, JoinHandle<Vec<Value>>) {
2559        let listener = TcpListener::bind("127.0.0.1:0")
2560            .await
2561            .expect("fixture listener");
2562        let address = listener.local_addr().expect("fixture listener address");
2563        let expected_count = responses.len();
2564        let handle = tokio::spawn(async move {
2565            let mut captured = Vec::with_capacity(expected_count);
2566            while captured.len() < expected_count {
2567                let (mut stream, _) = listener.accept().await.expect("fixture connection");
2568                let Some(request) = read_http_json(&mut stream).await else {
2569                    continue;
2570                };
2571                let index = captured.len();
2572                let id = request.get("id").cloned().unwrap_or_else(|| json!(1));
2573                captured.push(request);
2574                write_http_json(
2575                    &mut stream,
2576                    &json!({
2577                        "jsonrpc": "2.0",
2578                        "id": id,
2579                        "result": responses[index].clone(),
2580                    }),
2581                )
2582                .await;
2583            }
2584
2585            captured
2586        });
2587        (format!("http://{address}"), handle)
2588    }
2589
2590    fn runtime_dex(deployment: &DexDeployment) -> Value {
2591        json!({
2592            "dexDeploymentId": deployment.dex_deployment_id,
2593            "protocolId": deployment.protocol_id,
2594            "name": deployment.name,
2595            "chainId": deployment.chain_id,
2596            "programAddress": deployment.program_address,
2597            "adapterKind": deployment.adapter_kind,
2598            "status": deployment.status,
2599            "replacedByDexDeploymentId": deployment.replaced_by_dex_deployment_id,
2600        })
2601    }
2602
2603    fn runtime_pool(pool: &PoolDefinition) -> Value {
2604        json!({
2605            "poolDefinitionId": pool.pool_definition_id,
2606            "dexDeploymentId": pool.dex_deployment_id,
2607            "chainId": pool.chain_id,
2608            "address": pool.address,
2609            "token0DeploymentId": pool.token0_deployment_id,
2610            "token1DeploymentId": pool.token1_deployment_id,
2611            "adapter": {
2612                "kind": pool.adapter.kind,
2613                "feeNumerator": pool.adapter.fee_numerator,
2614                "feeDenominator": pool.adapter.fee_denominator,
2615            },
2616            "status": pool.status,
2617            "replacedByPoolDefinitionId": pool.replaced_by_pool_definition_id,
2618        })
2619    }
2620
2621    fn runtime_wrap(definition: &NativeWrapDefinition) -> Value {
2622        json!({
2623            "nativeWrapDefinitionId": definition.native_wrap_definition_id,
2624            "chainId": definition.chain_id,
2625            "nativeTokenDeploymentId": definition.native_token_deployment_id,
2626            "wrappedTokenDeploymentId": definition.wrapped_token_deployment_id,
2627            "status": definition.status,
2628        })
2629    }
2630
2631    fn runtime_alias(alias: &DexAlias) -> Value {
2632        json!({
2633            "namespace": alias.namespace,
2634            "name": alias.name,
2635            "dexDeploymentId": alias.dex_deployment_id,
2636            "poolDefinitionId": alias.pool_definition_id,
2637        })
2638    }
2639
2640    fn push_behavior(behavior: &mut Map<String, Value>, key: &str, row: Value) {
2641        behavior
2642            .get_mut(key)
2643            .and_then(Value::as_array_mut)
2644            .expect("behavior row array")
2645            .push(row);
2646    }
2647
2648    fn ids(pools: Vec<&'static PoolDefinition>) -> Value {
2649        let mut ids: Vec<_> = pools
2650            .into_iter()
2651            .map(|pool| pool.pool_definition_id)
2652            .collect();
2653        ids.sort_unstable();
2654        json!(ids)
2655    }
2656
2657    #[allow(clippy::too_many_lines)]
2658    fn lookup_behavior() -> Map<String, Value> {
2659        let mut behavior = Map::from_iter([
2660            ("getDexDeployment".to_owned(), json!([])),
2661            ("getPoolDefinition".to_owned(), json!([])),
2662            ("findPoolDefinitionByAddress".to_owned(), json!([])),
2663            ("findPoolDefinitionsByPair".to_owned(), json!([])),
2664            ("listPoolDefinitions".to_owned(), json!([])),
2665            ("getNativeWrapDefinition".to_owned(), json!([])),
2666            ("alias".to_owned(), json!([])),
2667            ("quote".to_owned(), json!([])),
2668        ]);
2669
2670        for deployment in DEX_DEPLOYMENTS {
2671            push_behavior(
2672                &mut behavior,
2673                "getDexDeployment",
2674                json!({
2675                    "input": deployment.dex_deployment_id,
2676                    "result": get_dex_deployment(deployment.dex_deployment_id).map(|value| value.dex_deployment_id),
2677                }),
2678            );
2679        }
2680        push_behavior(
2681            &mut behavior,
2682            "getDexDeployment",
2683            json!({
2684                "input": "dex-unknown",
2685                "result": get_dex_deployment("dex-unknown").map(|value| value.dex_deployment_id),
2686            }),
2687        );
2688
2689        for pool in POOL_DEFINITIONS {
2690            push_behavior(
2691                &mut behavior,
2692                "getPoolDefinition",
2693                json!({
2694                    "input": pool.pool_definition_id,
2695                    "result": get_pool_definition(pool.pool_definition_id).map(|value| value.pool_definition_id),
2696                }),
2697            );
2698        }
2699        push_behavior(
2700            &mut behavior,
2701            "getPoolDefinition",
2702            json!({
2703                "input": "pool-unknown",
2704                "result": get_pool_definition("pool-unknown").map(|value| value.pool_definition_id),
2705            }),
2706        );
2707
2708        for pool in POOL_DEFINITIONS {
2709            push_behavior(
2710                &mut behavior,
2711                "findPoolDefinitionByAddress",
2712                json!({
2713                    "chainId": pool.chain_id,
2714                    "address": pool.address,
2715                    "result": find_pool_definition_by_address(pool.chain_id, pool.address).map(|value| value.pool_definition_id),
2716                }),
2717            );
2718            if pool.chain_id.starts_with("eip155:") {
2719                let uppercase = format!("0x{}", pool.address[2..].to_ascii_uppercase());
2720                push_behavior(
2721                    &mut behavior,
2722                    "findPoolDefinitionByAddress",
2723                    json!({
2724                        "chainId": pool.chain_id,
2725                        "address": uppercase,
2726                        "result": find_pool_definition_by_address(pool.chain_id, &uppercase).map(|value| value.pool_definition_id),
2727                    }),
2728                );
2729            }
2730        }
2731        push_behavior(
2732            &mut behavior,
2733            "findPoolDefinitionByAddress",
2734            json!({
2735                "chainId": chain_id("ethereum"),
2736                "address": "0x0000000000000000000000000000000000000000",
2737                "result": find_pool_definition_by_address(
2738                    chain_id("ethereum"),
2739                    "0x0000000000000000000000000000000000000000",
2740                )
2741                .map(|value| value.pool_definition_id),
2742            }),
2743        );
2744        push_behavior(
2745            &mut behavior,
2746            "findPoolDefinitionByAddress",
2747            json!({
2748                "chainId": chain_id("ethereum"),
2749                "address": "not-an-address",
2750                "result": find_pool_definition_by_address(chain_id("ethereum"), "not-an-address")
2751                    .map(|value| value.pool_definition_id),
2752            }),
2753        );
2754        push_behavior(
2755            &mut behavior,
2756            "findPoolDefinitionByAddress",
2757            json!({
2758                "chainId": "unknown:chain",
2759                "address": "0x0000000000000000000000000000000000000001",
2760                "result": find_pool_definition_by_address(
2761                    "unknown:chain",
2762                    "0x0000000000000000000000000000000000000001",
2763                )
2764                .map(|value| value.pool_definition_id),
2765            }),
2766        );
2767
2768        for pool in POOL_DEFINITIONS {
2769            let forward = find_pool_definitions_by_pair(
2770                pool.chain_id,
2771                pool.token0_deployment_id,
2772                pool.token1_deployment_id,
2773            );
2774            let reverse = find_pool_definitions_by_pair(
2775                pool.chain_id,
2776                pool.token1_deployment_id,
2777                pool.token0_deployment_id,
2778            );
2779            push_behavior(
2780                &mut behavior,
2781                "findPoolDefinitionsByPair",
2782                json!({
2783                    "chainId": pool.chain_id,
2784                    "token0DeploymentId": pool.token0_deployment_id,
2785                    "token1DeploymentId": pool.token1_deployment_id,
2786                    "result": ids(forward),
2787                }),
2788            );
2789            push_behavior(
2790                &mut behavior,
2791                "findPoolDefinitionsByPair",
2792                json!({
2793                    "chainId": pool.chain_id,
2794                    "token0DeploymentId": pool.token1_deployment_id,
2795                    "token1DeploymentId": pool.token0_deployment_id,
2796                    "result": ids(reverse),
2797                }),
2798            );
2799        }
2800        push_behavior(
2801            &mut behavior,
2802            "findPoolDefinitionsByPair",
2803            json!({
2804                "chainId": chain_id("ethereum"),
2805                "token0DeploymentId": "deployment-0001",
2806                "token1DeploymentId": "deployment-0003",
2807                "result": ids(find_pool_definitions_by_pair(
2808                    chain_id("ethereum"),
2809                    "deployment-0001",
2810                    "deployment-0003",
2811                )),
2812            }),
2813        );
2814        push_behavior(
2815            &mut behavior,
2816            "findPoolDefinitionsByPair",
2817            json!({
2818                "chainId": "unknown:chain",
2819                "token0DeploymentId": "deployment-0002",
2820                "token1DeploymentId": "deployment-0008",
2821                "result": ids(find_pool_definitions_by_pair(
2822                    "unknown:chain",
2823                    "deployment-0002",
2824                    "deployment-0008",
2825                )),
2826            }),
2827        );
2828
2829        let mut filters = vec![json!({})];
2830        for (_, chain) in DEX_CHAIN_IDS {
2831            filters.push(json!({ "chainId": chain }));
2832        }
2833        for pool in POOL_DEFINITIONS {
2834            filters.push(json!({ "tokenDeploymentId": pool.token0_deployment_id }));
2835            filters.push(json!({ "tokenDeploymentId": pool.token1_deployment_id }));
2836        }
2837        let adapters: BTreeSet<_> = POOL_DEFINITIONS
2838            .iter()
2839            .map(|pool| pool.adapter.kind)
2840            .collect();
2841        for adapter in adapters {
2842            filters.push(json!({ "adapterKind": adapter }));
2843        }
2844        for pool in POOL_DEFINITIONS {
2845            filters.push(json!({
2846                "chainId": pool.chain_id,
2847                "tokenDeploymentId": pool.token0_deployment_id,
2848                "adapterKind": pool.adapter.kind,
2849            }));
2850        }
2851        filters.extend([
2852            json!({ "chainId": "unknown:chain" }),
2853            json!({ "tokenDeploymentId": "deployment-unknown" }),
2854            json!({ "adapterKind": "unknown-adapter" }),
2855        ]);
2856        for filter in filters {
2857            let options = ListPoolDefinitionsOptions {
2858                chain_id: filter.get("chainId").and_then(Value::as_str),
2859                token_deployment_id: filter.get("tokenDeploymentId").and_then(Value::as_str),
2860                adapter_kind: filter.get("adapterKind").and_then(Value::as_str),
2861            };
2862            push_behavior(
2863                &mut behavior,
2864                "listPoolDefinitions",
2865                json!({ "filter": filter, "result": ids(list_pool_definitions(options)) }),
2866            );
2867        }
2868
2869        for deployment in TOKEN_DEPLOYMENTS
2870            .iter()
2871            .filter(|deployment| deployment.standard == TokenStandard::Native)
2872        {
2873            push_behavior(
2874                &mut behavior,
2875                "getNativeWrapDefinition",
2876                json!({
2877                    "input": deployment.deployment_id,
2878                    "result": get_native_wrap_definition(deployment.deployment_id).map(|value| value.native_wrap_definition_id),
2879                }),
2880            );
2881        }
2882        for input in ["deployment-unknown", "native-wrap-0001"] {
2883            push_behavior(
2884                &mut behavior,
2885                "getNativeWrapDefinition",
2886                json!({
2887                    "input": input,
2888                    "result": get_native_wrap_definition(input)
2889                        .map(|value| value.native_wrap_definition_id),
2890                }),
2891            );
2892        }
2893        for alias in DEX_ALIASES {
2894            let (kind, result) = match (alias.dex_deployment_id, alias.pool_definition_id) {
2895                (Some(result), None) => ("dex", result),
2896                (None, Some(result)) => ("pool", result),
2897                _ => continue,
2898            };
2899            push_behavior(
2900                &mut behavior,
2901                "alias",
2902                json!({
2903                    "namespace": alias.namespace,
2904                    "name": alias.name,
2905                    "kind": kind,
2906                    "result": result,
2907                }),
2908            );
2909        }
2910        behavior
2911    }
2912
2913    fn chain_id(name: &str) -> &'static str {
2914        DEX_CHAIN_IDS
2915            .iter()
2916            .find(|(candidate, _)| *candidate == name)
2917            .map_or("", |(_, value)| value)
2918    }
2919
2920    fn request_from_fixture(value: &Value) -> ExactInputQuoteRequest {
2921        serde_json::from_value(value.clone()).expect("fixture request uses the Rust contract shape")
2922    }
2923
2924    fn actual_outcome(result: SwapResult<ExactInputQuoteResult>) -> Value {
2925        match result {
2926            Ok(value) => json!({
2927                "kind": "success",
2928                "value": serde_json::to_value(value).expect("quote result serializes"),
2929            }),
2930            Err(error) => match error.code_string() {
2931                Some(code) => json!({ "kind": "sdk-error", "code": code }),
2932                None => json!({
2933                    "kind": "transport-error",
2934                    "sourcePreserved": error.upstream().is_some(),
2935                }),
2936            },
2937        }
2938    }
2939
2940    fn expected_outcome(outcome: &Value) -> Value {
2941        let mut expected = outcome.clone();
2942        if expected.get("kind").and_then(Value::as_str) != Some("success") {
2943            return expected;
2944        }
2945        let Some(value) = expected.get_mut("value").and_then(Value::as_object_mut) else {
2946            return expected;
2947        };
2948        value.insert(
2949            "tokenCatalogDigest".to_owned(),
2950            json!(crate::TOKEN_CATALOG_CONTENT_DIGEST),
2951        );
2952        value.insert(
2953            "dexCatalogDigest".to_owned(),
2954            json!(DEX_CATALOG_CONTENT_DIGEST),
2955        );
2956        expected
2957    }
2958
2959    async fn execute_fixture_case(case: &Value) -> (Value, Vec<Value>) {
2960        let responses = case
2961            .get("rpcResponses")
2962            .and_then(Value::as_array)
2963            .cloned()
2964            .unwrap_or_default();
2965        let (endpoint, server) = if responses.is_empty() {
2966            ("http://127.0.0.1:1".to_owned(), None)
2967        } else {
2968            let (endpoint, server) = start_fixture_server(responses).await;
2969            (endpoint, Some(server))
2970        };
2971        let client = crate::ErpcClient::new_with_swap_clock(
2972            crate::ErpcClientConfig::new("parity")
2973                .with_endpoint(&endpoint)
2974                .with_avalanche_endpoint(&endpoint)
2975                .with_account_endpoint(&endpoint)
2976                .with_user_endpoint(&endpoint),
2977            fixed_fixture_clock,
2978        )
2979        .expect("fixture client");
2980        let request = request_from_fixture(case.get("request").expect("fixture request"));
2981        let result = client.swap.quote_exact_input(request).await;
2982        let captured = if let Some(server) = server {
2983            tokio::time::timeout(Duration::from_secs(5), server)
2984                .await
2985                .expect("fixture server completed")
2986                .expect("fixture server task joined")
2987        } else {
2988            Vec::new()
2989        };
2990        let trace = captured
2991            .into_iter()
2992            .map(|request| {
2993                json!({
2994                    "method": request.get("method").cloned().unwrap_or(Value::Null),
2995                    "params": request.get("params").cloned().unwrap_or(Value::Null),
2996                })
2997            })
2998            .collect();
2999        (actual_outcome(result), trace)
3000    }
3001
3002    fn execution_fixture_value() -> Value {
3003        fixture_value("swap-execution-cases.json")
3004    }
3005
3006    fn execution_address_word(address: &str) -> String {
3007        format!("0x{}{}", "00".repeat(12), &address[2..])
3008    }
3009
3010    fn mutate_execution_response(mutation: Option<&str>, index: usize, value: Value) -> Value {
3011        match (mutation, index) {
3012            (Some("emptyRouterCode"), 11) => json!("0x"),
3013            (Some("wrongFactory"), 12) => json!(execution_address_word(
3014                "0x1111111111111111111111111111111111111111"
3015            )),
3016            (Some("wrongWrapped"), 13) => json!(execution_address_word(
3017                "0x2222222222222222222222222222222222222222"
3018            )),
3019            (Some("malformedRouterQuote"), 14) => json!("0x20"),
3020            (Some("wrongRouterQuote"), 14) => {
3021                let Some(value) = value.as_str() else {
3022                    return value;
3023                };
3024                let mut value = value.to_owned();
3025                value.pop();
3026                value.push('b');
3027                json!(value)
3028            }
3029            (Some("quoteStale"), 9) | (Some("staleAfterRouter"), 15) => json!({
3030                "number": "0x18c7f20",
3031                "hash": format!("0x{}", "aa".repeat(32)),
3032                "timestamp": "0x6aa99537",
3033            }),
3034            _ => value,
3035        }
3036    }
3037
3038    async fn start_execution_fixture_server(case: &Value) -> (String, JoinHandle<Vec<Value>>) {
3039        let responses = case
3040            .get("rpcResponses")
3041            .and_then(Value::as_array)
3042            .cloned()
3043            .unwrap_or_default();
3044        let expected_trace = case
3045            .get("rpcTrace")
3046            .and_then(Value::as_array)
3047            .map_or(0, Vec::len);
3048        let mutation = case
3049            .get("mutation")
3050            .and_then(Value::as_str)
3051            .map(str::to_owned);
3052        let listener = TcpListener::bind("127.0.0.1:0")
3053            .await
3054            .expect("execution fixture listener");
3055        let address = listener
3056            .local_addr()
3057            .expect("execution fixture listener address");
3058        let handle = tokio::spawn(async move {
3059            let mut captured = Vec::with_capacity(expected_trace);
3060            let mut response_index = 0_usize;
3061            while captured.len() < expected_trace {
3062                let (mut stream, _) = listener
3063                    .accept()
3064                    .await
3065                    .expect("execution fixture connection");
3066                let Some(request) = read_http_json(&mut stream).await else {
3067                    continue;
3068                };
3069                let index = captured.len();
3070                let id = request.get("id").cloned().unwrap_or_else(|| json!(1));
3071                captured.push(request);
3072                let rpc_error = match mutation.as_deref() {
3073                    Some("preflightProviderError") if index == 0 => {
3074                        Some((-32_001, "provider preflight failure"))
3075                    }
3076                    Some("routerRevert") if index == 17 => Some((-32_000, "execution reverted")),
3077                    Some("routerRevertCode3") if index == 17 => Some((
3078                        3,
3079                        "execution reverted: ERC20: transfer amount exceeds balance",
3080                    )),
3081                    Some("routerNonRevertCode3") if index == 17 => {
3082                        Some((3, "invalid router request"))
3083                    }
3084                    Some("routerProviderError") if index == 17 => {
3085                        Some((-32_001, "provider simulation failure"))
3086                    }
3087                    _ => None,
3088                };
3089                if let Some((code, message)) = rpc_error {
3090                    write_http_rpc_error(&mut stream, &id, code, message).await;
3091                    break;
3092                }
3093                let response = responses
3094                    .get(response_index)
3095                    .cloned()
3096                    .unwrap_or(Value::Null);
3097                response_index += 1;
3098                let response = mutate_execution_response(mutation.as_deref(), index, response);
3099                write_http_json(
3100                    &mut stream,
3101                    &json!({
3102                        "jsonrpc": "2.0",
3103                        "id": id,
3104                        "result": response,
3105                    }),
3106                )
3107                .await;
3108            }
3109            captured
3110        });
3111        (format!("http://{address}"), handle)
3112    }
3113
3114    fn execution_actual_outcome<T: Serialize>(result: SwapExecutionResult<T>) -> Value {
3115        match result {
3116            Ok(value) => json!({
3117                "kind": "success",
3118                "value": serde_json::to_value(value).expect("execution result serializes"),
3119            }),
3120            Err(error) => match error.code_string() {
3121                Some(code) => json!({ "kind": "sdk-error", "code": code }),
3122                None => json!({
3123                    "kind": "transport-error",
3124                    "sourcePreserved": error.upstream().is_some(),
3125                }),
3126            },
3127        }
3128    }
3129
3130    fn expected_execution_outcome(outcome: &Value) -> Value {
3131        let mut expected = outcome.clone();
3132        if expected.get("kind").and_then(Value::as_str) != Some("success") {
3133            return expected;
3134        }
3135        let Some(value) = expected.get_mut("value").and_then(Value::as_object_mut) else {
3136            return expected;
3137        };
3138        if let Some(preparation) = value.get_mut("preparation").and_then(Value::as_object_mut) {
3139            preparation.insert(
3140                "executionCapabilityDigest".to_owned(),
3141                json!(SWAP_EXECUTION_CAPABILITIES_CONTENT_DIGEST),
3142            );
3143            if let Some(quote) = preparation.get_mut("quote").and_then(Value::as_object_mut) {
3144                quote.insert(
3145                    "tokenCatalogDigest".to_owned(),
3146                    json!(crate::TOKEN_CATALOG_CONTENT_DIGEST),
3147                );
3148                quote.insert(
3149                    "dexCatalogDigest".to_owned(),
3150                    json!(DEX_CATALOG_CONTENT_DIGEST),
3151                );
3152            }
3153        } else {
3154            value.insert(
3155                "executionCapabilityDigest".to_owned(),
3156                json!(SWAP_EXECUTION_CAPABILITIES_CONTENT_DIGEST),
3157            );
3158            if let Some(quote) = value.get_mut("quote").and_then(Value::as_object_mut) {
3159                quote.insert(
3160                    "tokenCatalogDigest".to_owned(),
3161                    json!(crate::TOKEN_CATALOG_CONTENT_DIGEST),
3162                );
3163                quote.insert(
3164                    "dexCatalogDigest".to_owned(),
3165                    json!(DEX_CATALOG_CONTENT_DIGEST),
3166                );
3167            }
3168        }
3169        expected
3170    }
3171
3172    async fn execute_execution_fixture_case(case: &Value) -> (Value, Vec<Value>) {
3173        let request_value = case.get("request").expect("execution fixture request");
3174        let Ok(request) =
3175            serde_json::from_value::<PrepareExactInputSwapRequest>(request_value.clone())
3176        else {
3177            return (
3178                json!({
3179                    "kind": "sdk-error",
3180                    "code": SwapExecutionErrorCode::InvalidArgument.as_str(),
3181                }),
3182                Vec::new(),
3183            );
3184        };
3185        let mutation = case.get("mutation").and_then(Value::as_str);
3186        if mutation == Some("cancelBeforeFirstRpc") {
3187            let cancellation = CancellationToken::new();
3188            cancellation.cancel();
3189            let client = crate::ErpcClient::new_with_swap_clock(
3190                crate::ErpcClientConfig::new("parity")
3191                    .with_endpoint("http://127.0.0.1:1")
3192                    .with_avalanche_endpoint("http://127.0.0.1:1")
3193                    .with_account_endpoint("http://127.0.0.1:1")
3194                    .with_user_endpoint("http://127.0.0.1:1"),
3195                fixed_fixture_clock,
3196            )
3197            .expect("cancellation fixture client");
3198            let result = client
3199                .swap
3200                .simulate_exact_input_swap_with(&request, Some(&cancellation))
3201                .await;
3202            return (execution_actual_outcome(result), Vec::new());
3203        }
3204
3205        let (endpoint, server) = if case
3206            .get("rpcResponses")
3207            .and_then(Value::as_array)
3208            .is_some_and(|responses| !responses.is_empty())
3209        {
3210            let (endpoint, server) = start_execution_fixture_server(case).await;
3211            (endpoint, Some(server))
3212        } else {
3213            ("http://127.0.0.1:1".to_owned(), None)
3214        };
3215        let client = crate::ErpcClient::new_with_swap_clock(
3216            crate::ErpcClientConfig::new("parity")
3217                .with_endpoint(&endpoint)
3218                .with_avalanche_endpoint(&endpoint)
3219                .with_account_endpoint(&endpoint)
3220                .with_user_endpoint(&endpoint),
3221            fixed_fixture_clock,
3222        )
3223        .expect("execution fixture client");
3224        let result = match case.get("method").and_then(Value::as_str) {
3225            Some("prepare") => {
3226                execution_actual_outcome(client.swap.prepare_exact_input_swap(&request).await)
3227            }
3228            Some("simulate") => {
3229                execution_actual_outcome(client.swap.simulate_exact_input_swap(&request).await)
3230            }
3231            _ => json!({
3232                "kind": "sdk-error",
3233                "code": SwapExecutionErrorCode::InvalidArgument.as_str(),
3234            }),
3235        };
3236        let captured = if let Some(server) = server {
3237            tokio::time::timeout(Duration::from_secs(5), server)
3238                .await
3239                .expect("execution fixture server completed")
3240                .expect("execution fixture server task joined")
3241        } else {
3242            Vec::new()
3243        };
3244        let trace = captured
3245            .into_iter()
3246            .map(|request| {
3247                json!({
3248                    "method": request.get("method").cloned().unwrap_or(Value::Null),
3249                    "params": request.get("params").cloned().unwrap_or(Value::Null),
3250                })
3251            })
3252            .collect();
3253        (result, trace)
3254    }
3255
3256    #[tokio::test]
3257    async fn capture_native_swap_execution_snapshot_when_requested() {
3258        let Some(output) = env::var_os("ERPC_SDK_SWAP_EXECUTION_PARITY_OUTPUT") else {
3259            return;
3260        };
3261        let fixture = execution_fixture_value();
3262        let mut behavior = Map::from_iter([
3263            ("prepare".to_owned(), json!([])),
3264            ("simulate".to_owned(), json!([])),
3265        ]);
3266        for case in fixture
3267            .get("cases")
3268            .and_then(Value::as_array)
3269            .expect("execution fixture cases")
3270        {
3271            let case_id = case
3272                .get("caseId")
3273                .and_then(Value::as_str)
3274                .expect("execution fixture case ID");
3275            let method = case
3276                .get("method")
3277                .and_then(Value::as_str)
3278                .expect("execution fixture method");
3279            let (actual, trace) = execute_execution_fixture_case(case).await;
3280            let expected =
3281                expected_execution_outcome(case.get("outcome").expect("execution fixture outcome"));
3282            assert_eq!(actual, expected, "native result mismatch for {case_id}");
3283            let expected_trace = case
3284                .get("rpcTrace")
3285                .and_then(Value::as_array)
3286                .cloned()
3287                .unwrap_or_default();
3288            assert_eq!(
3289                trace, expected_trace,
3290                "native RPC trace mismatch for {case_id}"
3291            );
3292            push_behavior(
3293                &mut behavior,
3294                method,
3295                json!({
3296                    "caseId": case_id,
3297                    "outcome": actual,
3298                    "rpcTrace": trace,
3299                }),
3300            );
3301        }
3302        let snapshot = json!({
3303            "snapshotVersion": 1,
3304            "snapshotKind": "swap-execution-native-runtime",
3305            "language": "rust",
3306            "runtime": concat!(
3307                "Rust compiled-library unit tests (erpc-sdk ",
3308                env!("CARGO_PKG_VERSION"),
3309                ")"
3310            ),
3311            "capabilityAsOfDate": SWAP_EXECUTION_CAPABILITIES_AS_OF_DATE,
3312            "capabilityDigest": SWAP_EXECUTION_CAPABILITIES_CONTENT_DIGEST,
3313            "behavior": behavior,
3314        });
3315        let output = Path::new(&output);
3316        if let Some(parent) = output.parent() {
3317            fs::create_dir_all(parent).expect("execution parity output directory");
3318        }
3319        let mut encoded =
3320            serde_json::to_vec_pretty(&snapshot).expect("execution snapshot serializes");
3321        encoded.push(b'\n');
3322        fs::write(output, encoded).expect("execution parity snapshot write");
3323    }
3324
3325    fn add_quote_row(
3326        behavior: &mut Map<String, Value>,
3327        case_id: &str,
3328        outcome: &Value,
3329        trace: &[Value],
3330    ) {
3331        push_behavior(
3332            behavior,
3333            "quote",
3334            json!({
3335                "caseId": case_id,
3336                "outcome": outcome,
3337                "rpcTrace": trace,
3338            }),
3339        );
3340    }
3341
3342    fn build_snapshot(behavior: &Map<String, Value>) -> Value {
3343        let mut chain_ids = Map::new();
3344        for (name, chain) in DEX_CHAIN_IDS {
3345            chain_ids.insert((*name).to_owned(), json!(chain));
3346        }
3347        json!({
3348            "snapshotVersion": 1,
3349            "snapshotKind": "native-runtime",
3350            "language": "rust",
3351            "runtime": concat!(
3352                "Rust compiled-library unit tests (erpc-sdk ",
3353                env!("CARGO_PKG_VERSION"),
3354                ")"
3355            ),
3356            "metadata": {
3357                "version": crate::TOKEN_CATALOG_VERSION,
3358                "asOfDate": crate::TOKEN_CATALOG_AS_OF_DATE,
3359                "contentDigest": crate::TOKEN_CATALOG_CONTENT_DIGEST,
3360                "chainIds": chain_ids,
3361            },
3362            "dexMetadata": {
3363                "version": DEX_CATALOG_VERSION,
3364                "asOfDate": DEX_CATALOG_AS_OF_DATE,
3365                "contentDigest": DEX_CATALOG_CONTENT_DIGEST,
3366            },
3367            "dexDeployments": DEX_DEPLOYMENTS.iter().map(runtime_dex).collect::<Vec<_>>(),
3368            "poolDefinitions": POOL_DEFINITIONS.iter().map(runtime_pool).collect::<Vec<_>>(),
3369            "nativeWrapDefinitions": NATIVE_WRAP_DEFINITIONS.iter().map(runtime_wrap).collect::<Vec<_>>(),
3370            "aliases": DEX_ALIASES.iter().map(runtime_alias).collect::<Vec<_>>(),
3371            "behavior": behavior,
3372        })
3373    }
3374
3375    #[tokio::test]
3376    async fn capture_native_dex_parity_snapshot_when_requested() {
3377        let Some(output) = env::var_os("ERPC_SDK_DEX_PARITY_OUTPUT") else {
3378            return;
3379        };
3380        let quote_cases = fixture_value("swap-quote-cases.json");
3381        let mut behavior = lookup_behavior();
3382        for section in ["validCases", "invalidCases", "rpcCases", "arithmeticCases"] {
3383            let cases = quote_cases
3384                .get(section)
3385                .and_then(Value::as_array)
3386                .expect("quote fixture section");
3387            for case in cases {
3388                if case
3389                    .get("applicability")
3390                    .and_then(Value::as_str)
3391                    .is_some_and(|value| value == "language-local")
3392                {
3393                    continue;
3394                }
3395                let case_id = case
3396                    .get("caseId")
3397                    .and_then(Value::as_str)
3398                    .expect("quote case ID");
3399                let (actual, trace) = execute_fixture_case(case).await;
3400                let expected = expected_outcome(case.get("outcome").expect("fixture outcome"));
3401                assert_eq!(actual, expected, "native result mismatch for {case_id}");
3402                let expected_trace = case
3403                    .get("rpcTrace")
3404                    .and_then(Value::as_array)
3405                    .cloned()
3406                    .unwrap_or_default();
3407                assert_eq!(
3408                    trace, expected_trace,
3409                    "native RPC trace mismatch for {case_id}"
3410                );
3411                add_quote_row(&mut behavior, case_id, &actual, &trace);
3412            }
3413        }
3414
3415        let snapshot = build_snapshot(&behavior);
3416        let output = Path::new(&output);
3417        if let Some(parent) = output.parent() {
3418            fs::create_dir_all(parent).expect("parity output directory");
3419        }
3420        let mut encoded = serde_json::to_vec_pretty(&snapshot).expect("parity snapshot serializes");
3421        encoded.push(b'\n');
3422        fs::write(output, encoded).expect("parity snapshot write");
3423    }
3424}