主页 > imtoken限制中国用户该咋办 > 以太坊合约地址是如何计算的? (附源码实现)
以太坊合约地址是如何计算的? (附源码实现)
imtoken限制中国用户该咋办 2023-08-10 05:09:35
Uniswap交易对地址是如何计算的
背景
在Uniswap源码中以太坊开源代码链接,可以看到工厂合约UniswapV2 Factory中的createPair方法以太坊开源代码链接,使用create2,提前知道配对合约地址,参考:
以后路由合约获取配对合约地址时,不需要再从工厂合约中获取。 通过pairFor方法和Token地址获取。 参考:
它是如何实施的? 你可以通过查看下面的solidity源代码来理解它。
完成
pragma solidity ^0.8;
contract Factory{
event Deployed(address addr,uint256 salt);
// 得到将要部署的合约的bytecode
function getBytecode(address _owner,uint _foo) public pure returns(bytes memory){
bytes memory bytecode= type(TestContract).creationCode;
return abi.encodePacked(bytecode,abi.encode(_owner,_foo));
}
// 2.计算合约的地址
// keccak256(0xff + sender.Address + salt + keccak256(getBytecode))
// 得到最后20bytes
function getAddress(bytes memory bytecode,uint _salt) public view returns(address){
bytes32 hash = keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
_salt,
keccak256(bytecode)
)
);
return address(uint160(uint256(hash)));
}
// 3 部署合约
function deploy(bytes memory bytecode,uint _salt) public payable{
address addr;
/*
how to call create
create2(v,p,n,s)
v amount of eth to send
p pointer to start of code in memory
n size of code
s salt
*/
assembly {
addr := create2(
// weisent with current call
callvalue(),
add(bytecode,0x20),
mload(bytecode),
_salt
)
}
emit Deployed(addr,_salt);
}
}
contract TestContract{
address public owner;
uint public foo;
constructor(address _owner,uint _foo) payable{
owner =_owner;
foo= _foo;
}
function getBalance() public view returns(uint){
return address(this).balance;
}
}
在remix中部署,首先调用getBytecode获取字节码,然后通过字节码和_salt随机获取地址。
测试
通过点击deploy方法,触发Deployed事件,可以看到两者的地址是一致的。
通过地址获取TestContract合约
本文参与登联社区写作激励计划,好文章好收益,欢迎正在阅读的你加入。