o2-tools 0.3.21-rc

Reusable tooling for trade account and order book contract interactions on Fuel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
use fuel_core_types::{
    fuel_tx::UtxoId,
    fuel_types::{
        Address,
        AssetId,
    },
};
use fuels::types::{
    coin::Coin,
    coin_type::CoinType,
    input::Input,
};
use std::{
    collections::{
        BTreeSet,
        HashMap,
        HashSet,
        hash_map::Entry,
    },
    sync::Arc,
};

pub struct CoinsResult {
    pub known_coins: Vec<FuelTxCoin>,
    pub unknown_coins: HashSet<UtxoId>,
}

/// Order in which the per-account UTXO set is walked when selecting coins.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum SelectionOrder {
    /// Oldest insertion first — drains old, untouched UTXOs before new change.
    Fifo,
    /// Largest amount first — fewest, most valuable coins.
    Largest,
}

#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct FuelTxCoin {
    pub amount: u64,
    pub asset_id: AssetId,
    pub utxo_id: UtxoId,
    pub owner: Address,
}

impl From<Coin> for FuelTxCoin {
    fn from(value: Coin) -> Self {
        Self {
            amount: value.amount,
            asset_id: value.asset_id,
            utxo_id: value.utxo_id,
            owner: value.owner,
        }
    }
}

impl From<FuelTxCoin> for Coin {
    fn from(value: FuelTxCoin) -> Self {
        Self {
            amount: value.amount,
            asset_id: value.asset_id,
            utxo_id: value.utxo_id,
            owner: value.owner,
        }
    }
}

impl TryFrom<&fuel_core_types::fuel_tx::Input> for FuelTxCoin {
    type Error = anyhow::Error;

    fn try_from(input: &fuel_core_types::fuel_tx::Input) -> Result<Self, Self::Error> {
        if let fuel_core_types::fuel_tx::Input::CoinSigned(coin) = input {
            return Ok(FuelTxCoin {
                utxo_id: coin.utxo_id,
                owner: coin.owner,
                amount: coin.amount,
                asset_id: coin.asset_id,
            });
        }
        anyhow::bail!("Invalid input type")
    }
}

impl From<FuelTxCoin> for Input {
    fn from(value: FuelTxCoin) -> Self {
        Input::resource_signed(CoinType::Coin(value.into()))
    }
}

impl Ord for FuelTxCoin {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.amount
            .cmp(&other.amount)
            .then_with(|| self.asset_id.cmp(&other.asset_id))
            .then_with(|| self.utxo_id.cmp(&other.utxo_id))
            .then_with(|| self.owner.cmp(&other.owner))
    }
}

impl PartialOrd for FuelTxCoin {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Internal wrapper that pins each coin to its insertion order so the
/// per-account set can be walked oldest-first (FIFO).
///
/// `seq` is a monotonically increasing counter assigned per `load_from_coins`
/// batch: every coin added in the same call shares a `seq`, and each later
/// batch gets a higher one. Ordering is therefore "oldest batch first", with
/// ties (coins added together) broken by amount, then `utxo_id` for a stable
/// total order. This makes fee selection drain old, untouched UTXOs first and
/// pushes freshly-added change coins to the back of the queue.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct OrderedCoin {
    seq: u64,
    coin: FuelTxCoin,
}

impl Ord for OrderedCoin {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.seq
            .cmp(&other.seq)
            .then_with(|| self.coin.amount.cmp(&other.coin.amount))
            .then_with(|| self.coin.utxo_id.cmp(&other.coin.utxo_id))
    }
}

impl PartialOrd for OrderedCoin {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Trait for types that can provide UTXO management capabilities.
/// This allows decoupling the concrete UtxoManager implementation from the
/// o2-tools crate, enabling consumers to provide their own implementation.
pub trait UtxoProvider: Send + 'static {
    fn balance_of(&self, owner: Address, asset_id: AssetId) -> u128;
    fn len_per_address(&self, asset_id: AssetId, address: Address) -> usize;
    fn guaranteed_extract_coins(
        &mut self,
        owner: Address,
        asset_id: AssetId,
        amount: u128,
        max_coins: usize,
    ) -> anyhow::Result<Vec<FuelTxCoin>>;
    fn load_from_coins_vec(&mut self, coins: Vec<FuelTxCoin>);
    fn number_of_coins_with_amount_greater_or_equal(
        &self,
        owner: Address,
        asset_id: AssetId,
        amount: u128,
    ) -> (u128, usize);
    fn extract_largest_coins(
        &mut self,
        owner: Address,
        asset_id: AssetId,
        max_value: u128,
    ) -> Vec<FuelTxCoin>;
    fn coin_count(&self) -> usize;
    fn utxo_ids(&self) -> Vec<UtxoId>;
    fn remove_coin(&mut self, utxo_id: &UtxoId) -> bool;
    fn total_balance(&self, asset_id: &AssetId) -> u128;
}

pub type SharedUtxoManager = Arc<tokio::sync::Mutex<dyn UtxoProvider>>;

/// A struct to manage UTXOs of internal accounts used to pay fee, match transactions, and
/// users predicate based accounts.
pub struct UtxoManager {
    account_utxos: HashMap<(Address, AssetId), BTreeSet<OrderedCoin>>,
    coins: HashMap<UtxoId, OrderedCoin>,
    /// Next insertion-order sequence handed out to a `load_from_coins` batch.
    next_seq: u64,
}

impl Default for UtxoManager {
    fn default() -> Self {
        Self::new()
    }
}

impl UtxoManager {
    pub fn new() -> Self {
        Self {
            account_utxos: HashMap::new(),
            coins: HashMap::new(),
            next_seq: 0,
        }
    }

    pub fn len_per_address(&self, asset_id: AssetId, address: Address) -> usize {
        self.account_utxos
            .get(&(address, asset_id))
            .map_or(0, |utxos| utxos.len())
    }

    pub fn new_from_coins<I>(coins: I) -> Self
    where
        I: Iterator<Item = FuelTxCoin>,
    {
        let mut _self = Self::new();

        _self.load_from_coins(coins);

        _self
    }

    pub fn load_from_coins<I>(&mut self, coins: I)
    where
        I: Iterator<Item = FuelTxCoin>,
    {
        // Every coin in this call shares one sequence so the batch lands at the
        // back of the FIFO queue together; the counter only advances if at
        // least one coin was actually added.
        let seq = self.next_seq;
        let mut used = false;

        for coin in coins {
            if coin.amount == 0 {
                continue;
            }

            // Re-adding an already-tracked coin must not move it to the back of
            // the queue, so keep its original position.
            if self.coins.contains_key(&coin.utxo_id) {
                continue;
            }

            let ordered = OrderedCoin { seq, coin };
            let key = (coin.owner, coin.asset_id);
            self.account_utxos.entry(key).or_default().insert(ordered);
            self.coins.insert(coin.utxo_id, ordered);
            used = true;
        }

        if used {
            self.next_seq += 1;
        }
    }

    fn extract_utxos(&mut self, utxos: &[UtxoId]) -> anyhow::Result<Vec<FuelTxCoin>> {
        let mut coins = vec![];

        for utxo_id in utxos {
            let ordered = self.coins.remove(utxo_id).ok_or_else(|| {
                anyhow::anyhow!("UTXO {utxo_id} not found in the UTXO manager")
            })?;

            let key = (ordered.coin.owner, ordered.coin.asset_id);
            let account = self.account_utxos.entry(key);

            match account {
                Entry::Occupied(mut occupied) => {
                    occupied.get_mut().remove(&ordered);

                    if occupied.get().is_empty() {
                        occupied.remove();
                    }

                    coins.push(ordered.coin);
                }
                Entry::Vacant(_) => {}
            }
        }

        Ok(coins)
    }

    /// Selects up to `max_coins` UTXOs covering `amount`, walking the
    /// per-account set in `order`. Returns `Some(utxo_ids)` only when the
    /// selected coins (which never exceed `max_coins`) reach `amount`;
    /// otherwise `None`, so callers can try another strategy.
    fn select_within_cap(
        &self,
        owner: Address,
        asset_id: AssetId,
        amount: u128,
        max_coins: usize,
        order: SelectionOrder,
    ) -> Option<Vec<UtxoId>> {
        let coins = self.account_utxos.get(&(owner, asset_id))?;

        // FIFO walks the set in insertion order (oldest first); Largest
        // re-sorts by amount so the fewest, most valuable coins are tried.
        let ordered: Vec<&OrderedCoin> = match order {
            SelectionOrder::Fifo => coins.iter().collect(),
            SelectionOrder::Largest => {
                let mut by_amount: Vec<&OrderedCoin> = coins.iter().collect();
                by_amount.sort_by(|a, b| {
                    b.coin
                        .amount
                        .cmp(&a.coin.amount)
                        .then_with(|| a.coin.utxo_id.cmp(&b.coin.utxo_id))
                });
                by_amount
            }
        };

        let mut total = 0u128;
        let mut selected = Vec::new();
        for oc in ordered {
            if total >= amount || selected.len() >= max_coins {
                break;
            }
            selected.push(oc.coin.utxo_id);
            total += oc.coin.amount as u128;
        }

        (total >= amount).then_some(selected)
    }

    /// Extracts coins covering `amount`, returning at most `max_coins`.
    ///
    /// Prefers old, untouched UTXOs first (FIFO). If FIFO cannot reach the
    /// target within the cap, it falls back to the largest coins, which pack
    /// the most value into the fewest inputs. Errors only when neither
    /// strategy can cover `amount` within `max_coins`.
    pub fn guaranteed_extract_coins(
        &mut self,
        owner: Address,
        asset_id: AssetId,
        amount: u128,
        max_coins: usize,
    ) -> anyhow::Result<Vec<FuelTxCoin>> {
        let utxos = self
            .select_within_cap(owner, asset_id, amount, max_coins, SelectionOrder::Fifo)
            .or_else(|| {
                self.select_within_cap(
                    owner,
                    asset_id,
                    amount,
                    max_coins,
                    SelectionOrder::Largest,
                )
            })
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "Not enough UTXOs found for the given {owner} and \
                    {asset_id} to cover {amount} within {max_coins} coins."
                )
            })?;

        self.extract_utxos(&utxos)
    }

    pub fn number_of_coins_with_amount_greater_or_equal(
        &self,
        owner: Address,
        asset_id: AssetId,
        amount: u128,
    ) -> (u128, usize) {
        self.account_utxos
            .get(&(owner, asset_id))
            .map_or((0, 0), |coins| {
                let mut count = 0;
                let mut total_balance = 0;

                for ordered in coins.iter() {
                    if ordered.coin.amount as u128 >= amount {
                        count += 1;
                        total_balance += ordered.coin.amount as u128;
                    }
                }

                (total_balance, count)
            })
    }

    pub fn balance_of(&self, owner: Address, asset_id: AssetId) -> u128 {
        self.account_utxos
            .get(&(owner, asset_id))
            .map_or(0, |coins| {
                coins
                    .iter()
                    .map(|ordered| ordered.coin.amount as u128)
                    .sum()
            })
    }

    /// Returns all tracked coins keyed by their `UtxoId`.
    pub fn coins(&self) -> HashMap<UtxoId, FuelTxCoin> {
        self.coins
            .iter()
            .map(|(utxo_id, ordered)| (*utxo_id, ordered.coin))
            .collect()
    }

    /// Returns the number of coins tracked.
    pub fn coin_count(&self) -> usize {
        self.coins.len()
    }

    /// Returns the UtxoIds of all tracked coins.
    pub fn utxo_ids(&self) -> Vec<UtxoId> {
        self.coins.keys().copied().collect()
    }

    /// Checks if a specific coin is tracked.
    pub fn contains(&self, utxo_id: &UtxoId) -> bool {
        self.coins.contains_key(utxo_id)
    }

    /// Returns the total balance for a given asset across all owners.
    pub fn total_balance(&self, asset_id: &AssetId) -> u128 {
        self.coins
            .values()
            .filter(|ordered| &ordered.coin.asset_id == asset_id)
            .map(|ordered| ordered.coin.amount as u128)
            .sum()
    }

    /// Removes a specific coin by UtxoId. Returns true if it was found and removed.
    pub fn remove_coin(&mut self, utxo_id: &UtxoId) -> bool {
        if let Some(ordered) = self.coins.remove(utxo_id) {
            let key = (ordered.coin.owner, ordered.coin.asset_id);
            if let Entry::Occupied(mut entry) = self.account_utxos.entry(key) {
                entry.get_mut().remove(&ordered);
                if entry.get().is_empty() {
                    entry.remove();
                }
            }
            true
        } else {
            false
        }
    }

    /// Extracts the largest coins for the given owner/asset up to
    /// `max_value` total, in descending order of amount. Used by coin
    /// management (split/drain), independently of the FIFO fee-paying path,
    /// so it re-sorts by amount rather than relying on the set's insertion
    /// order. Returns the extracted coins (removed from the manager).
    pub fn extract_largest_coins(
        &mut self,
        owner: Address,
        asset_id: AssetId,
        max_value: u128,
    ) -> Vec<FuelTxCoin> {
        let utxo_ids: Vec<UtxoId> = {
            let Some(coins) = self.account_utxos.get(&(owner, asset_id)) else {
                return vec![];
            };
            let mut by_amount: Vec<&OrderedCoin> = coins.iter().collect();
            // Largest amount first; utxo_id keeps the order deterministic.
            by_amount.sort_by(|a, b| {
                b.coin
                    .amount
                    .cmp(&a.coin.amount)
                    .then_with(|| a.coin.utxo_id.cmp(&b.coin.utxo_id))
            });
            let mut total = 0u128;
            by_amount
                .into_iter()
                .take_while(|ordered| {
                    if total >= max_value {
                        return false;
                    }
                    total += ordered.coin.amount as u128;
                    true
                })
                .map(|ordered| ordered.coin.utxo_id)
                .collect()
        };
        self.extract_utxos(&utxo_ids).unwrap_or_default()
    }
}

impl UtxoProvider for UtxoManager {
    fn balance_of(&self, owner: Address, asset_id: AssetId) -> u128 {
        UtxoManager::balance_of(self, owner, asset_id)
    }

    fn len_per_address(&self, asset_id: AssetId, address: Address) -> usize {
        UtxoManager::len_per_address(self, asset_id, address)
    }

    fn guaranteed_extract_coins(
        &mut self,
        owner: Address,
        asset_id: AssetId,
        amount: u128,
        max_coins: usize,
    ) -> anyhow::Result<Vec<FuelTxCoin>> {
        UtxoManager::guaranteed_extract_coins(self, owner, asset_id, amount, max_coins)
    }

    fn load_from_coins_vec(&mut self, coins: Vec<FuelTxCoin>) {
        self.load_from_coins(coins.into_iter());
    }

    fn number_of_coins_with_amount_greater_or_equal(
        &self,
        owner: Address,
        asset_id: AssetId,
        amount: u128,
    ) -> (u128, usize) {
        UtxoManager::number_of_coins_with_amount_greater_or_equal(
            self, owner, asset_id, amount,
        )
    }

    fn extract_largest_coins(
        &mut self,
        owner: Address,
        asset_id: AssetId,
        max_value: u128,
    ) -> Vec<FuelTxCoin> {
        UtxoManager::extract_largest_coins(self, owner, asset_id, max_value)
    }

    fn coin_count(&self) -> usize {
        UtxoManager::coin_count(self)
    }

    fn utxo_ids(&self) -> Vec<UtxoId> {
        UtxoManager::utxo_ids(self)
    }

    fn remove_coin(&mut self, utxo_id: &UtxoId) -> bool {
        UtxoManager::remove_coin(self, utxo_id)
    }

    fn total_balance(&self, asset_id: &AssetId) -> u128 {
        UtxoManager::total_balance(self, asset_id)
    }
}

#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
    use super::*;

    #[test]
    fn guaranteed_extract_coins__returns_coins_in_ascending_order_by_amount__when_coins_inserted_in_random_order()
     {
        // given
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);

        let coin1 = FuelTxCoin {
            amount: 100,
            asset_id,
            utxo_id: UtxoId::new(fuel_core_types::fuel_tx::TxId::from([1u8; 32]), 0),
            owner,
        };
        let coin2 = FuelTxCoin {
            amount: 50,
            asset_id,
            utxo_id: UtxoId::new(fuel_core_types::fuel_tx::TxId::from([2u8; 32]), 0),
            owner,
        };
        let coin3 = FuelTxCoin {
            amount: 200,
            asset_id,
            utxo_id: UtxoId::new(fuel_core_types::fuel_tx::TxId::from([3u8; 32]), 0),
            owner,
        };
        let coin4 = FuelTxCoin {
            amount: 75,
            asset_id,
            utxo_id: UtxoId::new(fuel_core_types::fuel_tx::TxId::from([4u8; 32]), 0),
            owner,
        };

        let mut manager = UtxoManager::new();
        manager.load_from_coins(vec![coin1, coin2, coin3, coin4].into_iter());

        // when
        let total_amount = 100 + 50 + 200 + 75;
        let extracted = manager
            .guaranteed_extract_coins(owner, asset_id, total_amount, usize::MAX)
            .unwrap();

        // then
        assert_eq!(extracted.len(), 4);
        assert_eq!(extracted[0].amount, 50); // coin2 (smallest)
        assert_eq!(extracted[1].amount, 75); // coin4
        assert_eq!(extracted[2].amount, 100); // coin1
        assert_eq!(extracted[3].amount, 200); // coin3 (largest)
        assert_eq!(manager.balance_of(owner, asset_id), 0);
    }

    #[test]
    fn extract_largest_coins__takes_largest_first_up_to_max_value() {
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);

        let coins: Vec<FuelTxCoin> = (1..=5)
            .map(|i| FuelTxCoin {
                amount: i * 100, // 100, 200, 300, 400, 500
                asset_id,
                utxo_id: UtxoId::new(
                    fuel_core_types::fuel_tx::TxId::from([i as u8; 32]),
                    0,
                ),
                owner,
            })
            .collect();
        let mut manager = UtxoManager::new();
        manager.load_from_coins(coins.into_iter());

        // Extract up to 600 in value (largest first: 500, then 400 -> total 900 > 600)
        // take_while stops after accumulating >= max_value, so we get 500 (total=500 < 600)
        // then 400 (total=900 >= 600, but take_while already entered), so we get 500 + 400.
        // Actually take_while: first 500 → total=500 < 600 → true; next 400 → total=900 → true
        // (check is at start: total >= max_value? 500 >= 600? no, so take it);
        // next iteration: total=900 >= 600? yes → stop.
        let extracted = manager.extract_largest_coins(owner, asset_id, 600);
        let amounts: Vec<u64> = extracted.iter().map(|c| c.amount).collect();
        // Should have extracted the two largest coins (500 and 400)
        assert_eq!(amounts.len(), 2);
        assert!(amounts.contains(&500));
        assert!(amounts.contains(&400));
        // Remaining: 100+200+300 = 600
        assert_eq!(manager.balance_of(owner, asset_id), 600);
    }

    fn coin(amount: u64, tag: u8, owner: Address, asset_id: AssetId) -> FuelTxCoin {
        FuelTxCoin {
            amount,
            asset_id,
            utxo_id: UtxoId::new(fuel_core_types::fuel_tx::TxId::from([tag; 32]), 0),
            owner,
        }
    }

    #[test]
    fn guaranteed_extract_coins__spends_oldest_batch_first__even_when_newer_coin_is_smaller()
     {
        // given: an old large coin loaded first, then a newer small coin.
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let old_large = coin(1_000, 1, owner, asset_id);
        let new_small = coin(10, 2, owner, asset_id);

        let mut manager = UtxoManager::new();
        manager.load_from_coins(vec![old_large].into_iter()); // batch 0
        manager.load_from_coins(vec![new_small].into_iter()); // batch 1

        // when: we need less than the old coin alone provides.
        let extracted = manager
            .guaranteed_extract_coins(owner, asset_id, 5, usize::MAX)
            .unwrap();

        // then: FIFO picks the old coin despite the newer one being smaller.
        assert_eq!(extracted.len(), 1);
        assert_eq!(extracted[0].utxo_id, old_large.utxo_id);
        assert_eq!(manager.balance_of(owner, asset_id), 10);
    }

    #[test]
    fn guaranteed_extract_coins__prefers_old_small_coin_over_new_large_coin() {
        // given: an old *small* coin, then a new *large* coin. This is the
        // case that distinguishes FIFO from largest-first selection.
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let old_small = coin(100, 1, owner, asset_id);
        let new_large = coin(900, 2, owner, asset_id);

        let mut manager = UtxoManager::new();
        manager.load_from_coins(vec![old_small].into_iter()); // batch 0
        manager.load_from_coins(vec![new_large].into_iter()); // batch 1

        // when: the target fits in either single coin.
        let extracted = manager
            .guaranteed_extract_coins(owner, asset_id, 100, usize::MAX)
            .unwrap();

        // then: FIFO takes the old small coin, not the larger newer one.
        assert_eq!(extracted.len(), 1);
        assert_eq!(extracted[0].utxo_id, old_small.utxo_id);
    }

    #[test]
    fn load_from_coins__breaks_ties_within_a_batch_by_amount() {
        // given: three coins added in a single batch (same age).
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let big = coin(300, 1, owner, asset_id);
        let small = coin(100, 2, owner, asset_id);
        let mid = coin(200, 3, owner, asset_id);

        let mut manager = UtxoManager::new();
        manager.load_from_coins(vec![big, small, mid].into_iter());

        // when: extract just enough for the smallest.
        let extracted = manager
            .guaranteed_extract_coins(owner, asset_id, 50, usize::MAX)
            .unwrap();

        // then: same-age coins are spent smallest-amount first.
        assert_eq!(extracted.len(), 1);
        assert_eq!(extracted[0].utxo_id, small.utxo_id);
    }

    #[test]
    fn load_from_coins__re_adding_existing_coin_keeps_its_queue_position() {
        // given: an old coin, then a new coin, then the old coin re-added.
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let old = coin(100, 1, owner, asset_id);
        let new = coin(100, 2, owner, asset_id);

        let mut manager = UtxoManager::new();
        manager.load_from_coins(vec![old].into_iter()); // batch 0
        manager.load_from_coins(vec![new].into_iter()); // batch 1
        manager.load_from_coins(vec![old].into_iter()); // re-add: must not move

        assert_eq!(manager.coin_count(), 2);

        // when: extract one coin's worth.
        let extracted = manager
            .guaranteed_extract_coins(owner, asset_id, 100, usize::MAX)
            .unwrap();

        // then: the old coin is still first despite being re-added last.
        assert_eq!(extracted.len(), 1);
        assert_eq!(extracted[0].utxo_id, old.utxo_id);
    }

    #[test]
    fn extract_largest_coins__still_takes_largest_first__across_batches() {
        // given: a small coin in an older batch, a large coin in a newer batch.
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let old_small = coin(100, 1, owner, asset_id);
        let new_large = coin(900, 2, owner, asset_id);

        let mut manager = UtxoManager::new();
        manager.load_from_coins(vec![old_small].into_iter()); // batch 0
        manager.load_from_coins(vec![new_large].into_iter()); // batch 1

        // when / then: split/drain path ignores age and takes the largest.
        let extracted = manager.extract_largest_coins(owner, asset_id, 500);
        assert_eq!(extracted.len(), 1);
        assert_eq!(extracted[0].utxo_id, new_large.utxo_id);
    }

    #[test]
    fn guaranteed_extract_coins__never_returns_more_than_max_coins() {
        // given: five equal coins in one batch.
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let coins: Vec<FuelTxCoin> =
            (1..=5).map(|i| coin(100, i, owner, asset_id)).collect();

        let mut manager = UtxoManager::new();
        manager.load_from_coins(coins.into_iter());

        // when: the target would need 4 coins but the cap is 2.
        let result = manager.guaranteed_extract_coins(owner, asset_id, 400, 2);

        // then: it errors rather than exceeding the cap.
        assert!(result.is_err());
        // and nothing was removed.
        assert_eq!(manager.coin_count(), 5);
    }

    #[test]
    fn guaranteed_extract_coins__falls_back_to_largest_when_fifo_cannot_meet_target_within_cap()
     {
        // given: many old dust coins, then one new large coin.
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let dust: Vec<FuelTxCoin> =
            (1..=5).map(|i| coin(10, i, owner, asset_id)).collect();
        let big = coin(1_000, 100, owner, asset_id);

        let mut manager = UtxoManager::new();
        manager.load_from_coins(dust.into_iter()); // batch 0 (old)
        manager.load_from_coins(vec![big].into_iter()); // batch 1 (new)

        // when: need 500 but cap is 2; the 2 oldest dust coins total only 20,
        // so FIFO fails and we fall back to largest (the single big coin).
        let extracted = manager
            .guaranteed_extract_coins(owner, asset_id, 500, 2)
            .unwrap();

        // then: the big coin alone satisfies the target within the cap.
        assert_eq!(extracted.len(), 1);
        assert_eq!(extracted[0].utxo_id, big.utxo_id);
    }

    #[test]
    fn guaranteed_extract_coins__errors_when_neither_strategy_can_cover_target() {
        // given: total balance below the target.
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let small = coin(100, 1, owner, asset_id);

        let mut manager = UtxoManager::new();
        manager.load_from_coins(vec![small].into_iter());

        // when / then: even uncapped, there isn't enough to cover 1_000.
        let result = manager.guaranteed_extract_coins(owner, asset_id, 1_000, usize::MAX);
        assert!(result.is_err());
        assert_eq!(manager.coin_count(), 1);
    }

    #[test]
    fn extract_largest_coins__returns_empty_when_no_coins() {
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let mut manager = UtxoManager::new();
        let extracted = manager.extract_largest_coins(owner, asset_id, 1000);
        assert!(extracted.is_empty());
    }

    #[test]
    fn extract_largest_coins__extracts_single_coin_when_only_one() {
        let owner = Address::from([1u8; 32]);
        let asset_id = AssetId::from([2u8; 32]);
        let coin = FuelTxCoin {
            amount: 1_000_000,
            asset_id,
            utxo_id: UtxoId::new(fuel_core_types::fuel_tx::TxId::from([1u8; 32]), 0),
            owner,
        };
        let mut manager = UtxoManager::new();
        manager.load_from_coins(vec![coin].into_iter());

        let extracted = manager.extract_largest_coins(owner, asset_id, 500_000);
        assert_eq!(extracted.len(), 1);
        assert_eq!(extracted[0].amount, 1_000_000);
        assert_eq!(manager.balance_of(owner, asset_id), 0);
    }
}