Unsigned integer division with division-by-zero returning zero
This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.
Overview
Opcode:0x04Introduced: Frontier (EVM genesis)DIV performs unsigned integer division on two 256-bit values. Unlike most programming languages, division by zero returns 0 instead of throwing an exception, preventing denial-of-service attacks.This operation is essential for ratio calculations, scaling, and implementing fractional arithmetic in smart contracts.
Specification
Stack Input:
a (top - dividend)b (divisor)
Stack Output:
a / b (if b ≠ 0)0 (if b = 0)
Gas Cost: 5 (GasFastStep)Operation:
result = (b == 0) ? 0 : (a / b)
Behavior
DIV pops two values from the stack, performs integer division (truncating toward zero), and pushes the quotient:
If b ≠ 0: Result is floor(a / b) (truncated)
If b = 0: Result is 0 (no exception)
The result is always the integer quotient with remainder discarded. Use MOD to get the remainder.
Examples
Basic Division
import { div } from '@tevm/voltaire/evm/arithmetic';import { createFrame } from '@tevm/voltaire/evm/Frame';// 10 / 2 = 5const frame = createFrame({ stack: [10n, 2n] });const err = div(frame);console.log(frame.stack); // [5n]console.log(frame.gasRemaining); // Original - 5
// Simple average (beware overflow)function average(uint256 a, uint256 b) pure returns (uint256) { return (a + b) / 2;}// Safe average avoiding overflowfunction safeAverage(uint256 a, uint256 b) pure returns (uint256) { return (a / 2) + (b / 2) + (a % 2 + b % 2) / 2;}
Scaling and Conversion
// Convert from higher to lower decimalsfunction scaleDown(uint256 amount, uint8 fromDecimals, uint8 toDecimals) pure returns (uint256) { require(fromDecimals >= toDecimals, "invalid decimals"); return amount / (10 ** (fromDecimals - toDecimals));}// Convert token amountsfunction convertToUSDC(uint256 tokenAmount, uint256 price) pure returns (uint256) { // Assuming price is in USDC per token (6 decimals) return (tokenAmount * price) / 1e18;}
Implementation
TypeScript
/** * DIV opcode (0x04) - Integer division (division by zero returns 0) */export function div(frame: FrameType): EvmError | null { // Consume gas (GasFastStep = 5) frame.gasRemaining -= 5n; if (frame.gasRemaining < 0n) { frame.gasRemaining = 0n; return { type: "OutOfGas" }; } // Pop operands if (frame.stack.length < 2) return { type: "StackUnderflow" }; const a = frame.stack.pop(); // dividend const b = frame.stack.pop(); // divisor // Division by zero returns 0 (no exception) const result = b === 0n ? 0n : a / b; // Push result if (frame.stack.length >= 1024) return { type: "StackOverflow" }; frame.stack.push(result); // Increment PC frame.pc += 1; return null;}
// If DIV reverted on zero:function maliciousRatio(uint256 numerator, uint256 denominator) pure returns (uint256) { return numerator / denominator;}// Attacker calls with denominator = 0// Contract execution would halt// This could DOS critical functionality
The EVM solution:
// Division by zero returns 0 (no revert)// Contracts MUST explicitly check divisorfunction safeRatio(uint256 numerator, uint256 denominator) pure returns (uint256) { require(denominator != 0, "division by zero"); return numerator / denominator;}
// DIV always rounds DOWN (toward zero)// For ceiling division:function divCeil(uint256 a, uint256 b) pure returns (uint256) { require(b > 0, "division by zero"); return (a + b - 1) / b;}// Examples:// divCeil(10, 3) = (10 + 3 - 1) / 3 = 12 / 3 = 4// divCeil(9, 3) = (9 + 3 - 1) / 3 = 11 / 3 = 3
Safe Fixed-Point Math
// Using PRBMath or similar libraryimport {UD60x18, ud} from "@prb/math/UD60x18.sol";function safeDivision(uint256 x, uint256 y) pure returns (uint256) { // Handles precision and overflow safely UD60x18 result = ud(x).div(ud(y)); return result.unwrap();}
Overflow in Multi-Step Calculations
// WRONG: Can overflow intermediate resultfunction mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256) { return (x * y) / denominator; // x * y can overflow!}// RIGHT: Use assembly for 512-bit intermediatefunction mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 z) { assembly { // Full 512-bit multiplication let mm := mulmod(x, y, not(0)) z := div(mul(x, y), denominator) // Check for overflow if iszero(and( gt(denominator, 0), or(iszero(mm), eq(div(mm, x), y)) )) { revert(0, 0) } }}
Benchmarks
DIV performance characteristics:Relative execution time:
ADD: 1.0x
MUL: 1.2x
DIV: 2.5x
MOD: 2.5x
Gas efficiency:
5 gas per 256-bit division
~200,000 divisions per million gas
Much faster than repeated subtraction (which would be ~3n gas for n subtractions)
Optimization tip:
// Division by constant powers of 2: use shiftuint256 result = x / 2; // 5 gas (DIV)uint256 result = x >> 1; // 3 gas (SHR) - 40% cheaper!uint256 result = x / 256; // 5 gas (DIV)uint256 result = x >> 8; // 3 gas (SHR)
References
Yellow Paper - Section 9.1 (Arithmetic Operations)