2

Is it possible to call Uniswap from a smart contrat and make a swap with smart contract ether, and not from the message sender ether ? (and send back the swapped token to the owner)

I tried like this on Kovan testnet but it failed :

pragma solidity ^0.8.2;
import "https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol"; 

contract Coffre{

  address owner =msg.sender;     
  
  IUniswapV2Router02 uni = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
  
  address private token_address = 0x514910771AF9Ca656af840dff83E8264EcF986CA; //chainlink
  
  function getPathForETHtoToken() private view returns (address[] memory) {
     address[] memory path = new address[](2);
     path[0] = uni.WETH();
     path[1] = token_address;
   return path;
   }
   
  function swapContractEthToLink() public {  
  uni.swapExactETHForTokens(0,getPathForETHtoToken(), owner, block.timestamp + 15);  
  }  

Also with swapExactETHForTokens I can't specify how many Eth from the contract I want to swap so it's probably not the right function

1

If you want to swap ETH for Tokens, you need to send ETH to your contract, so you are missing the payable feature in your function.

This is a code example that worked for me:

function swapExactETHforTokens(
    address tokenOut,
    uint256 amountOut,
    uint256 deadline
) external payable {
    address[] memory path = new address[](2);
    path[0] = uniswap.WETH();
    path[1] = tokenOut;

    uniswap.swapExactETHForTokens{value: msg.value}(
        amountOut,
        path,
        msg.sender,
        deadline
    );
}

As per your last remark:

Also with swapExactETHForTokens I can't specify how many Eth from the contract I want to swap so it's probably not the right function

You specify the amount of ETH by sending it when you call the payable function. Note that the function now is payable and transfers the ETH amount through {value: msg.value}

3
  • Thank you for your help. But your function spend eth from the address that call the smart contract. I want the function to spend eth that was already on the smart contract balance (filed before by another address for exemple) Do you think this is possible ?
    – Kioup
    Mar 11 '21 at 15:36
  • It is possible. Haven't tried, but I would create a payable function in the contract to receive ethers, and then you can call uniswap's function with the amount you want to transfer. For instance: uniswap.swapExactETHForTokens{value: amount} If the contract has not received any ether, the swap will fail. Mar 11 '21 at 16:49
  • Thank you for your help it works !
    – Kioup
    Mar 11 '21 at 19:32

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.