SafeERC20.sol 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. pragma solidity ^0.5.2;
  2. import "./IERC20.sol";
  3. import "../../math/SafeMath.sol";
  4. /**
  5. * @title SafeERC20
  6. * @dev Wrappers around ERC20 operations that throw on failure.
  7. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
  8. * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
  9. */
  10. library SafeERC20 {
  11. using SafeMath for uint256;
  12. function safeTransfer(IERC20 token, address to, uint256 value) internal {
  13. require(token.transfer(to, value));
  14. }
  15. function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
  16. require(token.transferFrom(from, to, value));
  17. }
  18. function safeApprove(IERC20 token, address spender, uint256 value) internal {
  19. // safeApprove should only be called when setting an initial allowance,
  20. // or when resetting it to zero. To increase and decrease it, use
  21. // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
  22. require((value == 0) || (token.allowance(address(this), spender) == 0));
  23. require(token.approve(spender, value));
  24. }
  25. function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
  26. uint256 newAllowance = token.allowance(address(this), spender).add(value);
  27. require(token.approve(spender, newAllowance));
  28. }
  29. function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
  30. uint256 newAllowance = token.allowance(address(this), spender).sub(value);
  31. require(token.approve(spender, newAllowance));
  32. }
  33. }