ERC721Utils.sol 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. library ERC721Utils {
  11. /**
  12. * @dev Performs an acceptance check for the provided `operator` by calling {IERC721-onERC721Received}
  13. * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
  14. *
  15. * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
  16. * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
  17. * the transfer.
  18. */
  19. function checkOnERC721Received(
  20. address operator,
  21. address from,
  22. address to,
  23. uint256 tokenId,
  24. bytes memory data
  25. ) internal {
  26. if (to.code.length > 0) {
  27. try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
  28. if (retval != IERC721Receiver.onERC721Received.selector) {
  29. // Token rejected
  30. revert IERC721Errors.ERC721InvalidReceiver(to);
  31. }
  32. } catch (bytes memory reason) {
  33. if (reason.length == 0) {
  34. // non-IERC721Receiver implementer
  35. revert IERC721Errors.ERC721InvalidReceiver(to);
  36. } else {
  37. assembly ("memory-safe") {
  38. revert(add(32, reason), mload(reason))
  39. }
  40. }
  41. }
  42. }
  43. }
  44. }