SafeERC20.sol 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)
  3. pragma solidity ^0.8.20;
  4. import {IERC20} from "../IERC20.sol";
  5. import {IERC1363} from "../../../interfaces/IERC1363.sol";
  6. /**
  7. * @title SafeERC20
  8. * @dev Wrappers around ERC-20 operations that throw on failure (when the token
  9. * contract returns false). Tokens that return no value (and instead revert or
  10. * throw on failure) are also supported, non-reverting calls are assumed to be
  11. * successful.
  12. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
  13. * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
  14. */
  15. library SafeERC20 {
  16. /**
  17. * @dev An operation with an ERC-20 token failed.
  18. */
  19. error SafeERC20FailedOperation(address token);
  20. /**
  21. * @dev Indicates a failed `decreaseAllowance` request.
  22. */
  23. error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
  24. /**
  25. * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
  26. * non-reverting calls are assumed to be successful.
  27. */
  28. function safeTransfer(IERC20 token, address to, uint256 value) internal {
  29. _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
  30. }
  31. /**
  32. * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
  33. * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
  34. */
  35. function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
  36. _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
  37. }
  38. /**
  39. * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
  40. * non-reverting calls are assumed to be successful.
  41. *
  42. * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
  43. * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
  44. * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
  45. * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
  46. */
  47. function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
  48. uint256 oldAllowance = token.allowance(address(this), spender);
  49. forceApprove(token, spender, oldAllowance + value);
  50. }
  51. /**
  52. * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
  53. * value, non-reverting calls are assumed to be successful.
  54. *
  55. * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
  56. * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
  57. * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
  58. * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
  59. */
  60. function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
  61. unchecked {
  62. uint256 currentAllowance = token.allowance(address(this), spender);
  63. if (currentAllowance < requestedDecrease) {
  64. revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
  65. }
  66. forceApprove(token, spender, currentAllowance - requestedDecrease);
  67. }
  68. }
  69. /**
  70. * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
  71. * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
  72. * to be set to zero before setting it to a non-zero value, such as USDT.
  73. *
  74. * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
  75. * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
  76. * set here.
  77. */
  78. function forceApprove(IERC20 token, address spender, uint256 value) internal {
  79. bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
  80. if (!_callOptionalReturnBool(token, approvalCall)) {
  81. _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
  82. _callOptionalReturn(token, approvalCall);
  83. }
  84. }
  85. /**
  86. * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
  87. * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
  88. * targeting contracts.
  89. *
  90. * Reverts if the returned value is other than `true`.
  91. */
  92. function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
  93. if (to.code.length == 0) {
  94. safeTransfer(token, to, value);
  95. } else if (!token.transferAndCall(to, value, data)) {
  96. revert SafeERC20FailedOperation(address(token));
  97. }
  98. }
  99. /**
  100. * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
  101. * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
  102. * targeting contracts.
  103. *
  104. * Reverts if the returned value is other than `true`.
  105. */
  106. function transferFromAndCallRelaxed(
  107. IERC1363 token,
  108. address from,
  109. address to,
  110. uint256 value,
  111. bytes memory data
  112. ) internal {
  113. if (to.code.length == 0) {
  114. safeTransferFrom(token, from, to, value);
  115. } else if (!token.transferFromAndCall(from, to, value, data)) {
  116. revert SafeERC20FailedOperation(address(token));
  117. }
  118. }
  119. /**
  120. * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
  121. * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
  122. * targeting contracts.
  123. *
  124. * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
  125. * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
  126. * once without retrying, and relies on the returned value to be true.
  127. *
  128. * Reverts if the returned value is other than `true`.
  129. */
  130. function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
  131. if (to.code.length == 0) {
  132. forceApprove(token, to, value);
  133. } else if (!token.approveAndCall(to, value, data)) {
  134. revert SafeERC20FailedOperation(address(token));
  135. }
  136. }
  137. /**
  138. * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
  139. * on the return value: the return value is optional (but if data is returned, it must not be false).
  140. * @param token The token targeted by the call.
  141. * @param data The call data (encoded using abi.encode or one of its variants).
  142. *
  143. * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
  144. */
  145. function _callOptionalReturn(IERC20 token, bytes memory data) private {
  146. uint256 returnSize;
  147. uint256 returnValue;
  148. assembly ("memory-safe") {
  149. let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
  150. // bubble errors
  151. if iszero(success) {
  152. let ptr := mload(0x40)
  153. returndatacopy(ptr, 0, returndatasize())
  154. revert(ptr, returndatasize())
  155. }
  156. returnSize := returndatasize()
  157. returnValue := mload(0)
  158. }
  159. if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
  160. revert SafeERC20FailedOperation(address(token));
  161. }
  162. }
  163. /**
  164. * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
  165. * on the return value: the return value is optional (but if data is returned, it must not be false).
  166. * @param token The token targeted by the call.
  167. * @param data The call data (encoded using abi.encode or one of its variants).
  168. *
  169. * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
  170. */
  171. function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
  172. bool success;
  173. uint256 returnSize;
  174. uint256 returnValue;
  175. assembly ("memory-safe") {
  176. success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
  177. returnSize := returndatasize()
  178. returnValue := mload(0)
  179. }
  180. return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
  181. }
  182. }