Division by zero occurs when a divisor in a calculation unexpectedly equals zero, causing an error.
In Solidity, attempting to divide by zero results in a runtime error, which can halt the transaction and potentially lead to unintended contract behavior.
This error often arises in situations where values are derived from user input, external data, or dynamic calculations that don’t account for zero values.
Game
Can you think of how this might be exploited if the contract doesn’t handle totalShares carefully?
// SPDX-License-Identifier: MIT// Open me in VSCode and really think before opening the hints!// Add @audit tags wherever suspicious// Go to the solidity docs to complete missing knowledge of what's happening here// Solve by drafting a fix!pragmasolidity ^0.8.0;contract DivisionByZeroGame {uint256public totalShares;mapping(address=>uint256) public userContributions;functionsetTotalShares(uint256 shares) public { totalShares = shares; }functioncalculateSharePercentage(address user) publicviewreturns (uint256) {uint256 userContribution = userContributions[user];// Calculate the user's percentage of total sharesreturn (userContribution *100) / totalShares; }}
Division by zero in Solidity causes the transaction to revert.
Consider what happens if totalShares is zero when calculateSharePercentage is called.
functioncalculateSharePercentage(address user) publicviewreturns (uint256) {uint256 userContribution = userContributions[user];// Fix: Check to prevent division by zerorequire(totalShares >0,"Total shares must be greater than zero");return (userContribution *100) / totalShares;}