Last active
January 3, 2023 16:04
-
-
Save voith/aebe4dba131241070edf808e244306f8 to your computer and use it in GitHub Desktop.
Pre compute contract address using foundry.
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
// SPDX-License-Identifier: MIT | |
pragma solidity 0.7.5; | |
import "forge-std/Test.sol"; | |
contract Greeter { | |
string greeting; | |
constructor(string memory _greeting) { | |
greeting = _greeting; | |
} | |
function greet() public view returns (string memory) { | |
return greeting; | |
} | |
function setGreeting(string memory _greeting) public virtual { | |
greeting = _greeting; | |
} | |
} | |
contract ComputeAddress is Test { | |
address user = address(0x1); | |
function computeAddress(address _sender) internal returns (address _address) { | |
bytes memory data; | |
uint _nonce = vm.getNonce(_sender); | |
if(_nonce == 0x00) { | |
data = abi.encodePacked( | |
bytes1(0xd6), bytes1(0x94), _sender, bytes1(0x80) | |
); | |
} | |
else if(_nonce <= 0x7f) { | |
data = abi.encodePacked( | |
bytes1(0xd6), bytes1(0x94), _sender, uint8(_nonce) | |
); | |
} | |
else if(_nonce <= 0xff) { | |
data = abi.encodePacked( | |
bytes1(0xd7), bytes1(0x94), _sender, bytes1(0x81), uint8(_nonce) | |
); | |
} | |
else if(_nonce <= 0xffff) { | |
data = abi.encodePacked( | |
bytes1(0xd8), bytes1(0x94), _sender, bytes1(0x82), uint16(_nonce) | |
); | |
} | |
else if(_nonce <= 0xffffff) { | |
data = abi.encodePacked( | |
bytes1(0xd9), bytes1(0x94), _sender, bytes1(0x83), uint24(_nonce) | |
); | |
} | |
else { | |
data = abi.encodePacked( | |
bytes1(0xda), bytes1(0x94), _sender, bytes1(0x84), uint32(_nonce) | |
); | |
} | |
bytes32 hash = keccak256(data); | |
assembly { | |
mstore(0, hash) | |
_address := mload(0) | |
} | |
} | |
function testAddress() external { | |
address computedAddress = computeAddress(user); | |
vm.startPrank(user); | |
Greeter greet = new Greeter("Initial Message"); | |
assertEq(computedAddress, address(greet)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment