Skip to content

Instantly share code, notes, and snippets.

@mudgen
Last active September 20, 2020 18:18
Show Gist options
  • Save mudgen/f3b8418371982ddc4091cc43a09f4daa to your computer and use it in GitHub Desktop.
Save mudgen/f3b8418371982ddc4091cc43a09f4daa to your computer and use it in GitHub Desktop.
Example showing how to use DELEGATECALL
// 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