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(|e| InvalidSnapshotError::ValueError(format!("invalid address `{value}`: {e}")))?;
74    raw.as_slice()
75        .try_into()
76        .map_err(|_not_20_bytes| {
77            InvalidSnapshotError::ValueError(format!("address `{value}` is not 20 bytes"))
78        })
79}
80
81fn word(value: &Bytes) -> Result<U256, InvalidSnapshotError> {
82    if value.len() > 32 {
83        return Err(InvalidSnapshotError::ValueError(format!(
84            "value of {} bytes does not fit a storage word",
85            value.len()
86        )));
87    }
88    Ok(U256::from_be_slice(value.as_ref()))
89}
90
91fn word_address(word: U256) -> Address {
92    word.to_be_bytes::<32>()[12..]
93        .try_into()
94        .expect("20 bytes")
95}
96
97/// A provider config: kind byte, then the vault for a vault provider.
98fn decode_provider(value: &Bytes) -> Result<ProviderConfig, InvalidSnapshotError> {
99    if value.len() != 21 {
100        return Err(InvalidSnapshotError::ValueError(format!(
101            "provider config of {} bytes",
102            value.len()
103        )));
104    }
105    let address = |range: std::ops::Range<usize>| -> Address {
106        value[range]
107            .try_into()
108            .expect("20 bytes")
109    };
110    let kind = match value[0] {
111        0 => ProviderKind::Balance,
112        1 => ProviderKind::Vault(address(1..21)),
113        2 => ProviderKind::Unbounded,
114        other => {
115            return Err(InvalidSnapshotError::ValueError(format!("provider kind {other}")));
116        }
117    };
118    Ok(ProviderConfig { kind })
119}
120
121pub enum AttributeChange<'a> {
122    Set(&'a String, &'a Bytes),
123    Delete(&'a String),
124}
125
126/// Applies attribute writes and deletions to `state`; a deleted value reads as zero, as unset
127/// storage does. Unknown attributes are ignored.
128pub fn apply_attributes<'a>(
129    state: &mut BiconomyState,
130    changes: impl IntoIterator<Item = AttributeChange<'a>>,
131) -> Result<(), InvalidSnapshotError> {
132    for change in changes {
133        let (name, value) = match change {
134            AttributeChange::Set(name, value) => (name, value.clone()),
135            AttributeChange::Delete(name) => (name, Bytes::new()),
136        };
137        let parts: Vec<&str> = name.split('/').collect();
138        match parts.as_slice() {
139            [attrs::FEE_BPS] => {
140                // feeBps is the low 16 bits of the venue's first slot.
141                state.fee_bps = (word(&value)? & U256::from(u16::MAX)).to::<u16>();
142            }
143            [attrs::MAKER_COUNT] => {
144                let count = word(&value)?;
145                state.maker_count = u64::try_from(count).map_err(|_out_of_range| {
146                    InvalidSnapshotError::ValueError(format!("maker_count {count}"))
147                })?;
148            }
149            [attrs::MAKER, index] => {
150                let index: u8 = index.parse().map_err(|e| {
151                    InvalidSnapshotError::ValueError(format!(
152                        "invalid maker index in `{name}`: {e}"
153                    ))
154                })?;
155                state
156                    .maker_slots
157                    .insert(index, word_address(word(&value)?));
158            }
159            [attrs::BOARD, mm, token_in, token_out, slot] => {
160                let slot: u8 = slot
161                    .parse()
162                    .ok()
163                    .filter(|slot| *slot < BOARD_WORDS)
164                    .ok_or_else(|| {
165                        InvalidSnapshotError::ValueError(format!("invalid board slot in `{name}`"))
166                    })?;
167                let key = board_key(
168                    &parse_address(mm)?,
169                    &parse_address(token_in)?,
170                    &parse_address(token_out)?,
171                );
172                let words = state.boards.entry(key).or_default();
173                let value = word(&value)?;
174                if value.is_zero() {
175                    words.remove(&slot);
176                } else {
177                    words.insert(slot, value);
178                }
179            }
180            [attrs::ANCHOR, mm, token0, token1] => {
181                let key = board_key(
182                    &parse_address(mm)?,
183                    &parse_address(token0)?,
184                    &parse_address(token1)?,
185                );
186                state.anchors.insert(key, word(&value)?);
187            }
188            [attrs::PAUSED, mm] => {
189                let mm = parse_address(mm)?;
190                if word(&value)?.is_zero() {
191                    state.paused.remove(&mm);
192                } else {
193                    state.paused.insert(mm);
194                }
195            }
196            [attrs::PROVIDER, provider] => {
197                let provider = parse_address(provider)?;
198                if value.is_empty() {
199                    state
200                        .providers
201                        .remove(&hex_address(&provider));
202                } else {
203                    state
204                        .providers
205                        .insert(hex_address(&provider), decode_provider(&value)?);
206                }
207            }
208            [attrs::SIGNER, provider] => {
209                let key = hex_address(&parse_address(provider)?);
210                state
211                    .signers
212                    .insert(key, word_address(word(&value)?));
213            }
214            [attrs::APPROVED_EXECUTOR, provider] => {
215                let key = hex_address(&parse_address(provider)?);
216                state
217                    .approved_executors
218                    .insert(key, word_address(word(&value)?));
219            }
220            [attrs::ROUTER_COUNT, vault] => {
221                let key = hex_address(&parse_address(vault)?);
222                state
223                    .router_counts
224                    .insert(key, word(&value)?);
225            }
226            [attrs::ROUTER, vault] => {
227                let key = hex_address(&parse_address(vault)?);
228                state
229                    .routers
230                    .insert(key, word_address(word(&value)?));
231            }
232            [attrs::BALANCE, token, holder] => {
233                let key = pair_key(&parse_address(token)?, &parse_address(holder)?);
234                state
235                    .balances
236                    .insert(key, word(&value)?);
237            }
238            [attrs::ALLOWANCE, token, owner, spender] => {
239                let key = allowance_key(
240                    &parse_address(token)?,
241                    &parse_address(owner)?,
242                    &parse_address(spender)?,
243                );
244                state
245                    .allowances
246                    .insert(key, word(&value)?);
247            }
248            _ => {}
249        }
250    }
251    Ok(())
252}
253
254pub fn decode_biconomy_snapshot(
255    snapshot: &ComponentWithState,
256    header: &BlockHeader,
257) -> Result<BiconomyState, InvalidSnapshotError> {
258    let static_address = |name: &str| -> Result<Address, InvalidSnapshotError> {
259        let value = snapshot
260            .component
261            .static_attributes
262            .get(name)
263            .ok_or_else(|| InvalidSnapshotError::MissingAttribute(name.to_owned()))?;
264        value
265            .as_ref()
266            .try_into()
267            .map_err(|_wrong_length| {
268                InvalidSnapshotError::ValueError(format!("invalid {name} {value}"))
269            })
270    };
271    let mut state = BiconomyState {
272        venue: static_address(attrs::PAMM_ADDRESS)?,
273        executor: static_address(attrs::EXECUTOR)?,
274        // As of the header; the stream decoder moves it to the execution block via
275        // `apply_block`, with the chain's block time and its flashblock handling.
276        block: BlockEnvState { number: header.number, timestamp: header.timestamp },
277        ..Default::default()
278    };
279    apply_attributes(
280        &mut state,
281        snapshot
282            .state
283            .attributes
284            .iter()
285            .map(|(name, value)| AttributeChange::Set(name, value)),
286    )?;
287    Ok(state)
288}
289
290impl TryFromWithBlock<ComponentWithState, BlockHeader> for BiconomyState {
291    type Error = InvalidSnapshotError;
292
293    async fn try_from_with_header(
294        snapshot: ComponentWithState,
295        block: BlockHeader,
296        _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
297        _all_tokens: &HashMap<Bytes, Token>,
298        _decoder_context: &DecoderContext,
299    ) -> Result<Self, Self::Error> {
300        decode_biconomy_snapshot(&snapshot, &block)
301    }
302}