Last active
September 20, 2020 18:18
-
-
Save mudgen/f3b8418371982ddc4091cc43a09f4daa to your computer and use it in GitHub Desktop.
Example showing how to use DELEGATECALL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Author: Nick Mudge (https://twitter.com/mudgen) | |
// This is part of my tweet thread, "Six things you need to know to use DELEGATECALL safely": https://twitter.com/mudgen | |
// Shows how to use DELEGATECALL | |
// Using OpenZeppelin's Address library check to see if | |
// myContract has code. | |
require(Address.isContract(myContractAddress), "Address has no code"); | |
// Set function argument we are going to use. | |
uint myArg = 10; | |
// Create the function call with argument. | |
bytes memory functionCall = abi.encodeWithSignature("myFunction(uint256)", myArg); | |
// Execute delegatecall | |
( | |
bool success, | |
bytes memory result | |
) = myContractAddress.delegatecall(functionCall); | |
// If the function call succeeded | |
if(success) { | |
// We know that "myFunction" returns an | |
// uint256 so we decode it and return it. | |
return abi.decode(result, (uint256)); | |
} | |
else { | |
// If function did not succeed then revert with | |
// error message if there is one. | |
if (result.length > 0) { | |
// bubble up the error | |
revert(string(result)); | |
} else { | |
revert("myFunction had an error"); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment