ERC2771Context.sol 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)
  3. pragma solidity ^0.8.20;
  4. import {Context} from "../utils/Context.sol";
  5. /**
  6. * @dev Context variant with ERC2771 support.
  7. *
  8. * WARNING: Avoid using this pattern in contracts that rely in a specific calldata length as they'll
  9. * be affected by any forwarder whose `msg.data` is suffixed with the `from` address according to the ERC2771
  10. * specification adding the address size in bytes (20) to the calldata size. An example of an unexpected
  11. * behavior could be an unintended fallback (or another function) invocation while trying to invoke the `receive`
  12. * function only accessible if `msg.data.length == 0`.
  13. */
  14. abstract contract ERC2771Context is Context {
  15. /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
  16. address private immutable _trustedForwarder;
  17. /// @custom:oz-upgrades-unsafe-allow constructor
  18. constructor(address trustedForwarder) {
  19. _trustedForwarder = trustedForwarder;
  20. }
  21. function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
  22. return forwarder == _trustedForwarder;
  23. }
  24. function _msgSender() internal view virtual override returns (address sender) {
  25. if (isTrustedForwarder(msg.sender) && msg.data.length >= 20) {
  26. // The assembly code is more direct than the Solidity version using `abi.decode`.
  27. /// @solidity memory-safe-assembly
  28. assembly {
  29. sender := shr(96, calldataload(sub(calldatasize(), 20)))
  30. }
  31. } else {
  32. return super._msgSender();
  33. }
  34. }
  35. function _msgData() internal view virtual override returns (bytes calldata) {
  36. if (isTrustedForwarder(msg.sender) && msg.data.length >= 20) {
  37. return msg.data[:msg.data.length - 20];
  38. } else {
  39. return super._msgData();
  40. }
  41. }
  42. }