Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created November 17, 2018 06:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miguelmota/c9102d370a3c1891dbd23e821be82ae2 to your computer and use it in GitHub Desktop.
Save miguelmota/c9102d370a3c1891dbd23e821be82ae2 to your computer and use it in GitHub Desktop.
JavaScript build ethereum create2 address (counterfactual smart contract address)
function buildCreate2Address(creatorAddress, saltHex, byteCode) {
const parts = [
'ff',
creatorAddress.slice(2),
saltHex.slice(2),
web3.utils.sha3(byteCode).slice(2),
]
const partsHash = web3.utils.sha3(`0x${parts.join('')}`)
return `0x${partsHash.slice(-40)}`.toLowerCase()
}
function numberToUint256(value) {
try {
const hex = value.toString(16)
return `0x${'0'.repeat(64 - hex.length)}${hex}`
} catch (err) {}
return null
}
const {bytecode} = require('./build/contracts/Channel.json')
const creatorAddress = '0xc776E37126Bc5fa0e12e775416bB59E4884F8B2f'
const salt = 1
const contractAddress = buildCreate2Address(
creatorAddress,
numberToUint256(salt),
bytecode,
)
console.log(contractAddress) // 0x3ecba4f4fb671afef7fd2489923dc3b60fc3853a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment