WETH to ETH – How to Convert WETH Back to ETH in Solidity

contract-developmentcontract-invocationsolidityuniswapwrapped-tokens

I am trying to convert back WETH into ETH (actually BNB on BSC). I am doing the following:

    function allToBNB() public{
        WETH.transfer(address(this), WETH.balanceOf(address(this)));
    }`

In my constructor I defined WETH:

    IWETH private WETH;

    constructor() public{
        pancakeRouter = PancakeRouter(PANCAKESWAP_ROUTER_ADDRESS);
        WETH = IWETH(pancakeRouter.WETH());
        require(WETH.approve(address(pancakeRouter), 115792089237316195423570985008687907853269984665640564039457584007913129639935), 'approve failed.');
    }
    

And the interface for WETH is:

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function approve(address spender, uint value) external returns (bool);
    function balanceOf(address owner) external view returns (uint);
}

However, when I call allToBNB, I see a self transfer of all my WBNB balance to myself (the contract) instead of it unwrapping back into BNB (https://testnet.bscscan.com/tx/0x60be76d6c0574ad549e98c678eb8ea9e668d96192926a9e71995ff69be0f863d).

Maybe I need to call the withdraw function? but this seems to use the msg.address instead of the contract address for the return.

What am I doing wrong? Thanks.

Best Answer

In order to convert WBNB to BNB you have to call withdraw from WBNB contract

function withdraw(uint wad) public {
    require(balanceOf[msg.sender] >= wad);
    balanceOf[msg.sender] -= wad;
    msg.sender.transfer(wad);
    Withdrawal(msg.sender, wad);
}
Related Topic