在编写同一个 sol 文件,已经导入了 uniswapfactroy 和 uniswapexchange 的接口文件,接下来新建一个 util 文件完成 ethToTokenSwapInput,代码如下
contract UniswapUtils {
// ropsten testnet
address public constant UNISWAP_FACTORY_ADDRESS = 0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351;
// DAI address
address public constant DAI_ADDRESS = 0xaD6D458402F60fD3Bd25163575031ACDce07538D;
function getUniswapExchange(address _tokenAddress)
public
view
returns (address)
{
return
IUniswapFactory(UNISWAP_FACTORY_ADDRESS).getExchange(_tokenAddress);
}
/**
* @dev ETH=>DAI
* @param _ethAmount amount of ETH sold
* @return Amount of DAI bought
*/
function ethToDai(uint256 _ethAmount)
public
returns (uint256)
{
return ethToDai(_ethAmount, uint256(1));
}
/**
* @dev ETH=>DAI
* @param _ethAmount amount of ETH sold
* @param _minTokenAmount minimum DAI bought
* @return Amount of DAI bought
*/
function ethToDai(uint256 _ethAmount, uint256 _minTokenAmount)
public
returns (uint256)
{
IUniswapExchange uniswapExchange=IUniswapExchange(getUniswapExchange(DAI_ADDRESS));
return uniswapExchange.ethToTokenSwapInput.value(_ethAmount)(_minTokenAmount, uint256(now + 60));
}
}
在remix上测试ethtoDai(),显示错误,错误原因如下: https://ropsten.etherscan.io/tx/0xe2d3af02a85a1135c88d33d4f94e98dcf1825fa9ffb6b48388d3d970ab380051