SafeERC20.sol 9.2 KB

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