I wrote the solidity function below to swap ether for other tokens on a Uniswap exchange. It works.

function buyCryptoOnUniswap1(uint256 etherCost , address cryptoToken) public payable returns (uint256) {

  IUniswapV2Router02 usi = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
   if(etherCost > address(this).balance){
          return 0;
    uint deadline = now + 300; // using 'now' for convenience, for mainnet pass deadline from frontend!
    uint[] memory amounts = usi.swapExactETHForTokens.value(etherCost)(0, getPathForETHToToken(cryptoToken), address(this), deadline);
    uint256 outputTokenCount = uint256(amounts[1]);
    return outputTokenCount;

  function getPathForETHToToken(address crypto) private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = usi.WETH();
    path[1] = crypto;
    return path;

According to the docs, the returned value called amounts is an array of uints which consists of the input token amount and all subsequent output token amounts.

amounts, uint[] memory, The input token amount and all subsequent output token amounts.

So I hazarded a guess as to it(the number of purchased tokens) been in index 1 of the return value.

Please how do I get the number of tokens returned by this transaction?

Sorry, but it doesn't seem so clear from the documentation..



It is obviously the amount of the last token in the path, i.e., amounts[amounts.length - 1].

  • Thanks. I wanted to be sure, so that I would not be surprised in production. Thanks again – gbenroscience Jul 4 '20 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.