Skip to main content

tycho_simulation/evm/protocol/biconomy/
decoder.rs

1//! Attribute layout of a Biconomy venue component, shared with the `base-biconomy` substreams
2//! package. Addresses are `0x`-prefixed lowercase hex; values are big-endian integers. Nothing
3//! is read over RPC: every value is a storage word, or a provider config set by the package.
4//!
5//! | attribute                                | value                                          |
6//! |------------------------------------------|------------------------------------------------|
7//! | `fee_bps`                                | venue storage slot 0 (`feeBps` is its low 16 bits) |
8//! | `maker_count`                            | venue storage slot 1 (`makerList.length`)      |
9//! | `maker/{i}`                              | `makerList[i]`                                 |
10//! | `board/{mm}/{tokenIn}/{tokenOut}/{slot}` | executor storage word `slot` (0..24) of board  |
11//! | `anchor/{mm}/{token0}/{token1}`          | executor anchor word for the sorted pair       |
12//! | `paused/{mm}`                            | 1 when the maker paused itself                 |
13//! | `provider/{provider}`                    | kind byte (0 balance, 1 vault, 2 unbounded), vault |
14//! | `signer/{provider}`                      | the provider's `signer()` word                 |
15//! | `approved_executor/{provider}`           | the provider's `approvedExecutor` word         |
16//! | `router_count/{vault}`, `router/{vault}` | the vault's router array length and first element (`router()`) |
17//! | `balance/{token}/{holder}`               | the token's `balanceOf` storage word           |
18//! | `allowance/{token}/{owner}/{spender}`    | the token's `allowance` storage word           |
19//!
20//! Static attributes: `pamm_address` (the venue) and `executor`.
21
22use std::collections::HashMap;
23
24use alloy::primitives::U256;
25use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader};
26use tycho_common::{models::token::Token, Bytes};
27
28use super::{
29    math::{Address, BOARD_WORDS},
30    state::{BiconomyState, BlockEnvState, ProviderConfig, ProviderKind},
31};
32use crate::protocol::{
33    errors::InvalidSnapshotError,
34    models::{DecoderContext, TryFromWithBlock},
35};
36
37pub mod attrs {
38    pub const FEE_BPS: &str = "fee_bps";
39    pub const MAKER_COUNT: &str = "maker_count";
40    pub const MAKER: &str = "maker";
41    pub const BOARD: &str = "board";
42    pub const ANCHOR: &str = "anchor";
43    pub const PAUSED: &str = "paused";
44    pub const PROVIDER: &str = "provider";
45    pub const BALANCE: &str = "balance";
46    pub const ALLOWANCE: &str = "allowance";
47    pub const SIGNER: &str = "signer";
48    pub const APPROVED_EXECUTOR: &str = "approved_executor";
49    pub const ROUTER_COUNT: &str = "router_count";
50    pub const ROUTER: &str = "router";
51    pub const PAMM_ADDRESS: &str = "pamm_address";
52    pub const EXECUTOR: &str = "executor";
53}
54
55pub fn hex_address(address: &Address) -> String {
56    format!("0x{}", alloy::hex::encode(address))
57}
58
59pub fn board_key(mm: &Address, a: &Address, b: &Address) -> String {
60    format!("{}/{}/{}", hex_address(mm), hex_address(a), hex_address(b))
61}
62
63pub fn allowance_key(token: &Address, owner: &Address, spender: &Address) -> String {
64    board_key(token, owner, spender)
65}
66
67pub fn pair_key(a: &Address, b: &Address) -> String {
68    format!("{}/{}", hex_address(a), hex_address(b))
69}
70
71fn parse_address(value: &str) -> Result<Address, InvalidSnapshotError> {
72    let raw = alloy::hex::decode(value.trim_start_matches("0x"))
73        .map_err(|_| InvalidSnapshotError::ValueError(format!("invalid address `{value}`")))?;
74    raw.as_slice()
75        .try_into()
76        .map_err(|_| InvalidSnapshotError::ValueError(format!("address `{value}` is not 20 bytes")))
77}
78
79fn word(value: &Bytes) -> Result<U256, InvalidSnapshotError> {
80    if value.len() > 32 {
81        return Err(InvalidSnapshotError::ValueError(format!(
82            "value of {} bytes does not fit a storage word",
83            value.len()
84        )));
85    }
86    Ok(U256::from_be_slice(value.as_ref()))
87}
88
89fn word_address(word: U256) -> Address {
90    word.to_be_bytes::<32>()[12..]
91        .try_into()
92        .expect("20 bytes")
93}
94
95/// A provider config: kind byte, then the vault for a vault provider.
96fn decode_provider(value: &Bytes) -> Result<ProviderConfig, InvalidSnapshotError> {
97    if value.len() != 21 {
98        return Err(InvalidSnapshotError::ValueError(format!(
99            "provider config of {} bytes",
100            value.len()
101        )));
102    }
103    let address = |range: std::ops::Range<usize>| -> Address {
104        value[range]
105            .try_into()
106            .expect("20 bytes")
107    };
108    let kind = match value[0] {
109        0 => ProviderKind::Balance,
110        1 => ProviderKind::Vault(address(1..21)),
111        2 => ProviderKind::Unbounded,
112        other => {
113            return Err(InvalidSnapshotError::ValueError(format!("provider kind {other}")));
114        }
115    };
116    Ok(ProviderConfig { kind })
117}
118
119pub enum AttributeChange<'a> {
120    Set(&'a String, &'a Bytes),
121    Delete(&'a String),
122}
123
124/// Applies attribute writes and deletions to `state`; a deleted value reads as zero, as unset
125/// storage does. Unknown attributes are ignored.
126pub fn apply_attributes<'a>(
127    state: &mut BiconomyState,
128    changes: impl IntoIterator<Item = AttributeChange<'a>>,
129) -> Result<(), InvalidSnapshotError> {
130    for change in changes {
131        let (name, value) = match change {
132            AttributeChange::Set(name, value) => (name, value.clone()),
133            AttributeChange::Delete(name) => (name, Bytes::new()),
134        };
135        let parts: Vec<&str> = name.split('/').collect();
136        match parts.as_slice() {
137            [attrs::FEE_BPS] => {
138                // feeBps is the low 16 bits of the venue's first slot.
139                state.fee_bps = (word(&value)? & U256::from(u16::MAX)).to::<u16>();
140            }
141            [attrs::MAKER_COUNT] => {
142                let count = word(&value)?;
143                state.maker_count = u64::try_from(count).map_err(|_| {
144                    InvalidSnapshotError::ValueError(format!("maker_count {count}"))
145                })?;
146            }
147            [attrs::MAKER, index] => {
148                let index: u8 = index.parse().map_err(|_| {
149                    InvalidSnapshotError::ValueError(format!("invalid maker index in `{name}`"))
150                })?;
151                state
152                    .maker_slots
153                    .insert(index, word_address(word(&value)?));
154            }
155            [attrs::BOARD, mm, token_in, token_out, slot] => {
156                let slot: u8 = slot
157                    .parse()
158                    .ok()
159                    .filter(|slot| *slot < BOARD_WORDS)
160                    .ok_or_else(|| {
161                        InvalidSnapshotError::ValueError(format!("invalid board slot in `{name}`"))
162                    })?;
163                let key = board_key(
164                    &parse_address(mm)?,
165                    &parse_address(token_in)?,
166                    &parse_address(token_out)?,
167                );
168                let words = state.boards.entry(key).or_default();
169                let value = word(&value)?;
170                if value.is_zero() {
171                    words.remove(&slot);
172                } else {
173                    words.insert(slot, value);
174                }
175            }
176            [attrs::ANCHOR, mm, token0, token1] => {
177                let key = board_key(
178                    &parse_address(mm)?,
179                    &parse_address(token0)?,
180                    &parse_address(token1)?,
181                );
182                state.anchors.insert(key, word(&value)?);
183            }
184            [attrs::PAUSED, mm] => {
185                let mm = parse_address(mm)?;
186                if word(&value)?.is_zero() {
187                    state.paused.remove(&mm);
188                } else {
189                    state.paused.insert(mm);
190                }
191            }
192            [attrs::PROVIDER, provider] => {
193                let provider = parse_address(provider)?;
194                if value.is_empty() {
195                    state
196                        .providers
197                        .remove(&hex_address(&provider));
198                } else {
199                    state
200                        .providers
201                        .insert(hex_address(&provider), decode_provider(&value)?);
202                }
203            }
204            [attrs::SIGNER, provider] => {
205                let key = hex_address(&parse_address(provider)?);
206                state
207                    .signers
208                    .insert(key, word_address(word(&value)?));
209            }
210            [attrs::APPROVED_EXECUTOR, provider] => {
211                let key = hex_address(&parse_address(provider)?);
212                state
213                    .approved_executors
214                    .insert(key, word_address(word(&value)?));
215            }
216            [attrs::ROUTER_COUNT, vault] => {
217                let key = hex_address(&parse_address(vault)?);
218                state
219                    .router_counts
220                    .insert(key, word(&value)?);
221            }
222            [attrs::ROUTER, vault] => {
223                let key = hex_address(&parse_address(vault)?);
224                state
225                    .routers
226                    .insert(key, word_address(word(&value)?));
227            }
228            [attrs::BALANCE, token, holder] => {
229                let key = pair_key(&parse_address(token)?, &parse_address(holder)?);
230                state
231                    .balances
232                    .insert(key, word(&value)?);
233            }
234            [attrs::ALLOWANCE, token, owner, spender] => {
235                let key = allowance_key(
236                    &parse_address(token)?,
237                    &parse_address(owner)?,
238                    &parse_address(spender)?,
239                );
240                state
241                    .allowances
242                    .insert(key, word(&value)?);
243            }
244            _ => {}
245        }
246    }
247    Ok(())
248}
249
250pub fn decode_biconomy_snapshot(
251    snapshot: &ComponentWithState,
252    header: &BlockHeader,
253) -> Result<BiconomyState, InvalidSnapshotError> {
254    let static_address = |name: &str| -> Result<Address, InvalidSnapshotError> {
255        let value = snapshot
256            .component
257            .static_attributes
258            .get(name)
259            .ok_or_else(|| InvalidSnapshotError::MissingAttribute(name.to_owned()))?;
260        value
261            .as_ref()
262            .try_into()
263            .map_err(|_| InvalidSnapshotError::ValueError(format!("invalid {name} {value}")))
264    };
265    let mut state = BiconomyState {
266        venue: static_address(attrs::PAMM_ADDRESS)?,
267        executor: static_address(attrs::EXECUTOR)?,
268        // As of the header; the stream decoder moves it to the execution block via
269        // `apply_block`, with the chain's block time and its flashblock handling.
270        block: BlockEnvState { number: header.number, timestamp: header.timestamp },
271        ..Default::default()
272    };
273    apply_attributes(
274        &mut state,
275        snapshot
276            .state
277            .attributes
278            .iter()
279            .map(|(name, value)| AttributeChange::Set(name, value)),
280    )?;
281    Ok(state)
282}
283
284impl TryFromWithBlock<ComponentWithState, BlockHeader> for BiconomyState {
285    type Error = InvalidSnapshotError;
286
287    async fn try_from_with_header(
288        snapshot: ComponentWithState,
289        block: BlockHeader,
290        _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
291        _all_tokens: &HashMap<Bytes, Token>,
292        _decoder_context: &DecoderContext,
293    ) -> Result<Self, Self::Error> {
294        decode_biconomy_snapshot(&snapshot, &block)
295    }
296}