ERC2771Forwarder.sol 17 KB

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