【问题标题】:Swap multiple tokens at once一次交换多个代币
【发布时间】:2021-11-13 23:22:27
【问题描述】:

我有以下代码可以将 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,然后函数会交换令牌。

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

【问题讨论】:

  • 尝试测试您的代码,但它对我不起作用。在“cryptoAmount”中,我输入了 0.001,但出现错误:向 UniswapExample.convertEthToCrypto 交易错误:错误编码参数:错误:无效的 BigNumber 字符串(argument="value" value="0.001" code=INVALID_ARGUMENT version=bignumber/5.5。 0)。请帮忙

标签: ethereum solidity binance-smart-chain


【解决方案1】:

如果我是你,我会使用 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);

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 2012-11-15
    • 2020-01-23
    • 2022-07-22
    • 2021-10-26
    • 2022-07-29
    • 2022-08-13
    • 2016-10-04
    相关资源
    最近更新 更多