Example foundry project demonstrating how to change the bytecode of a deployed contract. This example is heavily inspired by this excellent talk.
The "trick" to change bytecode of a deployed contract consists of combining a selfdestruct
call on the original implementation and then redeploying different bytecode to the same address using CREATE2
.
- Contract whose constructor returns bytecode loaded from another contract, instead of its own compiled source code. Choice.sol
- Contract that can control the bytecode to be deployed in storage and creates an instance of above mentioned contract with
CREATE2
- Implementations that contain a
selfdestruct
call. (ContractV1,ContractV2)
- Deploy
Overwrite.sol
contract. (DeployDependencies.sol) - Call
Overwrite
contract and set the code to be deployed to the first version.(SetCode.sol) - Call
Overwrite
contract and deploy contract with givensalt
value. (CreateInstance.sol) - Call selfdestruct method on the deployed instance (DestroyInstance.sol)
- Repeat step 2 with the new bytecode
- Repeat step 3 using the same
salt
value
The best source of documentation is the foundry-book which contains chapters on all elements of the framework.
- Install
foundryup
tool by runningcurl -L https://foundry.paradigm.xyz | bash
- Install / Update foundry with
foundryup
forge install
forge test