From 2514d46133831c3531bdc0a99166f4b0f414ed2b Mon Sep 17 00:00:00 2001 From: Aayush Date: Sun, 13 Apr 2025 11:48:55 +0000 Subject: [PATCH] checkinginsufficientbalace-zeroaddress-with-gas-optimization --- src/tokens/ERC20.sol | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/tokens/ERC20.sol b/src/tokens/ERC20.sol index 96570446..b760d87d 100644 --- a/src/tokens/ERC20.sol +++ b/src/tokens/ERC20.sol @@ -73,20 +73,23 @@ abstract contract ERC20 { return true; } - function transfer(address to, uint256 amount) public virtual returns (bool) { - balanceOf[msg.sender] -= amount; - - // Cannot overflow because the sum of all user - // balances can't exceed the max uint256 value. - unchecked { - balanceOf[to] += amount; - } + error InsufficientBalance(); + error TransferToZeroAddress(); - emit Transfer(msg.sender, to, amount); + function transfer(address to, uint256 amount) public returns (bool) { + if (balanceOf[msg.sender] < amount) revert InsufficientBalance(); + if (to == address(0)) revert TransferToZeroAddress(); - return true; + unchecked { + balanceOf[msg.sender] -= amount; + balanceOf[to] += amount; } + emit Transfer(msg.sender, to, amount); + return true; +} + + function transferFrom( address from, address to,