EIP-211 · Final · Core · 2017-02-13
EIP-211: New opcodes: RETURNDATASIZE and RETURNDATACOPY
Adds RETURNDATASIZE and RETURNDATACOPY so a contract can read return data of any length after a call, which makes proxies and revert-reason forwarding possible.
What problem does it solve?
Before Byzantium (2017), a CALL had to say up front where to put the output and how big it was. If the callee returned more, the rest was cut off. If it returned less, the caller could not tell. That is fine when you know the function's ABI, but it breaks for:
- Generic forwarders and proxies, which pass any call through to another contract and must return whatever comes back.
- Dynamic return types such as
stringorbytes[], whose length is not known in advance. - Error messages from EIP-140
REVERT, which can be any length.
Workarounds such as calling twice (once to get the size) were costly and awkward.
How it works
Each call frame gets a return data buffer, similar to calldata:
- Every call-like opcode (
CALL,CALLCODE,DELEGATECALL,STATICCALL,CREATE,CREATE2) clears the buffer. When it finishes, the buffer holds the callee's full output, either return data or revert data. CREATE/CREATE2leave the buffer empty on success and hold the revert data on failure.- If no call frame is actually created (for example, not enough balance for the value transfer), the buffer is empty.
Two new opcodes read it:
| Opcode | Byte | Effect | Gas |
|---|---|---|---|
RETURNDATASIZE |
0x3d |
Push the buffer length | 2 |
RETURNDATACOPY |
0x3e |
Copy (destOffset, offset, length) into memory |
3 + 3 per word |
Unlike CALLDATACOPY, reading past the end of the buffer is not zero-padded. It is an exceptional halt that consumes all gas.
Sample code
The core of every modern proxy: forward the call and bubble up the result or the revert unchanged.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Forwarder {
address public immutable target;
constructor(address t) { target = t; }
fallback() external payable {
address t = target;
assembly {
calldatacopy(0, 0, calldatasize())
let ok := call(gas(), t, callvalue(), 0, calldatasize(), 0, 0) // output size 0: unknown
returndatacopy(0, 0, returndatasize()) // EIP-211
switch ok
case 0 { revert(0, returndatasize()) } // forward revert reason
default { return(0, returndatasize()) }
}
}
}
In high-level Solidity, (bool ok, bytes memory data) = t.call(payload); uses these opcodes behind the scenes to fill data.
Things to know
- The buffer is overwritten by the next call, so copy what you need before making another call.
- An out-of-bounds
RETURNDATACOPYfails hard instead of padding with zeros. Always usereturndatasize()as the bound. RETURNDATASIZEcosts 2 gas and is a cheap way to push0right after a frame starts. Minimal proxies such as ERC-1167 used this trick beforePUSH0existed.- Shipped in Byzantium together with
REVERTand EIP-214STATICCALL. See EIP-609.