1
function _approveTokenIfNeeded(address token, address spender) private {
        if (IERC20(token).allowance(address(this), spender) == 0) {
            IERC20(token).safeApprove(spender, uint256(~0));
        }
    }

I found this function in a popular DeFi protocol.

uint256(~0) looks new to me.

Is this a different way of getting the largest available uint256 value? Like type(uint256).max?

The compiler version is v0.7.0+commit.9e61f92b.

1 Answer 1

3

The tilde (~) is the symbol for bitwise negation, i.e. it flips every bit of the value it operates on. In this case, yes, it's being used to essentially get type(uint256).max

You can find this operator by searching "~" on the types (specifically the Operators section) page of the Solidity Lang docs

2
  • 2
    Other flavours for max: ~uint(0) , (2**256) - 1, and my personal favourite, 115792089237316195423570985008687907853269984665640564039457584007913129639935 :-)
    – Ashraile
    Nov 15 at 20:25
  • Thank you so much!!!
    – Mila A
    Nov 16 at 11:58

Your Answer

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

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