tycho_execution/encoding/evm/
utils.rs1use 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
23pub 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
35pub fn biguint_to_u256(value: &BigUint) -> U256 {
37 let bytes = value.to_bytes_be();
38 U256::from_be_slice(&bytes)
39}
40
41pub fn percentage_to_uint24(decimal: f64) -> U24 {
44 const MAX_UINT24: u32 = 16_777_215; let scaled = (decimal / 1.0) * (MAX_UINT24 as f64);
47 U24::from(scaled.round())
48}
49
50pub 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
63pub 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
71pub 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
81pub fn get_runtime() -> Result<(Handle, Option<Arc<Runtime>>), EncodingError> {
82 match Handle::try_current() {
83 Ok(h) => Ok((h, None)),
84 Err(_) => {
85 let rt = Arc::new(Runtime::new().map_err(|_| {
86 EncodingError::FatalError("Failed to create a new tokio runtime".to_string())
87 })?);
88 Ok((rt.handle().clone(), Some(rt)))
89 }
90 }
91}
92
93pub type EVMProvider = Arc<
94 FillProvider<
95 JoinFill<
96 alloy::providers::Identity,
97 JoinFill<GasFiller, JoinFill<BlobGasFiller, JoinFill<NonceFiller, ChainIdFiller>>>,
98 >,
99 RootProvider,
100 >,
101>;
102
103pub async fn get_client() -> Result<EVMProvider, EncodingError> {
105 dotenv::dotenv().ok();
106 let eth_rpc_url = env::var("RPC_URL")
107 .map_err(|_| EncodingError::FatalError("Missing RPC_URL in environment".to_string()))?;
108 let client = ProviderBuilder::new()
109 .connect(ð_rpc_url)
110 .await
111 .map_err(|_| EncodingError::FatalError("Failed to build provider".to_string()))?;
112 Ok(Arc::new(client))
113}
114
115pub fn ple_encode(action_data_array: Vec<Vec<u8>>) -> Vec<u8> {
120 let mut encoded_action_data: Vec<u8> = Vec::new();
121
122 for action_data in action_data_array {
123 let args = (encoded_action_data, action_data.len() as u16, action_data);
124 encoded_action_data = args.abi_encode_packed();
125 }
126
127 encoded_action_data
128}
129
130static CALLDATA_WRITE_MUTEX: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
131pub fn write_calldata_to_file(test_identifier: &str, hex_calldata: &str) {
134 let _lock = CALLDATA_WRITE_MUTEX
135 .lock()
136 .expect("Couldn't acquire lock");
137
138 let file_path = "foundry/test/assets/calldata.txt";
139 let file = OpenOptions::new()
140 .read(true)
141 .open(file_path)
142 .expect("Failed to open calldata file for reading");
143 let reader = BufReader::new(file);
144
145 let mut lines = Vec::new();
146 let mut found = false;
147 for line in reader.lines().map_while(Result::ok) {
148 let mut parts = line.splitn(2, ':'); let key = parts.next().unwrap_or("");
150 if key == test_identifier {
151 lines.push(format!("{test_identifier}:{hex_calldata}"));
152 found = true;
153 } else {
154 lines.push(line);
155 }
156 }
157
158 if !found {
160 lines.push(format!("{test_identifier}:{hex_calldata}"));
161 }
162
163 let mut file = OpenOptions::new()
165 .write(true)
166 .truncate(true)
167 .open(file_path)
168 .expect("Failed to open calldata file for writing");
169
170 for line in lines {
171 writeln!(file, "{line}").expect("Failed to write calldata");
172 }
173}