1

I've written the following function which swaps DAI back to WETH and then withdraws the WETH and returns the Ether.

After running the function on REMIX I've got the Ether on the contract balance as I want to have it, but I do not understand why. I should be happy, but when I look at the implementation of the WETH9 withdraw function it looks like the Ether should be sent to msg.sender. So I don't understand why it is sent to the contract balance? What am I missing?

function _returnToEth() public payable {
    require(getTokenBalance(DAI) > 0, "No funds to be redistributed");

    (bool _success, uint24 _poolFee) = _uniswapV3PoolExists(DAI, WETH);
    require(_success, "Pool does not exist");

    uint _amountIn = getTokenBalance(DAI);

    ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
      tokenIn: DAI,
      tokenOut: WETH,
      fee: _poolFee,
      recipient: address(this),
      deadline: block.timestamp + 15,
      amountIn: _amountIn,
      amountOutMinimum: 1,
      sqrtPriceLimitX96: 0
    });

    // Approve the SwapRouter contract for the amount of DAI
   
    IERC20(DAI).approve(address(SwapRouter), _amountIn);

    SwapRouter.exactInputSingle(params);
    
    // Unwrap WETH to ETH and send to this contract
    uint balanceWETH = IWETH9(WETH).balanceOf(address(this));

    IERC20(WETH).approve(address(this), balanceWETH);

    if (balanceWETH > 0) {
        IWETH9(WETH).withdraw(balanceWETH);
    }

1 Answer 1

0

When you execute IWETH9(WETH).withdraw(balanceWETH), your contract is calling WETH contract. So for WETH contract's context, your contract is the msg.sender. This is why the funds are getting to sent to it.

2
  • 1
    Thanks for the immediate answer. So if I call an instance of another contract it's my contract which is calling (means the "msg.sender") but if I call an internal function in my contract the "msg.sender" is the calling account ? Jan 10, 2022 at 13:12
  • Yep 👍 [need to reach minimal chars in comment] Jan 10, 2022 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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