【发布时间】: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