Solidity – How to Retrieve Amount of Tokens Received from 0x Swap

0xsolidity

I was wondering if there is any way to get the amount of tokens received from an on-chain swap inside of a smart contract (solidity)? Or is that data inside of the swap calldata? If so, how can that be extracted from the bytes32 calldata inside of solidity?

I'm using this function for swapping with 0x and it works, but I want to know the amount of tokens received from the swap.

//swap function
    function swapTokens(
        // amount to swap -- for approve function
        uint256 amount,
        // // The `sellTokenAddress` field from the API response.
        IERC20 sellToken,
        // // The `buyTokenAddress` field from the API response.
        // IERC20 buyToken,
        // // The `allowanceTarget` field from the API response.
        //address spender,
        // The `data` field from the API response.
        bytes calldata swapCallData // Must attach ETH equal to the `value` field from the API response.
    ) internal {
        // Give `spender` an infinite allowance to spend this contract's `sellToken`.
        // Note that for some tokens (e.g., USDT, KNC), you must first reset any existing
        // allowance to 0 before being able to update it.
        require(sellToken.approve(swapTargetAddress, 0), "approve to 0 failed");
        require(sellToken.approve(swapTargetAddress, amount), "approve failed");

        // Call the encoded swap function call on the contract at `swapTarget`,
        // passing along any ETH attached to this function call to cover protocol fees.
        (bool success, ) = swapTargetAddress.call(swapCallData);
        require(success, "SWAP_CALL_FAILED");
        // Refund any unspent protocol fees to the sender.
        //msg.sender.transfer(address(this).balance);

        // ...
    }

Best Answer

After some thorough research, I have come to an answer myself. The 0x swap calldata does not hold the amount that is going to be received. In fact, there is no way to retrieve the amount of tokens received before the actual swap has been executed.

A workaround for this problem would be to track the token balance before and after the swap, and then take the difference of that.

Related Topic