diff --git a/examples/explorer/main.rs b/examples/explorer/main.rs index 57a909d3..df46c6bf 100644 --- a/examples/explorer/main.rs +++ b/examples/explorer/main.rs @@ -3,9 +3,10 @@ pub mod utils; extern crate tycho_simulation; +use std::env; + use clap::Parser; use futures::{future::select_all, StreamExt}; -use std::env; use tokio::{sync::mpsc, task::JoinHandle}; use tycho_client::feed::component_tracker::ComponentFilter; use tycho_core::dto::Chain; diff --git a/examples/explorer/ui.rs b/examples/explorer/ui.rs index 2b823731..386f1eef 100644 --- a/examples/explorer/ui.rs +++ b/examples/explorer/ui.rs @@ -1,3 +1,5 @@ +use std::{cmp::max, str::FromStr, time::Instant}; + use futures::StreamExt; use itertools::Itertools; use num_bigint::BigUint; @@ -13,7 +15,6 @@ use ratatui::{ }, DefaultTerminal, Frame, }; -use std::{cmp::max, str::FromStr, time::Instant}; use tokio::{select, sync::mpsc::Receiver}; use tycho_core::Bytes; use tycho_simulation::protocol::{ diff --git a/rustfmt.toml b/rustfmt.toml index 3a6c51e4..f806cc98 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -7,4 +7,5 @@ binop_separator = "Back" trailing_comma = "Vertical" trailing_semicolon = false use_field_init_shorthand = true -chain_width=40 \ No newline at end of file +chain_width=40 +group_imports = "StdExternalCrate" \ No newline at end of file diff --git a/src/evm/account_storage.rs b/src/evm/account_storage.rs index 96f000b6..dfa12a5d 100644 --- a/src/evm/account_storage.rs +++ b/src/evm/account_storage.rs @@ -229,11 +229,11 @@ impl AccountStorage { #[cfg(test)] mod tests { - use super::*; + use std::{collections::HashMap, error::Error, str::FromStr}; use revm::primitives::{AccountInfo, Address, KECCAK_EMPTY, U256}; - use std::{collections::HashMap, error::Error, str::FromStr}; + use super::*; use crate::evm::account_storage::{Account, AccountStorage}; #[test] diff --git a/src/evm/decoder.rs b/src/evm/decoder.rs index 5682e971..db891a44 100644 --- a/src/evm/decoder.rs +++ b/src/evm/decoder.rs @@ -1,16 +1,3 @@ -use crate::{ - evm::{ - engine_db::{update_engine, SHARED_TYCHO_DB}, - tycho_models::{AccountUpdate, ResponseAccount}, - }, - models::Token, - protocol::{ - errors::InvalidSnapshotError, - models::{BlockUpdate, ProtocolComponent, TryFromWithBlock}, - state::ProtocolSim, - }, -}; -use alloy_primitives::Address; use std::{ collections::{hash_map::Entry, HashMap}, future::Future, @@ -18,12 +5,27 @@ use std::{ str::FromStr, sync::Arc, }; + +use alloy_primitives::Address; use thiserror::Error; use tokio::sync::RwLock; use tracing::{debug, info, warn}; use tycho_client::feed::{synchronizer::ComponentWithState, FeedMessage, Header}; use tycho_core::Bytes; +use crate::{ + evm::{ + engine_db::{update_engine, SHARED_TYCHO_DB}, + tycho_models::{AccountUpdate, ResponseAccount}, + }, + models::Token, + protocol::{ + errors::InvalidSnapshotError, + models::{BlockUpdate, ProtocolComponent, TryFromWithBlock}, + state::ProtocolSim, + }, +}; + #[derive(Error, Debug)] pub enum StreamDecodeError { #[error("{0}")] @@ -328,6 +330,13 @@ impl TychoStreamDecoder { #[cfg(test)] mod tests { + use std::{fs, path::Path}; + + use num_bigint::ToBigUint; + use rstest::*; + use tycho_client::feed::FeedMessage; + use tycho_core::Bytes; + use crate::{ evm::{ decoder::{StreamDecodeError, TychoStreamDecoder}, @@ -335,11 +344,6 @@ mod tests { }, models::Token, }; - use num_bigint::ToBigUint; - use rstest::*; - use std::{fs, path::Path}; - use tycho_client::feed::FeedMessage; - use tycho_core::Bytes; async fn setup_decoder(set_tokens: bool) -> TychoStreamDecoder { let mut decoder = TychoStreamDecoder::new(); diff --git a/src/evm/engine_db/simulation_db.rs b/src/evm/engine_db/simulation_db.rs index 9879dc44..16acb0e7 100644 --- a/src/evm/engine_db/simulation_db.rs +++ b/src/evm/engine_db/simulation_db.rs @@ -5,7 +5,6 @@ use std::{ }; use alloy::providers::Provider; - use alloy_primitives::StorageValue; use revm::{ db::DatabaseRef, @@ -444,18 +443,18 @@ where #[cfg(test)] mod tests { - use super::*; use std::{env, error::Error, str::FromStr}; use alloy::{ providers::{ProviderBuilder, RootProvider}, transports::BoxTransport, }; - use dotenv::dotenv; use rstest::rstest; use tokio::runtime::Runtime; + use super::*; + fn get_runtime() -> Option> { let runtime = tokio::runtime::Handle::try_current() .is_err() diff --git a/src/evm/engine_db/tycho_db.rs b/src/evm/engine_db/tycho_db.rs index 83c77a43..6a07da3c 100644 --- a/src/evm/engine_db/tycho_db.rs +++ b/src/evm/engine_db/tycho_db.rs @@ -347,13 +347,13 @@ impl DatabaseRef for PreCachedDB { #[cfg(test)] mod tests { - use super::*; + use std::{error::Error, str::FromStr}; use chrono::DateTime; use revm::primitives::U256; use rstest::{fixture, rstest}; - use std::{error::Error, str::FromStr}; + use super::*; use crate::evm::tycho_models::{AccountUpdate, Block, Chain, ChangeType}; #[fixture] diff --git a/src/evm/protocol/filters.rs b/src/evm/protocol/filters.rs index 1e4a3d8d..947d97a9 100644 --- a/src/evm/protocol/filters.rs +++ b/src/evm/protocol/filters.rs @@ -1,9 +1,11 @@ -use crate::evm::protocol::vm::utils::json_deserialize_be_bigint_list; -use num_bigint::BigInt; use std::collections::HashSet; + +use num_bigint::BigInt; use tracing::info; use tycho_client::feed::synchronizer::ComponentWithState; +use crate::evm::protocol::vm::utils::json_deserialize_be_bigint_list; + const ZERO_ADDRESS: &str = "0x0000000000000000000000000000000000000000"; pub fn balancer_pool_filter(component: &ComponentWithState) -> bool { // Check for rate_providers in static_attributes diff --git a/src/evm/protocol/safe_math.rs b/src/evm/protocol/safe_math.rs index c400a3e4..b0b2f53e 100644 --- a/src/evm/protocol/safe_math.rs +++ b/src/evm/protocol/safe_math.rs @@ -5,9 +5,10 @@ //! Should an operation cause an overflow a result containing TradeSimulationError //! will be returned. //! Functions for the types I256, U256, U512 are available. -use crate::protocol::errors::SimulationError; use alloy_primitives::{I256, U256, U512}; +use crate::protocol::errors::SimulationError; + pub fn safe_mul_u256(a: U256, b: U256) -> Result { let res = a.checked_mul(b); _construc_result_u256(res) @@ -109,11 +110,12 @@ pub fn _construc_result_i256(res: Option) -> Result #[cfg(test)] mod safe_math_tests { - use super::*; use std::str::FromStr; use rstest::rstest; + use super::*; + const U256_MAX: U256 = U256::from_limbs([u64::MAX, u64::MAX, u64::MAX, u64::MAX]); const U512_MAX: U512 = U512::from_limbs([ u64::MAX, diff --git a/src/evm/protocol/u256_num.rs b/src/evm/protocol/u256_num.rs index 620ee3b8..f06e7be3 100644 --- a/src/evm/protocol/u256_num.rs +++ b/src/evm/protocol/u256_num.rs @@ -1,10 +1,8 @@ //! Numeric methods for the U256 type -use alloy_primitives::U256; -use std::{cmp::max, panic}; +use std::{cmp::max, collections::HashMap, panic}; -use alloy_primitives::bytes::Bytes; +use alloy_primitives::{bytes::Bytes, U256}; use num_bigint::BigUint; -use std::collections::HashMap; /// Converts a U256 integer into it's closest floating point representation /// @@ -129,10 +127,10 @@ pub fn map_slots_to_u256( #[cfg(test)] mod test { - use super::*; - use rstest::rstest; + use super::*; + #[rstest] #[case::one(U256::from(1u64), 1.0f64)] #[case::two(U256::from(2), 2.0f64)] diff --git a/src/evm/protocol/uniswap_v2/reserve_price.rs b/src/evm/protocol/uniswap_v2/reserve_price.rs index b1be5a90..23d4b4f4 100644 --- a/src/evm/protocol/uniswap_v2/reserve_price.rs +++ b/src/evm/protocol/uniswap_v2/reserve_price.rs @@ -1,6 +1,7 @@ -use crate::evm::protocol::u256_num::u256_to_f64; use alloy_primitives::U256; +use crate::evm::protocol::u256_num::u256_to_f64; + /// Computes a spot price given two token reserves /// /// To find the most accurate spot price possible: @@ -29,11 +30,12 @@ pub fn spot_price_from_reserves( #[cfg(test)] mod test { - use super::*; + use std::str::FromStr; use approx::assert_ulps_eq; use rstest::rstest; - use std::str::FromStr; + + use super::*; #[rstest] #[case::dai_weth( diff --git a/src/evm/protocol/uniswap_v2/state.rs b/src/evm/protocol/uniswap_v2/state.rs index de486c90..06a1680b 100644 --- a/src/evm/protocol/uniswap_v2/state.rs +++ b/src/evm/protocol/uniswap_v2/state.rs @@ -1,6 +1,10 @@ +use std::{any::Any, collections::HashMap}; + use alloy_primitives::U256; use num_bigint::{BigUint, ToBigUint}; +use tycho_core::{dto::ProtocolStateDelta, Bytes}; +use super::reserve_price::spot_price_from_reserves; use crate::{ evm::protocol::{ safe_math::{safe_add_u256, safe_div_u256, safe_mul_u256, safe_sub_u256}, @@ -13,10 +17,6 @@ use crate::{ state::ProtocolSim, }, }; -use std::{any::Any, collections::HashMap}; -use tycho_core::{dto::ProtocolStateDelta, Bytes}; - -use super::reserve_price::spot_price_from_reserves; #[derive(Clone, Debug, PartialEq, Eq)] pub struct UniswapV2State { @@ -147,17 +147,18 @@ impl ProtocolSim for UniswapV2State { #[cfg(test)] mod tests { - use super::*; - - use std::collections::{HashMap, HashSet}; + use std::{ + collections::{HashMap, HashSet}, + str::FromStr, + }; use approx::assert_ulps_eq; use num_traits::One; use rstest::rstest; - use std::str::FromStr; - use tycho_core::hex_bytes::Bytes; + use super::*; + #[rstest] #[case::same_dec( U256::from_str("6770398782322527849696614").unwrap(), diff --git a/src/evm/protocol/uniswap_v2/tycho_decoder.rs b/src/evm/protocol/uniswap_v2/tycho_decoder.rs index b6737a66..78d552d1 100644 --- a/src/evm/protocol/uniswap_v2/tycho_decoder.rs +++ b/src/evm/protocol/uniswap_v2/tycho_decoder.rs @@ -1,15 +1,15 @@ -use alloy_primitives::U256; use std::collections::HashMap; + +use alloy_primitives::U256; use tycho_client::feed::{synchronizer::ComponentWithState, Header}; use tycho_core::Bytes; +use super::state::UniswapV2State; use crate::{ models::Token, protocol::{errors::InvalidSnapshotError, models::TryFromWithBlock}, }; -use super::state::UniswapV2State; - impl TryFromWithBlock for UniswapV2State { type Error = InvalidSnapshotError; @@ -42,16 +42,16 @@ impl TryFromWithBlock for UniswapV2State { #[cfg(test)] mod tests { - use super::*; - - use chrono::DateTime; use std::{collections::HashMap, str::FromStr}; + use chrono::DateTime; use tycho_core::{ dto::{Chain, ChangeType, ProtocolComponent, ResponseProtocolState}, hex_bytes::Bytes, }; + use super::*; + fn usv2_component() -> ProtocolComponent { let creation_time = DateTime::from_timestamp(1622526000, 0) .unwrap() diff --git a/src/evm/protocol/uniswap_v3/solidity_math.rs b/src/evm/protocol/uniswap_v3/solidity_math.rs index baae70fa..e78df459 100644 --- a/src/evm/protocol/uniswap_v3/solidity_math.rs +++ b/src/evm/protocol/uniswap_v3/solidity_math.rs @@ -1,8 +1,9 @@ +use alloy_primitives::{U256, U512}; + use crate::{ evm::protocol::safe_math::{div_mod_u512, safe_div_u512, safe_mul_u512}, protocol::errors::SimulationError, }; -use alloy_primitives::{U256, U512}; pub fn mul_div_rounding_up(a: U256, b: U256, denom: U256) -> Result { let a_big = U512::from(a); diff --git a/src/evm/protocol/uniswap_v3/sqrt_price_math.rs b/src/evm/protocol/uniswap_v3/sqrt_price_math.rs index 146728bd..380db134 100644 --- a/src/evm/protocol/uniswap_v3/sqrt_price_math.rs +++ b/src/evm/protocol/uniswap_v3/sqrt_price_math.rs @@ -1,3 +1,6 @@ +use alloy_primitives::U256; + +use super::solidity_math::{mul_div, mul_div_rounding_up}; use crate::{ evm::protocol::{ safe_math::{div_mod_u256, safe_add_u256, safe_div_u256, safe_mul_u256, safe_sub_u256}, @@ -5,9 +8,6 @@ use crate::{ }, protocol::errors::SimulationError, }; -use alloy_primitives::U256; - -use super::solidity_math::{mul_div, mul_div_rounding_up}; const Q96: U256 = U256::from_limbs([0, 4294967296, 0, 0]); const RESOLUTION: U256 = U256::from_limbs([96, 0, 0, 0]); @@ -170,10 +170,12 @@ pub fn sqrt_price_q96_to_f64(x: U256, token_0_decimals: u32, token_1_decimals: u #[cfg(test)] mod tests { - use super::*; + use std::str::FromStr; + use approx::assert_ulps_eq; use rstest::rstest; - use std::str::FromStr; + + use super::*; fn u256(s: &str) -> U256 { U256::from_str(s).unwrap() diff --git a/src/evm/protocol/uniswap_v3/state.rs b/src/evm/protocol/uniswap_v3/state.rs index d138d8c9..3ae4421f 100644 --- a/src/evm/protocol/uniswap_v3/state.rs +++ b/src/evm/protocol/uniswap_v3/state.rs @@ -1,9 +1,19 @@ -use alloy_primitives::{Sign, I256, U256}; use std::{any::Any, collections::HashMap}; +use alloy_primitives::{Sign, I256, U256}; use num_bigint::BigUint; use tracing::trace; +use tycho_core::{dto::ProtocolStateDelta, Bytes}; +use super::{ + enums::FeeAmount, + liquidity_math, + sqrt_price_math::sqrt_price_q96_to_f64, + swap_math, + tick_list::{TickInfo, TickList}, + tick_math, + tycho_decoder::i24_be_bytes_to_i32, +}; use crate::{ evm::protocol::{ safe_math::{safe_add_u256, safe_sub_u256}, @@ -16,17 +26,6 @@ use crate::{ state::ProtocolSim, }, }; -use tycho_core::{dto::ProtocolStateDelta, Bytes}; - -use super::{ - enums::FeeAmount, - liquidity_math, - sqrt_price_math::sqrt_price_q96_to_f64, - swap_math, - tick_list::{TickInfo, TickList}, - tick_math, - tycho_decoder::i24_be_bytes_to_i32, -}; #[derive(Clone, Debug, PartialEq, Eq)] pub struct UniswapV3State { @@ -403,16 +402,16 @@ impl ProtocolSim for UniswapV3State { #[cfg(test)] mod tests { - use super::*; - - use num_bigint::ToBigUint; use std::{ collections::{HashMap, HashSet}, str::FromStr, }; + use num_bigint::ToBigUint; use tycho_core::hex_bytes::Bytes; + use super::*; + #[test] fn test_get_amount_out_full_range_liquidity() { let token_x = Token::new( diff --git a/src/evm/protocol/uniswap_v3/swap_math.rs b/src/evm/protocol/uniswap_v3/swap_math.rs index ef783aa5..59e0463d 100644 --- a/src/evm/protocol/uniswap_v3/swap_math.rs +++ b/src/evm/protocol/uniswap_v3/swap_math.rs @@ -1,10 +1,10 @@ -use crate::{evm::protocol::safe_math::safe_sub_u256, protocol::errors::SimulationError}; use alloy_primitives::{I256, U256}; use super::{ solidity_math::{mul_div, mul_div_rounding_up}, sqrt_price_math, }; +use crate::{evm::protocol::safe_math::safe_sub_u256, protocol::errors::SimulationError}; pub fn compute_swap_step( sqrt_ratio_current: U256, @@ -138,12 +138,10 @@ pub fn compute_swap_step( #[cfg(test)] mod tests { - use super::*; - - use super::super::enums::FeeAmount; - use std::{ops::Neg, str::FromStr}; + use super::{super::enums::FeeAmount, *}; + struct TestCase { price: U256, target: U256, diff --git a/src/evm/protocol/uniswap_v3/tick_list.rs b/src/evm/protocol/uniswap_v3/tick_list.rs index 3491db97..e1046480 100644 --- a/src/evm/protocol/uniswap_v3/tick_list.rs +++ b/src/evm/protocol/uniswap_v3/tick_list.rs @@ -1,6 +1,7 @@ -use alloy_primitives::U256; use std::cmp; +use alloy_primitives::U256; + use super::tick_math; #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -253,10 +254,10 @@ fn div_floor(lhs: i32, rhs: i32) -> i32 { #[cfg(test)] mod tests { - use super::*; - use rstest::rstest; + use super::*; + fn create_tick_list() -> TickList { let tick_infos = vec![create_tick_info(10, 10), create_tick_info(20, -5), create_tick_info(40, -5)]; diff --git a/src/evm/protocol/uniswap_v3/tick_math.rs b/src/evm/protocol/uniswap_v3/tick_math.rs index 15316353..fbbcf6ba 100644 --- a/src/evm/protocol/uniswap_v3/tick_math.rs +++ b/src/evm/protocol/uniswap_v3/tick_math.rs @@ -1,6 +1,7 @@ -use alloy_primitives::{Sign, I256, U256}; use std::ops::BitOr; +use alloy_primitives::{Sign, I256, U256}; + use crate::{ evm::protocol::safe_math::{div_mod_u256, safe_div_u256, safe_mul_u256}, protocol::errors::SimulationError, @@ -202,9 +203,10 @@ pub fn get_tick_at_sqrt_ratio(sqrt_price: U256) -> Result #[cfg(test)] mod tests { - use super::*; use std::str::FromStr; + use super::*; + struct TestCase { tick: i32, ratio: U256, diff --git a/src/evm/protocol/uniswap_v3/tycho_decoder.rs b/src/evm/protocol/uniswap_v3/tycho_decoder.rs index 44d7ab5c..1594e100 100644 --- a/src/evm/protocol/uniswap_v3/tycho_decoder.rs +++ b/src/evm/protocol/uniswap_v3/tycho_decoder.rs @@ -1,16 +1,15 @@ -use alloy_primitives::U256; use std::collections::HashMap; +use alloy_primitives::U256; use tycho_client::feed::{synchronizer::ComponentWithState, Header}; use tycho_core::Bytes; +use super::{enums::FeeAmount, state::UniswapV3State, tick_list::TickInfo}; use crate::{ models::Token, protocol::{errors::InvalidSnapshotError, models::TryFromWithBlock}, }; -use super::{enums::FeeAmount, state::UniswapV3State, tick_list::TickInfo}; - impl TryFromWithBlock for UniswapV3State { type Error = InvalidSnapshotError; diff --git a/src/evm/protocol/utils.rs b/src/evm/protocol/utils.rs index 79c98fc2..db737ba9 100644 --- a/src/evm/protocol/utils.rs +++ b/src/evm/protocol/utils.rs @@ -1,7 +1,8 @@ -use crate::protocol::errors::SimulationError; use alloy_primitives::Address; use tycho_core::Bytes; +use crate::protocol::errors::SimulationError; + /// Safely converts a `Bytes` object to an `Address` object. /// /// Checks the length of the `Bytes` before attempting to convert, and returns a `SimulationError` diff --git a/src/evm/protocol/vm/adapter_contract.rs b/src/evm/protocol/vm/adapter_contract.rs index 516ceea0..e5df7d6e 100644 --- a/src/evm/protocol/vm/adapter_contract.rs +++ b/src/evm/protocol/vm/adapter_contract.rs @@ -1,13 +1,15 @@ -use alloy_primitives::{Address, U256}; - -use alloy_sol_types::SolValue; use std::{ collections::{HashMap, HashSet}, fmt::Debug, }; +use alloy_primitives::{Address, U256}; +use alloy_sol_types::SolValue; use revm::DatabaseRef; +use super::{ + erc20_token::Overwrites, models::Capability, tycho_simulation_contract::TychoSimulationContract, +}; use crate::{ evm::{ account_storage::StateUpdate, @@ -17,10 +19,6 @@ use crate::{ protocol::errors::SimulationError, }; -use super::{ - erc20_token::Overwrites, models::Capability, tycho_simulation_contract::TychoSimulationContract, -}; - #[derive(Debug)] pub struct Trade { pub received_amount: U256, diff --git a/src/evm/protocol/vm/erc20_token.rs b/src/evm/protocol/vm/erc20_token.rs index 186995b1..cf6fd339 100644 --- a/src/evm/protocol/vm/erc20_token.rs +++ b/src/evm/protocol/vm/erc20_token.rs @@ -1,9 +1,14 @@ +use std::{collections::HashMap, fmt::Debug}; + use alloy_primitives::{Address, U256}; use alloy_sol_types::SolValue; use lazy_static::lazy_static; use revm::DatabaseRef; -use std::{collections::HashMap, fmt::Debug}; +use super::{ + constants::EXTERNAL_ACCOUNT, tycho_simulation_contract::TychoSimulationContract, + utils::get_storage_slot_index_at_key, +}; use crate::{ evm::{ engine_db::{engine_db_interface::EngineDatabaseInterface, simulation_db::BlockHeader}, @@ -13,11 +18,6 @@ use crate::{ protocol::errors::SimulationError, }; -use super::{ - constants::EXTERNAL_ACCOUNT, tycho_simulation_contract::TychoSimulationContract, - utils::get_storage_slot_index_at_key, -}; - #[derive(Clone, Debug, PartialEq)] /// A struct representing ERC20 tokens storage slots. pub struct ERC20Slots { @@ -228,17 +228,16 @@ where #[cfg(test)] mod tests { - use super::*; + use std::{env, str::FromStr, sync::Arc}; use alloy::{ providers::{ProviderBuilder, RootProvider}, transports::BoxTransport, }; - use std::{env, str::FromStr, sync::Arc}; - use chrono::NaiveDateTime; use dotenv::dotenv; + use super::*; use crate::evm::engine_db::simulation_db::SimulationDB; fn setup_factory() -> ERC20OverwriteFactory { diff --git a/src/evm/protocol/vm/state.rs b/src/evm/protocol/vm/state.rs index a4e31a4b..056a2277 100644 --- a/src/evm/protocol/vm/state.rs +++ b/src/evm/protocol/vm/state.rs @@ -12,6 +12,12 @@ use revm::DatabaseRef; use tracing::info; use tycho_core::{dto::ProtocolStateDelta, Bytes}; +use super::{ + constants::{EXTERNAL_ACCOUNT, MAX_BALANCE}, + erc20_token::{ERC20OverwriteFactory, ERC20Slots, Overwrites}, + models::Capability, + tycho_simulation_contract::TychoSimulationContract, +}; use crate::{ evm::{ engine_db::{ @@ -29,13 +35,6 @@ use crate::{ }, }; -use super::{ - constants::{EXTERNAL_ACCOUNT, MAX_BALANCE}, - erc20_token::{ERC20OverwriteFactory, ERC20Slots, Overwrites}, - models::Capability, - tycho_simulation_contract::TychoSimulationContract, -}; - #[derive(Clone, Debug)] pub struct EVMPoolState where @@ -585,20 +584,22 @@ where #[cfg(test)] mod tests { - use super::*; - use alloy_primitives::B256; use std::{ collections::{HashMap, HashSet}, path::PathBuf, str::FromStr, }; + use alloy_primitives::B256; use num_bigint::ToBigUint; use num_traits::One; use revm::primitives::{AccountInfo, Bytecode, KECCAK_EMPTY}; use serde_json::Value; - use super::super::{models::Capability, state_builder::EVMPoolStateBuilder}; + use super::{ + super::{models::Capability, state_builder::EVMPoolStateBuilder}, + *, + }; use crate::evm::{ engine_db::{create_engine, SHARED_TYCHO_DB}, simulation::SimulationEngine, diff --git a/src/evm/protocol/vm/state_builder.rs b/src/evm/protocol/vm/state_builder.rs index b00aec3d..b4a95f7d 100644 --- a/src/evm/protocol/vm/state_builder.rs +++ b/src/evm/protocol/vm/state_builder.rs @@ -1,11 +1,11 @@ -use alloy_primitives::{Address, U256}; -use alloy_sol_types::SolValue; use std::{ collections::{HashMap, HashSet}, fmt::Debug, path::PathBuf, }; +use alloy_primitives::{Address, U256}; +use alloy_sol_types::SolValue; use chrono::Utc; use itertools::Itertools; use revm::{ @@ -14,7 +14,16 @@ use revm::{ DatabaseRef, }; use tracing::warn; +use tycho_core::Bytes as TychoBytes; +use super::{ + constants::{EXTERNAL_ACCOUNT, MAX_BALANCE}, + erc20_token::{brute_force_slots, ERC20Slots}, + models::Capability, + state::EVMPoolState, + tycho_simulation_contract::TychoSimulationContract, + utils::{get_code_for_contract, load_erc20_bytecode}, +}; use crate::{ evm::{ engine_db::{ @@ -26,16 +35,6 @@ use crate::{ }, protocol::errors::SimulationError, }; -use tycho_core::Bytes as TychoBytes; - -use super::{ - constants::{EXTERNAL_ACCOUNT, MAX_BALANCE}, - erc20_token::{brute_force_slots, ERC20Slots}, - models::Capability, - state::EVMPoolState, - tycho_simulation_contract::TychoSimulationContract, - utils::{get_code_for_contract, load_erc20_bytecode}, -}; #[derive(Debug)] /// `EVMPoolStateBuilder` is a builder pattern implementation for creating instances of @@ -455,14 +454,15 @@ where #[cfg(test)] mod tests { - use super::*; + use std::str::FromStr; + + use alloy_primitives::B256; + use super::*; use crate::evm::{ engine_db::{tycho_db::PreCachedDB, SHARED_TYCHO_DB}, protocol::utils::bytes_to_address, }; - use alloy_primitives::B256; - use std::str::FromStr; #[test] fn test_build_without_required_fields() { diff --git a/src/evm/protocol/vm/tycho_decoder.rs b/src/evm/protocol/vm/tycho_decoder.rs index a5267c31..f66557dd 100644 --- a/src/evm/protocol/vm/tycho_decoder.rs +++ b/src/evm/protocol/vm/tycho_decoder.rs @@ -10,14 +10,13 @@ use tracing::info; use tycho_client::feed::{synchronizer::ComponentWithState, Header}; use tycho_core::Bytes; +use super::{state::EVMPoolState, state_builder::EVMPoolStateBuilder}; use crate::{ evm::engine_db::{simulation_db::BlockHeader, tycho_db::PreCachedDB, SHARED_TYCHO_DB}, models::Token, protocol::{errors::InvalidSnapshotError, models::TryFromWithBlock}, }; -use super::{state::EVMPoolState, state_builder::EVMPoolStateBuilder}; - impl From
for BlockHeader { fn from(header: Header) -> Self { let now = SystemTime::now() @@ -179,25 +178,26 @@ fn to_adapter_file_name(protocol_system: &str) -> String { #[cfg(test)] mod tests { - use super::*; + use std::{collections::HashSet, fs, path::Path, str::FromStr}; - use crate::{ - evm::{ - engine_db::{create_engine, engine_db_interface::EngineDatabaseInterface}, - tycho_models::AccountUpdate, - }, - protocol::models::TryFromWithBlock, - }; use chrono::DateTime; use num_bigint::ToBigUint; use revm::primitives::{AccountInfo, Address, Bytecode, KECCAK_EMPTY}; use serde_json::Value; - use std::{collections::HashSet, fs, path::Path, str::FromStr}; use tycho_core::{ dto::{Chain, ChangeType, ProtocolComponent, ResponseProtocolState}, Bytes, }; + use super::*; + use crate::{ + evm::{ + engine_db::{create_engine, engine_db_interface::EngineDatabaseInterface}, + tycho_models::AccountUpdate, + }, + protocol::models::TryFromWithBlock, + }; + #[test] fn test_to_adapter_file_name() { assert_eq!(to_adapter_file_name("balancer_v2"), "BalancerV2SwapAdapter.evm.runtime"); diff --git a/src/evm/protocol/vm/tycho_simulation_contract.rs b/src/evm/protocol/vm/tycho_simulation_contract.rs index 1f56bcef..a1b0e573 100644 --- a/src/evm/protocol/vm/tycho_simulation_contract.rs +++ b/src/evm/protocol/vm/tycho_simulation_contract.rs @@ -5,6 +5,10 @@ use alloy_sol_types::SolValue; use chrono::Utc; use revm::{db::DatabaseRef, primitives::AccountInfo}; +use super::{ + constants::{EXTERNAL_ACCOUNT, MAX_BALANCE}, + utils::{coerce_error, get_contract_bytecode}, +}; use crate::{ evm::{ engine_db::engine_db_interface::EngineDatabaseInterface, @@ -13,11 +17,6 @@ use crate::{ protocol::errors::SimulationError, }; -use super::{ - constants::{EXTERNAL_ACCOUNT, MAX_BALANCE}, - utils::{coerce_error, get_contract_bytecode}, -}; - #[derive(Debug, Clone)] pub struct TychoSimulationResponse { pub return_value: Vec, @@ -157,15 +156,15 @@ where #[cfg(test)] mod tests { - use super::*; - use alloy_primitives::hex; use std::str::FromStr; + use alloy_primitives::hex; use revm::{ db::DatabaseRef, primitives::{AccountInfo, Bytecode, B256}, }; + use super::*; use crate::evm::{ engine_db::engine_db_interface::EngineDatabaseInterface, protocol::vm::utils::string_to_bytes32, diff --git a/src/evm/protocol/vm/utils.rs b/src/evm/protocol/vm/utils.rs index 381956e6..ebe39233 100644 --- a/src/evm/protocol/vm/utils.rs +++ b/src/evm/protocol/vm/utils.rs @@ -14,7 +14,6 @@ use alloy::{ }; use alloy_primitives::{Address, U256}; use alloy_sol_types::SolValue; - use hex::FromHex; use mini_moka::sync::Cache; use num_bigint::BigInt; @@ -482,14 +481,15 @@ pub fn json_deserialize_be_bigint_list(input: &[u8]) -> Result, Simu #[cfg(test)] mod tests { - use super::*; + use std::{fs::remove_file, io::Write}; - use crate::utils::hexstring_to_vec; use dotenv::dotenv; use hex::decode; - use std::{fs::remove_file, io::Write}; use tempfile::NamedTempFile; + use super::*; + use crate::utils::hexstring_to_vec; + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[cfg_attr(not(feature = "network_tests"), ignore)] async fn test_get_code_for_address() { diff --git a/src/evm/simulation.rs b/src/evm/simulation.rs index 44401357..dde35e53 100644 --- a/src/evm/simulation.rs +++ b/src/evm/simulation.rs @@ -17,14 +17,13 @@ use strum_macros::Display; use tokio::runtime::{Handle, Runtime}; use tracing::{debug, info}; -use crate::evm::engine_db::{ - engine_db_interface::EngineDatabaseInterface, simulation_db::OverriddenSimulationDB, -}; - use super::{ account_storage::StateUpdate, traces::{handle_traces, TraceResult}, }; +use crate::evm::engine_db::{ + engine_db_interface::EngineDatabaseInterface, simulation_db::OverriddenSimulationDB, +}; /// An error representing any transaction simulation result other than successful execution #[derive(Debug, Display, Clone, PartialEq)] @@ -368,7 +367,7 @@ impl SimulationParameters { #[cfg(test)] mod tests { - use super::*; + use std::{env, error::Error, str::FromStr, sync::Arc, time::Instant}; use alloy::{ providers::{ProviderBuilder, RootProvider}, @@ -377,14 +376,13 @@ mod tests { use alloy_primitives::Keccak256; use alloy_sol_types::SolValue; use dotenv::dotenv; - use std::{env, error::Error, str::FromStr, sync::Arc, time::Instant}; - use revm::primitives::{ bytes, hex, Account, AccountInfo, AccountStatus, Address, Bytecode, Bytes, EvmState as rState, EvmStorageSlot, ExecutionResult, HaltReason, InvalidTransaction, OutOfGasError, Output, ResultAndState, SuccessReason, B256, }; + use super::*; use crate::{ evm::engine_db::{ engine_db_interface::EngineDatabaseInterface, simulation_db::SimulationDB, diff --git a/src/evm/stream.rs b/src/evm/stream.rs index 86f31dd1..ca2248f6 100644 --- a/src/evm/stream.rs +++ b/src/evm/stream.rs @@ -1,3 +1,13 @@ +use std::{collections::HashMap, sync::Arc}; + +use futures::{Stream, StreamExt}; +use tokio_stream::wrappers::ReceiverStream; +use tycho_client::{ + feed::{component_tracker::ComponentFilter, synchronizer::ComponentWithState}, + stream::{StreamError, TychoStreamBuilder}, +}; +use tycho_core::{dto::Chain, Bytes}; + use crate::{ evm::decoder::{StreamDecodeError, TychoStreamDecoder}, models::Token, @@ -7,14 +17,6 @@ use crate::{ state::ProtocolSim, }, }; -use futures::{Stream, StreamExt}; -use std::{collections::HashMap, sync::Arc}; -use tokio_stream::wrappers::ReceiverStream; -use tycho_client::{ - feed::{component_tracker::ComponentFilter, synchronizer::ComponentWithState}, - stream::{StreamError, TychoStreamBuilder}, -}; -use tycho_core::{dto::Chain, Bytes}; pub struct ProtocolStreamBuilder { decoder: TychoStreamDecoder, diff --git a/src/evm/tycho_models.rs b/src/evm/tycho_models.rs index d3f13aac..4939ce2a 100644 --- a/src/evm/tycho_models.rs +++ b/src/evm/tycho_models.rs @@ -1,16 +1,16 @@ -use std::collections::HashMap; +use std::{collections::HashMap, fmt::Display}; -use crate::evm::protocol::u256_num; use alloy_primitives::{Address, B256, U256}; use chrono::{NaiveDateTime, Utc}; use serde::{Deserialize, Serialize}; -use std::fmt::Display; use strum_macros::{Display, EnumString}; use uuid::Uuid; -use crate::serde_helpers::{hex_bytes, hex_bytes_option}; - use super::engine_db::simulation_db::BlockHeader; +use crate::{ + evm::protocol::u256_num, + serde_helpers::{hex_bytes, hex_bytes_option}, +}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, Default)] pub struct ExtractorIdentity { diff --git a/src/models.rs b/src/models.rs index 24073b27..530d880e 100644 --- a/src/models.rs +++ b/src/models.rs @@ -5,17 +5,16 @@ //! //! Tokens provide instructions on how to handle prices and amounts, //! while Swap and SwapSequence are usually used as results types. -use alloy_primitives::U256; use std::{ convert::TryFrom, hash::{Hash, Hasher}, }; +use alloy_primitives::U256; use num_bigint::BigUint; -use tycho_core::Bytes; +use tycho_core::{dto::ResponseToken, Bytes}; use crate::utils::hexstring_to_vec; -use tycho_core::dto::ResponseToken; #[derive(Clone, Debug, Eq)] pub struct Token { @@ -107,9 +106,10 @@ impl TryFrom for Token { #[cfg(test)] mod tests { - use super::*; use num_bigint::ToBigUint; + use super::*; + #[test] fn test_constructor() { let token = Token::new( diff --git a/src/protocol/models.rs b/src/protocol/models.rs index af1602b8..bdf69807 100644 --- a/src/protocol/models.rs +++ b/src/protocol/models.rs @@ -27,14 +27,11 @@ use std::{collections::HashMap, future::Future}; use num_bigint::BigUint; - -use tycho_core::Bytes; - use tycho_client::feed::Header; - -use crate::models::Token; +use tycho_core::Bytes; use super::state::ProtocolSim; +use crate::models::Token; /// ProtocolComponent struct represents the properties of a trading pair /// diff --git a/src/protocol/state.rs b/src/protocol/state.rs index 436d3489..c587b925 100644 --- a/src/protocol/state.rs +++ b/src/protocol/state.rs @@ -47,6 +47,7 @@ use std::{any::Any, collections::HashMap}; use num_bigint::BigUint; +use tycho_core::{dto::ProtocolStateDelta, Bytes}; use crate::{ models::Token, @@ -55,7 +56,6 @@ use crate::{ models::GetAmountOutResult, }, }; -use tycho_core::{dto::ProtocolStateDelta, Bytes}; /// ProtocolSim trait /// This trait defines the methods that a protocol state must implement in order to be used diff --git a/src/serde_helpers.rs b/src/serde_helpers.rs index 111ba10b..5cf7c979 100644 --- a/src/serde_helpers.rs +++ b/src/serde_helpers.rs @@ -70,11 +70,11 @@ pub mod hex_bytes_option { #[cfg(test)] mod tests { - use super::*; - use serde::{Deserialize, Serialize}; use serde_json; + use super::*; + #[derive(Debug, Serialize, Deserialize)] struct TestStruct { #[serde(with = "hex_bytes")] diff --git a/src/utils.rs b/src/utils.rs index 6a4d4727..f7b8c521 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,8 +1,10 @@ -use crate::{models::Token, protocol::errors::SimulationError}; use std::collections::HashMap; + use tycho_client::{rpc::RPCClient, HttpRPCClient}; use tycho_core::{dto::Chain, Bytes}; +use crate::{models::Token, protocol::errors::SimulationError}; + /// Converts a hexadecimal string into a `Vec`. /// /// This function accepts a hexadecimal string with or without the `0x` prefix. If the prefix diff --git a/tycho_simulation_py/src/simulation_py.rs b/tycho_simulation_py/src/simulation_py.rs index 236d1646..867ec4fb 100644 --- a/tycho_simulation_py/src/simulation_py.rs +++ b/tycho_simulation_py/src/simulation_py.rs @@ -1,19 +1,20 @@ +use std::{collections::HashMap, str::FromStr}; + use alloy::{providers::RootProvider, transports::BoxTransport}; use num_bigint::BigUint; -use revm::primitives::{Address, U256 as rU256}; - -use crate::structs_py::{ - AccountInfo, BlockHeader, SimulationDB, SimulationErrorDetails, SimulationParameters, - SimulationResult, StateUpdate, TychoDB, -}; use pyo3::{prelude::*, types::PyType}; -use std::{collections::HashMap, str::FromStr}; +use revm::primitives::{Address, U256 as rU256}; use tycho_simulation::evm::{ account_storage, engine_db::{engine_db_interface::EngineDatabaseInterface, simulation_db, tycho_db}, simulation, }; +use crate::structs_py::{ + AccountInfo, BlockHeader, SimulationDB, SimulationErrorDetails, SimulationParameters, + SimulationResult, StateUpdate, TychoDB, +}; + #[derive(Clone, Copy)] enum DatabaseType { RpcReader, diff --git a/tycho_simulation_py/src/structs_py.rs b/tycho_simulation_py/src/structs_py.rs index 6fc89476..bd0ff9dc 100644 --- a/tycho_simulation_py/src/structs_py.rs +++ b/tycho_simulation_py/src/structs_py.rs @@ -1,17 +1,15 @@ #![allow(non_local_definitions)] //TODO: Update PYO3 to >= 0.21.2 (https://github.com/PyO3/pyo3/issues/4094#issuecomment-2064510190) -use num_bigint::BigUint; -use pyo3::{exceptions::PyRuntimeError, prelude::*}; -use revm::primitives::{Address as RevmAddress, Bytecode, B256, U256}; -use tokio::runtime::Runtime; -use tracing::info; - -use std::{collections::HashMap, str::FromStr, sync::Arc}; +use std::{collections::HashMap, fmt::Debug, str::FromStr, sync::Arc}; use alloy::{ providers::{ProviderBuilder, RootProvider}, transports::BoxTransport, }; -use std::fmt::Debug; +use num_bigint::BigUint; +use pyo3::{exceptions::PyRuntimeError, prelude::*}; +use revm::primitives::{Address as RevmAddress, Bytecode, B256, U256}; +use tokio::runtime::Runtime; +use tracing::info; use tycho_simulation::evm::{ account_storage, engine_db::{simulation_db, tycho_db},