Skip to content

Commit 2da004c

Browse files
committed
Merge pull request #81 from aguilar1x/fix/safe-arithmetic-fee-share
fix: safe arithmetic fee share
1 parent f35d1b9 commit 2da004c

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

contracts/escrow/src/core/dispute.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,11 @@ impl DisputeManager {
7575
}
7676
for (addr, amount) in distributions.iter() {
7777
if amount > 0 {
78-
let fee_share = (amount * total_fees) / total;
79-
let net_amount = amount - fee_share;
78+
let fee_share = BasicMath::safe_div(
79+
BasicMath::safe_mul(amount, total_fees)?,
80+
total,
81+
)?;
82+
let net_amount = BasicMath::safe_sub(amount, fee_share)?;
8083
if net_amount > 0 {
8184
token_client.transfer(&contract_address, &addr, &net_amount);
8285
}
@@ -148,8 +151,11 @@ impl DisputeManager {
148151
if amount <= 0 {
149152
continue;
150153
}
151-
let fee_share = (amount * total_fees) / total;
152-
let net_amount = amount - fee_share;
154+
let fee_share = BasicMath::safe_div(
155+
BasicMath::safe_mul(amount, total_fees)?,
156+
total,
157+
)?;
158+
let net_amount = BasicMath::safe_sub(amount, fee_share)?;
153159
if net_amount > 0 {
154160
token_client.transfer(&contract_address, &addr, &net_amount);
155161
}

contracts/escrow/src/modules/math/basic.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ pub struct BasicMath;
55
pub trait BasicArithmetic {
66
fn safe_add(a: i128, b: i128) -> Result<i128, ContractError>;
77
fn safe_sub(a: i128, b: i128) -> Result<i128, ContractError>;
8+
fn safe_mul(a: i128, b: i128) -> Result<i128, ContractError>;
9+
fn safe_div(a: i128, b: i128) -> Result<i128, ContractError>;
810
}
911

1012
impl BasicArithmetic for BasicMath {
@@ -15,4 +17,15 @@ impl BasicArithmetic for BasicMath {
1517
fn safe_sub(a: i128, b: i128) -> Result<i128, ContractError> {
1618
a.checked_sub(b).ok_or(ContractError::Underflow)
1719
}
20+
21+
fn safe_mul(a: i128, b: i128) -> Result<i128, ContractError> {
22+
a.checked_mul(b).ok_or(ContractError::Overflow)
23+
}
24+
25+
fn safe_div(a: i128, b: i128) -> Result<i128, ContractError> {
26+
if b == 0 {
27+
return Err(ContractError::DivisionError);
28+
}
29+
a.checked_div(b).ok_or(ContractError::Overflow)
30+
}
1831
}

0 commit comments

Comments
 (0)