function _mint(address account, uint256 value) internal {
assembly ("memory-safe") {
if iszero(account) {
mstore(0x00, shl(224, 0xec442f05))
mstore(add(0x00, 4), 0x00)
revert(0x00, 0x24)
}
let ptr := mload(0x40)
let balanceSlot := _balances.slot
let supplySlot := _totalSupply.slot
let supply := sload(supplySlot)
@> sstore(supplySlot, add(supply, value))
mstore(ptr, account)
mstore(add(ptr, 0x20), balanceSlot)
let accountBalanceSlot := keccak256(ptr, 0x40)
let accountBalance := sload(accountBalanceSlot)
@> sstore(accountBalanceSlot, add(accountBalance, value))
}
}
pragma solidity ^0.8.24;
import {Test} from "forge-std/Test.sol";
import {ERC20} from "../src/ERC20.sol";
contract MintHarness is ERC20 {
constructor() ERC20("Token", "TKN") {}
function exposedMint(address account, uint256 value) external {
_mint(account, value);
}
}
contract MintOverflow is Test {
MintHarness internal token;
address internal attacker = address(0x2029
function setUp() public {
token = new MintHarness();
}
function test_mintOverflow() public {
token.exposedMint(attacker, type(uint256).max);
token.exposedMint(attacker, 1);
assertEq(token.totalSupply(), 0, "totalSupply wrapped to 0");
assertEq(token.balanceOf(attacker), 0, "attacker balance wrapped to 0");
}
}
//Fixed the overflow by checking the user balance before proceeding minting
function _mint(address account, uint256 value) internal {
assembly ("memory-safe") {
if iszero(account) {
mstore(0x00, shl(224, 0xec442f05))
mstore(add(0x00, 4), 0x00)
revert(0x00, 0x24)
}
let ptr := mload(0x40)
let balanceSlot := _balances.slot
let supplySlot := _totalSupply.slot
let supply := sload(supplySlot)
+ let supplyHeadroom := sub(not(0), supply)
+ if gt(value, supplyHeadroom) {
+ mstore(0x00, shl(224, 0xe450d38c))
+ mstore(add(0x00, 4), address())
+ mstore(add(0x00, 0x24), supply)
+ mstore(add(0x00, 0x44), value)
+ revert(0x00, 0x64)
+ }
mstore(ptr, account)
mstore(add(ptr, 0x20), balanceSlot)
let accountBalanceSlot := keccak256(ptr, 0x40)
let accountBalance := sload(accountBalanceSlot)
+ let balanceHeadroom := sub(not(0), accountBalance)
+ if gt(value, balanceHeadroom) {
+ mstore(0x00, shl(224, 0xe450d38c))
+ mstore(add(0x00, 4), account)
+ mstore(add(0x00, 0x24), accountBalance)
+ mstore(add(0x00, 0x44), value)
+ revert(0x00, 0x64)
+ }
sstore(supplySlot, add(supply, value))
sstore(accountBalanceSlot, add(accountBalance, value))
+ mstore(ptr, value)
+ log3(ptr, 0x20, 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0, account)
}
}