tycho_simulation/evm/protocol/vm/
utils.rs1use 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 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 if let (Some(gas_limit), Some(gas_used)) = (gas_limit, gas_used) {
42 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 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 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 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 } 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 if let Ok(decoded) = String::abi_decode(&data_bytes) {
117 return decoded;
118 }
119
120 if let Ok(decoded) = String::abi_decode(&data_bytes[4..]) {
122 return decoded;
123 }
124 }
125 format!("Failed to decode: {data}")
127}
128
129pub 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); }
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
206pub(crate) async fn get_code_for_contract(
228 address: &str,
229 connection_string: Option<String>,
230) -> Result<Bytecode, SimulationError> {
231 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 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 let provider = ProviderBuilder::new()
280 .connect(connection_string)
281 .await?;
282 provider.get_code_at(addr).await
283 })
284 })
285}
286
287pub 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
332pub 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
386pub 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
442pub(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
507pub(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 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 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 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 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 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 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"; 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}