Skip to main content

nautilus_model/defi/
wallet.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::{collections::HashSet, fmt::Display};
17
18use alloy_primitives::{Address, U256};
19
20use crate::{
21    defi::{Token, currency::TokenCurrency},
22    types::{AccountBalance, Money, Quantity},
23};
24
25/// Represents the balance of a specific ERC-20 token held in a wallet.
26///
27/// This struct tracks the raw token amount along with optional USD valuation
28/// and the token metadata.
29#[derive(Debug)]
30pub struct TokenBalance {
31    /// The raw token amount as a 256-bit unsigned integer.
32    pub amount: U256,
33    /// The optional USD equivalent value of the token balance.
34    pub amount_usd: Option<Quantity>,
35    /// The token metadata including chain, address, name, symbol, and decimals.
36    pub token: Token,
37}
38
39impl TokenBalance {
40    /// Creates a new [`TokenBalance`] instance.
41    #[must_use]
42    pub const fn new(amount: U256, token: Token) -> Self {
43        Self {
44            amount,
45            token,
46            amount_usd: None,
47        }
48    }
49
50    /// Converts the raw token amount to a human-readable [`Quantity`].
51    ///
52    /// # Errors
53    ///
54    /// Returns an error if the U256 amount cannot be converted to a `Quantity`.
55    pub fn as_quantity(&self) -> anyhow::Result<Quantity> {
56        Quantity::from_u256(self.amount, self.token.decimals).map_err(Into::into)
57    }
58
59    fn as_money(&self) -> anyhow::Result<Money> {
60        let currency = self.token.currency()?;
61        Money::from_u256(self.amount, currency).map_err(Into::into)
62    }
63
64    /// Sets the USD equivalent value for this token balance.
65    pub fn set_amount_usd(&mut self, amount_usd: Quantity) {
66        self.amount_usd = Some(amount_usd);
67    }
68}
69
70impl Display for TokenBalance {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        let quantity = self.as_quantity().unwrap_or_default();
73        let label = TokenCurrency::from(&self.token).code();
74
75        match &self.amount_usd {
76            Some(usd) => write!(
77                f,
78                "TokenBalance(token={}, amount={}, usd=${:.2})",
79                label,
80                quantity.as_decimal(),
81                usd.as_f64()
82            ),
83            None => write!(
84                f,
85                "TokenBalance(token={}, amount={})",
86                label,
87                quantity.as_decimal()
88            ),
89        }
90    }
91}
92
93/// Represents the complete balance state of a blockchain wallet.
94///
95/// Tracks both the native currency balance (e.g., ETH, ARB) and ERC-20 token
96/// balances for a wallet address. The `token_universe` defines which tokens
97/// should be tracked for balance fetching.
98#[derive(Debug)]
99pub struct WalletBalance {
100    /// The balance of the chain's native currency
101    pub native_currency: Option<Money>,
102    /// Collection of ERC-20 token balances held in the wallet.
103    pub token_balances: Vec<TokenBalance>,
104    /// Set of token addresses to track for balance updates.
105    pub token_universe: HashSet<Address>,
106}
107
108impl WalletBalance {
109    /// Creates a new [`WalletBalance`] with the specified token universe.
110    #[must_use]
111    pub const fn new(token_universe: HashSet<Address>) -> Self {
112        Self {
113            native_currency: None,
114            token_balances: vec![],
115            token_universe,
116        }
117    }
118
119    /// Returns `true` if the token universe has been initialized with token addresses.
120    #[must_use]
121    pub fn is_token_universe_initialized(&self) -> bool {
122        !self.token_universe.is_empty()
123    }
124
125    /// Sets the native currency balance for the wallet.
126    pub fn set_native_currency_balance(&mut self, balance: Money) {
127        self.native_currency = Some(balance);
128    }
129
130    /// Adds an ERC-20 token balance to the wallet.
131    pub fn add_token_balance(&mut self, token_balance: TokenBalance) {
132        self.token_balances.push(token_balance);
133    }
134
135    /// Replaces the complete native and token balance snapshot.
136    ///
137    /// # Errors
138    ///
139    /// Returns an error if the token balances do not exactly match the configured universe,
140    /// contain duplicate currencies, or cannot be represented as account balances. The existing
141    /// snapshot remains unchanged on error.
142    pub fn replace_balances(
143        &mut self,
144        native_currency: Money,
145        mut token_balances: Vec<TokenBalance>,
146    ) -> anyhow::Result<Vec<AccountBalance>> {
147        token_balances.sort_unstable_by_key(|balance| balance.token.address);
148        let replacement = Self {
149            native_currency: Some(native_currency),
150            token_balances,
151            token_universe: self.token_universe.clone(),
152        };
153        let balances = replacement.account_balances(replacement.token_balances.iter())?;
154        *self = replacement;
155        Ok(balances)
156    }
157
158    /// Returns the complete wallet snapshot as account balances.
159    ///
160    /// # Errors
161    ///
162    /// Returns an error if the snapshot is incomplete, contains duplicate currencies, or a token
163    /// amount cannot be represented as money.
164    pub fn as_account_balances(&self) -> anyhow::Result<Vec<AccountBalance>> {
165        let mut token_balances = self.token_balances.iter().collect::<Vec<_>>();
166        token_balances.sort_unstable_by_key(|balance| balance.token.address);
167        self.account_balances(token_balances)
168    }
169
170    fn account_balances<'a>(
171        &'a self,
172        token_balances: impl IntoIterator<Item = &'a TokenBalance>,
173    ) -> anyhow::Result<Vec<AccountBalance>> {
174        self.validate_token_addresses()?;
175
176        let native_currency = self
177            .native_currency
178            .ok_or_else(|| anyhow::anyhow!("Wallet balance snapshot has no native currency"))?;
179        let mut symbols = HashSet::new();
180        symbols.insert(native_currency.currency.code.as_str());
181
182        let mut balances = Vec::with_capacity(self.token_balances.len() + 1);
183        balances.push(AccountBalance::new_checked(
184            native_currency,
185            Money::zero(native_currency.currency),
186            native_currency,
187        )?);
188
189        for token_balance in token_balances {
190            if !symbols.insert(token_balance.token.symbol.as_str()) {
191                anyhow::bail!(
192                    "Wallet balance snapshot contains duplicate currency {}",
193                    token_balance.token.symbol,
194                );
195            }
196
197            let total = token_balance.as_money()?;
198            balances.push(AccountBalance::new_checked(
199                total,
200                Money::zero(total.currency),
201                total,
202            )?);
203        }
204
205        Ok(balances)
206    }
207
208    fn validate_token_addresses(&self) -> anyhow::Result<()> {
209        let mut token_addresses = HashSet::with_capacity(self.token_balances.len());
210        let mut duplicates = Vec::new();
211
212        for balance in &self.token_balances {
213            if !token_addresses.insert(balance.token.address) {
214                duplicates.push(balance.token.address);
215            }
216        }
217
218        if !duplicates.is_empty() {
219            duplicates.sort_unstable();
220            duplicates.dedup();
221            anyhow::bail!(
222                "Wallet balance snapshot contains duplicate token addresses: {}",
223                format_addresses(&duplicates)
224            );
225        }
226
227        let mut missing = self
228            .token_universe
229            .difference(&token_addresses)
230            .copied()
231            .collect::<Vec<_>>();
232        let mut unexpected = token_addresses
233            .difference(&self.token_universe)
234            .copied()
235            .collect::<Vec<_>>();
236        missing.sort_unstable();
237        unexpected.sort_unstable();
238
239        match (missing.is_empty(), unexpected.is_empty()) {
240            (false, false) => anyhow::bail!(
241                "Wallet balance snapshot is missing configured token addresses: {}; contains unexpected token addresses: {}",
242                format_addresses(&missing),
243                format_addresses(&unexpected)
244            ),
245            (false, true) => anyhow::bail!(
246                "Wallet balance snapshot is missing configured token addresses: {}",
247                format_addresses(&missing)
248            ),
249            (true, false) => anyhow::bail!(
250                "Wallet balance snapshot contains unexpected token addresses: {}",
251                format_addresses(&unexpected)
252            ),
253            (true, true) => Ok(()),
254        }
255    }
256}
257
258fn format_addresses(addresses: &[Address]) -> String {
259    addresses
260        .iter()
261        .map(ToString::to_string)
262        .collect::<Vec<_>>()
263        .join(", ")
264}
265
266#[cfg(test)]
267mod tests {
268    use std::sync::Arc;
269
270    use alloy_primitives::{U256, address};
271    use rstest::rstest;
272
273    use super::*;
274    use crate::defi::{
275        SharedChain, Token,
276        chain::chains,
277        stubs::{arbitrum, usdc, weth},
278    };
279
280    fn create_token(symbol: &str, decimals: u8) -> Token {
281        Token::new(
282            Arc::new(chains::ETHEREUM.clone()),
283            address!("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
284            format!("{symbol} Token"),
285            symbol.to_string(),
286            decimals,
287        )
288    }
289
290    #[rstest]
291    fn test_token_balance_as_quantity_18_decimals(#[from(arbitrum)] chain: SharedChain) {
292        // Test case: NU token with 18 decimals
293        // Raw amount: 10342000000000000000000 (10342 * 10^18)
294        // Expected: 10342.000000000000000000
295        let token = Token::new(
296            chain,
297            address!("0x4fE83213D56308330EC302a8BD641f1d0113A4Cc"),
298            "NuCypher".to_string(),
299            "NU".to_string(),
300            18,
301        );
302        let amount = U256::from(10342u64) * U256::from(10u64).pow(U256::from(18u64));
303        let balance = TokenBalance::new(amount, token);
304
305        let quantity = balance.as_quantity().unwrap();
306        assert_eq!(
307            quantity.as_decimal().to_string(),
308            "10342.000000000000000000"
309        );
310    }
311
312    #[rstest]
313    fn test_token_balance_as_quantity_6_decimals() {
314        // Test case: USDC with 6 decimals
315        // Raw amount: 92220728254 (92220.728254 * 10^6)
316        // Expected: 92220.728254
317        let token = create_token("USDC", 6);
318        let amount = U256::from(92_220_728_254_u64);
319        let balance = TokenBalance::new(amount, token);
320
321        let quantity = balance.as_quantity().unwrap();
322        assert_eq!(quantity.as_decimal().to_string(), "92220.728254");
323    }
324
325    #[rstest]
326    fn test_token_balance_as_quantity_fractional_18_decimals(#[from(arbitrum)] chain: SharedChain) {
327        // Test case: mETH with 18 decimals and fractional amount
328        // Raw amount: 758325512078001391
329        // Expected: 0.758325512078001391
330        let token = Token::new(
331            chain,
332            address!("0xd5F7838F5C461fefF7FE49ea5ebaF7728bB0ADfa"),
333            "mETH".to_string(),
334            "mETH".to_string(),
335            18,
336        );
337        let amount = U256::from(758_325_512_078_001_391_u64);
338        let balance = TokenBalance::new(amount, token);
339
340        let quantity = balance.as_quantity().unwrap();
341        assert_eq!(quantity.as_decimal().to_string(), "0.758325512078001391");
342    }
343
344    #[rstest]
345    fn test_token_balance_display_18_decimals(#[from(arbitrum)] chain: SharedChain) {
346        // Test Display implementation with 18 decimal token
347        let token = Token::new(
348            chain,
349            address!("0x912CE59144191C1204E64559FE8253a0e49E6548"),
350            "Arbitrum".to_string(),
351            "ARB".to_string(),
352            18,
353        );
354        // 7922.013795343949480329 ARB
355        let amount = U256::from_str_radix("7922013795343949480329", 10).unwrap();
356        let balance = TokenBalance::new(amount, token);
357
358        let display = balance.to_string();
359        assert!(display.contains("ARB"));
360        assert!(display.contains("7922.013795343949480329"));
361    }
362
363    #[rstest]
364    fn test_token_balance_display_6_decimals() {
365        // Test Display implementation with 6 decimal token (USDC)
366        let token = create_token("USDC", 6);
367        let amount = U256::from(92_220_728_254_u64); // 92220.728254 USDC
368        let balance = TokenBalance::new(amount, token);
369
370        let display = balance.to_string();
371        assert!(display.contains("USDC"));
372        assert!(display.contains("92220.728254"));
373    }
374
375    #[rstest]
376    fn test_token_balance_set_amount_usd(weth: Token) {
377        let amount = U256::from(1u64) * U256::from(10u64).pow(U256::from(18u64));
378        let mut balance = TokenBalance::new(amount, weth);
379
380        assert!(balance.amount_usd.is_none());
381
382        let usd_value = Quantity::from("3500.00");
383        balance.set_amount_usd(usd_value);
384
385        assert!(balance.amount_usd.is_some());
386        assert_eq!(
387            balance.amount_usd.unwrap().as_decimal().to_string(),
388            "3500.00"
389        );
390    }
391
392    #[rstest]
393    fn test_wallet_balance_new_empty() {
394        let wallet = WalletBalance::new(HashSet::new());
395
396        assert!(wallet.native_currency.is_none());
397        assert!(wallet.token_balances.is_empty());
398        assert!(!wallet.is_token_universe_initialized());
399    }
400
401    #[rstest]
402    fn test_wallet_balance_with_token_universe() {
403        let mut tokens = HashSet::new();
404        tokens.insert(address!("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")); // USDC
405        tokens.insert(address!("0x912CE59144191C1204E64559FE8253a0e49E6548")); // ARB
406
407        let wallet = WalletBalance::new(tokens);
408
409        assert!(wallet.is_token_universe_initialized());
410        assert_eq!(wallet.token_universe.len(), 2);
411    }
412
413    #[rstest]
414    fn test_wallet_balance_set_native_currency() {
415        let mut wallet = WalletBalance::new(HashSet::new());
416
417        assert!(wallet.native_currency.is_none());
418
419        let eth_balance = Money::new(50.936_054, crate::types::Currency::ETH());
420        wallet.set_native_currency_balance(eth_balance);
421
422        assert!(wallet.native_currency.is_some());
423    }
424
425    #[rstest]
426    fn test_wallet_balance_add_token_balance(usdc: Token, weth: Token) {
427        let mut wallet = WalletBalance::new(HashSet::new());
428
429        let usdc_balance = TokenBalance::new(U256::from(100_000_000u64), usdc); // 100 USDC
430        let weth_balance = TokenBalance::new(U256::from(10u64).pow(U256::from(18u64)), weth); // 1 WETH
431
432        wallet.add_token_balance(usdc_balance);
433        wallet.add_token_balance(weth_balance);
434
435        assert_eq!(wallet.token_balances.len(), 2);
436        assert_eq!(wallet.token_balances[0].token.symbol, "USDC");
437        assert_eq!(wallet.token_balances[1].token.symbol, "WETH");
438    }
439
440    #[rstest]
441    fn test_replace_balances_retains_snapshot_on_conversion_failure(weth: Token) {
442        let mut wallet = WalletBalance::new(HashSet::from([weth.address]));
443        let native_currency = weth.chain.native_currency();
444        let native = Money::from_wei(U256::from(1_000_000_000_000_000_000_u64), native_currency);
445        let token = TokenBalance::new(U256::from(2_000_000_000_000_000_000_u64), weth.clone());
446        wallet.replace_balances(native, vec![token]).unwrap();
447
448        let error = wallet
449            .replace_balances(
450                Money::from_wei(U256::from(3_000_000_000_000_000_000_u64), native_currency),
451                vec![TokenBalance::new(U256::MAX, weth)],
452            )
453            .unwrap_err();
454
455        assert!(
456            error.to_string().contains("exceeds QuantityRaw range"),
457            "was: {error}"
458        );
459        assert_eq!(wallet.native_currency.unwrap(), native);
460        assert_eq!(wallet.token_balances.len(), 1);
461        assert_eq!(
462            wallet.token_balances[0].amount,
463            U256::from(2_000_000_000_000_000_000_u64)
464        );
465    }
466
467    #[rstest]
468    fn test_account_balances_reports_missing_token_address(usdc: Token, weth: Token) {
469        let missing = weth.address;
470        let wallet = WalletBalance {
471            native_currency: None,
472            token_balances: vec![TokenBalance::new(U256::from(1_u64), usdc.clone())],
473            token_universe: HashSet::from([usdc.address, missing]),
474        };
475
476        let error = wallet.as_account_balances().unwrap_err();
477
478        assert_eq!(
479            error.to_string(),
480            format!("Wallet balance snapshot is missing configured token addresses: {missing}")
481        );
482    }
483
484    #[rstest]
485    fn test_account_balances_reports_unexpected_token_address(usdc: Token, weth: Token) {
486        let unexpected = weth.address;
487        let wallet = WalletBalance {
488            native_currency: None,
489            token_balances: vec![
490                TokenBalance::new(U256::from(1_u64), usdc.clone()),
491                TokenBalance::new(U256::from(2_u64), weth),
492            ],
493            token_universe: HashSet::from([usdc.address]),
494        };
495
496        let error = wallet.as_account_balances().unwrap_err();
497
498        assert_eq!(
499            error.to_string(),
500            format!("Wallet balance snapshot contains unexpected token addresses: {unexpected}")
501        );
502    }
503
504    #[rstest]
505    fn test_account_balances_reports_missing_and_unexpected_token_addresses(
506        usdc: Token,
507        weth: Token,
508    ) {
509        let missing = usdc.address;
510        let unexpected = weth.address;
511        let wallet = WalletBalance {
512            native_currency: None,
513            token_balances: vec![TokenBalance::new(U256::from(1_u64), weth)],
514            token_universe: HashSet::from([missing]),
515        };
516
517        let error = wallet.as_account_balances().unwrap_err();
518
519        assert_eq!(
520            error.to_string(),
521            format!(
522                "Wallet balance snapshot is missing configured token addresses: {missing}; contains unexpected token addresses: {unexpected}"
523            )
524        );
525    }
526
527    #[rstest]
528    fn test_account_balances_reports_duplicate_before_set_differences(usdc: Token, weth: Token) {
529        let duplicate = usdc.address;
530        let wallet = WalletBalance {
531            native_currency: None,
532            token_balances: vec![
533                TokenBalance::new(U256::from(1_u64), usdc.clone()),
534                TokenBalance::new(U256::from(2_u64), usdc),
535            ],
536            token_universe: HashSet::from([weth.address]),
537        };
538
539        let error = wallet.as_account_balances().unwrap_err();
540
541        assert_eq!(
542            error.to_string(),
543            format!("Wallet balance snapshot contains duplicate token addresses: {duplicate}")
544        );
545    }
546
547    #[rstest]
548    fn test_replace_balances_rejects_duplicate_currency_symbols(
549        usdc: Token,
550        #[from(arbitrum)] chain: SharedChain,
551    ) {
552        let duplicate = Token::new(
553            chain,
554            address!("0x0000000000000000000000000000000000000001"),
555            "Other USD Coin".to_string(),
556            "USDC".to_string(),
557            18,
558        );
559        let mut wallet = WalletBalance::new(HashSet::from([usdc.address, duplicate.address]));
560
561        let error = wallet
562            .replace_balances(
563                Money::from_wei(
564                    U256::from(1_000_000_000_000_000_000_u64),
565                    usdc.chain.native_currency(),
566                ),
567                vec![
568                    TokenBalance::new(U256::from(1_u64), usdc),
569                    TokenBalance::new(U256::from(2_u64), duplicate),
570                ],
571            )
572            .unwrap_err();
573
574        assert_eq!(
575            error.to_string(),
576            "Wallet balance snapshot contains duplicate currency USDC"
577        );
578        assert!(wallet.native_currency.is_none());
579        assert!(wallet.token_balances.is_empty());
580    }
581}