ERC2771Forwarder.sol 16 KB

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