SafeERC20.sol 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. pragma solidity ^0.4.24;
  2. import "./ERC20.sol";
  3. import "./IERC20.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(
  13. IERC20 token,
  14. address to,
  15. uint256 value
  16. )
  17. internal
  18. {
  19. require(token.transfer(to, value));
  20. }
  21. function safeTransferFrom(
  22. IERC20 token,
  23. address from,
  24. address to,
  25. uint256 value
  26. )
  27. internal
  28. {
  29. require(token.transferFrom(from, to, value));
  30. }
  31. function safeApprove(
  32. IERC20 token,
  33. address spender,
  34. uint256 value
  35. )
  36. internal
  37. {
  38. // safeApprove should only be called when setting an initial allowance,
  39. // or when resetting it to zero. To increase and decrease it, use
  40. // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
  41. require((value == 0) || (token.allowance(msg.sender, spender) == 0));
  42. require(token.approve(spender, value));
  43. }
  44. function safeIncreaseAllowance(
  45. IERC20 token,
  46. address spender,
  47. uint256 value
  48. )
  49. internal
  50. {
  51. uint256 newAllowance = token.allowance(address(this), spender).add(value);
  52. require(token.approve(spender, newAllowance));
  53. }
  54. function safeDecreaseAllowance(
  55. IERC20 token,
  56. address spender,
  57. uint256 value
  58. )
  59. internal
  60. {
  61. uint256 newAllowance = token.allowance(address(this), spender).sub(value);
  62. require(token.approve(spender, newAllowance));
  63. }
  64. }