7

SafeERC20 is not really clear to me from Openzeppelin's explanation. What makes safeERC20 better than normal ERC20? In what way is it safer?

Wrappers around ERC20 operations that throw on failure (when the token contract returns false). Tokens that return no value (and instead revert or throw on failure) are also supported, non-reverting calls are assumed to be successful. To use this library you can add a using SafeERC20 for IERC20; statement to your contract, which allows you to call the safe operations as token.safeTransfer(…​), etc.

1 Answer 1

8

SafeERC20 is a wrapper library around ERC20 calls that make safe the interaction with someone else’s ERC20 token, in your contracts. What makes SafeERC20 better than then normal ERC20 is that the former can ensure the safety of normal ERC20 function calls by checking the boolean return values of ERC20 operations and revert the transaction if they fail, at the same time allowing you to support some non-standard ERC20 tokens they don’t have boolean return values. In addition, SafeERC20 provides helpers to increase or decrease an allowance, to mitigate front-running attack that is possible with vanilla approve() of normal ERC20.

For example, the safeApprove() method:

function safeApprove(IERC20 token, address spender, uint256 value) 
    internal {
    // safeApprove should only be called when setting an initial 
    allowance,
    // or when resetting it to zero. To increase and decrease it, use
    // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
    require(
        (value == 0) || (token.allowance(address(this), spender) == 0),
        "SafeERC20: approve from non-zero to non-zero allowance"
    );
    _callOptionalReturn(token, 
    abi.encodeWithSelector(token.approve.selector, spender, value));
}

Because the approve() method of ERC20 is prone to front-running attacks, the safeApprove() method ensures that, when the current allowance is non-zero, it must be set to zero first before allowing a new allowance. This check ensures protecting the contract from unintended behavior.

See: https://soliditydeveloper.com/safe-erc20

2

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.