SafeERC20.sol 9.8 KB

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