Skip to main content

tycho_simulation/evm/protocol/vm/
utils.rs

1use std::{collections::HashMap, env, fmt::Debug, str::FromStr};
2
3use alloy::{
4    primitives::{Address, Bytes, Keccak256, U256},
5    providers::{Provider, ProviderBuilder},
6    sol_types::SolValue,
7    transports::{RpcError, TransportErrorKind},
8};
9use hex::FromHex;
10use num_bigint::BigInt;
11use revm::{
12    state::{AccountInfo, Bytecode},
13    DatabaseRef,
14};
15use serde_json::Value;
16use tycho_common::simulation::errors::SimulationError;
17
18use crate::evm::{
19    engine_db::engine_db_interface::EngineDatabaseInterface,
20    simulation::{SimulationEngine, SimulationEngineError, SimulationParameters},
21    ContractCompiler, SlotId,
22};
23
24pub(crate) fn coerce_error(
25    err: &SimulationEngineError,
26    pool_state: &str,
27    gas_limit: Option<u64>,
28) -> SimulationError {
29    match err {
30        // Check for revert situation (if error message starts with "0x")
31        SimulationEngineError::TransactionError { ref data, ref gas_used }
32            if data.starts_with("0x") =>
33        {
34            let reason = parse_solidity_error_message(data);
35            let err = SimulationEngineError::TransactionError {
36                data: format!("Revert! Reason: {reason}"),
37                gas_used: *gas_used,
38            };
39
40            // Check if we are running out of gas
41            if let (Some(gas_limit), Some(gas_used)) = (gas_limit, gas_used) {
42                // if we used up 97% or more issue a OutOfGas error.
43                let usage = *gas_used as f64 / gas_limit as f64;
44                if usage >= 0.97 {
45                    return SimulationError::InvalidInput(
46                        format!(
47                            "SimulationError: Likely out-of-gas. Used: {:.2}% of gas limit. \
48                            Original error: {}. \
49                            Pool state: {}",
50                            usage * 100.0,
51                            err,
52                            pool_state,
53                        ),
54                        None,
55                    );
56                }
57            }
58            SimulationError::FatalError(format!("Simulation reverted for unknown reason: {reason}"))
59        }
60        // Check if "OutOfGas" is part of the error message
61        SimulationEngineError::TransactionError { ref data, ref gas_used }
62            if data.contains("OutOfGas") =>
63        {
64            let usage_msg = if let (Some(gas_limit), Some(gas_used)) = (gas_limit, gas_used) {
65                let usage = *gas_used as f64 / gas_limit as f64;
66                format!("Used: {:.2}% of gas limit. ", usage * 100.0)
67            } else {
68                String::new()
69            };
70
71            SimulationError::InvalidInput(
72                format!(
73                    "SimulationError: out-of-gas. {usage_msg} Original error: {data}. Pool state: {pool_state}"
74                ),
75                None,
76            )
77        }
78        SimulationEngineError::TransactionError { ref data, .. } => {
79            SimulationError::FatalError(format!("TransactionError: {data}"))
80        }
81        SimulationEngineError::StorageError(message) => {
82            SimulationError::RecoverableError(message.clone())
83        }
84        SimulationEngineError::OutOfGas(..) | SimulationEngineError::TraceError(_) => {
85            SimulationError::FatalError(err.clone().to_string())
86        }
87    }
88}
89
90fn parse_solidity_error_message(data: &str) -> String {
91    // 10 for "0x" + 8 hex chars error signature
92    if data.len() >= 10 {
93        let Ok(data_bytes) = Vec::from_hex(&data[2..]) else {
94            return format!("Failed to decode: {data}")
95        };
96
97        // Check for specific error selectors:
98        // Solidity Error(string) signature: 0x08c379a0
99        if data_bytes.starts_with(&[0x08, 0xc3, 0x79, 0xa0]) {
100            if let Ok(decoded) = String::abi_decode(&data_bytes[4..]) {
101                return decoded;
102            }
103
104            // Solidity Panic(uint256) signature: 0x4e487b71
105        } else if data_bytes.starts_with(&[0x4e, 0x48, 0x7b, 0x71]) {
106            if let Ok(decoded) = U256::abi_decode(&data_bytes[4..]) {
107                let panic_codes = get_solidity_panic_codes();
108                return panic_codes
109                    .get(&decoded.as_limbs()[0])
110                    .cloned()
111                    .unwrap_or_else(|| format!("Panic({decoded})"));
112            }
113        }
114
115        // Try decoding as a string (old Solidity revert case)
116        if let Ok(decoded) = String::abi_decode(&data_bytes) {
117            return decoded;
118        }
119
120        // Custom error, try to decode string again with offset
121        if let Ok(decoded) = String::abi_decode(&data_bytes[4..]) {
122            return decoded;
123        }
124    }
125    // Fallback if no decoding succeeded
126    format!("Failed to decode: {data}")
127}
128
129/// Get storage slot index of a value stored at a certain key in a mapping
130///
131/// # Arguments
132///
133/// * `key`: Key in a mapping. Can be any H160 value (such as an address).
134/// * `mapping_slot`: An `U256` representing the storage slot at which the mapping itself is stored.
135///   See the examples for more explanation.
136/// * `compiler`: The compiler with which the target contract was compiled. Solidity and Vyper
137///   handle maps differently.
138///
139/// # Returns
140///
141/// An `U256` representing the  index of a storage slot where the value at the given
142/// key is stored.
143///
144/// # Examples
145///
146/// If a mapping is declared as a first variable in Solidity code, its storage slot
147/// is 0 (e.g. `balances` in our mocked ERC20 contract). Here's how to compute
148/// a storage slot where balance of a given account is stored:
149///
150/// ```
151/// use alloy::primitives::{U256, Address};
152/// use tycho_simulation::evm::ContractCompiler;
153/// use tycho_simulation::evm::protocol::vm::utils::get_storage_slot_index_at_key;
154/// let address: Address = "0xC63135E4bF73F637AF616DFd64cf701866BB2628".parse().expect("Invalid address");
155/// get_storage_slot_index_at_key(address, U256::from(0), ContractCompiler::Solidity);
156/// ```
157///
158/// For nested mappings, we need to apply the function twice. An example of this is
159/// `allowances` in ERC20. It is a mapping of form:
160/// `HashMap<Owner, HashMap<Spender, U256>>`. In our mocked ERC20 contract, `allowances`
161/// is a second variable, so it is stored at slot 1. Here's how to get a storage slot
162/// where an allowance of `address_spender` to spend `address_owner`'s money is stored:
163///
164/// ```
165/// use alloy::primitives::{U256, Address};
166/// use tycho_simulation::evm::ContractCompiler;
167/// use tycho_simulation::evm::protocol::vm::utils::get_storage_slot_index_at_key;
168/// let address_spender: Address = "0xC63135E4bF73F637AF616DFd64cf701866BB2628".parse().expect("Invalid address");
169/// let address_owner: Address = "0x6F4Feb566b0f29e2edC231aDF88Fe7e1169D7c05".parse().expect("Invalid address");
170/// get_storage_slot_index_at_key(address_spender, get_storage_slot_index_at_key(address_owner, U256::from(1), ContractCompiler::Solidity), ContractCompiler::Solidity);
171/// ```
172///
173/// # See Also
174///
175/// [Solidity Storage Layout documentation](https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_storage.html#mappings-and-dynamic-arrays)
176pub fn get_storage_slot_index_at_key(
177    key: Address,
178    mapping_slot: SlotId,
179    compiler: ContractCompiler,
180) -> SlotId {
181    let mut key_bytes = key.as_slice().to_vec();
182    if key_bytes.len() < 32 {
183        let padding = vec![0u8; 32 - key_bytes.len()];
184        key_bytes.splice(0..0, padding); // Prepend zeros to the start
185    }
186
187    let mapping_slot_bytes: [u8; 32] = mapping_slot.to_be_bytes();
188    compiler.compute_map_slot(&mapping_slot_bytes, &key_bytes)
189}
190
191fn get_solidity_panic_codes() -> HashMap<u64, String> {
192    let mut panic_codes = HashMap::new();
193    panic_codes.insert(0, "GenericCompilerPanic".to_string());
194    panic_codes.insert(1, "AssertionError".to_string());
195    panic_codes.insert(17, "ArithmeticOver/Underflow".to_string());
196    panic_codes.insert(18, "ZeroDivisionError".to_string());
197    panic_codes.insert(33, "UnknownEnumMember".to_string());
198    panic_codes.insert(34, "BadStorageByteArrayEncoding".to_string());
199    panic_codes.insert(51, "EmptyArray".to_string());
200    panic_codes.insert(0x32, "OutOfBounds".to_string());
201    panic_codes.insert(0x41, "OutOfMemory".to_string());
202    panic_codes.insert(0x51, "BadFunctionPointer".to_string());
203    panic_codes
204}
205
206/// Fetches the bytecode for a specified contract address, returning an error if the address is
207/// an Externally Owned Account (EOA) or if no code is associated with it.
208///
209/// This function checks the specified address on the blockchain, attempting to retrieve any
210/// contract bytecode deployed at that address. If the address corresponds to an EOA or any
211/// other address without associated bytecode, an `RpcError::EmptyResponse` error is returned.
212///
213/// # Parameters
214/// - `address`: The address of the account or contract to query, as a string.
215/// - `connection_string`: An optional RPC connection string. If not provided, the function will
216///   default to the `RPC_URL` environment variable.
217///
218/// # Returns
219/// - `Ok(Bytecode)`: The bytecode of the contract at the specified address, if present.
220/// - `Err(RpcError)`: An error if the address does not have associated bytecode, if there is an
221///   issue with the RPC connection, or if the address is invalid.
222///
223/// # Errors
224/// - Returns `RpcError::InvalidRequest` if `address` is not parsable or if no RPC URL is set.
225/// - Returns `RpcError::EmptyResponse` if the address has no associated bytecode (e.g., EOA).
226/// - Returns `RpcError::InvalidResponse` for issues with the RPC provider response.
227pub(crate) async fn get_code_for_contract(
228    address: &str,
229    connection_string: Option<String>,
230) -> Result<Bytecode, SimulationError> {
231    // Get the connection string, defaulting to the RPC_URL environment variable
232    let connection_string = connection_string.or_else(|| env::var("RPC_URL").ok());
233
234    let Some(connection_string) = connection_string else {
235        return Err(SimulationError::FatalError(
236            "RPC_URL environment variable is not set".to_string(),
237        ))
238    };
239
240    let addr = Address::from_str(address).map_err(|e| {
241        SimulationError::FatalError(format!("Invalid address format: {address}: {e}"))
242    })?;
243    // Call eth_getCode to get the bytecode of the contract
244    match sync_get_code(&connection_string, addr) {
245        Ok(code) if code.is_empty() => {
246            Err(SimulationError::FatalError("Empty code response from RPC".to_string()))
247        }
248        Ok(code) => {
249            let bytecode = Bytecode::new_raw(Bytes::from(code.to_vec()));
250            Ok(bytecode)
251        }
252        Err(e) => match e {
253            RpcError::Transport(err) => Err(SimulationError::RecoverableError(format!(
254                "Failed to get code for contract due to internal RPC error: {err:?}"
255            ))),
256            RpcError::ErrorResp(_) |
257            RpcError::NullResp |
258            RpcError::UnsupportedFeature(_) |
259            RpcError::LocalUsageError(_) |
260            RpcError::SerError(_) |
261            RpcError::DeserError { .. } => Err(SimulationError::FatalError(format!(
262                "Failed to get code for contract. Invalid response from RPC: {e:?}"
263            ))),
264        },
265    }
266}
267
268#[expect(
269    clippy::disallowed_methods,
270    reason = "keeps alloy's non-Sync provider future out of the Send + Sync future TryFromWithBlock requires; panics on a current-thread runtime"
271)]
272fn sync_get_code(
273    connection_string: &str,
274    addr: Address,
275) -> Result<Bytes, RpcError<TransportErrorKind>> {
276    tokio::task::block_in_place(|| {
277        tokio::runtime::Handle::current().block_on(async {
278            // Create a provider with the URL
279            let provider = ProviderBuilder::new()
280                .connect(connection_string)
281                .await?;
282            provider.get_code_at(addr).await
283        })
284    })
285}
286
287/// Converts a hexadecimal string into a fixed-size 32-byte array.
288///
289/// This function takes a string slice (e.g., a pool ID) that may or may not have
290/// a `0x` prefix. It decodes the hex string into bytes, ensuring it does not exceed
291/// 32 bytes in length. If the string is valid and fits within 32 bytes, the bytes
292/// are copied into a `[u8; 32]` array, with right zero-padding for unused bytes.
293///
294/// # Arguments
295///
296/// * `pool_id` - A string slice representing a hexadecimal pool ID. It can optionally start with
297///   the `0x` prefix.
298///
299/// # Returns
300///
301/// * `Ok([u8; 32])` - On success, returns a 32-byte array with the decoded bytes. If the input is
302///   shorter than 32 bytes, the rest of the array is right padded with zeros.
303/// * `Err(SimulationError)` - Returns an error if:
304///     - The input string is not a valid hexadecimal string.
305///     - The decoded bytes exceed 32 bytes in length.
306///
307/// # Example
308/// ```
309/// use tycho_simulation::evm::protocol::vm::utils::string_to_bytes32;
310///
311/// let pool_id = "0x1234abcd";
312/// match string_to_bytes32(pool_id) {
313///     Ok(bytes32) => println!("Bytes32: {:?}", bytes32),
314///     Err(e) => eprintln!("Error: {}", e),
315/// }
316pub fn string_to_bytes32(pool_id: &str) -> Result<[u8; 32], SimulationError> {
317    let pool_id_no_prefix =
318        if let Some(stripped) = pool_id.strip_prefix("0x") { stripped } else { pool_id };
319    let bytes = hex::decode(pool_id_no_prefix)
320        .map_err(|e| SimulationError::FatalError(format!("Invalid hex string: {e}")))?;
321    if bytes.len() > 32 {
322        return Err(SimulationError::FatalError(format!(
323            "Hex string exceeds 32 bytes: length {}",
324            bytes.len()
325        )));
326    }
327    let mut array = [0u8; 32];
328    array[..bytes.len()].copy_from_slice(&bytes);
329    Ok(array)
330}
331
332/// Decodes a JSON-encoded list of hexadecimal strings into a `Vec<Vec<u8>>`.
333///
334/// This function parses a JSON array where each element is a string representing a hexadecimal
335/// value. It converts each hex string into a vector of bytes (`Vec<u8>`), and aggregates them into
336/// a `Vec<Vec<u8>>`.
337///
338/// # Arguments
339///
340/// * `input` - A byte slice (`&[u8]`) containing JSON-encoded data. The JSON must be a valid array
341///   of hex strings.
342///
343/// # Returns
344///
345/// * `Ok(Vec<Vec<u8>>)` - On success, returns a vector of byte vectors.
346/// * `Err(SimulationError)` - Returns an error if:
347///     - The input is not valid JSON.
348///     - The JSON is not an array.
349///     - Any array element is not a string.
350///     - Any string is not a valid hexadecimal string.
351///
352/// # Example
353/// ```
354/// use tycho_simulation::evm::protocol::vm::utils::json_deserialize_address_list;
355///
356/// let json_input = br#"["0x1234", "0xc0ffee"]"#;
357/// match json_deserialize_address_list(json_input) {
358///     Ok(result) => println!("Decoded: {:?}", result),
359///     Err(e) => eprintln!("Error: {}", e),
360/// }
361/// ```
362pub fn json_deserialize_address_list(input: &[u8]) -> Result<Vec<Vec<u8>>, SimulationError> {
363    let json_value: Value = serde_json::from_slice(input)
364        .map_err(|e| SimulationError::FatalError(format!("Invalid JSON: {input:?}: {e}")))?;
365
366    if let Value::Array(hex_strings) = json_value {
367        let mut result = Vec::new();
368
369        for val in hex_strings {
370            if let Value::String(hexstring) = val {
371                let bytes = hex::decode(hexstring.trim_start_matches("0x")).map_err(|e| {
372                    SimulationError::FatalError(format!("Invalid hex string: {hexstring}: {e}"))
373                })?;
374                result.push(bytes);
375            } else {
376                return Err(SimulationError::FatalError("Array contains a non-string value".into()));
377            }
378        }
379
380        Ok(result)
381    } else {
382        Err(SimulationError::FatalError("Input is not a JSON array".into()))
383    }
384}
385
386/// Decodes a JSON-encoded list of hexadecimal strings into a `Vec<BigInt>`.
387///
388/// This function parses a JSON array where each element is a string representing a hexadecimal
389/// value. It converts each hex string into a `BigInt` using big-endian byte interpretation, and
390/// aggregates them into a `Vec<BigInt>`.
391///
392/// # Arguments
393///
394/// * `input` - A byte slice (`&[u8]`) containing JSON-encoded data. The JSON must be a valid array
395///   of hex strings.
396///
397/// # Returns
398///
399/// * `Ok(Vec<BigInt>)` - On success, returns a vector of `BigInt` values.
400/// * `Err(SimulationError)` - Returns an error if:
401///     - The input is not valid JSON.
402///     - The JSON is not an array.
403///     - Any array element is not a string.
404///     - Any string is not a valid hexadecimal string.
405///
406/// # Example
407/// ```
408/// use tycho_simulation::evm::protocol::vm::utils::json_deserialize_be_bigint_list;
409/// use num_bigint::BigInt;
410/// use tycho_simulation::evm;
411/// let json_input = br#"["0x1234", "0xdeadbeef"]"#;
412/// match json_deserialize_be_bigint_list(json_input) {
413///     Ok(result) => println!("Decoded BigInts: {:?}", result),
414///     Err(e) => eprintln!("Error: {}", e),
415/// }
416/// ```
417pub fn json_deserialize_be_bigint_list(input: &[u8]) -> Result<Vec<BigInt>, SimulationError> {
418    let json_value: Value = serde_json::from_slice(input)
419        .map_err(|e| SimulationError::FatalError(format!("Invalid JSON: {input:?}: {e}")))?;
420
421    if let Value::Array(hex_strings) = json_value {
422        let mut result = Vec::new();
423
424        for val in hex_strings {
425            if let Value::String(hexstring) = val {
426                let bytes = hex::decode(hexstring.trim_start_matches("0x")).map_err(|e| {
427                    SimulationError::FatalError(format!("Invalid hex string: {hexstring}: {e}"))
428                })?;
429                let bigint = BigInt::from_signed_bytes_be(&bytes);
430                result.push(bigint);
431            } else {
432                return Err(SimulationError::FatalError("Array contains a non-string value".into()));
433            }
434        }
435
436        Ok(result)
437    } else {
438        Err(SimulationError::FatalError("Input is not a JSON array".into()))
439    }
440}
441
442/// Load the pool's stateless/implementation contracts (the `stateless_contract_addr_{i}` state
443/// attributes) into the engine's DB so getter calls on proxy pools resolve their delegatecall
444/// targets. Curve pools are commonly EIP-1167 proxies whose implementation code is not part of the
445/// indexed pool storage; without this, getters delegatecall into empty code and revert.
446///
447/// Addresses may be static (`0x…`) or dynamic (`call:0x<factory>:method()`), and code is fetched
448/// via RPC unless provided inline as `stateless_contract_code_{i}`. The engine shares its DB with
449/// `SHARED_TYCHO_DB`, so accounts loaded here persist for later `delta_transition` rebuilds.
450pub(crate) async fn load_stateless_contracts<D: EngineDatabaseInterface + Clone + Debug>(
451    engine: &SimulationEngine<D>,
452    attributes: &HashMap<String, tycho_common::Bytes>,
453) -> Result<(), SimulationError>
454where
455    <D as DatabaseRef>::Error: Debug,
456    <D as EngineDatabaseInterface>::Error: Debug,
457{
458    let mut index = 0;
459    while let Some(encoded) = attributes.get(&format!("stateless_contract_addr_{index}")) {
460        let address = String::from_utf8(encoded.to_vec()).map_err(|e| {
461            SimulationError::FatalError(format!("stateless contract address is not UTF-8: {e}"))
462        })?;
463        let inline_code = attributes
464            .get(&format!("stateless_contract_code_{index}"))
465            .map(|value| value.to_vec());
466        index += 1;
467
468        let (account, code) = match inline_code {
469            Some(bytecode) => (address, Bytecode::new_raw(bytecode.into())),
470            None => {
471                let resolved = if address.starts_with("call") {
472                    resolve_call_address(engine, &address)?
473                } else {
474                    address
475                };
476                let code = get_code_for_contract(&resolved, None).await?;
477                (resolved, code)
478            }
479        };
480        let account: Address = account.parse().map_err(|e| {
481            SimulationError::FatalError(format!(
482                "stateless contract has an invalid address {account}: {e}"
483            ))
484        })?;
485        engine
486            .state
487            .init_account(
488                account,
489                AccountInfo {
490                    balance: U256::ZERO,
491                    nonce: 0,
492                    code_hash: code.hash_slow(),
493                    code: Some(code),
494                },
495                None,
496                false,
497            )
498            .map_err(|e| {
499                SimulationError::FatalError(format!(
500                    "stateless contract init_account failed: {e:?}"
501                ))
502            })?;
503    }
504    Ok(())
505}
506
507/// Resolve a dynamic `call:0x<address>:method()` directive to a concrete implementation address by
508/// simulating the parameterless `method()` view and decoding its returned address.
509pub(crate) fn resolve_call_address<D: EngineDatabaseInterface + Clone + Debug>(
510    engine: &SimulationEngine<D>,
511    directive: &str,
512) -> Result<String, SimulationError>
513where
514    <D as DatabaseRef>::Error: Debug,
515    <D as EngineDatabaseInterface>::Error: Debug,
516{
517    let method = directive
518        .split(':')
519        .next_back()
520        .ok_or_else(|| {
521            SimulationError::FatalError(format!("malformed stateless call directive {directive}"))
522        })?;
523    let to: Address = directive
524        .split(':')
525        .nth(1)
526        .ok_or_else(|| {
527            SimulationError::FatalError(format!(
528                "stateless call directive is missing its target {directive}"
529            ))
530        })?
531        .parse()
532        .map_err(|e| {
533            SimulationError::FatalError(format!(
534                "stateless call directive has an invalid target {directive}: {e}"
535            ))
536        })?;
537    let mut hasher = Keccak256::new();
538    hasher.update(method.as_bytes());
539    let selector = hasher.finalize()[..4].to_vec();
540    let res = engine
541        .simulate(&SimulationParameters {
542            caller: Address::ZERO,
543            to,
544            data: selector,
545            ..Default::default()
546        })
547        .map_err(|e| SimulationError::FatalError(format!("stateless call failed: {e}")))?;
548    let address = Address::abi_decode(res.result.as_ref())
549        .map_err(|e| SimulationError::FatalError(format!("stateless call decode failed: {e}")))?;
550    Ok(address.to_string())
551}
552
553#[cfg(test)]
554mod tests {
555    use dotenvy::dotenv;
556
557    use super::*;
558    use crate::utils::hexstring_to_vec;
559
560    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
561    #[cfg_attr(not(feature = "network_tests"), ignore = "requires RPC_URL")]
562    async fn test_get_code_for_address() {
563        let rpc_url = env::var("RPC_URL").unwrap_or_else(|_| {
564            dotenv().expect("Missing .env file");
565            env::var("RPC_URL").expect("Missing RPC_URL in .env file")
566        });
567
568        let address = "0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640";
569        let result = get_code_for_contract(address, Some(rpc_url)).await;
570
571        assert!(result.is_ok(), "Network call should not fail");
572
573        let code = result.unwrap();
574        assert!(!code.bytes().is_empty(), "Code should not be empty");
575    }
576
577    #[test]
578    fn test_maybe_coerce_error_revert_no_gas_info() {
579        let err = SimulationEngineError::TransactionError{
580            data: "0x08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000011496e76616c6964206f7065726174696f6e000000000000000000000000000000".to_string(),
581            gas_used: None
582        };
583
584        let result = coerce_error(&err, "test_pool", None);
585
586        if let SimulationError::FatalError(msg) = result {
587            assert!(msg.contains("Simulation reverted for unknown reason: Invalid operation"));
588        } else {
589            panic!("Expected SolidityError error");
590        }
591    }
592
593    #[test]
594    fn test_maybe_coerce_error_out_of_gas() {
595        // Test out-of-gas situation with gas limit and gas used provided
596        let err = SimulationEngineError::TransactionError{
597            data: "0x08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000011496e76616c6964206f7065726174696f6e000000000000000000000000000000".to_string(),
598            gas_used: Some(980)
599        };
600
601        let result = coerce_error(&err, "test_pool", Some(1000));
602
603        if let SimulationError::InvalidInput(message, _partial_result) = result {
604            assert!(message.contains("Used: 98.00% of gas limit."));
605            assert!(message.contains("test_pool"));
606        } else {
607            panic!("Expected OutOfGas error");
608        }
609    }
610
611    #[test]
612    fn test_maybe_coerce_error_no_gas_limit_info() {
613        // Test out-of-gas situation without gas limit info
614        let err = SimulationEngineError::TransactionError {
615            data: "OutOfGas".to_string(),
616            gas_used: None,
617        };
618
619        let result = coerce_error(&err, "test_pool", None);
620
621        if let SimulationError::InvalidInput(message, _partial_result) = result {
622            assert!(message.contains("Original error: OutOfGas"));
623            assert!(message.contains("Pool state: test_pool"));
624        } else {
625            panic!("Expected RetryDifferentInput error");
626        }
627    }
628
629    #[test]
630    fn test_maybe_coerce_error_storage_error() {
631        let err = SimulationEngineError::StorageError("Storage error:".to_string());
632
633        let result = coerce_error(&err, "test_pool", None);
634
635        if let SimulationError::RecoverableError(message) = result {
636            assert_eq!(message, "Storage error:");
637        } else {
638            println!("{result:?}");
639            panic!("Expected RetryLater error");
640        }
641    }
642
643    #[test]
644    fn test_maybe_coerce_error_no_match() {
645        // Test for non-revert, non-out-of-gas, non-storage errors
646        let err = SimulationEngineError::TransactionError {
647            data: "Some other error".to_string(),
648            gas_used: None,
649        };
650
651        let result = coerce_error(&err, "test_pool", None);
652
653        if let SimulationError::FatalError(message) = result {
654            assert_eq!(message, "TransactionError: Some other error");
655        } else {
656            panic!("Expected solidity error");
657        }
658    }
659
660    #[test]
661    fn test_parse_solidity_error_message_error_string() {
662        // Test parsing Solidity Error(string) message
663        let data = "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000e416d6f756e7420746f6f206c6f77000000000000000000000000000000000000";
664
665        let result = parse_solidity_error_message(data);
666
667        assert_eq!(result, "Amount too low");
668    }
669
670    #[test]
671    fn test_parse_solidity_error_message_panic_code() {
672        // Test parsing Solidity Panic(uint256) message
673        let data = "0x4e487b710000000000000000000000000000000000000000000000000000000000000001";
674
675        let result = parse_solidity_error_message(data);
676
677        assert_eq!(result, "AssertionError");
678    }
679
680    #[test]
681    fn test_parse_solidity_error_message_failed_to_decode() {
682        // Test failed decoding with invalid data
683        let data = "0x1234567890";
684
685        let result = parse_solidity_error_message(data);
686
687        assert!(result.contains("Failed to decode"));
688    }
689
690    #[test]
691    fn test_hexstring_to_vec() {
692        let hexstring = "0x68656c6c6f";
693        let expected = vec![0x68, 0x65, 0x6c, 0x6c, 0x6f];
694        let result = hexstring_to_vec(hexstring).unwrap();
695        assert_eq!(result, expected);
696    }
697
698    #[test]
699    fn test_hexstring_to_vec_no_prefix() {
700        let hexstring = "68656c6c6f";
701        let expected = vec![0x68, 0x65, 0x6c, 0x6c, 0x6f];
702        let result = hexstring_to_vec(hexstring).unwrap();
703        assert_eq!(result, expected);
704    }
705
706    #[test]
707    fn test_hexstring_to_vec_invalid_characters() {
708        let hexstring = "0x68656c6c6z"; // Invalid character 'z'
709        let result = hexstring_to_vec(hexstring);
710        assert!(result.is_err());
711        if let Err(SimulationError::FatalError(msg)) = result {
712            assert!(msg.contains("Invalid hex string"));
713        } else {
714            panic!("Expected EncodingError");
715        }
716    }
717
718    #[test]
719    fn test_json_deserialize_address_list() {
720        let json_input = r#"["0x1234","0xabcd"]"#.as_bytes();
721        let result = json_deserialize_address_list(json_input).unwrap();
722        assert_eq!(result, vec![vec![0x12, 0x34], vec![0xab, 0xcd]]);
723    }
724
725    #[test]
726    fn test_json_deserialize_bigint_list() {
727        let json_input = r#"["0x0b1a2bc2ec500000","0x02c68af0bb140000"]"#.as_bytes();
728        let result = json_deserialize_be_bigint_list(json_input).unwrap();
729        assert_eq!(
730            result,
731            vec![BigInt::from(800000000000000000u64), BigInt::from(200000000000000000u64)]
732        );
733    }
734
735    #[test]
736    fn test_invalid_deserialize_address_list() {
737        let json_input = r#"["invalid_hex"]"#.as_bytes();
738        let result = json_deserialize_address_list(json_input);
739        assert!(result.is_err());
740    }
741
742    #[test]
743    fn test_invalid_deserialize_bigint_list() {
744        let json_input = r#"["invalid_hex"]"#.as_bytes();
745        let result = json_deserialize_be_bigint_list(json_input);
746        assert!(result.is_err());
747    }
748}