Uniswap Solidity – Determine Tokens Bought with swapExactETHForTokens

solidityuniswap

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..

Thanks

Best Answer

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

Related Topic