Token-0x

First Flight #54
Beginner FriendlyDeFi
100 EXP
Submission Details
Impact: low
Likelihood: high

BalanceOf function contain a useless `mstore`.

Author Revealed upon completion

Root + Impact

In the _balanceOf function there is a mstore that is not necessary

https://github.com/CodeHawks-Contests/2025-12-token-0x/blob/7f9f55d58a485a36fb56284d8d0e8a415544bf9b/src/helpers/ERC20Internals.sol#L35

Description

  • The _balanceOf function is a major function in the contract that is called multiple times throughout the contract's life.

  • Any bloating in the code in that function can lead to increasing gas spent.

// Root cause in the codebase with @> marks to highlight the relevant section
function _balanceOf(address owner) internal view returns (uint256) {
assembly {
if iszero(owner) {
revert(0, 0)
}
let baseSlot := _balances.slot
let ptr := mload(0x40)
mstore(ptr, owner)
mstore(add(ptr, 0x20), baseSlot)
let dataSlot := keccak256(ptr, 0x40)
let amount := sload(dataSlot)
mstore(ptr, amount)
@> mstore(add(ptr, 0x20), 0)
return(ptr, 0x20)
}
}

Risk

Likelihood:

  • Every time someone calls _balanceOf will cause to spent more gas than needed.

Impact:

  • More gas spended than needed.

  • Code bloating.

Proof of Concept

Leave the function like this and run the tests, all tests will pass.

function _balanceOf(address owner) internal view returns (uint256) {
assembly {
if iszero(owner) {
revert(0, 0)
}
let baseSlot := _balances.slot
let ptr := mload(0x40)
mstore(ptr, owner)
mstore(add(ptr, 0x20), baseSlot)
let dataSlot := keccak256(ptr, 0x40)
let amount := sload(dataSlot)
mstore(ptr, amount)
return(ptr, 0x20)
}
}

Recommended Mitigation

function _balanceOf(address owner) internal view returns (uint256) {
assembly {
if iszero(owner) {
revert(0, 0)
}
let baseSlot := _balances.slot
let ptr := mload(0x40)
mstore(ptr, owner)
mstore(add(ptr, 0x20), baseSlot)
let dataSlot := keccak256(ptr, 0x40)
let amount := sload(dataSlot)
mstore(ptr, amount)
- mstore(add(ptr, 0x20), 0)
return(ptr, 0x20)
}
}

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.

Give us feedback!