ERC2771Forwarder.sol 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.0) (metatx/ERC2771Forwarder.sol)
  3. pragma solidity ^0.8.20;
  4. import {ERC2771Context} from "./ERC2771Context.sol";
  5. import {ECDSA} from "../utils/cryptography/ECDSA.sol";
  6. import {EIP712} from "../utils/cryptography/EIP712.sol";
  7. import {Nonces} from "../utils/Nonces.sol";
  8. import {Address} from "../utils/Address.sol";
  9. /**
  10. * @dev A forwarder compatible with ERC2771 contracts. See {ERC2771Context}.
  11. *
  12. * This forwarder operates on forward requests that include:
  13. *
  14. * * `from`: An address to operate on behalf of. It is required to be equal to the request signer.
  15. * * `to`: The address that should be called.
  16. * * `value`: The amount of native token to attach with the requested call.
  17. * * `gas`: The amount of gas limit that will be forwarded with the requested call.
  18. * * `nonce`: A unique transaction ordering identifier to avoid replayability and request invalidation.
  19. * * `deadline`: A timestamp after which the request is not executable anymore.
  20. * * `data`: Encoded `msg.data` to send with the requested call.
  21. *
  22. * Relayers are able to submit batches if they are processing a high volume of requests. With high
  23. * throughput, relayers may run into limitations of the chain such as limits on the number of
  24. * transactions in the mempool. In these cases the recommendation is to distribute the load among
  25. * multiple accounts.
  26. *
  27. * WARNING: Do not approve this contract to spend tokens. Anyone can use this forwarder
  28. * to execute calls with an arbitrary calldata to any address. Any form of approval may
  29. * result in a loss of funds for the approving party.
  30. *
  31. * NOTE: Batching requests includes an optional refund for unused `msg.value` that is achieved by
  32. * performing a call with empty calldata. While this is within the bounds of ERC-2771 compliance,
  33. * if the refund receiver happens to consider the forwarder a trusted forwarder, it MUST properly
  34. * handle `msg.data.length == 0`. `ERC2771Context` in OpenZeppelin Contracts versions prior to 4.9.3
  35. * do not handle this properly.
  36. *
  37. * ==== Security Considerations
  38. *
  39. * If a relayer submits a forward request, it should be willing to pay up to 100% of the gas amount
  40. * specified in the request. This contract does not implement any kind of retribution for this gas,
  41. * and it is assumed that there is an out of band incentive for relayers to pay for execution on
  42. * behalf of signers. Often, the relayer is operated by a project that will consider it a user
  43. * acquisition cost.
  44. *
  45. * By offering to pay for gas, relayers are at risk of having that gas used by an attacker toward
  46. * some other purpose that is not aligned with the expected out of band incentives. If you operate a
  47. * relayer, consider whitelisting target contracts and function selectors. When relaying ERC-721 or
  48. * ERC-1155 transfers specifically, consider rejecting the use of the `data` field, since it can be
  49. * used to execute arbitrary code.
  50. */
  51. contract ERC2771Forwarder is EIP712, Nonces {
  52. using ECDSA for bytes32;
  53. struct ForwardRequestData {
  54. address from;
  55. address to;
  56. uint256 value;
  57. uint256 gas;
  58. uint48 deadline;
  59. bytes data;
  60. bytes signature;
  61. }
  62. bytes32 internal constant _FORWARD_REQUEST_TYPEHASH =
  63. keccak256(
  64. "ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,uint48 deadline,bytes data)"
  65. );
  66. /**
  67. * @dev Emitted when a `ForwardRequest` is executed.
  68. *
  69. * NOTE: An unsuccessful forward request could be due to an invalid signature, an expired deadline,
  70. * or simply a revert in the requested call. The contract guarantees that the relayer is not able to force
  71. * the requested call to run out of gas.
  72. */
  73. event ExecutedForwardRequest(address indexed signer, uint256 nonce, bool success);
  74. /**
  75. * @dev The request `from` doesn't match with the recovered `signer`.
  76. */
  77. error ERC2771ForwarderInvalidSigner(address signer, address from);
  78. /**
  79. * @dev The `requestedValue` doesn't match with the available `msgValue`.
  80. */
  81. error ERC2771ForwarderMismatchedValue(uint256 requestedValue, uint256 msgValue);
  82. /**
  83. * @dev The request `deadline` has expired.
  84. */
  85. error ERC2771ForwarderExpiredRequest(uint48 deadline);
  86. /**
  87. * @dev The request target doesn't trust the `forwarder`.
  88. */
  89. error ERC2771UntrustfulTarget(address target, address forwarder);
  90. /**
  91. * @dev See {EIP712-constructor}.
  92. */
  93. constructor(string memory name) EIP712(name, "1") {}
  94. /**
  95. * @dev Returns `true` if a request is valid for a provided `signature` at the current block timestamp.
  96. *
  97. * A transaction is considered valid when the target trusts this forwarder, the request hasn't expired
  98. * (deadline is not met), and the signer matches the `from` parameter of the signed request.
  99. *
  100. * NOTE: A request may return false here but it won't cause {executeBatch} to revert if a refund
  101. * receiver is provided.
  102. */
  103. function verify(ForwardRequestData calldata request) public view virtual returns (bool) {
  104. (bool isTrustedForwarder, bool active, bool signerMatch, ) = _validate(request);
  105. return isTrustedForwarder && active && signerMatch;
  106. }
  107. /**
  108. * @dev Executes a `request` on behalf of `signature`'s signer using the ERC-2771 protocol. The gas
  109. * provided to the requested call may not be exactly the amount requested, but the call will not run
  110. * out of gas. Will revert if the request is invalid or the call reverts, in this case the nonce is not consumed.
  111. *
  112. * Requirements:
  113. *
  114. * - The request value should be equal to the provided `msg.value`.
  115. * - The request should be valid according to {verify}.
  116. */
  117. function execute(ForwardRequestData calldata request) public payable virtual {
  118. // We make sure that msg.value and request.value match exactly.
  119. // If the request is invalid or the call reverts, this whole function
  120. // will revert, ensuring value isn't stuck.
  121. if (msg.value != request.value) {
  122. revert ERC2771ForwarderMismatchedValue(request.value, msg.value);
  123. }
  124. if (!_execute(request, true)) {
  125. revert Address.FailedInnerCall();
  126. }
  127. }
  128. /**
  129. * @dev Batch version of {execute} with optional refunding and atomic execution.
  130. *
  131. * In case a batch contains at least one invalid request (see {verify}), the
  132. * request will be skipped and the `refundReceiver` parameter will receive back the
  133. * unused requested value at the end of the execution. This is done to prevent reverting
  134. * the entire batch when a request is invalid or has already been submitted.
  135. *
  136. * If the `refundReceiver` is the `address(0)`, this function will revert when at least
  137. * one of the requests was not valid instead of skipping it. This could be useful if
  138. * a batch is required to get executed atomically (at least at the top-level). For example,
  139. * refunding (and thus atomicity) can be opt-out if the relayer is using a service that avoids
  140. * including reverted transactions.
  141. *
  142. * Requirements:
  143. *
  144. * - The sum of the requests' values should be equal to the provided `msg.value`.
  145. * - All of the requests should be valid (see {verify}) when `refundReceiver` is the zero address.
  146. *
  147. * NOTE: Setting a zero `refundReceiver` guarantees an all-or-nothing requests execution only for
  148. * the first-level forwarded calls. In case a forwarded request calls to a contract with another
  149. * subcall, the second-level call may revert without the top-level call reverting.
  150. */
  151. function executeBatch(
  152. ForwardRequestData[] calldata requests,
  153. address payable refundReceiver
  154. ) public payable virtual {
  155. bool atomic = refundReceiver == address(0);
  156. uint256 requestsValue;
  157. uint256 refundValue;
  158. for (uint256 i; i < requests.length; ++i) {
  159. requestsValue += requests[i].value;
  160. bool success = _execute(requests[i], atomic);
  161. if (!success) {
  162. refundValue += requests[i].value;
  163. }
  164. }
  165. // The batch should revert if there's a mismatched msg.value provided
  166. // to avoid request value tampering
  167. if (requestsValue != msg.value) {
  168. revert ERC2771ForwarderMismatchedValue(requestsValue, msg.value);
  169. }
  170. // Some requests with value were invalid (possibly due to frontrunning).
  171. // To avoid leaving ETH in the contract this value is refunded.
  172. if (refundValue != 0) {
  173. // We know refundReceiver != address(0) && requestsValue == msg.value
  174. // meaning we can ensure refundValue is not taken from the original contract's balance
  175. // and refundReceiver is a known account.
  176. Address.sendValue(refundReceiver, refundValue);
  177. }
  178. }
  179. /**
  180. * @dev Validates if the provided request can be executed at current block timestamp with
  181. * the given `request.signature` on behalf of `request.signer`.
  182. */
  183. function _validate(
  184. ForwardRequestData calldata request
  185. ) internal view virtual returns (bool isTrustedForwarder, bool active, bool signerMatch, address signer) {
  186. (bool isValid, address recovered) = _recoverForwardRequestSigner(request);
  187. return (
  188. _isTrustedByTarget(request.to),
  189. request.deadline >= block.timestamp,
  190. isValid && recovered == request.from,
  191. recovered
  192. );
  193. }
  194. /**
  195. * @dev Returns a tuple with the recovered the signer of an EIP712 forward request message hash
  196. * and a boolean indicating if the signature is valid.
  197. *
  198. * NOTE: The signature is considered valid if {ECDSA-tryRecover} indicates no recover error for it.
  199. */
  200. function _recoverForwardRequestSigner(
  201. ForwardRequestData calldata request
  202. ) internal view virtual returns (bool, address) {
  203. (address recovered, ECDSA.RecoverError err, ) = _hashTypedDataV4(
  204. keccak256(
  205. abi.encode(
  206. _FORWARD_REQUEST_TYPEHASH,
  207. request.from,
  208. request.to,
  209. request.value,
  210. request.gas,
  211. nonces(request.from),
  212. request.deadline,
  213. keccak256(request.data)
  214. )
  215. )
  216. ).tryRecover(request.signature);
  217. return (err == ECDSA.RecoverError.NoError, recovered);
  218. }
  219. /**
  220. * @dev Validates and executes a signed request returning the request call `success` value.
  221. *
  222. * Internal function without msg.value validation.
  223. *
  224. * Requirements:
  225. *
  226. * - The caller must have provided enough gas to forward with the call.
  227. * - The request must be valid (see {verify}) if the `requireValidRequest` is true.
  228. *
  229. * Emits an {ExecutedForwardRequest} event.
  230. *
  231. * IMPORTANT: Using this function doesn't check that all the `msg.value` was sent, potentially
  232. * leaving value stuck in the contract.
  233. */
  234. function _execute(
  235. ForwardRequestData calldata request,
  236. bool requireValidRequest
  237. ) internal virtual returns (bool success) {
  238. (bool isTrustedForwarder, bool active, bool signerMatch, address signer) = _validate(request);
  239. // Need to explicitly specify if a revert is required since non-reverting is default for
  240. // batches and reversion is opt-in since it could be useful in some scenarios
  241. if (requireValidRequest) {
  242. if (!isTrustedForwarder) {
  243. revert ERC2771UntrustfulTarget(request.to, address(this));
  244. }
  245. if (!active) {
  246. revert ERC2771ForwarderExpiredRequest(request.deadline);
  247. }
  248. if (!signerMatch) {
  249. revert ERC2771ForwarderInvalidSigner(signer, request.from);
  250. }
  251. }
  252. // Ignore an invalid request because requireValidRequest = false
  253. if (isTrustedForwarder && signerMatch && active) {
  254. // Nonce should be used before the call to prevent reusing by reentrancy
  255. uint256 currentNonce = _useNonce(signer);
  256. uint256 reqGas = request.gas;
  257. address to = request.to;
  258. uint256 value = request.value;
  259. bytes memory data = abi.encodePacked(request.data, request.from);
  260. uint256 gasLeft;
  261. assembly {
  262. success := call(reqGas, to, value, add(data, 0x20), mload(data), 0, 0)
  263. gasLeft := gas()
  264. }
  265. _checkForwardedGas(gasLeft, request);
  266. emit ExecutedForwardRequest(signer, currentNonce, success);
  267. }
  268. }
  269. /**
  270. * @dev Returns whether the target trusts this forwarder.
  271. *
  272. * This function performs a static call to the target contract calling the
  273. * {ERC2771Context-isTrustedForwarder} function.
  274. */
  275. function _isTrustedByTarget(address target) private view returns (bool) {
  276. bytes memory encodedParams = abi.encodeCall(ERC2771Context.isTrustedForwarder, (address(this)));
  277. bool success;
  278. uint256 returnSize;
  279. uint256 returnValue;
  280. /// @solidity memory-safe-assembly
  281. assembly {
  282. // Perform the staticcal and save the result in the scratch space.
  283. // | Location | Content | Content (Hex) |
  284. // |-----------|----------|--------------------------------------------------------------------|
  285. // | | | result ↓ |
  286. // | 0x00:0x1F | selector | 0x0000000000000000000000000000000000000000000000000000000000000001 |
  287. success := staticcall(gas(), target, add(encodedParams, 0x20), mload(encodedParams), 0, 0x20)
  288. returnSize := returndatasize()
  289. returnValue := mload(0)
  290. }
  291. return success && returnSize >= 0x20 && returnValue > 0;
  292. }
  293. /**
  294. * @dev Checks if the requested gas was correctly forwarded to the callee.
  295. *
  296. * As a consequence of https://eips.ethereum.org/EIPS/eip-150[EIP-150]:
  297. * - At most `gasleft() - floor(gasleft() / 64)` is forwarded to the callee.
  298. * - At least `floor(gasleft() / 64)` is kept in the caller.
  299. *
  300. * It reverts consuming all the available gas if the forwarded gas is not the requested gas.
  301. *
  302. * IMPORTANT: The `gasLeft` parameter should be measured exactly at the end of the forwarded call.
  303. * Any gas consumed in between will make room for bypassing this check.
  304. */
  305. function _checkForwardedGas(uint256 gasLeft, ForwardRequestData calldata request) private pure {
  306. // To avoid insufficient gas griefing attacks, as referenced in https://ronan.eth.limo/blog/ethereum-gas-dangers/
  307. //
  308. // A malicious relayer can attempt to shrink the gas forwarded so that the underlying call reverts out-of-gas
  309. // but the forwarding itself still succeeds. In order to make sure that the subcall received sufficient gas,
  310. // we will inspect gasleft() after the forwarding.
  311. //
  312. // Let X be the gas available before the subcall, such that the subcall gets at most X * 63 / 64.
  313. // We can't know X after CALL dynamic costs, but we want it to be such that X * 63 / 64 >= req.gas.
  314. // Let Y be the gas used in the subcall. gasleft() measured immediately after the subcall will be gasleft() = X - Y.
  315. // If the subcall ran out of gas, then Y = X * 63 / 64 and gasleft() = X - Y = X / 64.
  316. // Under this assumption req.gas / 63 > gasleft() is true is true if and only if
  317. // req.gas / 63 > X / 64, or equivalently req.gas > X * 63 / 64.
  318. // This means that if the subcall runs out of gas we are able to detect that insufficient gas was passed.
  319. //
  320. // We will now also see that req.gas / 63 > gasleft() implies that req.gas >= X * 63 / 64.
  321. // The contract guarantees Y <= req.gas, thus gasleft() = X - Y >= X - req.gas.
  322. // - req.gas / 63 > gasleft()
  323. // - req.gas / 63 >= X - req.gas
  324. // - req.gas >= X * 63 / 64
  325. // In other words if req.gas < X * 63 / 64 then req.gas / 63 <= gasleft(), thus if the relayer behaves honestly
  326. // the forwarding does not revert.
  327. if (gasLeft < request.gas / 63) {
  328. // We explicitly trigger invalid opcode to consume all gas and bubble-up the effects, since
  329. // neither revert or assert consume all gas since Solidity 0.8.20
  330. // https://docs.soliditylang.org/en/v0.8.20/control-structures.html#panic-via-assert-and-error-via-require
  331. /// @solidity memory-safe-assembly
  332. assembly {
  333. invalid()
  334. }
  335. }
  336. }
  337. }