0

在关于 uniswapv2router 的实现中,uniswapv2router.WETH() 返回规范的 WETH 地址。我想知道它是如何返回 WETH 地址的。我知道的一件事是,在 uniwapv2router.sol 代码中,构造函数设置了WETH值。但是,在下面的示例中,我看不到uniswapRouter. 抱歉新手问题!

pragma solidity 0.7.1;

import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol";

contract UniswapExample {
  address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ;

  IUniswapV2Router02 public uniswapRouter;
  address private multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;

  constructor() {
    uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
  }

  function convertEthToDai(uint daiAmount) public payable {
    uint deadline = block.timestamp + 15; // using 'now' for convenience, for mainnet pass deadline from frontend!
    uniswapRouter.swapETHForExactTokens{ value: msg.value }(daiAmount, getPathForETHtoDAI(), address(this), deadline);
    
    // refund leftover ETH to user
    (bool success,) = msg.sender.call{ value: address(this).balance }("");
    require(success, "refund failed");
  }
  
  function getEstimatedETHforDAI(uint daiAmount) public view returns (uint[] memory) {
    return uniswapRouter.getAmountsIn(daiAmount, getPathForETHtoDAI());
  }

  function getPathForETHtoDAI() private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = uniswapRouter.WETH();
    path[1] = multiDaiKovan;
    
    return path;
  }
  
  // important to receive ETH
  receive() payable external {}
}
4

1 回答 1

0
uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);

该片段初始化一个指向部署在指定地址 ( UNISWAP_ROUTER_ADDRESS) 上的合约的指针,假设它实现了IUniswapV2Router02接口。

如果你想部署指定的合约,你需要使用new关键字:

// can't deploy an interface, needs to be a contract
UniswapV2Router02 newlyDeployedRouter = new UniswapV2Router02(
    // constructor params
    factoryAddress,
    wethAddress
);
于 2022-01-08T14:42:37.533 回答