feat: Take Chain object containing native/wrapped addresses

- This way this chain object contains everything we need, we don't need to worry about doing any transformation or calling any supplementary functions inside any of the encoders
- Needed to move our new Chain object to a higher level since this is used in the higher-level encoder traits. This required some weird default values in the constants in order to avoid using alloy's hex literal. I could have instead opted to make Bytes parse a string I think, though this would mean possibly returning an error at the constants level, which is not nice either.

Question:
- Do we want the user to be in charge of passing the native and wrapped token every single time? This may be a bit annoying for the user. For now, I have defaulted to those in constants.rs, this would take 5 mins to remove though if you don't like it, and it would get rid of this complicated bytes initialization.
This commit is contained in:
TAMARA LIPOWSKI
2025-02-05 15:33:20 -05:00
parent f8b3baff55
commit e83b8d9aef
15 changed files with 190 additions and 103 deletions

View File

@@ -1,5 +1,13 @@
use num_bigint::BigUint;
use tycho_core::{dto::ProtocolComponent, Bytes};
use tycho_core::{
dto::{Chain as TychoCoreChain, ProtocolComponent},
Bytes,
};
use crate::encoding::{
constants::{NATIVE_ADDRESSES, WRAPPED_ADDRESSES},
errors::EncodingError,
};
#[derive(Clone, Default, Debug)]
pub struct Solution {
@@ -68,3 +76,65 @@ pub struct EncodingContext {
pub exact_out: bool,
pub router_address: Bytes,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ChainId(pub u64);
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Chain {
pub id: ChainId,
pub name: String,
pub native_token: Bytes,
pub wrapped_token: Bytes,
}
impl ChainId {
pub fn id(&self) -> u64 {
self.0
}
}
impl From<TychoCoreChain> for ChainId {
fn from(chain: TychoCoreChain) -> Self {
match chain {
TychoCoreChain::Ethereum => ChainId(1),
TychoCoreChain::ZkSync => ChainId(324),
TychoCoreChain::Arbitrum => ChainId(42161),
TychoCoreChain::Starknet => ChainId(0),
}
}
}
impl Chain {
pub fn from_tycho_core_chain(
chain: TychoCoreChain,
native_token: Option<Bytes>,
wrapped_token: Option<Bytes>,
) -> Result<Self, EncodingError> {
let native_token_address = match native_token {
Some(token) => token,
None => NATIVE_ADDRESSES.get(&chain)
.cloned()
.ok_or_else(|| EncodingError::InvalidInput(format!(
"Native token does not have a default address for chain {:?}. Please pass the native token address",
chain
)))?,
};
let wrapped_token_address = match wrapped_token {
Some(token) => token,
None => WRAPPED_ADDRESSES.get(&chain)
.cloned()
.ok_or_else(|| EncodingError::InvalidInput(format!(
"Wrapped token does not have a default address for chain {:?}. Please pass the wrapped token address",
chain
)))?,
};
Ok(Chain {
id: chain.into(),
name: chain.to_string(),
native_token: native_token_address,
wrapped_token: wrapped_token_address,
})
}
}