Goober117
Goober117

Reputation: 51

How to Pre-Generate an Ethereum Contract Adress

I'm trying to generate the address of a contract before its deployed. This is my code, using Web3.py:

sender = w3.eth.default_account
expected_address = w3.keccak(rlp.encode([sender, 0]))[12:]
print("Expected address:")
print(expected_address.hex())

But I'm not generating the same address as when I deploy the contract. sender has not yet sent a transaction, so the nonce should be zero. I saw a snippet of code using a normalize_transaction function on the sender address but I was unable to find out where to import it from, is that what I'm missing?

Upvotes: 0

Views: 941

Answers (1)

bguiz
bguiz

Reputation: 28627

  • CREATE uses keccak256(rlp([sender, nonce])) to work out the deployed address
  • CREATE2 uses keccak256(0xff ++ address ++ salt ++ keccak256(init_code)) to work out the deployed address

Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1014.md

Implementation using "Example 4" from EIP-1014:

from eth_utils import to_checksum_address
from web3 import Web3

pre = bytes.fromhex('ff')
address = bytes.fromhex('00000000000000000000000000000000deadbeef')
salt = bytes.fromhex('0x00000000000000000000000000000000000000000000000000000000cafebabe')
init_code_hash = Web3.keccak(bytes.fromhex('0xdeadbeef'))
result_hash = Web3.keccak(pre + address + salt + init_code_hash)
result_address = to_checksum_address(result_hash[12:].hex())

Upvotes: 2

Related Questions