Skip to main content

tycho_common/models/
token.rs

1use std::{
2    collections::HashMap,
3    hash::{Hash, Hasher},
4    sync::Arc,
5};
6
7use deepsize::DeepSizeOf;
8use num_bigint::BigUint;
9use serde::{Deserialize, Serialize};
10
11use super::{Address, Balance};
12use crate::{dto::ResponseToken, models::Chain, traits::TokenOwnerFinding, Bytes};
13
14/// Cost related to a token transfer, for example amount of gas in evm chains.
15pub type TransferCost = u64;
16
17/// Tax related to a token transfer. Should be given in Basis Points (1/100th of a percent)
18pub type TransferTax = u64;
19
20#[derive(Debug, Clone, Deserialize, Serialize, Eq, DeepSizeOf)]
21pub struct Token {
22    pub address: Bytes,
23    pub symbol: String,
24    pub decimals: u32,
25    pub tax: TransferTax,
26    pub gas: Vec<Option<TransferCost>>,
27    pub chain: Chain,
28    /// Quality is between 0-100, where:
29    ///  - 100: Normal token
30    ///  - 75: Rebase token
31    ///  - 50: Fee token
32    ///  - 10: Token analysis failed at creation
33    ///  - 9-5: Token analysis failed on cronjob (after creation).
34    ///  - 0: Failed to extract decimals onchain
35    pub quality: u32,
36}
37
38impl Token {
39    pub fn new(
40        address: &Bytes,
41        symbol: &str,
42        decimals: u32,
43        tax: u64,
44        gas: &[Option<u64>],
45        chain: Chain,
46        quality: u32,
47    ) -> Self {
48        Self {
49            address: address.clone(),
50            symbol: symbol.to_string(),
51            decimals,
52            tax,
53            gas: gas.to_owned(),
54            chain,
55            quality,
56        }
57    }
58
59    /// One
60    /// Get one token in BigUint format
61    ///
62    /// ## Return
63    /// Returns one token as BigUint
64    pub fn one(&self) -> BigUint {
65        BigUint::from(10u32).pow(self.decimals)
66    }
67
68    pub fn gas_usage(&self) -> BigUint {
69        BigUint::from(
70            self.gas
71                .clone()
72                .into_iter()
73                .flatten()
74                .collect::<Vec<u64>>()
75                .iter()
76                .min()
77                .copied()
78                .unwrap_or(0u64),
79        )
80    }
81}
82
83impl PartialOrd for Token {
84    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
85        self.address.partial_cmp(&other.address)
86    }
87}
88
89impl PartialEq for Token {
90    fn eq(&self, other: &Self) -> bool {
91        self.address == other.address
92    }
93}
94
95impl Hash for Token {
96    fn hash<H: Hasher>(&self, state: &mut H) {
97        self.address.hash(state);
98    }
99}
100
101impl From<Arc<Token>> for Address {
102    fn from(val: Arc<Token>) -> Self {
103        val.address.clone()
104    }
105}
106
107impl From<ResponseToken> for Token {
108    fn from(value: ResponseToken) -> Self {
109        Self {
110            chain: value.chain.into(),
111            address: value.address,
112            symbol: value.symbol,
113            decimals: value.decimals,
114            tax: value.tax,
115            gas: value.gas,
116            quality: value.quality,
117        }
118    }
119}
120
121/// Represents the quality of a token.
122///
123/// * `Good`: Indicates that the token has successfully passed the analysis process.
124/// * `Bad`: Indicates that the token has failed the analysis process. In this case, a detailed
125///   reason for the failure is provided.
126///
127/// Note: Transfer taxes do not impact the token's quality.
128/// Even if a token has transfer taxes, as long as it successfully passes the analysis,
129/// it will still be marked as `Good`.
130#[derive(Debug, Clone, Eq, PartialEq)]
131pub enum TokenQuality {
132    Good,
133    Bad { reason: String },
134}
135
136impl TokenQuality {
137    pub fn is_good(&self) -> bool {
138        matches!(self, Self::Good { .. })
139    }
140
141    #[expect(
142        clippy::needless_pass_by_value,
143        reason = "public API; taking `&impl ToString` is a breaking change"
144    )]
145    pub fn bad(reason: impl ToString) -> Self {
146        Self::Bad { reason: reason.to_string() }
147    }
148}
149
150/// A store for tracking token owners and their balances.
151///
152/// The `TokenOwnerStore` maintains a mapping between token addresses and their respective
153/// owner's address and balance. It can be used to quickly retrieve token owner information
154/// without needing to query external sources.
155#[derive(Debug)]
156pub struct TokenOwnerStore {
157    /// A `HashMap` where the key is the token address and the value is a tuple containing
158    /// the owner address and the balance of the owner for the token.
159    values: HashMap<Address, (Address, Balance)>,
160}
161
162impl TokenOwnerStore {
163    pub fn new(values: HashMap<Address, (Address, Balance)>) -> Self {
164        TokenOwnerStore { values }
165    }
166}
167
168#[async_trait::async_trait]
169impl TokenOwnerFinding for TokenOwnerStore {
170    async fn find_owner(
171        &self,
172        token: Address,
173        min_balance: Balance,
174    ) -> Result<Option<(Address, Balance)>, String> {
175        Ok(self
176            .values
177            .get(&token)
178            .filter(|(_, balance)| {
179                BigUint::from_bytes_be(balance.as_ref()) >=
180                    BigUint::from_bytes_be(min_balance.as_ref())
181            })
182            .cloned())
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use std::str::FromStr;
189
190    use super::*;
191
192    #[test]
193    fn test_constructor() {
194        let token = Token::new(
195            &Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
196            "USDC",
197            6,
198            1000,
199            &[Some(1000u64)],
200            Chain::Ethereum,
201            100,
202        );
203
204        assert_eq!(token.symbol, "USDC");
205        assert_eq!(token.decimals, 6);
206        assert_eq!(
207            format!("{token_address:#x}", token_address = token.address),
208            "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
209        );
210    }
211
212    #[test]
213    fn test_cmp() {
214        let usdc = Token::new(
215            &Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
216            "USDC",
217            6,
218            1000,
219            &[Some(1000u64)],
220            Chain::Ethereum,
221            100,
222        );
223        let usdc2 = Token::new(
224            &Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
225            "USDC2",
226            6,
227            1000,
228            &[Some(1000u64)],
229            Chain::Ethereum,
230            100,
231        );
232        let weth = Token::new(
233            &Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
234            "WETH",
235            18,
236            1000,
237            &[Some(1000u64)],
238            Chain::Ethereum,
239            100,
240        );
241
242        assert!(usdc < weth);
243        assert_eq!(usdc, usdc2);
244    }
245
246    #[test]
247    fn test_one() {
248        let usdc = Token::new(
249            &Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(),
250            "USDC",
251            6,
252            1000,
253            &[Some(1000u64)],
254            Chain::Ethereum,
255            100,
256        );
257
258        assert_eq!(usdc.one(), BigUint::from(1000000u64));
259    }
260
261    #[tokio::test]
262    async fn test_find_owner_respects_min_balance() {
263        let token = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
264        let owner = Bytes::from_str("0x1111111111111111111111111111111111111111").unwrap();
265        // Owner holds 1000 (unsigned big-endian).
266        let store = TokenOwnerStore::new(HashMap::from([(
267            token.clone(),
268            (owner.clone(), Bytes::from(1_000u64)),
269        )]));
270
271        // Below the requested minimum -> no adequate owner.
272        assert_eq!(
273            store
274                .find_owner(token.clone(), Bytes::from(2_000u64))
275                .await
276                .unwrap(),
277            None
278        );
279        // Exactly at the minimum -> returned.
280        assert_eq!(
281            store
282                .find_owner(token.clone(), Bytes::from(1_000u64))
283                .await
284                .unwrap(),
285            Some((owner.clone(), Bytes::from(1_000u64)))
286        );
287        // Above the minimum -> returned.
288        assert_eq!(
289            store
290                .find_owner(token.clone(), Bytes::from(500u64))
291                .await
292                .unwrap(),
293            Some((owner, Bytes::from(1_000u64)))
294        );
295        // Unknown token -> None.
296        let other = Bytes::from_str("0x2222222222222222222222222222222222222222").unwrap();
297        assert_eq!(
298            store
299                .find_owner(other, Bytes::from(1u64))
300                .await
301                .unwrap(),
302            None
303        );
304    }
305}