tycho_execution/encoding/evm/
utils.rs

1use std::{
2    env,
3    fs::OpenOptions,
4    io::{BufRead, BufReader, Write},
5    sync::{Arc, Mutex},
6};
7
8use alloy::{
9    primitives::{aliases::U24, Address, U256, U8},
10    providers::{
11        fillers::{BlobGasFiller, ChainIdFiller, FillProvider, GasFiller, JoinFill, NonceFiller},
12        ProviderBuilder, RootProvider,
13    },
14    sol_types::SolValue,
15};
16use num_bigint::BigUint;
17use once_cell::sync::Lazy;
18use tokio::runtime::{Handle, Runtime};
19use tycho_common::Bytes;
20
21use crate::encoding::{errors::EncodingError, models::Swap};
22
23/// Safely converts a `Bytes` object to an `Address` object.
24///
25/// Checks the length of the `Bytes` before attempting to convert, and returns an `EncodingError`
26/// if not 20 bytes long.
27pub fn bytes_to_address(address: &Bytes) -> Result<Address, EncodingError> {
28    if address.len() == 20 {
29        Ok(Address::from_slice(address))
30    } else {
31        Err(EncodingError::InvalidInput(format!("Invalid address: {address}",)))
32    }
33}
34
35/// Converts a general `BigUint` to an EVM-specific `U256` value.
36pub fn biguint_to_u256(value: &BigUint) -> U256 {
37    let bytes = value.to_bytes_be();
38    U256::from_be_slice(&bytes)
39}
40
41/// Converts a decimal to a `U24` value. The percentage is a `f64` value between 0 and 1.
42/// MAX_UINT24 corresponds to 100%.
43pub fn percentage_to_uint24(decimal: f64) -> U24 {
44    const MAX_UINT24: u32 = 16_777_215; // 2^24 - 1
45
46    let scaled = (decimal / 1.0) * (MAX_UINT24 as f64);
47    U24::from(scaled.round())
48}
49
50/// Gets the position of a token in a list of tokens.
51pub fn get_token_position(tokens: &Vec<&Bytes>, token: &Bytes) -> Result<U8, EncodingError> {
52    let position = U8::from(
53        tokens
54            .iter()
55            .position(|t| *t == token)
56            .ok_or_else(|| {
57                EncodingError::InvalidInput(format!("Token {token} not found in tokens array"))
58            })?,
59    );
60    Ok(position)
61}
62
63/// Pads a byte slice to a fixed size array of N bytes.
64pub fn pad_to_fixed_size<const N: usize>(input: &[u8]) -> Result<[u8; N], EncodingError> {
65    let mut padded = [0u8; N];
66    let start = N - input.len();
67    padded[start..].copy_from_slice(input);
68    Ok(padded)
69}
70
71/// Extracts a static attribute from a swap.
72pub fn get_static_attribute(swap: &Swap, attribute_name: &str) -> Result<Vec<u8>, EncodingError> {
73    Ok(swap
74        .component
75        .static_attributes
76        .get(attribute_name)
77        .ok_or_else(|| EncodingError::FatalError(format!("Attribute {attribute_name} not found")))?
78        .to_vec())
79}
80
81/// Returns the current Tokio runtime handle, or creates a new one if it doesn't exist.
82/// It also returns the runtime to prevent it from being dropped before use.
83/// This is required since tycho-execution does not have a pre-existing runtime.
84pub fn get_runtime() -> Result<(Handle, Option<Arc<Runtime>>), EncodingError> {
85    match Handle::try_current() {
86        Ok(h) => Ok((h, None)),
87        Err(_) => {
88            let rt = Arc::new(Runtime::new().map_err(|_| {
89                EncodingError::FatalError("Failed to create a new tokio runtime".to_string())
90            })?);
91            Ok((rt.handle().clone(), Some(rt)))
92        }
93    }
94}
95
96pub type EVMProvider = Arc<
97    FillProvider<
98        JoinFill<
99            alloy::providers::Identity,
100            JoinFill<GasFiller, JoinFill<BlobGasFiller, JoinFill<NonceFiller, ChainIdFiller>>>,
101        >,
102        RootProvider,
103    >,
104>;
105
106/// Gets the client used for interacting with the EVM-compatible network.
107pub async fn get_client() -> Result<EVMProvider, EncodingError> {
108    dotenv::dotenv().ok();
109    let eth_rpc_url = env::var("RPC_URL")
110        .map_err(|_| EncodingError::FatalError("Missing RPC_URL in environment".to_string()))?;
111    let client = ProviderBuilder::new()
112        .connect(&eth_rpc_url)
113        .await
114        .map_err(|_| EncodingError::FatalError("Failed to build provider".to_string()))?;
115    Ok(Arc::new(client))
116}
117
118/// Uses prefix-length encoding to efficient encode action data.
119///
120/// Prefix-length encoding is a data encoding method where the beginning of a data segment
121/// (the "prefix") contains information about the length of the following data.
122pub fn ple_encode(action_data_array: Vec<Vec<u8>>) -> Vec<u8> {
123    let mut encoded_action_data: Vec<u8> = Vec::new();
124
125    for action_data in action_data_array {
126        let args = (encoded_action_data, action_data.len() as u16, action_data);
127        encoded_action_data = args.abi_encode_packed();
128    }
129
130    encoded_action_data
131}
132
133static CALLDATA_WRITE_MUTEX: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
134// Function used in tests to write calldata to a file that then is used by the corresponding
135// solidity tests.
136pub fn write_calldata_to_file(test_identifier: &str, hex_calldata: &str) {
137    let _lock = CALLDATA_WRITE_MUTEX
138        .lock()
139        .expect("Couldn't acquire lock");
140
141    let file_path = "foundry/test/assets/calldata.txt";
142    let file = OpenOptions::new()
143        .read(true)
144        .open(file_path)
145        .expect("Failed to open calldata file for reading");
146    let reader = BufReader::new(file);
147
148    let mut lines = Vec::new();
149    let mut found = false;
150    for line in reader.lines().map_while(Result::ok) {
151        let mut parts = line.splitn(2, ':'); // split at the :
152        let key = parts.next().unwrap_or("");
153        if key == test_identifier {
154            lines.push(format!("{test_identifier}:{hex_calldata}"));
155            found = true;
156        } else {
157            lines.push(line);
158        }
159    }
160
161    // If the test identifier wasn't found, append a new line
162    if !found {
163        lines.push(format!("{test_identifier}:{hex_calldata}"));
164    }
165
166    // Write the updated contents back to the file
167    let mut file = OpenOptions::new()
168        .write(true)
169        .truncate(true)
170        .open(file_path)
171        .expect("Failed to open calldata file for writing");
172
173    for line in lines {
174        writeln!(file, "{line}").expect("Failed to write calldata");
175    }
176}