TExcelTAD
Home › Solidity › Security: More Pitfalls

Security: More Pitfalls

Reentrancy and access control are the headline bugs, but many others appear again and again in audits. This lesson tours the most important ones, each with a local demo and its fix: misuse of unchecked, fake randomness, denial of service, ether-balance assumptions and front-running.

1. unchecked arithmetic

Solidity 0.8 checks overflow by default, but unchecked blocks (added for gas savings) bring the old wrap-around behaviour back. A classic mistake is subtracting balances inside one:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Points {
    mapping(address => uint256) public balance;

    constructor() { balance[msg.sender] = 10; }

    function spendBuggy(uint256 amount) external {
        unchecked { balance[msg.sender] -= amount; }     // BUG: can underflow
    }

    function spendSafe(uint256 amount) external {
        require(balance[msg.sender] >= amount, "insufficient");
        unchecked { balance[msg.sender] -= amount; }     // safe: checked just above
    }
}

contract Main {
    function main() external {
        Points p = new Points();
        p.spendBuggy(11);
        console.log("balance after spending 11 of 10:");
        console.log(p.balance(address(this)));
        Points fresh = new Points();
        console.log("safe version, spending 11 of 10:");
        fresh.spendSafe(11);
    }
}
balance after spending 11 of 10:
115792089237316195423570985008687907853269984665640564039457584007913129639935
safe version, spending 11 of 10:
main() failed: reverted with reason: insufficient

The buggy version turned 10 − 11 into an astronomically large balance. The safe version's require guarantees the subtraction can't wrap. Only put arithmetic in unchecked after proving it can't overflow.

2. Block values are not random

Everything on chain is deterministic and visible. block.timestamp, block.number and block.prevrandao are known to (and partly controlled by) the block producer, and any contract in the same transaction can compute the same "random" number first:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract CoinFlip {
    constructor() payable {}

    function guess(bool heads) external {
        bool result = uint256(keccak256(abi.encode(block.timestamp, block.number))) % 2 == 0;
        if (heads == result) {
            payable(msg.sender).transfer(1 ether);
        }
    }
}

contract Predictor {
    function play(CoinFlip game, uint256 rounds) external {
        for (uint256 i = 0; i < rounds; i++) {
            // compute the same "unpredictable" value, then always guess right
            bool result = uint256(keccak256(abi.encode(block.timestamp, block.number))) % 2 == 0;
            game.guess(result);
        }
    }
    receive() external payable {}
}

contract Main {
    constructor() payable {}

    function main() external {
        CoinFlip game = new CoinFlip{value: 10 ether}();
        Predictor p = new Predictor();
        p.play(game, 5);
        console.log("predictor won:", address(p).balance / 1 ether, "ETH in 5 rounds");
    }
}
predictor won: 5 ETH in 5 rounds

Fix: use a verifiable randomness oracle (such as Chainlink VRF) or a commit-reveal scheme in which participants commit to secrets first (see ABI Encoding & keccak256).

3. Denial of service by a reverting recipient

If a function pushes ether to an address that rejects it, the whole function reverts. In an auction that refunds the previous leader, one malicious bidder can block all future bids:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract PushAuction {
    address public leader;
    uint256 public highest;

    function bid() external payable {
        require(msg.value > highest, "bid too low");
        if (leader != address(0)) {
            (bool ok, ) = leader.call{value: highest}("");   // refund the old leader
            require(ok, "refund failed");
        }
        leader = msg.sender;
        highest = msg.value;
    }
}

contract Blocker {
    function bid(PushAuction a) external payable { a.bid{value: msg.value}(); }
    // no receive(): refunds to this contract always fail
}

contract Bidder {
    function bid(PushAuction a) external payable { a.bid{value: msg.value}(); }
    receive() external payable {}
}

contract Main {
    constructor() payable {}

    function main() external {
        PushAuction auction = new PushAuction();
        new Blocker().bid{value: 1 ether}(auction);
        console.log("blocker leads with 1 ETH");
        new Bidder().bid{value: 5 ether}(auction);     // can never outbid
    }
}
blocker leads with 1 ETH
main() failed: reverted with reason: refund failed

Fix: the pull pattern from Sending Ether: record refunds in a mapping and let each bidder withdraw their own.

4. Don't trust address(this).balance

A contract can receive ether without any of its functions running (for example as the target of selfdestruct or as a block reward recipient). Logic like require(address(this).balance == expected) can be broken by someone simply sending ether. Track deposits in your own variable instead:

solidity
uint256 public totalDeposited;            // updated in deposit()
// compare against totalDeposited, not address(this).balance

5. Front-running (transaction ordering)

Pending transactions sit in a public mempool before they're included in a block. Anyone can see them and send their own transaction with a higher fee to be ordered first. Examples:

  • Someone submits the answer to a puzzle that pays a reward; a bot copies the answer and outbids the gas fee.
  • A large trade on an exchange is seen in advance, and a bot buys before it and sells after it ("sandwiching").

Defenses are design-level:

Defense Idea
Commit-reveal submit a hash first, reveal later, so there's nothing to copy
Slippage limits swap(amountIn, minAmountOut): revert if the price moved too much
Deadlines require(block.timestamp <= deadline) so stale transactions fail
Bind to sender include msg.sender in a commitment, so a copy by someone else is invalid
solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Riddle {
    bytes32 public immutable answerHash = keccak256(abi.encode("echo"));
    mapping(address => bytes32) public commits;
    address public winner;

    function commit(bytes32 h) external { commits[msg.sender] = h; }

    // the commitment includes the sender, so copying someone else's reveal doesn't help
    function reveal(string calldata answer, bytes32 salt) external {
        require(commits[msg.sender] == keccak256(abi.encode(msg.sender, answer, salt)), "no matching commit");
        require(keccak256(abi.encode(answer)) == answerHash, "wrong answer");
        require(winner == address(0), "already solved");
        winner = msg.sender;
    }
}

contract Player {
    function commit(Riddle r, bytes32 h) external { r.commit(h); }
    function reveal(Riddle r, string calldata a, bytes32 salt) external { r.reveal(a, salt); }
}

contract Main {
    function main() external {
        Riddle riddle = new Riddle();
        Player solver = new Player();
        Player copycat = new Player();

        bytes32 salt = keccak256("solver secret");
        solver.commit(riddle, keccak256(abi.encode(address(solver), "echo", salt)));

        // the copycat sees the reveal in the mempool and replays it first
        try copycat.reveal(riddle, "echo", salt) {} catch Error(string memory reason) {
            console.log("copycat:", reason);
        }
        solver.reveal(riddle, "echo", salt);
        console.log("winner is solver?", riddle.winner() == address(solver));
    }
}
copycat: no matching commit
winner is solver? true

Habits that prevent most bugs

  • Keep contracts small and simple; complexity hides bugs.
  • Use audited libraries for standard pieces.
  • Write tests for the unhappy paths (Testing & Deployment), and use fuzzing.
  • Read public audit reports and post-mortems: the same patterns repeat.

Test yourself

Why is uint256(keccak256(abi.encode(block.timestamp))) % 6 a bad dice roll?

  1. keccak256 is slow
  2. Anyone, including other contracts in the same block, can compute the same value
  3. It always returns 0
  4. Timestamps are encrypted

Which design avoids the 'reverting recipient blocks the auction' problem?

  1. Using transfer instead of call
  2. Letting outbid users withdraw refunds themselves (pull payments)
  3. Sending refunds in a loop
  4. Increasing the gas limit

What protects a swap from being sandwiched at a bad price?

  1. A minimum-output (slippage) parameter that makes the swap revert if the price moved
  2. Using view functions
  3. Calling it twice
  4. Using tx.origin