Skip to content

Commit

Permalink
feat: Replace ethers types in block hash
Browse files Browse the repository at this point in the history
--- don't change below this line ---
ENG-3850 <#DTT#>
  • Loading branch information
dianacarvalho1 committed Dec 6, 2024
1 parent 803d1f9 commit 62a9a3d
Show file tree
Hide file tree
Showing 10 changed files with 31 additions and 66 deletions.
5 changes: 2 additions & 3 deletions examples/explorer/data_feed/tycho.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ use std::{
str::FromStr,
};

use alloy_primitives::Address;
use alloy_primitives::{Address, B256};
use chrono::Utc;
use ethers::prelude::H256;
use tokio::sync::mpsc::Sender;
use tracing::{debug, info, warn};

Expand Down Expand Up @@ -151,7 +150,7 @@ pub async fn process_messages(
let block_hash = header.clone().hash;
let block = BlockHeader {
number: block_id,
hash: H256::from_slice(&block_hash[..]),
hash: B256::from_slice(&block_hash[..]),
timestamp: Utc::now().timestamp() as u64,
};

Expand Down
10 changes: 4 additions & 6 deletions src/evm/engine_db/simulation_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ impl<DB: DatabaseRef> DatabaseRef for OverriddenSimulationDB<'_, DB> {
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, Default)]
pub struct BlockHeader {
pub number: u64,
pub hash: H256,
pub hash: B256,
pub timestamp: u64,
}

impl From<BlockHeader> for BlockId {
fn from(value: BlockHeader) -> Self {
Self::from(value.hash)
Self::from(H256::from_slice(&value.hash.0))
}
}

Expand Down Expand Up @@ -449,9 +449,7 @@ impl<M: Middleware> DatabaseRef for SimulationDB<M> {
/// instead of querying a node.
fn block_hash_ref(&self, _number: u64) -> Result<B256, Self::Error> {
match &self.block {
Some(header) => Ok(B256::try_from(header.hash.as_bytes()).unwrap_or_else(|_| {
panic!("Failed to convert header hash {:?} to B256", header.hash)
})),
Some(header) => Ok(header.hash),
None => Ok(B256::ZERO),
}
}
Expand Down Expand Up @@ -635,7 +633,7 @@ mod tests {
let update = StateUpdate { storage: Some(new_storage), balance: Some(new_balance) };
let mut updates = HashMap::default();
updates.insert(address, update);
let new_block = BlockHeader { number: 1, hash: H256::default(), timestamp: 234 };
let new_block = BlockHeader { number: 1, hash: B256::default(), timestamp: 234 };

let reverse_update = mock_sim_db.update_state(&updates, new_block);

Expand Down
2 changes: 1 addition & 1 deletion src/evm/engine_db/tycho_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ impl DatabaseRef for PreCachedDB {
/// If block header is set, returns the hash. Otherwise returns a zero hash.
fn block_hash_ref(&self, _number: u64) -> Result<B256, Self::Error> {
match self.inner.read().unwrap().block {
Some(header) => Ok(B256::from_slice(header.hash.as_bytes())),
Some(header) => Ok(header.hash),
None => Ok(B256::default()),
}
}
Expand Down
37 changes: 2 additions & 35 deletions src/evm/protocol/u256_num.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
//! Numeric methods for the U256 type
use alloy_primitives::{Address, U256};
use std::{cmp::max, collections::HashMap, panic};
use alloy_primitives::U256;
use std::{cmp::max, panic};

use ethers::types::U256 as EthersU256;
use num_bigint::BigUint;

/// Converts a U256 integer into it's closest floating point representation
Expand Down Expand Up @@ -105,38 +104,6 @@ pub fn biguint_to_u256(value: &BigUint) -> U256 {
U256::from_be_slice(&bytes)
}

pub fn convert_ethers_to_alloy(ethers_u256: EthersU256) -> U256 {
let mut bytes = [0u8; 32]; // 32-byte buffer
ethers_u256.to_big_endian(&mut bytes); // Fill the buffer with big-endian bytes
U256::from_be_bytes(bytes) // Convert to Alloy U256
}
pub fn convert_alloy_to_ethers(alloy_value: U256) -> EthersU256 {
let bytes = alloy_value.to_be_bytes::<32>();
EthersU256::from_big_endian(&bytes)
}

pub fn convert_alloy_to_ethers_overwrites(
input: Option<HashMap<Address, HashMap<U256, U256>>>,
) -> Option<HashMap<Address, HashMap<EthersU256, EthersU256>>> {
input.map(|outer_map| {
outer_map
.into_iter()
.map(|(address, inner_map)| {
let converted_inner_map = inner_map
.into_iter()
.map(|(key, value)| {
(
EthersU256::from_big_endian(&key.to_be_bytes::<32>()),
EthersU256::from_big_endian(&value.to_be_bytes::<32>()),
)
})
.collect();
(address, converted_inner_map)
})
.collect()
})
}

#[cfg(test)]
mod test {
use super::*;
Expand Down
6 changes: 3 additions & 3 deletions src/evm/protocol/vm/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -500,13 +500,13 @@ where
#[cfg(test)]
mod tests {
use super::*;
use alloy_primitives::B256;
use std::{
collections::{HashMap, HashSet},
path::PathBuf,
str::FromStr,
};

use ethers::prelude::H256;
use num_bigint::ToBigUint;
use num_traits::One;
use revm::primitives::{AccountInfo, Bytecode, KECCAK_EMPTY};
Expand Down Expand Up @@ -549,7 +549,7 @@ mod tests {

let block = BlockHeader {
number: 20463609,
hash: H256::from_str(
hash: B256::from_str(
"0x4315fd1afc25cc2ebc72029c543293f9fd833eeb305e2e30159459c827733b1b",
)
.unwrap(),
Expand Down Expand Up @@ -580,7 +580,7 @@ mod tests {
let tokens = vec![dai_addr, bal_addr];
let block = BlockHeader {
number: 18485417,
hash: H256::from_str(
hash: B256::from_str(
"0x28d41d40f2ac275a4f5f621a636b9016b527d11d37d610a45ac3a821346ebf8c",
)
.expect("Invalid block hash"),
Expand Down
8 changes: 3 additions & 5 deletions src/evm/protocol/vm/state_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ use super::{
/// # Example
/// Constructing a `EVMPoolState` with only the required parameters:
/// ```rust
/// use ethers::types::Address;
/// use crate::evm::simulation_db::BlockHeader;
/// use crate::protocol::errors::SimulationError;
///
Expand Down Expand Up @@ -434,16 +433,15 @@ impl EVMPoolStateBuilder {
mod tests {
use super::*;

use alloy_primitives::B256;
use std::str::FromStr;

use ethers::types::H256;

#[test]
fn test_build_without_required_fields() {
let id = "pool_1".to_string();
let tokens = vec![Address::repeat_byte(0)];
let balances = HashMap::new();
let block = BlockHeader { number: 1, hash: H256::default(), timestamp: 234 };
let block = BlockHeader { number: 1, hash: B256::default(), timestamp: 234 };

let result =
tokio_test::block_on(EVMPoolStateBuilder::new(id, tokens, balances, block).build());
Expand All @@ -463,7 +461,7 @@ mod tests {
let token2 = Address::from_str("0000000000000000000000000000000000000002").unwrap();
let token3 = Address::from_str("0000000000000000000000000000000000000003").unwrap();
let tokens = vec![token2, token3];
let block = BlockHeader { number: 1, hash: H256::default(), timestamp: 234 };
let block = BlockHeader { number: 1, hash: B256::default(), timestamp: 234 };
let balances = HashMap::new();

let mut builder = EVMPoolStateBuilder::new(id, tokens, balances, block);
Expand Down
17 changes: 12 additions & 5 deletions src/evm/protocol/vm/tycho_decoder.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
use alloy_primitives::{Address, U256};
use alloy_primitives::{Address, B256, U256};
use std::{
collections::HashMap,
path::PathBuf,
time::{SystemTime, UNIX_EPOCH},
};

use ethers::types::H256;

use tycho_client::feed::{synchronizer::ComponentWithState, Header};
use tycho_core::Bytes;
use tycho_ethereum::BytesCodec;

use crate::{
evm::engine_db::{simulation_db::BlockHeader, tycho_db::PreCachedDB},
Expand All @@ -25,7 +22,17 @@ impl From<Header> for BlockHeader {
.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
.as_secs();
BlockHeader { number: header.number, hash: H256::from_bytes(&header.hash), timestamp: now }
BlockHeader {
number: header.number,
hash: B256::new(
header
.hash
.as_ref()
.try_into()
.expect("Hash must be 32 bytes"),
),
timestamp: now,
}
}
}

Expand Down
2 changes: 0 additions & 2 deletions src/evm/protocol/vm/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,6 @@ fn parse_solidity_error_message(data: &str) -> String {
///
/// ```
/// use tycho_simulation::protocol::vm::utils::get_storage_slot_index_at_key;
/// use ethers::types::{Address, U256};
/// let address: Address = "0xC63135E4bF73F637AF616DFd64cf701866BB2628".parse().expect("Invalid address");
/// get_storage_slot_index_at_key(address, U256::from(0));
/// ```
Expand All @@ -174,7 +173,6 @@ fn parse_solidity_error_message(data: &str) -> String {
///
/// ```
/// use tycho_simulation::protocol::vm::utils::get_storage_slot_index_at_key;
/// use ethers::types::{Address, U256};
/// let address_spender: Address = "0xC63135E4bF73F637AF616DFd64cf701866BB2628".parse().expect("Invalid address");
/// let address_owner: Address = "0x6F4Feb566b0f29e2edC231aDF88Fe7e1169D7c05".parse().expect("Invalid address");
/// get_storage_slot_index_at_key(address_spender, get_storage_slot_index_at_key(address_owner, U256::from(1)));
Expand Down
3 changes: 1 addition & 2 deletions src/evm/tycho_models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::collections::HashMap;

use alloy_primitives::bytes::Bytes;
use chrono::{NaiveDateTime, Utc};
use ethers::types::H256;
use revm::primitives::{Address, B256, U256, U256 as rU256};
use serde::{Deserialize, Serialize};
use std::fmt::Display;
Expand Down Expand Up @@ -90,7 +89,7 @@ impl From<Block> for BlockHeader {
fn from(value: Block) -> Self {
Self {
number: value.number,
hash: H256::from(value.hash.0),
hash: value.hash,
timestamp: value.ts.and_utc().timestamp() as u64,
}
}
Expand Down
7 changes: 3 additions & 4 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@
//!
//! ERC20Tokens provide instructions on how to handle prices and amounts,
//! while Swap and SwapSequence are usually used as results types.
use alloy_primitives::Address;
use alloy_primitives::{Address, U256};
use std::{
convert::TryFrom,
hash::{Hash, Hasher},
str::FromStr,
};

use ethers::types::U256;
use num_bigint::BigUint;

use tycho_core::dto::ResponseToken;
Expand Down Expand Up @@ -57,7 +56,7 @@ impl ERC20Token {
/// ## Return
/// Return one token as U256
pub fn one(&self) -> U256 {
U256::exp10(self.decimals)
U256::from(10).pow(U256::from(self.decimals))
}
}

Expand Down Expand Up @@ -155,6 +154,6 @@ mod tests {
10000.to_biguint().unwrap(),
);

assert_eq!(usdc.one().as_u64(), 1000000);
assert_eq!(usdc.one(), U256::from(1000000));
}
}

0 comments on commit 62a9a3d

Please sign in to comment.