一次交换多个令牌

Swap multiple tokens at once

我有以下代码可以将 ETH(或 BNB 在 BSC 测试网上的情况下)换成特定代币:

pragma solidity 0.7.1;

import "https://github.com/pancakeswap/pancake-swap-periphery/blob/master/contracts/interfaces/IPancakeRouter02.sol";



contract UniswapExample {
  address internal constant UNISWAP_ROUTER_ADDRESS = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 ; //Router for pancake

  IPancakeRouter02 public uniswapRouter;
  
   //Store addresses
  //address[] tokens = new address[](2);
  
  //address private usdt = 0x7ef95a0FEE0Dd31b22626fA2e10Ee6A223F8a684;
  //address private busd = 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7;
  //address private dai = 0x8a9424745056Eb399FD19a0EC26A14316684e274;
 
  address private crypto1 = 0x7ef95a0FEE0Dd31b22626fA2e10Ee6A223F8a684;
  address private crypto2 = 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7;
  address private crypto3 = 0x8a9424745056Eb399FD19a0EC26A14316684e274;
  
  //uint totalSum;

  constructor() {
    uniswapRouter = IPancakeRouter02(UNISWAP_ROUTER_ADDRESS);
    
  }
  
  function convertEthToCrypto(uint cryptoAmount) public payable {
    uint deadline = block.timestamp + 15; // using 'now' for convenience, for mainnet pass deadline from frontend!
    uniswapRouter.swapETHForExactTokens{ value: msg.value }(cryptoAmount, getPathForETH(crypto1), address(this), deadline);
    
    // refund leftover ETH to user
    (bool success,) = msg.sender.call{ value: address(this).balance }("");
    require(success, "refund failed");
  }
                 
  function getPathForETH(address crypto) public view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = uniswapRouter.WETH();
    path[1] = crypto;
    
    return path;
  }
  
  
  function getETH() public view returns(address) {
      return uniswapRouter.WETH();
  }
  
  // important to receive ETH
  receive() payable external {}
}

这里convertEthToCrypto交换一个令牌,是一个支付功能。所以在 Remix 中我输入了特定数量的 WEI,函数交换了令牌。

但是我如何设法一次交换多个令牌?

如果我是你,我会使用 swapExactTokensForTokens 并根据需要调用它。 您甚至可以创建一个循环来管理,如果您有许多密码要交换,或者如果它始终相同,则对调用进行硬编码。 这是 DAI 和 USDT 的简单示例。 您可以用变量替换代码并根据需要使用循环。

address[] memory path = new address[](2);
path[0] = address(DAI);
path[1] = address(USDT);
UniswapV2Router02.swapExactTokensForTokens(amountIn, amountOutMin, path, msg.sender, block.timestamp);