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