MinimalForwarder.sol 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. import "../utils/cryptography/ECDSA.sol";
  4. import "../utils/cryptography/draft-EIP712.sol";
  5. /**
  6. * @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.
  7. */
  8. contract MinimalForwarder is EIP712 {
  9. using ECDSA for bytes32;
  10. struct ForwardRequest {
  11. address from;
  12. address to;
  13. uint256 value;
  14. uint256 gas;
  15. uint256 nonce;
  16. bytes data;
  17. }
  18. bytes32 private constant _TYPEHASH =
  19. keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)");
  20. mapping(address => uint256) private _nonces;
  21. constructor() EIP712("MinimalForwarder", "0.0.1") {}
  22. function getNonce(address from) public view returns (uint256) {
  23. return _nonces[from];
  24. }
  25. function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {
  26. address signer = _hashTypedDataV4(
  27. keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))
  28. ).recover(signature);
  29. return _nonces[req.from] == req.nonce && signer == req.from;
  30. }
  31. function execute(ForwardRequest calldata req, bytes calldata signature)
  32. public
  33. payable
  34. returns (bool, bytes memory)
  35. {
  36. require(verify(req, signature), "MinimalForwarder: signature does not match request");
  37. _nonces[req.from] = req.nonce + 1;
  38. (bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(
  39. abi.encodePacked(req.data, req.from)
  40. );
  41. // Validate that the relayer has sent enough gas for the call.
  42. // See https://ronan.eth.link/blog/ethereum-gas-dangers/
  43. assert(gasleft() > req.gas / 63);
  44. return (success, returndata);
  45. }
  46. }