SafeERC20.sol 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. if (!_safeTransfer(token, to, value, true)) {
  30. revert SafeERC20FailedOperation(address(token));
  31. }
  32. }
  33. /**
  34. * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
  35. * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
  36. */
  37. function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
  38. if (!_safeTransferFrom(token, from, to, value, true)) {
  39. revert SafeERC20FailedOperation(address(token));
  40. }
  41. }
  42. /**
  43. * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
  44. */
  45. function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
  46. return _safeTransfer(token, to, value, false);
  47. }
  48. /**
  49. * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
  50. */
  51. function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
  52. return _safeTransferFrom(token, from, to, value, false);
  53. }
  54. /**
  55. * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
  56. * non-reverting calls are assumed to be successful.
  57. *
  58. * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
  59. * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
  60. * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
  61. * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
  62. */
  63. function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
  64. uint256 oldAllowance = token.allowance(address(this), spender);
  65. forceApprove(token, spender, oldAllowance + value);
  66. }
  67. /**
  68. * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
  69. * value, non-reverting calls are assumed to be successful.
  70. *
  71. * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
  72. * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
  73. * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
  74. * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
  75. */
  76. function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
  77. unchecked {
  78. uint256 currentAllowance = token.allowance(address(this), spender);
  79. if (currentAllowance < requestedDecrease) {
  80. revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
  81. }
  82. forceApprove(token, spender, currentAllowance - requestedDecrease);
  83. }
  84. }
  85. /**
  86. * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
  87. * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
  88. * to be set to zero before setting it to a non-zero value, such as USDT.
  89. *
  90. * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
  91. * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
  92. * set here.
  93. */
  94. function forceApprove(IERC20 token, address spender, uint256 value) internal {
  95. if (!_safeApprove(token, spender, value, false)) {
  96. if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
  97. if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
  98. }
  99. }
  100. /**
  101. * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
  102. * 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 transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
  108. if (to.code.length == 0) {
  109. safeTransfer(token, to, value);
  110. } else if (!token.transferAndCall(to, value, data)) {
  111. revert SafeERC20FailedOperation(address(token));
  112. }
  113. }
  114. /**
  115. * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
  116. * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
  117. * targeting contracts.
  118. *
  119. * Reverts if the returned value is other than `true`.
  120. */
  121. function transferFromAndCallRelaxed(
  122. IERC1363 token,
  123. address from,
  124. address to,
  125. uint256 value,
  126. bytes memory data
  127. ) internal {
  128. if (to.code.length == 0) {
  129. safeTransferFrom(token, from, to, value);
  130. } else if (!token.transferFromAndCall(from, to, value, data)) {
  131. revert SafeERC20FailedOperation(address(token));
  132. }
  133. }
  134. /**
  135. * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
  136. * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
  137. * targeting contracts.
  138. *
  139. * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
  140. * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
  141. * once without retrying, and relies on the returned value to be true.
  142. *
  143. * Reverts if the returned value is other than `true`.
  144. */
  145. function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
  146. if (to.code.length == 0) {
  147. forceApprove(token, to, value);
  148. } else if (!token.approveAndCall(to, value, data)) {
  149. revert SafeERC20FailedOperation(address(token));
  150. }
  151. }
  152. /**
  153. * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
  154. * return value is optional (but if data is returned, it must not be false).
  155. *
  156. * @param token The token targeted by the call.
  157. * @param to The recipient of the tokens
  158. * @param value The amount of token to transfer
  159. * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
  160. */
  161. function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
  162. bytes4 selector = IERC20.transfer.selector;
  163. assembly ("memory-safe") {
  164. let fmp := mload(0x40)
  165. mstore(0x00, selector)
  166. mstore(0x04, and(to, shr(96, not(0))))
  167. mstore(0x24, value)
  168. success := call(gas(), token, 0, 0, 0x44, 0, 0x20)
  169. // if call success and return is true, all is good.
  170. // otherwise (not success or return is not true), we need to perform further checks
  171. if iszero(and(success, eq(mload(0x00), 1))) {
  172. // if the call was a failure and bubble is enabled, bubble the error
  173. if and(iszero(success), bubble) {
  174. returndatacopy(fmp, 0, returndatasize())
  175. revert(fmp, returndatasize())
  176. }
  177. // if the return value is not true, then the call is only successful if:
  178. // - the token address has code
  179. // - the returndata is empty
  180. success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
  181. }
  182. mstore(0x40, fmp)
  183. }
  184. }
  185. /**
  186. * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
  187. * value: the return value is optional (but if data is returned, it must not be false).
  188. *
  189. * @param token The token targeted by the call.
  190. * @param from The sender of the tokens
  191. * @param to The recipient of the tokens
  192. * @param value The amount of token to transfer
  193. * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
  194. */
  195. function _safeTransferFrom(
  196. IERC20 token,
  197. address from,
  198. address to,
  199. uint256 value,
  200. bool bubble
  201. ) private returns (bool success) {
  202. bytes4 selector = IERC20.transferFrom.selector;
  203. assembly ("memory-safe") {
  204. let fmp := mload(0x40)
  205. mstore(0x00, selector)
  206. mstore(0x04, and(from, shr(96, not(0))))
  207. mstore(0x24, and(to, shr(96, not(0))))
  208. mstore(0x44, value)
  209. success := call(gas(), token, 0, 0, 0x64, 0, 0x20)
  210. // if call success and return is true, all is good.
  211. // otherwise (not success or return is not true), we need to perform further checks
  212. if iszero(and(success, eq(mload(0x00), 1))) {
  213. // if the call was a failure and bubble is enabled, bubble the error
  214. if and(iszero(success), bubble) {
  215. returndatacopy(fmp, 0, returndatasize())
  216. revert(fmp, returndatasize())
  217. }
  218. // if the return value is not true, then the call is only successful if:
  219. // - the token address has code
  220. // - the returndata is empty
  221. success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
  222. }
  223. mstore(0x40, fmp)
  224. mstore(0x60, 0)
  225. }
  226. }
  227. /**
  228. * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
  229. * the return value is optional (but if data is returned, it must not be false).
  230. *
  231. * @param token The token targeted by the call.
  232. * @param spender The spender of the tokens
  233. * @param value The amount of token to transfer
  234. * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
  235. */
  236. function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
  237. bytes4 selector = IERC20.approve.selector;
  238. assembly ("memory-safe") {
  239. let fmp := mload(0x40)
  240. mstore(0x00, selector)
  241. mstore(0x04, and(spender, shr(96, not(0))))
  242. mstore(0x24, value)
  243. success := call(gas(), token, 0, 0, 0x44, 0, 0x20)
  244. // if call success and return is true, all is good.
  245. // otherwise (not success or return is not true), we need to perform further checks
  246. if iszero(and(success, eq(mload(0x00), 1))) {
  247. // if the call was a failure and bubble is enabled, bubble the error
  248. if and(iszero(success), bubble) {
  249. returndatacopy(fmp, 0, returndatasize())
  250. revert(fmp, returndatasize())
  251. }
  252. // if the return value is not true, then the call is only successful if:
  253. // - the token address has code
  254. // - the returndata is empty
  255. success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
  256. }
  257. mstore(0x40, fmp)
  258. }
  259. }
  260. }