1
1
use num:: rational:: Ratio ;
2
+ use num_traits:: CheckedSub ;
2
3
use primitives:: { BalancesMap , BigNum , Channel , DomainError , ValidatorDesc } ;
3
4
4
5
pub fn get_balances_after_fees_tree (
5
6
balances : & BalancesMap ,
6
7
channel : & Channel ,
7
8
) -> Result < BalancesMap , DomainError > {
8
- let deposit = channel. deposit_amount . clone ( ) ;
9
+ let deposit_amount = channel. deposit_amount . clone ( ) ;
9
10
10
11
let total_distributed = balances. iter ( ) . map ( |( _, balance) | balance) . sum :: < BigNum > ( ) ;
11
12
@@ -14,22 +15,22 @@ pub fn get_balances_after_fees_tree(
14
15
. map ( |validator| & validator. fee )
15
16
. sum :: < BigNum > ( ) ;
16
17
17
- if total_validators_fee > deposit {
18
+ if total_validators_fee > deposit_amount {
18
19
return Err ( DomainError :: RuleViolation (
19
20
"total fees <= deposit: fee constraint violated" . into ( ) ,
20
21
) ) ;
21
22
}
22
23
23
- if total_distributed > deposit {
24
+ if total_distributed > deposit_amount {
24
25
return Err ( DomainError :: RuleViolation (
25
26
"distributed <= deposit: OUTPACE rule #4" . into ( ) ,
26
27
) ) ;
27
28
}
28
29
29
- let to_distribute = & deposit - & total_validators_fee;
30
+ let deposit_to_distribute = & deposit_amount - & total_validators_fee;
30
31
31
- let ratio = Ratio :: new ( to_distribute . clone ( ) , deposit . clone ( ) ) ;
32
- let fee_ratio = Ratio :: new ( total_distributed. clone ( ) , deposit . clone ( ) ) ;
32
+ let ratio = Ratio :: new ( deposit_to_distribute . clone ( ) , deposit_amount . clone ( ) ) ;
33
+ let fee_ratio = Ratio :: new ( total_distributed. clone ( ) , deposit_amount . clone ( ) ) ;
33
34
34
35
let mut balances_after_fees = BalancesMap :: default ( ) ;
35
36
let mut total = BigNum :: from ( 0 ) ;
@@ -41,18 +42,16 @@ pub fn get_balances_after_fees_tree(
41
42
balances_after_fees. insert ( key. clone ( ) , adjusted_balance) ;
42
43
}
43
44
44
- let rounding_error = if deposit == total_distributed {
45
- & to_distribute - & total_distributed
45
+ let rounding_error = if deposit_amount == total_distributed {
46
+ deposit_to_distribute
47
+ . checked_sub ( & total)
48
+ . ok_or ( DomainError :: RuleViolation (
49
+ "rounding_err should never be negative" . to_owned ( ) ,
50
+ ) ) ?
46
51
} else {
47
52
BigNum :: from ( 0 )
48
53
} ;
49
54
50
- if rounding_error < BigNum :: from ( 0 ) {
51
- return Err ( DomainError :: RuleViolation (
52
- "The Rounding error should never be negative" . into ( ) ,
53
- ) ) ;
54
- }
55
-
56
55
let balances_after_fees = distribute_fee (
57
56
balances_after_fees,
58
57
rounding_error,
0 commit comments