tycho_simulation/evm/protocol/utils/
mod.rs

1pub mod slipstreams;
2pub(super) mod solidity_math;
3pub mod uniswap;
4
5use alloy::primitives::Address;
6use tycho_common::{simulation::errors::SimulationError, Bytes};
7
8/// Safely converts a `Bytes` object to an `Address` object.
9///
10/// Checks the length of the `Bytes` before attempting to convert, and returns a `SimulationError`
11/// if not 20 bytes long.
12pub(crate) fn bytes_to_address(address: &Bytes) -> Result<Address, SimulationError> {
13    if address.len() == 20 {
14        Ok(Address::from_slice(address))
15    } else {
16        Err(SimulationError::InvalidInput(
17            format!("Invalid ERC20 token address: {address:?}"),
18            None,
19        ))
20    }
21}
22
23#[cfg(test)]
24mod tests {
25    use super::*;
26    use crate::utils::hexstring_to_vec;
27    #[test]
28    fn test_bytes_to_address_0x() {
29        let address =
30            Bytes::from(hexstring_to_vec("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap());
31        assert_eq!(
32            bytes_to_address(&address).unwrap(),
33            Address::from_slice(&hex::decode("c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap())
34        );
35    }
36
37    #[test]
38    fn test_bytes_to_address_invalid() {
39        let address = Bytes::from(hex::decode("C02aaA").unwrap());
40        assert!(bytes_to_address(&address).is_err());
41    }
42}