Skip to content

Instantly share code, notes, and snippets.

@cwhinfrey
Last active July 9, 2023 17:02
Show Gist options
  • Save cwhinfrey/91f63c4f0471308f63d7657f8339062e to your computer and use it in GitHub Desktop.
Save cwhinfrey/91f63c4f0471308f63d7657f8339062e to your computer and use it in GitHub Desktop.
SafeERC20 with safeIncreaseAllowance and safeDecreaseAllowance
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
)
internal
{
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment