-
-
Save tienshaoku/0d99ea04104f2e47f6b0b25d647a0d31 to your computer and use it in GitHub Desktop.
function swapETHToDai() public payable returns(uint[] memory) { | |
// static array: address[k] memory array; | |
// The following is the dynamic array way of initialization | |
address[] memory _paths = new address[](2); | |
// Also, push() is for storage array. | |
_paths[0] = WETHAddress; | |
_paths[1] = DaiAddress; | |
return uniswapV2Router01.swapExactETHForTokens{value: msg.value}(0, _paths, msg.sender, now + 120); | |
} | |
function swapDaiForETH(uint _DaiAmount) public returns(uint[] memory) { | |
require(Dai.transferFrom(msg.sender, address(this), _DaiAmount)); | |
address[] memory _paths = new address[](2); | |
_paths[0] = DaiAddress; | |
_paths[1] = WETHAddress; | |
Dai.approve(address(uniswapV2Router01), _DaiAmount); | |
return uniswapV2Router01.swapExactTokensForETH(_DaiAmount, 0, _paths, msg.sender, now + 120); | |
} |
tienshaoku
commented
Jun 9, 2020
via email
I have indeed a question! Below you find to version of the same contract. The first one I learnt from you and the second would be a shortcut but I'm not sure whether I miss something.
pragma solidity ^0.5.0;
import "./IUniswapV2Router01.sol";
contract ExactEthForTokenV2 {
address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapV2Router01 public uniswaprouter;
constructor () public {
uniswaprouter = IUniswapV2Router01(UNISWAP_ROUTER_ADDRESS);
}
function swapETHToNBT() public payable {
address[] memory _paths = new address;
_paths[0] = WETHAddress;
_paths[1] = TokenAddress;
uniswaprouter.swapExactETHForTokens.value(msg.value)(0, _paths, address(this), now + 15);
//Question: Is there any benefit of doing it as you do:
//First, IUniswapV2Router01 public uniswaprouter;
//Second, uniswaprouter = IUniswapV2Router01(UNISWAP_ROUTER_ADDRESS);
//Third, uniswaprouter.swapExactETHForTokens.value(msg.value)(0, _paths, address(this), now + 15);
//Is it also possible to use the Interface address directly (see the last line below) to call swapExactETHForTokens.
pragma solidity ^0.5.0;
import "./IUniswapV2Router01.sol";
contract ExactEthForTokenV2 {
address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor () public {
}
function swapETHToNBT() public payable {
address[] memory _paths = new address;
_paths[0] = WETHAddress;
_paths[1] = TokenAddress;
IUniswapV2Router01(UNISWAP_ROUTER_ADDRESS).swapExactETHForTokens.value(msg.value)(0, _paths, address(this), now + 15);
Hi Shao
I figured the problem out in the meantime.
Thanks again
aleks