MinimalForwarder.sol 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.8.0) (metatx/MinimalForwarder.sol)
  3. pragma solidity ^0.8.0;
  4. import "../utils/cryptography/ECDSA.sol";
  5. import "../utils/cryptography/EIP712.sol";
  6. /**
  7. * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.
  8. *
  9. * MinimalForwarder is mainly meant for testing, as it is missing features to be a good production-ready forwarder. This
  10. * contract does not intend to have all the properties that are needed for a sound forwarding system. A fully
  11. * functioning forwarding system with good properties requires more complexity. We suggest you look at other projects
  12. * such as the GSN which do have the goal of building a system like that.
  13. */
  14. contract MinimalForwarder is EIP712 {
  15. using ECDSA for bytes32;
  16. struct ForwardRequest {
  17. address from;
  18. address to;
  19. uint256 value;
  20. uint256 gas;
  21. uint256 nonce;
  22. bytes data;
  23. }
  24. bytes32 private constant _TYPEHASH =
  25. keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)");
  26. mapping(address => uint256) private _nonces;
  27. constructor() EIP712("MinimalForwarder", "0.0.1") {}
  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(
  38. ForwardRequest calldata req,
  39. bytes calldata signature
  40. ) public payable returns (bool, bytes memory) {
  41. require(verify(req, signature), "MinimalForwarder: signature does not match request");
  42. _nonces[req.from] = req.nonce + 1;
  43. (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(
  44. abi.encodePacked(req.data, req.from)
  45. );
  46. // Validate that the relayer has sent enough gas for the call.
  47. // See https://ronan.eth.limo/blog/ethereum-gas-dangers/
  48. if (gasleft() <= req.gas / 63) {
  49. // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since
  50. // neither revert or assert consume all gas since Solidity 0.8.0
  51. // https://docs.soliditylang.org/en/v0.8.0/control-structures.html#panic-via-assert-and-error-via-require
  52. /// @solidity memory-safe-assembly
  53. assembly {
  54. invalid()
  55. }
  56. }
  57. return (success, returndata);
  58. }
  59. }