use std::collections::HashMap;
use alloy::primitives::{I256, U256};
use tycho_common::Bytes;
use crate::{
evm::protocol::utils::uniswap::tick_math::{MAX_SQRT_RATIO, MIN_SQRT_RATIO},
protocol::errors::InvalidSnapshotError,
};
pub(super) const INT128_MAX: U256 = U256::from_limbs([u64::MAX, u64::MAX >> 1, 0, 0]);
pub(super) fn exact_input(amount_specified: I256) -> Result<U256, &'static str> {
if amount_specified == I256::ZERO {
return Err("a swap of zero reverts SwapAmountCannotBeZero");
}
if amount_specified > I256::ZERO {
return Err("exact-output swaps are not quoted");
}
let amount_in = amount_specified.unsigned_abs();
if amount_in > INT128_MAX {
return Err("an input above type(int128).max overflows the swap delta");
}
Ok(amount_in)
}
pub(super) fn swap_bound(price: U256, zero_for_one: bool) -> U256 {
if zero_for_one {
price.max(MIN_SQRT_RATIO + U256::from(1))
} else {
price.min(MAX_SQRT_RATIO - U256::from(1))
}
}
pub(super) fn field<T>(
attributes: &HashMap<String, Bytes>,
name: &str,
decode: impl FnOnce(&str, &Bytes) -> Result<T, InvalidSnapshotError>,
base: Option<T>,
) -> Result<T, InvalidSnapshotError> {
match (attributes.get(name), base) {
(Some(value), _) => decode(name, value),
(None, Some(base)) => Ok(base),
(None, None) => Err(InvalidSnapshotError::MissingAttribute(name.to_string())),
}
}
pub(super) fn fixed<const N: usize>(
name: &str,
value: &Bytes,
what: &str,
) -> Result<[u8; N], InvalidSnapshotError> {
<[u8; N]>::try_from(value.as_ref()).map_err(|_wrong_width| {
InvalidSnapshotError::ValueError(format!(
"{name} is {} bytes ({value}), not the {N}-byte {what}",
value.len()
))
})
}
pub(super) fn u64_be(name: &str, value: &Bytes) -> Result<u64, InvalidSnapshotError> {
Ok(u64::from_be_bytes(fixed(name, value, "big-endian u64")?))
}
pub(super) fn u32_be(name: &str, value: &Bytes) -> Result<u32, InvalidSnapshotError> {
let wide = u64_be(name, value)?;
u32::try_from(wide).map_err(|_overflow| {
InvalidSnapshotError::ValueError(format!("{name} = {wide} does not fit a uint32"))
})
}
pub(super) fn flag(name: &str, value: &Bytes) -> Result<bool, InvalidSnapshotError> {
match value.as_ref() {
[0] => Ok(false),
[1] => Ok(true),
_ => Err(InvalidSnapshotError::ValueError(format!(
"{name} is {value}, not a one-byte 0 or 1"
))),
}
}
pub(super) fn tick_i32(name: &str, value: &Bytes) -> Result<i32, InvalidSnapshotError> {
Ok(i32::from_be_bytes(fixed(name, value, "big-endian i32")?))
}