Skip to content

Instantly share code, notes, and snippets.

@voith
Created January 3, 2023 16:20
Show Gist options
  • Save voith/2c2140fe4c6f20ccedbf5c7273a79698 to your computer and use it in GitHub Desktop.
Save voith/2c2140fe4c6f20ccedbf5c7273a79698 to your computer and use it in GitHub Desktop.
Pre compute address while deploying contracts with foundry
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.5;
import "forge-std/Script.sol";
import "forge-std/console.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 Deploy is Script {
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 run() external {
uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
address addr = vm.addr(deployerPrivateKey);
console.logAddress(addr);
console.logAddress(computeAddress(addr));
vm.startBroadcast(deployerPrivateKey);
Greeter greet = new Greeter("Initial Message");
vm.stopBroadcast();
console.logAddress(address(greet));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment