Execute code preserving msg.sender and msg.value - foundation for libraries and proxies
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:0xf4Introduced: Homestead (EIP-7)DELEGATECALL executes code from another account while preserving the complete execution context (msg.sender, msg.value, storage). This enables library patterns and upgradeable proxy contracts by allowing code reuse without changing the caller’s state context.
Specification
Stack Input:
gas (max gas to forward)address (target account code to execute)inOffset (calldata memory offset)inLength (calldata size)outOffset (returndata memory offset)outLength (returndata size)
Stack Output:
success (1 if call succeeded, 0 if failed)
Gas Cost: 700 + cold_access + memory_expansionOperation:
import { DELEGATECALL } from '@tevm/voltaire/evm/system';import { Address } from '@tevm/voltaire/primitives';const frame = createFrame({ gasRemaining: 1000000n, address: Address("0x1234..."), caller: Address("0x5678..."), value: 1_000_000_000_000_000_000n // 1 ETH from original call});// Call library functionconst libraryAddress = Address("0xLibrary...");const calldata = new Uint8Array([/* function selector + params */]);// Write calldata to memoryfor (let i = 0; i < calldata.length; i++) { frame.memory.set(i, calldata[i]);}// Stack: [gas=100000, address, inOffset=0, inLength, outOffset=0, outLength=32]frame.stack.push(32n); // outLengthframe.stack.push(0n); // outOffsetframe.stack.push(BigInt(calldata.length)); // inLengthframe.stack.push(0n); // inOffsetframe.stack.push(BigInt(libraryAddress)); // library addressframe.stack.push(100000n); // gasconst err = DELEGATECALL(frame);// In library code:// - msg.sender = 0x5678... (preserved!)// - msg.value = 1 ETH (preserved!)// - storage modifications affect 0x1234...// - address(this) = 0x1234...console.log(frame.stack[0]); // 1n if success
Proxy Pattern
contract Proxy { address public implementation; constructor(address _implementation) { implementation = _implementation; } // Fallback forwards all calls to implementation fallback() external payable { address impl = implementation; assembly { // Copy calldata calldatacopy(0, 0, calldatasize()) // DELEGATECALL to implementation let result := delegatecall( gas(), impl, 0, calldatasize(), 0, 0 ) // Copy returndata returndatacopy(0, 0, returndatasize()) // Return or revert based on result switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } // Upgrade implementation (admin only) function upgrade(address newImpl) external { require(msg.sender == admin, "Not admin"); implementation = newImpl; }}contract Implementation { // Storage layout MUST match Proxy! address public implementation; // Slot 0 address public admin; // Slot 1 uint256 public value; // Slot 2 function setValue(uint256 _value) external { // Executes in Proxy's context // msg.sender = original caller (preserved!) // storage modifications affect Proxy storage value = _value; } function getValue() external view returns (uint256) { // Reads from Proxy's storage return value; }}
Library Contract
// Library with reusable logiclibrary SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "Overflow"); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "Overflow"); return c; }}// Using library via DELEGATECALLcontract Calculator { using SafeMath for uint256; function calculate(uint256 a, uint256 b) external pure returns (uint256) { // Compiler generates DELEGATECALL to SafeMath return a.add(b).mul(2); }}
Upgradeable Storage Pattern
// Eternal storage patterncontract EternalStorage { mapping(bytes32 => uint256) uintStorage; mapping(bytes32 => address) addressStorage; function getUint(bytes32 key) external view returns (uint256) { return uintStorage[key]; } function setUint(bytes32 key, uint256 value) external { uintStorage[key] = value; }}contract LogicV1 { EternalStorage public store; function setValue(uint256 value) external { // Store via delegatecall-safe pattern store.setUint(keccak256("myValue"), value); } function getValue() external view returns (uint256) { return store.getUint(keccak256("myValue")); }}contract LogicV2 { EternalStorage public store; // Upgraded logic with new features function setValue(uint256 value) external { require(value > 0, "Must be positive"); store.setUint(keccak256("myValue"), value * 2); } function getValue() external view returns (uint256) { return store.getUint(keccak256("myValue")); }}
Gas Cost
Total cost: 700 + cold_access + memory_expansion + forwarded_gas
Base Cost: 700 gas (Tangerine Whistle+)
Pre-Tangerine Whistle: 40 gas
No Value Transfer Cost
DELEGATECALL never transfers value - preserves msg.value:
// No CallValueTransferGas// No CallNewAccountGas
Cold Access: +2,600 gas (Berlin+)
EIP-2929 (Berlin+): First access to target address:
// VULNERABLE: Library can selfdestructcontract MaliciousLibrary { function destroy() external { selfdestruct(payable(msg.sender)); // Destroys PROXY, not library! }}// MITIGATION: Never SELFDESTRUCT in delegatecalled code// Or use EIP-6780 (Cancun+) which limits SELFDESTRUCT
Function Selector Collision
Different functions with same selector can cause unexpected behavior:
// VULNERABLE: Selector collisioncontract Implementation { // collides_uint256(uint256) and burn(uint256) have same selector! function collides_uint256(uint256) external { } function burn(uint256) external { }}// MITIGATION: Check for collisions, use namespaced selectors
Delegate to Untrusted Contract
Only DELEGATECALL to trusted, audited code:
// VULNERABLE: User-controlled delegatecallcontract Vulnerable { function proxyCall(address target, bytes memory data) external { // User controls target - CAN EXECUTE ARBITRARY CODE! target.delegatecall(data); }}// SAFE: Whitelist allowed targetscontract Safe { mapping(address => bool) public allowed; function proxyCall(address target, bytes memory data) external { require(allowed[target], "Target not allowed"); target.delegatecall(data); }}