EIP-5000 · Stagnant · Core · 2022-03-14
EIP-5000: MULDIV instruction
Proposed a MULDIV opcode that computes x * y / z with a 512-bit intermediate in one 8-gas instruction, replacing the ~50-instruction full-precision mulDiv used throughout DeFi.
What problem does it solve?
Fixed-point maths is everywhere in DeFi: prices, interest, shares, AMM curves. The core operation is x * y / z, but in 256-bit arithmetic x * y can overflow even when the final result fits. The standard workaround is a "full-precision mulDiv" built from mulmod and some clever algebra (popularised by Uniswap and others), which costs about 50 instructions plus stack shuffling.
EIP-5000 proposes doing it in hardware: a single EVM instruction with a 512-bit intermediate product.
How it works
New opcode MULDIV at 0x1e:
- Pops
x, theny, thenz(same argument order asADDMOD/MULMOD). - If
z != 0: pushes((x * y) / z) mod 2**256, withx * ycomputed in 512 bits. - If
z == 0: pushes(x * y) / 2**256, i.e. the high 256 bits of the full product. - Costs 8 gas, the same as
ADDMOD/MULMOD.
# * and // in 512-bit precision
def muldiv(x, y, z):
if z == 0:
return (x * y) // 2**256
return ((x * y) // z) % 2**256
The z == 0 case deliberately breaks the EVM convention that division by zero returns 0. It makes the opcode double as a 256×256→512 multiplier: MUL gives the low half and MULDIV(x, y, 0) gives the high half. That is useful for cryptography and for detecting overflow in checked arithmetic (if the high half is non-zero, the product overflowed).
Sample code
Test vectors from the spec, written in EVM-assembly style:
PUSH32 0xfff...fff ; z = 2**256 - 1
PUSH32 0xfff...fff ; y = 2**256 - 1
PUSH32 0xfff...fff ; x = 2**256 - 1
MULDIV ; -> 0xfff...fff (x*y/z = x)
PUSH32 0x00 ; z = 0 -> high half of x*y
PUSH32 0xfff...fff
PUSH32 0xfff...fff
MULDIV ; -> 0xfff...ffe
A typical fixed-point use, e.g. amount * price / 1e18, would compile to just three pushes and one MULDIV (hypothetical bytecode, no compiler emits this today):
PUSH32 0x0de0b6b3a7640000 ; z = 1e18 (divisor)
PUSH32 <price> ; y
PUSH32 <amount> ; x
MULDIV ; amount * price / 1e18, no intermediate overflow
Things to know
- Status: Stagnant. It is not on mainnet; opcode
0x1eis unassigned there. Keep using library implementations such as OpenZeppelin'sMath.mulDiv. - Watch the zero-divisor semantics: passing
z = 0does not revert or return 0, it returns the high word of the product. - The result wraps modulo 2256 when the true quotient is larger, so overflow-checked code still needs to verify that.
- Security Considerations in the spec were left as "TBA".