问题描述
我刚刚开始使用 ETH 和 BSC 构建代币,这是我在许多合约中看到的一个声明。 在 Constructor 方法中,Uniswap 路由器可能与 V2 版本一致。这个有什么用?
constructor () public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this),_uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
为什么需要这个初始化?这是什么功能?
感谢有人能提供帮助。
谢谢
解决方法
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);
这一行初始化了一个指向 0x10ED...
地址的指针,并期望合约(部署在 0x10ED...
地址处)实现 IUniswapV2Router02
接口。
接口是在调用者合约源代码的某处定义的。
它允许您执行和调用接口定义的函数,而不是构建低级调用。它还允许您使用返回的数据类型而不是解析返回的二进制文件。
示例:
pragma solidity ^0.8.5;
interface IRemote {
function foo() external view returns (bool);
}
contract MyContract {
IRemote remote;
constructor() {
remote = IRemote(address(0x123));
}
function getFoo() external view returns (bool) {
bool returnedValue = remote.foo();
return returnedValue;
}
}