MinimalForwarderUpgradeable.sol 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (metatx/MinimalForwarder.sol)
  3. pragma solidity ^0.8.0;
  4. import "../utils/cryptography/ECDSAUpgradeable.sol";
  5. import "../utils/cryptography/draft-EIP712Upgradeable.sol";
  6. import "../proxy/utils/Initializable.sol";
  7. /**
  8. * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.
  9. */
  10. contract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {
  11. using ECDSAUpgradeable for bytes32;
  12. struct ForwardRequest {
  13. address from;
  14. address to;
  15. uint256 value;
  16. uint256 gas;
  17. uint256 nonce;
  18. bytes data;
  19. }
  20. bytes32 private constant _TYPEHASH =
  21. keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)");
  22. mapping(address => uint256) private _nonces;
  23. function __MinimalForwarder_init() internal onlyInitializing {
  24. __EIP712_init_unchained("MinimalForwarder", "0.0.1");
  25. __MinimalForwarder_init_unchained();
  26. }
  27. function __MinimalForwarder_init_unchained() internal onlyInitializing {}
  28. function getNonce(address from) public view returns (uint256) {
  29. return _nonces[from];
  30. }
  31. function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {
  32. address signer = _hashTypedDataV4(
  33. keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))
  34. ).recover(signature);
  35. return _nonces[req.from] == req.nonce && signer == req.from;
  36. }
  37. function execute(ForwardRequest calldata req, bytes calldata signature)
  38. public
  39. payable
  40. returns (bool, bytes memory)
  41. {
  42. require(verify(req, signature), "MinimalForwarder: signature does not match request");
  43. _nonces[req.from] = req.nonce + 1;
  44. (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(
  45. abi.encodePacked(req.data, req.from)
  46. );
  47. // Validate that the relayer has sent enough gas for the call.
  48. // See https://ronan.eth.link/blog/ethereum-gas-dangers/
  49. if (gasleft() <= req.gas / 63) {
  50. // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since
  51. // neither revert or assert consume all gas since Solidity 0.8.0
  52. // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require
  53. assembly {
  54. invalid()
  55. }
  56. }
  57. return (success, returndata);
  58. }
  59. uint256[49] private __gap;
  60. }