Skip to content

Instantly share code, notes, and snippets.

@cwhinfrey
Created July 8, 2019 01:19
Show Gist options
  • Save cwhinfrey/1d234fbf00ef71e13b29b1d843068548 to your computer and use it in GitHub Desktop.
Save cwhinfrey/1d234fbf00ef71e13b29b1d843068548 to your computer and use it in GitHub Desktop.
Create2 Library
/**
* @title Create2
*
* @dev Utility library for deploying contracts with the CREATE2 EVM opcode and
* computing the contract address of CREATE2 deployments
*/
library Create2 {
/**
* @dev Function to compute the address of a contract created with CREATE2.
* @param _salt The salt used to the contract address computation
* @param _code The bytecode of the contract to be deployed
* @return the computed address of the smart contract.
*/
function computeAddress(
bytes32 _salt, bytes memory _code
) internal view returns (address) {
bytes32 codeHash = keccak256(_code);
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), address(this), _salt, codeHash)
);
return address(bytes20(_data << 96));
}
/**
* @dev Deploy contract with CREATE2
* @param _salt The salt used to the contract address computation
* @param _code The bytecode of of the contract to be deployed
*/
function deploy(
bytes32 _salt, bytes memory _code
) internal returns(address) {
address _addr;
// solhint-disable-next-line no-inline-assembly
assembly {
_addr := create2(0, add(_code, 0x20), mload(_code), _salt)
if iszero(_addr) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
return _addr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment