From ad95c00420cd75766f212716ae1c472f085860ff Mon Sep 17 00:00:00 2001 From: Serhat Dolmaci Date: Tue, 23 Jun 2026 20:55:44 +0300 Subject: [PATCH] use checked arithmetic in hyllar token transfers replace raw -= and += with checked_sub and checked_add in transfer and transfer_from to prevent silent overflow/underflow wrapping. also fix the same issue in the allowance deduction. defense-in-depth: the balance checks already prevent underflow but checked arithmetic ensures no silent wrapping if the guards ever get out of sync with the actual mutations. --- crates/contracts/hyllar/src/lib.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/contracts/hyllar/src/lib.rs b/crates/contracts/hyllar/src/lib.rs index b9b23a74e..6099e7d12 100644 --- a/crates/contracts/hyllar/src/lib.rs +++ b/crates/contracts/hyllar/src/lib.rs @@ -126,9 +126,10 @@ impl ERC20 for Hyllar { return Err("Insufficient balance".to_string()); } - *self.balances.entry(sender.to_string()).or_insert(0) -= amount; - *self.balances.entry(recipient.to_string()).or_insert(0) += amount; - + let sender_entry = self.balances.entry(sender.to_string()).or_insert(0); + *sender_entry = sender_entry.checked_sub(amount).ok_or("Insufficient balance")?; + let recipient_entry = self.balances.entry(recipient.to_string()).or_insert(0); + *recipient_entry = recipient_entry.checked_add(amount).ok_or("Balance overflow")?; Ok(()) } @@ -151,11 +152,12 @@ impl ERC20 for Hyllar { return Err("Insufficient balance".to_string()); } - *self.balances.entry(owner.to_string()).or_insert(0) -= amount; - *self.balances.entry(recipient.to_string()).or_insert(0) += amount; - + let owner_entry = self.balances.entry(owner.to_string()).or_insert(0); + *owner_entry = owner_entry.checked_sub(amount).ok_or("Insufficient balance")?; + let recipient_entry_tf = self.balances.entry(recipient.to_string()).or_insert(0); + *recipient_entry_tf = recipient_entry_tf.checked_add(amount).ok_or("Balance overflow")?; // Decrease the allowance - let new_allowance = allowance - amount; + let new_allowance = allowance.checked_sub(amount).ok_or("Allowance underflow")?; self.allowances .insert((owner.to_string(), spender.to_string()), new_allowance);