|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | + |
| 3 | +pragma solidity ^0.8.0; |
| 4 | + |
| 5 | +import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; |
| 6 | +import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; |
| 7 | + |
| 8 | +/* |
| 9 | + * @dev Minimal forwarder for GSNv2 |
| 10 | + */ |
| 11 | +contract Forwarder is EIP712 { |
| 12 | + using ECDSA for bytes32; |
| 13 | + |
| 14 | + struct ForwardRequest { |
| 15 | + address from; |
| 16 | + address to; |
| 17 | + uint256 value; |
| 18 | + uint256 gas; |
| 19 | + uint256 nonce; |
| 20 | + bytes data; |
| 21 | + } |
| 22 | + |
| 23 | + bytes32 private constant TYPEHASH = |
| 24 | + keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)"); |
| 25 | + |
| 26 | + mapping(address => uint256) private _nonces; |
| 27 | + |
| 28 | + constructor() EIP712("GSNv2 Forwarder", "0.0.1") {} |
| 29 | + |
| 30 | + function getNonce(address from) public view returns (uint256) { |
| 31 | + return _nonces[from]; |
| 32 | + } |
| 33 | + |
| 34 | + function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) { |
| 35 | + address signer = _hashTypedDataV4( |
| 36 | + keccak256(abi.encode(TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data))) |
| 37 | + ).recover(signature); |
| 38 | + |
| 39 | + return _nonces[req.from] == req.nonce && signer == req.from; |
| 40 | + } |
| 41 | + |
| 42 | + function execute(ForwardRequest calldata req, bytes calldata signature) |
| 43 | + public |
| 44 | + payable |
| 45 | + returns (bool, bytes memory) |
| 46 | + { |
| 47 | + require(verify(req, signature), "MinimalForwarder: signature does not match request"); |
| 48 | + _nonces[req.from] = req.nonce + 1; |
| 49 | + |
| 50 | + // solhint-disable-next-line avoid-low-level-calls |
| 51 | + (bool success, bytes memory result) = req.to.call{ gas: req.gas, value: req.value }( |
| 52 | + abi.encodePacked(req.data, req.from) |
| 53 | + ); |
| 54 | + |
| 55 | + if (!success) { |
| 56 | + // Next 5 lines from https://ethereum.stackexchange.com/a/83577 |
| 57 | + if (result.length < 68) revert("Transaction reverted silently"); |
| 58 | + assembly { |
| 59 | + result := add(result, 0x04) |
| 60 | + } |
| 61 | + revert(abi.decode(result, (string))); |
| 62 | + } |
| 63 | + // Check gas: https://ronan.eth.link/blog/ethereum-gas-dangers/ |
| 64 | + assert(gasleft() > req.gas / 63); |
| 65 | + return (success, result); |
| 66 | + } |
| 67 | +} |
0 commit comments