Skip to main content

tycho_simulation/evm/protocol/curve/
policy.rs

1//! The policy contract of a Twocrypto pool, as the indexer reports it in state attributes.
2use std::collections::HashMap;
3
4use alloy::primitives::U256;
5use serde::{Deserialize, Serialize};
6use thiserror::Error;
7use tycho_common::Bytes;
8
9/// Name of the state attribute that holds the pool's policy contract.
10pub const POLICY_ATTRIBUTE: &str = "policy";
11/// Name of the state attribute that holds the version of the policy's grant rules.
12pub const POLICY_VERSION_ATTRIBUTE: &str = "policy_version";
13/// Name of the state attribute that holds the key that signs the policy's grants.
14pub const POLICY_CONTROLLER_ATTRIBUTE: &str = "policy_controller";
15/// Name of the state attribute that holds the only caller that can submit a grant.
16pub const POLICY_ROUTER_ATTRIBUTE: &str = "policy_router";
17/// Name of the state attribute that is `1` while the policy refuses grants.
18pub const POLICY_KILLED_ATTRIBUTE: &str = "policy_killed";
19/// Name of the state attribute that holds the lowest fee of a granted swap, in units of 1e-10.
20pub const POLICY_MIN_FEE_ATTRIBUTE: &str = "policy_min_fee";
21
22/// A policy attribute whose value is malformed.
23#[derive(Debug, Error)]
24#[error("curve `{name}` attribute is {value}, expected {expected}")]
25pub struct PolicyDecodeError {
26    name: String,
27    value: Bytes,
28    expected: &'static str,
29}
30
31impl PolicyDecodeError {
32    fn new(name: &str, value: &Bytes, expected: &'static str) -> Self {
33        Self { name: name.to_string(), value: value.clone(), expected }
34    }
35}
36
37/// The policy contract of a pool and the terms of its grants. A zero attribute value means unset:
38/// a pool without a grant policy has version 0.
39#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct CurvePolicy {
41    address: Option<Bytes>,
42    version: U256,
43    controller: Option<Bytes>,
44    router: Option<Bytes>,
45    is_killed: bool,
46    min_fee: U256,
47}
48
49impl CurvePolicy {
50    /// Decodes the policy from a pool's state attributes. Absent attributes stay unset.
51    pub fn from_attributes(attributes: &HashMap<String, Bytes>) -> Result<Self, PolicyDecodeError> {
52        let mut policy = Self::default();
53        for (name, value) in attributes {
54            policy.update(name, value)?;
55        }
56        Ok(policy)
57    }
58
59    /// Sets the value of a policy attribute. Ignores other attributes.
60    pub fn update(&mut self, name: &str, value: &Bytes) -> Result<(), PolicyDecodeError> {
61        match name {
62            POLICY_ATTRIBUTE => self.address = decode_address(name, value)?,
63            POLICY_VERSION_ATTRIBUTE => self.version = decode_uint(name, value)?,
64            POLICY_CONTROLLER_ATTRIBUTE => self.controller = decode_address(name, value)?,
65            POLICY_ROUTER_ATTRIBUTE => self.router = decode_address(name, value)?,
66            POLICY_KILLED_ATTRIBUTE => self.is_killed = !decode_uint(name, value)?.is_zero(),
67            POLICY_MIN_FEE_ATTRIBUTE => self.min_fee = decode_uint(name, value)?,
68            _ => {}
69        }
70        Ok(())
71    }
72
73    /// Unsets a deleted policy attribute. Ignores other attributes.
74    pub fn delete(&mut self, name: &str) {
75        match name {
76            POLICY_ATTRIBUTE => self.address = None,
77            POLICY_VERSION_ATTRIBUTE => self.version = U256::ZERO,
78            POLICY_CONTROLLER_ATTRIBUTE => self.controller = None,
79            POLICY_ROUTER_ATTRIBUTE => self.router = None,
80            POLICY_KILLED_ATTRIBUTE => self.is_killed = false,
81            POLICY_MIN_FEE_ATTRIBUTE => self.min_fee = U256::ZERO,
82            _ => {}
83        }
84    }
85
86    /// The policy contract. `None` if the pool has no policy.
87    pub fn address(&self) -> Option<&Bytes> {
88        self.address.as_ref()
89    }
90
91    /// The version of the grant rules. 0 if the policy has no grants.
92    pub fn version(&self) -> U256 {
93        self.version
94    }
95
96    /// The key that signs the policy's grants. `None` if unset.
97    pub fn controller(&self) -> Option<&Bytes> {
98        self.controller.as_ref()
99    }
100
101    /// The only caller that can submit a grant. `None` if unset.
102    pub fn router(&self) -> Option<&Bytes> {
103        self.router.as_ref()
104    }
105
106    /// Whether the policy refuses grants.
107    pub fn is_killed(&self) -> bool {
108        self.is_killed
109    }
110
111    /// The lowest fee of a granted swap, in units of 1e-10.
112    pub fn min_fee(&self) -> U256 {
113        self.min_fee
114    }
115}
116
117/// Decodes an address attribute. The zero address means unset.
118fn decode_address(name: &str, value: &Bytes) -> Result<Option<Bytes>, PolicyDecodeError> {
119    if value.len() != 20 {
120        return Err(PolicyDecodeError::new(name, value, "a 20-byte address"));
121    }
122    if value.iter().all(|byte| *byte == 0) {
123        return Ok(None);
124    }
125    Ok(Some(value.clone()))
126}
127
128/// Decodes a big-endian unsigned integer attribute.
129fn decode_uint(name: &str, value: &Bytes) -> Result<U256, PolicyDecodeError> {
130    U256::try_from_be_slice(value)
131        .ok_or_else(|| PolicyDecodeError::new(name, value, "at most 32 bytes"))
132}
133
134#[cfg(test)]
135mod tests {
136    use rstest::rstest;
137
138    use super::*;
139
140    fn attributes(entries: &[(&str, Vec<u8>)]) -> HashMap<String, Bytes> {
141        entries
142            .iter()
143            .map(|(name, value)| (name.to_string(), Bytes::from(value.clone())))
144            .collect()
145    }
146
147    #[test]
148    fn test_from_attributes() {
149        let policy = CurvePolicy::from_attributes(&attributes(&[
150            (POLICY_ATTRIBUTE, vec![1; 20]),
151            (POLICY_VERSION_ATTRIBUTE, vec![1]),
152            (POLICY_CONTROLLER_ATTRIBUTE, vec![2; 20]),
153            (POLICY_ROUTER_ATTRIBUTE, vec![3; 20]),
154            (POLICY_KILLED_ATTRIBUTE, vec![1]),
155            (POLICY_MIN_FEE_ATTRIBUTE, vec![0x01, 0x86, 0xa0]),
156            ("balances", vec![9; 64]),
157        ]))
158        .expect("decode");
159
160        let expected = CurvePolicy {
161            address: Some(Bytes::from(vec![1; 20])),
162            version: U256::from(1),
163            controller: Some(Bytes::from(vec![2; 20])),
164            router: Some(Bytes::from(vec![3; 20])),
165            is_killed: true,
166            min_fee: U256::from(100_000),
167        };
168        assert_eq!(policy, expected);
169    }
170
171    #[test]
172    fn test_from_attributes_zero_values() {
173        let policy = CurvePolicy::from_attributes(&attributes(&[
174            (POLICY_ATTRIBUTE, vec![0; 20]),
175            (POLICY_VERSION_ATTRIBUTE, vec![0]),
176            (POLICY_CONTROLLER_ATTRIBUTE, vec![0; 20]),
177            (POLICY_ROUTER_ATTRIBUTE, vec![0; 20]),
178            (POLICY_KILLED_ATTRIBUTE, vec![0]),
179            (POLICY_MIN_FEE_ATTRIBUTE, vec![]),
180        ]))
181        .expect("decode");
182
183        assert_eq!(policy, CurvePolicy::default());
184    }
185
186    #[rstest]
187    #[case::short_address(POLICY_ATTRIBUTE, vec![7; 19])]
188    #[case::empty_address(POLICY_CONTROLLER_ATTRIBUTE, vec![])]
189    #[case::wide_uint(POLICY_MIN_FEE_ATTRIBUTE, vec![1; 33])]
190    fn test_update_malformed_value(#[case] name: &str, #[case] value: Vec<u8>) {
191        let mut policy = CurvePolicy::default();
192
193        assert!(policy
194            .update(name, &Bytes::from(value))
195            .is_err());
196    }
197
198    #[test]
199    fn test_delete() {
200        let mut policy = CurvePolicy::from_attributes(&attributes(&[
201            (POLICY_ATTRIBUTE, vec![1; 20]),
202            (POLICY_MIN_FEE_ATTRIBUTE, vec![5]),
203        ]))
204        .expect("decode");
205
206        policy.delete(POLICY_ATTRIBUTE);
207        policy.delete(POLICY_MIN_FEE_ATTRIBUTE);
208
209        assert_eq!(policy, CurvePolicy::default());
210    }
211}