ERC721Utils.sol 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {IERC721Receiver} from "../IERC721Receiver.sol";
  4. import {IERC721Errors} from "../../../interfaces/draft-IERC6093.sol";
  5. /**
  6. * @dev Library that provide common ERC-721 utility functions.
  7. *
  8. * See https://eips.ethereum.org/EIPS/eip-721[ERC-721].
  9. *
  10. * _Available since v5.1._
  11. */
  12. library ERC721Utils {
  13. /**
  14. * @dev Performs an acceptance check for the provided `operator` by calling {IERC721-onERC721Received}
  15. * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
  16. *
  17. * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
  18. * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
  19. * the transfer.
  20. */
  21. function checkOnERC721Received(
  22. address operator,
  23. address from,
  24. address to,
  25. uint256 tokenId,
  26. bytes memory data
  27. ) internal {
  28. if (to.code.length > 0) {
  29. try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
  30. if (retval != IERC721Receiver.onERC721Received.selector) {
  31. // Token rejected
  32. revert IERC721Errors.ERC721InvalidReceiver(to);
  33. }
  34. } catch (bytes memory reason) {
  35. if (reason.length == 0) {
  36. // non-IERC721Receiver implementer
  37. revert IERC721Errors.ERC721InvalidReceiver(to);
  38. } else {
  39. assembly ("memory-safe") {
  40. revert(add(32, reason), mload(reason))
  41. }
  42. }
  43. }
  44. }
  45. }
  46. }