use std::collections::{BTreeMap, HashMap};
use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
use tycho_common::{models::token::Token, Bytes};
use super::{
attributes::{
apply_reserve, decode_bin_id_attribute, decode_bool_attribute, decode_u16_attribute,
decode_u32_attribute,
},
state::PancakeswapInfinityBinState,
};
use crate::{
evm::protocol::utils::uniswap::lp_fee::DYNAMIC_FEE_FLAG,
protocol::{
errors::InvalidSnapshotError,
models::{DecoderContext, TryFromWithBlock},
},
};
impl TryFromWithBlock<ComponentWithState, BlockHeader> for PancakeswapInfinityBinState {
type Error = InvalidSnapshotError;
async fn try_from_with_header(
snapshot: ComponentWithState,
_block: BlockHeader,
_account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
_all_tokens: &HashMap<Bytes, Token>,
_decoder_context: &DecoderContext,
) -> Result<Self, Self::Error> {
let static_attrs = snapshot.component.static_attributes;
let state_attrs = snapshot.state.attributes;
let parameters = attribute(&static_attrs, "parameters")?;
if has_swap_hooks(parameters)? {
return Err(InvalidSnapshotError::ValueError(format!(
"pool registers a swap hook (parameters {parameters}); its quotes depend on the hook"
)));
}
let lp_fee = decode_u32_attribute("key_lp_fee", attribute(&static_attrs, "key_lp_fee")?)?;
if lp_fee == DYNAMIC_FEE_FLAG {
return Err(InvalidSnapshotError::ValueError(
"pool has a dynamic LP fee (key_lp_fee), set by its hook per swap".to_string(),
));
}
let bin_step = decode_u16_attribute("bin_step", attribute(&static_attrs, "bin_step")?)?;
let active_id =
decode_bin_id_attribute("active_id", attribute(&state_attrs, "active_id")?)?;
let active_in_tree = match state_attrs.get("active_in_tree") {
Some(flag) => decode_bool_attribute("active_in_tree", flag)?,
None => true,
};
let protocol_fee = |key: &str| {
decode_u16_attribute(key, attribute(&state_attrs, key)?)
.map_err(InvalidSnapshotError::from)
};
let protocol_fee_zero_for_one = protocol_fee("protocol_fees/zero2one")?;
let protocol_fee_one_for_zero = protocol_fee("protocol_fees/one2zero")?;
let mut bins = BTreeMap::new();
for (key, value) in state_attrs
.iter()
.filter(|(key, _)| key.starts_with("bins/"))
{
apply_reserve(&mut bins, key, value)?;
}
bins.retain(|_, reserves| *reserves != (0, 0));
Self::new(
active_id,
active_in_tree,
bin_step,
lp_fee,
protocol_fee_zero_for_one,
protocol_fee_one_for_zero,
bins,
)
.map_err(|err| InvalidSnapshotError::ValueError(err.to_string()))
}
}
const SWAP_HOOK_BITS: u16 = (1 << 6) | (1 << 7) | (1 << 10) | (1 << 11);
fn has_swap_hooks(parameters: &Bytes) -> Result<bool, InvalidSnapshotError> {
let word: &[u8; 32] = parameters
.as_ref()
.try_into()
.map_err(|_not_32_bytes| {
InvalidSnapshotError::ValueError(format!(
"parameters is {} bytes, expected 32",
parameters.len()
))
})?;
Ok(u16::from_be_bytes([word[30], word[31]]) & SWAP_HOOK_BITS != 0)
}
fn attribute<'a>(
attrs: &'a HashMap<String, Bytes>,
key: &str,
) -> Result<&'a Bytes, InvalidSnapshotError> {
attrs
.get(key)
.ok_or_else(|| InvalidSnapshotError::MissingAttribute(key.to_string()))
}
#[cfg(test)]
mod tests {
use chrono::DateTime;
use rstest::rstest;
use tycho_common::models::{
protocol::{ProtocolComponent, ProtocolComponentState},
Chain, ChangeType,
};
use super::{super::attributes::reserve_attributes, *};
use crate::evm::protocol::test_utils::try_decode_snapshot_with_defaults;
const ACTIVE_ID: u32 = 8_388_608;
fn component(static_attrs: &[(&str, Bytes)]) -> ProtocolComponent {
ProtocolComponent {
id: "0xbin".to_string(),
protocol_system: "pancakeswap_infinity_bin".to_string(),
protocol_type_name: "pancakeswap_infinity_bin_pool".to_string(),
chain: Chain::Base,
tokens: Vec::new(),
contract_addresses: Vec::new(),
static_attributes: static_attrs
.iter()
.map(|(key, value)| (key.to_string(), value.clone()))
.collect(),
change: ChangeType::Creation,
creation_tx: Bytes::from(vec![0u8; 32]),
created_at: DateTime::from_timestamp(1622526000, 0)
.unwrap()
.naive_utc(),
}
}
fn parameters(hooks_bitmap: u16) -> Bytes {
let mut word = vec![0u8; 32];
word[28..30].copy_from_slice(&10u16.to_be_bytes());
word[30..].copy_from_slice(&hooks_bitmap.to_be_bytes());
Bytes::from(word)
}
fn statics() -> Vec<(&'static str, Bytes)> {
vec![
("bin_step", Bytes::from(10u16.to_be_bytes().to_vec())),
("key_lp_fee", Bytes::from(vec![0x64])),
("parameters", parameters(0)),
]
}
fn snapshot(
static_attrs: &[(&str, Bytes)],
state_attrs: &[(&str, Bytes)],
) -> ComponentWithState {
ComponentWithState {
state: ProtocolComponentState::new(
"0xbin",
state_attrs
.iter()
.map(|(key, value)| (key.to_string(), value.clone()))
.collect(),
HashMap::new(),
),
component: component(static_attrs),
component_tvl: None,
entrypoints: Vec::new(),
}
}
fn with_bins<'a>(
attrs: &[(&'a str, Bytes)],
bins: &'a [(String, Bytes)],
) -> Vec<(&'a str, Bytes)> {
attrs
.iter()
.cloned()
.chain(
bins.iter()
.map(|(key, value)| (key.as_str(), value.clone())),
)
.collect()
}
#[tokio::test]
async fn test_decodes_full_snapshot() {
let bins = reserve_attributes(ACTIVE_ID, 7, 11);
let snapshot = snapshot(
&statics(),
&with_bins(
&[
("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
("protocol_fees/zero2one", Bytes::from(vec![0x03])),
("protocol_fees/one2zero", Bytes::from(vec![0x05])),
],
&bins,
),
);
let state = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot)
.await
.unwrap();
assert_eq!(state.bin_step, 10);
assert_eq!(state.active_id, ACTIVE_ID);
assert!(state.active_in_tree, "absent flag reads as in the tree");
assert_eq!(state.lp_fee, 100);
assert_eq!(state.protocol_fee_zero_for_one, 3);
assert_eq!(state.protocol_fee_one_for_zero, 5);
assert_eq!(state.bins[&ACTIVE_ID], (7, 11));
}
#[tokio::test]
async fn test_decodes_active_bin_outside_the_tree() {
let snapshot = snapshot(
&statics(),
&[
("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
("active_in_tree", Bytes::from(vec![0x00])),
("protocol_fees/zero2one", Bytes::from(vec![0x03])),
("protocol_fees/one2zero", Bytes::from(vec![0x05])),
],
);
let state = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot)
.await
.unwrap();
assert!(!state.active_in_tree);
}
#[tokio::test]
async fn test_state_fee_attribute_is_ignored() {
let snapshot = snapshot(
&statics(),
&[
("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
("protocol_fees/zero2one", Bytes::from(vec![0x03])),
("protocol_fees/one2zero", Bytes::from(vec![0x05])),
("fee", Bytes::from(vec![0x01, 0xf4])),
],
);
let state = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot)
.await
.unwrap();
assert_eq!(state.lp_fee, 100);
}
#[tokio::test]
#[rstest]
#[case::missing_bin_step("bin_step", "bin_step")]
#[case::missing_active_id("active_id", "active_id")]
#[case::missing_lp_fee("key_lp_fee", "key_lp_fee")]
#[case::missing_parameters("parameters", "parameters")]
#[case::missing_protocol_fee_zero2one("protocol_fees/zero2one", "protocol_fees/zero2one")]
#[case::missing_protocol_fee_one2zero("protocol_fees/one2zero", "protocol_fees/one2zero")]
async fn test_missing_required_attribute_errors(#[case] removed: &str, #[case] reported: &str) {
let statics: Vec<_> = statics()
.into_iter()
.filter(|(key, _)| *key != removed)
.collect();
let states: Vec<_> = [
("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
("protocol_fees/zero2one", Bytes::from(vec![0x03])),
("protocol_fees/one2zero", Bytes::from(vec![0x03])),
]
.into_iter()
.filter(|(key, _)| *key != removed)
.collect();
let result = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot(
&statics, &states,
))
.await;
assert!(
matches!(
result,
Err(InvalidSnapshotError::MissingAttribute(ref attr)) if attr == reported
),
"expected MissingAttribute({reported}), got {result:?}"
);
}
#[tokio::test]
#[rstest]
#[case::before_swap("parameters", parameters(1 << 6))]
#[case::after_swap("parameters", parameters(1 << 7))]
#[case::before_swap_returns_delta("parameters", parameters(1 << 10))]
#[case::after_swap_returns_delta("parameters", parameters(1 << 11))]
#[case::dynamic_lp_fee("key_lp_fee", Bytes::from(vec![0x00, 0x80, 0x00, 0x00]))]
#[case::short_parameters("parameters", Bytes::from(vec![0u8; 31]))]
async fn test_rejects_pools_it_cannot_quote(#[case] key: &str, #[case] value: Bytes) {
let mut statics = statics();
for (name, existing) in &mut statics {
if *name == key {
*existing = value.clone();
}
}
let result = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot(
&statics,
&[
("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
("protocol_fees/zero2one", Bytes::from(vec![0x03])),
("protocol_fees/one2zero", Bytes::from(vec![0x05])),
],
))
.await;
assert!(
matches!(result, Err(InvalidSnapshotError::ValueError(_))),
"{key} = {value} decoded: {result:?}"
);
}
#[tokio::test]
async fn test_accepts_non_swap_hooks() {
let mut statics = statics();
statics[2].1 = parameters(0b11_0011_0011_1111);
let result = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot(
&statics,
&[
("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
("protocol_fees/zero2one", Bytes::from(vec![0x03])),
("protocol_fees/one2zero", Bytes::from(vec![0x05])),
],
))
.await;
assert!(result.is_ok(), "non-swap hooks rejected: {result:?}");
}
#[tokio::test]
async fn test_skips_empty_bins() {
let bins: Vec<_> =
[reserve_attributes(ACTIVE_ID, 0, 1_000), reserve_attributes(ACTIVE_ID + 1, 0, 0)]
.concat();
let snapshot = snapshot(
&statics(),
&with_bins(
&[
("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x00])),
("protocol_fees/zero2one", Bytes::from(vec![0x03])),
("protocol_fees/one2zero", Bytes::from(vec![0x05])),
],
&bins,
),
);
let state = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot)
.await
.unwrap();
assert_eq!(state.bins.len(), 1);
assert_eq!(state.bins[&ACTIVE_ID], (0, 1_000));
}
}