[Ethereum] Call swapExactETHForTokens from contract and pay with contract balance

contract-developmentdefipancakeswapswapsuniswap

I am starting to learn solidity so this is probably a very basic question, but I couldn't find enough clarification only.

My goal is to purchase a token on PancakeSwap/UniSwap using the ETH balance of my smart contract. The contract has enough ETH balance for the swap.

If possible I want to swap this ETH for some TokenA, instead of having to use WETH, as I think this would be easier since I can selfdestruct and recover all my funds with easy if I don't have any tokens.

I am attempting to call swapExactETHForTokens of the router as follows:

    function swap() public {
        uint deadline = block.timestamp + 100;
        address[] memory path = new address[](2);
        path[0] = address(WBNB);
        path[1] = address(target);
        pancakeRouter.swapExactETHForTokens(0, path, owner, deadline);
    }

The problem is that I do not have enough funds, which makes sense since I have not specified the amount of ETH I want to trade. I think I could solve this by making this function payable and sending the amount of ETH I want to trade. (https://uniswap.org/docs/v2/smart-contracts/router02/)

However, this is not what I want to achieve. I would like to use the balance of the contract to perform this transaction. What would be the easiest / fastest / less gas intensive way to achieve this?

Thanks.

Edit:

I think I did not stress enough the need to use the contract balance as funds. I know the intended usage would be to send the ETH with the tx and not send any ETH to the contract directly.

Why do I want to use the funds in the SC instead? because this way I can, for instance, send 100 tx to this contract that execute this swap call, and only one of them will run successfully, since the funs are limited. So I guess I should swap for WBNB then?

Best Answer

You should be able to achieve that if you send the ether along the function call. In solc v0.8 you achieve that using the function call options {value: amount}.

The resulting function should look like this:

function swap() public {
    uint deadline = block.timestamp + 100;
    address[] memory path = new address[](2);
    path[0] = address(WBNB);
    path[1] = address(target);

    // Send all balance
    uint256 amount = address(this).balance;

    // TODO: Check the result
    pancakeRouter.swapExactETHForTokens{value: amount}(0, path, owner, deadline);
}
Related Topic