ERC2771Forwarder.test.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. const { ethers } = require('hardhat');
  2. const { expect } = require('chai');
  3. const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
  4. const { getDomain, ForwardRequest } = require('../helpers/eip712');
  5. const { sum } = require('../helpers/math');
  6. const time = require('../helpers/time');
  7. async function fixture() {
  8. const [sender, refundReceiver, another, ...accounts] = await ethers.getSigners();
  9. const forwarder = await ethers.deployContract('ERC2771Forwarder', ['ERC2771Forwarder']);
  10. const receiver = await ethers.deployContract('CallReceiverMockTrustingForwarder', [forwarder]);
  11. const domain = await getDomain(forwarder);
  12. const types = { ForwardRequest };
  13. const forgeRequest = async (override = {}, signer = sender) => {
  14. const req = {
  15. from: await signer.getAddress(),
  16. to: await receiver.getAddress(),
  17. value: 0n,
  18. data: receiver.interface.encodeFunctionData('mockFunction'),
  19. gas: 100000n,
  20. deadline: (await time.clock.timestamp()) + 60n,
  21. nonce: await forwarder.nonces(sender),
  22. ...override,
  23. };
  24. req.signature = await signer.signTypedData(domain, types, req);
  25. return req;
  26. };
  27. const estimateRequest = request =>
  28. ethers.provider.estimateGas({
  29. from: forwarder,
  30. to: request.to,
  31. data: ethers.solidityPacked(['bytes', 'address'], [request.data, request.from]),
  32. value: request.value,
  33. gasLimit: request.gas,
  34. });
  35. return {
  36. sender,
  37. refundReceiver,
  38. another,
  39. accounts,
  40. forwarder,
  41. receiver,
  42. forgeRequest,
  43. estimateRequest,
  44. domain,
  45. types,
  46. };
  47. }
  48. describe('ERC2771Forwarder', function () {
  49. beforeEach(async function () {
  50. Object.assign(this, await loadFixture(fixture));
  51. });
  52. describe('verify', function () {
  53. describe('with valid signature', function () {
  54. it('returns true without altering the nonce', async function () {
  55. const request = await this.forgeRequest();
  56. expect(await this.forwarder.nonces(request.from)).to.equal(request.nonce);
  57. expect(await this.forwarder.verify(request)).to.be.true;
  58. expect(await this.forwarder.nonces(request.from)).to.equal(request.nonce);
  59. });
  60. });
  61. describe('with tampered values', function () {
  62. it('returns false with valid signature for non-current nonce', async function () {
  63. const request = await this.forgeRequest({ nonce: 1337n });
  64. expect(await this.forwarder.verify(request)).to.be.false;
  65. });
  66. it('returns false with valid signature for expired deadline', async function () {
  67. const request = await this.forgeRequest({ deadline: (await time.clock.timestamp()) - 1n });
  68. expect(await this.forwarder.verify(request)).to.be.false;
  69. });
  70. });
  71. });
  72. describe('execute', function () {
  73. describe('with valid requests', function () {
  74. it('emits an event and consumes nonce for a successful request', async function () {
  75. const request = await this.forgeRequest();
  76. expect(await this.forwarder.nonces(request.from)).to.equal(request.nonce);
  77. await expect(this.forwarder.execute(request))
  78. .to.emit(this.receiver, 'MockFunctionCalled')
  79. .to.emit(this.forwarder, 'ExecutedForwardRequest')
  80. .withArgs(request.from, request.nonce, true);
  81. expect(await this.forwarder.nonces(request.from)).to.equal(request.nonce + 1n);
  82. });
  83. it('reverts with an unsuccessful request', async function () {
  84. const request = await this.forgeRequest({
  85. data: this.receiver.interface.encodeFunctionData('mockFunctionRevertsNoReason'),
  86. });
  87. await expect(this.forwarder.execute(request)).to.be.revertedWithCustomError(this.forwarder, 'FailedCall');
  88. });
  89. });
  90. describe('with tampered request', function () {
  91. it('reverts with valid signature for non-current nonce', async function () {
  92. const request = await this.forgeRequest();
  93. // consume nonce
  94. await this.forwarder.execute(request);
  95. // nonce has changed
  96. await expect(this.forwarder.execute(request))
  97. .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderInvalidSigner')
  98. .withArgs(
  99. ethers.verifyTypedData(
  100. this.domain,
  101. this.types,
  102. { ...request, nonce: request.nonce + 1n },
  103. request.signature,
  104. ),
  105. request.from,
  106. );
  107. });
  108. it('reverts with valid signature for expired deadline', async function () {
  109. const request = await this.forgeRequest({ deadline: (await time.clock.timestamp()) - 1n });
  110. await expect(this.forwarder.execute(request))
  111. .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderExpiredRequest')
  112. .withArgs(request.deadline);
  113. });
  114. it('reverts with valid signature but mismatched value', async function () {
  115. const request = await this.forgeRequest({ value: 100n });
  116. await expect(this.forwarder.execute(request))
  117. .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderMismatchedValue')
  118. .withArgs(request.value, 0n);
  119. });
  120. });
  121. it('bubbles out of gas', async function () {
  122. const request = await this.forgeRequest({
  123. data: this.receiver.interface.encodeFunctionData('mockFunctionOutOfGas'),
  124. gas: 1_000_000n,
  125. });
  126. const gasLimit = 100_000n;
  127. await expect(this.forwarder.execute(request, { gasLimit })).to.be.revertedWithoutReason();
  128. const { gasUsed } = await ethers.provider
  129. .getBlock('latest')
  130. .then(block => block.getTransaction(0))
  131. .then(tx => ethers.provider.getTransactionReceipt(tx.hash));
  132. expect(gasUsed).to.equal(gasLimit);
  133. });
  134. it('bubbles out of gas forced by the relayer', async function () {
  135. const request = await this.forgeRequest();
  136. // If there's an incentive behind executing requests, a malicious relayer could grief
  137. // the forwarder by executing requests and providing a top-level call gas limit that
  138. // is too low to successfully finish the request after the 63/64 rule.
  139. // We set the baseline to the gas limit consumed by a successful request if it was executed
  140. // normally. Note this includes the 21000 buffer that also the relayer will be charged to
  141. // start a request execution.
  142. const estimate = await this.estimateRequest(request);
  143. // Because the relayer call consumes gas until the `CALL` opcode, the gas left after failing
  144. // the subcall won't enough to finish the top level call (after testing), so we add a
  145. // moderated buffer.
  146. const gasLimit = estimate + 2_000n;
  147. // The subcall out of gas should be caught by the contract and then bubbled up consuming
  148. // the available gas with an `invalid` opcode.
  149. await expect(this.forwarder.execute(request, { gasLimit })).to.be.revertedWithoutReason();
  150. const { gasUsed } = await ethers.provider
  151. .getBlock('latest')
  152. .then(block => block.getTransaction(0))
  153. .then(tx => ethers.provider.getTransactionReceipt(tx.hash));
  154. // We assert that indeed the gas was totally consumed.
  155. expect(gasUsed).to.equal(gasLimit);
  156. });
  157. });
  158. describe('executeBatch', function () {
  159. const requestsValue = requests => sum(...requests.map(request => request.value));
  160. const requestCount = 3;
  161. const idx = 1; // index that will be tampered with
  162. beforeEach(async function () {
  163. this.forgeRequests = override =>
  164. Promise.all(this.accounts.slice(0, requestCount).map(signer => this.forgeRequest(override, signer)));
  165. this.requests = await this.forgeRequests({ value: 10n });
  166. this.value = requestsValue(this.requests);
  167. });
  168. describe('with valid requests', function () {
  169. it('sanity', async function () {
  170. for (const request of this.requests) {
  171. expect(await this.forwarder.verify(request)).to.be.true;
  172. }
  173. });
  174. it('emits events', async function () {
  175. const receipt = this.forwarder.executeBatch(this.requests, this.another, { value: this.value });
  176. for (const request of this.requests) {
  177. await expect(receipt)
  178. .to.emit(this.receiver, 'MockFunctionCalled')
  179. .to.emit(this.forwarder, 'ExecutedForwardRequest')
  180. .withArgs(request.from, request.nonce, true);
  181. }
  182. });
  183. it('increase nonces', async function () {
  184. await this.forwarder.executeBatch(this.requests, this.another, { value: this.value });
  185. for (const request of this.requests) {
  186. expect(await this.forwarder.nonces(request.from)).to.equal(request.nonce + 1n);
  187. }
  188. });
  189. });
  190. describe('with tampered requests', function () {
  191. it('reverts with mismatched value', async function () {
  192. // tamper value of one of the request + resign
  193. this.requests[idx] = await this.forgeRequest({ value: 100n }, this.accounts[1]);
  194. await expect(this.forwarder.executeBatch(this.requests, this.another, { value: this.value }))
  195. .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderMismatchedValue')
  196. .withArgs(requestsValue(this.requests), this.value);
  197. });
  198. describe('when the refund receiver is the zero address', function () {
  199. beforeEach(function () {
  200. this.refundReceiver = ethers.ZeroAddress;
  201. });
  202. it('reverts with at least one valid signature for non-current nonce', async function () {
  203. // Execute first a request
  204. await this.forwarder.execute(this.requests[idx], { value: this.requests[idx].value });
  205. // And then fail due to an already used nonce
  206. await expect(this.forwarder.executeBatch(this.requests, this.refundReceiver, { value: this.value }))
  207. .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderInvalidSigner')
  208. .withArgs(
  209. ethers.verifyTypedData(
  210. this.domain,
  211. this.types,
  212. { ...this.requests[idx], nonce: this.requests[idx].nonce + 1n },
  213. this.requests[idx].signature,
  214. ),
  215. this.requests[idx].from,
  216. );
  217. });
  218. it('reverts with at least one valid signature for expired deadline', async function () {
  219. this.requests[idx] = await this.forgeRequest(
  220. { ...this.requests[idx], deadline: (await time.clock.timestamp()) - 1n },
  221. this.accounts[1],
  222. );
  223. await expect(this.forwarder.executeBatch(this.requests, this.refundReceiver, { value: this.amount }))
  224. .to.be.revertedWithCustomError(this.forwarder, 'ERC2771ForwarderExpiredRequest')
  225. .withArgs(this.requests[idx].deadline);
  226. });
  227. });
  228. describe('when the refund receiver is a known address', function () {
  229. beforeEach(async function () {
  230. this.initialRefundReceiverBalance = await ethers.provider.getBalance(this.refundReceiver);
  231. this.initialTamperedRequestNonce = await this.forwarder.nonces(this.requests[idx].from);
  232. });
  233. it('ignores a request with a valid signature for non-current nonce', async function () {
  234. // Execute first a request
  235. await this.forwarder.execute(this.requests[idx], { value: this.requests[idx].value });
  236. this.initialTamperedRequestNonce++; // Should be already incremented by the individual `execute`
  237. // And then ignore the same request in a batch due to an already used nonce
  238. const events = await this.forwarder
  239. .executeBatch(this.requests, this.refundReceiver, { value: this.value })
  240. .then(tx => tx.wait())
  241. .then(receipt =>
  242. receipt.logs.filter(
  243. log => log?.fragment?.type == 'event' && log?.fragment?.name == 'ExecutedForwardRequest',
  244. ),
  245. );
  246. expect(events).to.have.lengthOf(this.requests.length - 1);
  247. });
  248. it('ignores a request with a valid signature for expired deadline', async function () {
  249. this.requests[idx] = await this.forgeRequest(
  250. { ...this.requests[idx], deadline: (await time.clock.timestamp()) - 1n },
  251. this.accounts[1],
  252. );
  253. const events = await this.forwarder
  254. .executeBatch(this.requests, this.refundReceiver, { value: this.value })
  255. .then(tx => tx.wait())
  256. .then(receipt =>
  257. receipt.logs.filter(
  258. log => log?.fragment?.type == 'event' && log?.fragment?.name == 'ExecutedForwardRequest',
  259. ),
  260. );
  261. expect(events).to.have.lengthOf(this.requests.length - 1);
  262. });
  263. afterEach(async function () {
  264. // The invalid request value was refunded
  265. expect(await ethers.provider.getBalance(this.refundReceiver)).to.equal(
  266. this.initialRefundReceiverBalance + this.requests[idx].value,
  267. );
  268. // The invalid request from's nonce was not incremented
  269. expect(await this.forwarder.nonces(this.requests[idx].from)).to.equal(this.initialTamperedRequestNonce);
  270. });
  271. });
  272. it('bubbles out of gas', async function () {
  273. this.requests[idx] = await this.forgeRequest({
  274. data: this.receiver.interface.encodeFunctionData('mockFunctionOutOfGas'),
  275. gas: 1_000_000n,
  276. });
  277. const gasLimit = 300_000n;
  278. await expect(
  279. this.forwarder.executeBatch(this.requests, ethers.ZeroAddress, {
  280. gasLimit,
  281. value: requestsValue(this.requests),
  282. }),
  283. ).to.be.revertedWithoutReason();
  284. const { gasUsed } = await ethers.provider
  285. .getBlock('latest')
  286. .then(block => block.getTransaction(0))
  287. .then(tx => ethers.provider.getTransactionReceipt(tx.hash));
  288. expect(gasUsed).to.equal(gasLimit);
  289. });
  290. it('bubbles out of gas forced by the relayer', async function () {
  291. // Similarly to the single execute, a malicious relayer could grief requests.
  292. // We estimate until the selected request as if they were executed normally
  293. const estimate = await Promise.all(this.requests.slice(0, idx + 1).map(this.estimateRequest)).then(gas =>
  294. sum(...gas),
  295. );
  296. // We add a Buffer to account for all the gas that's used before the selected call.
  297. // Note is slightly bigger because the selected request is not the index 0 and it affects
  298. // the buffer needed.
  299. const gasLimit = estimate + 10_000n;
  300. // The subcall out of gas should be caught by the contract and then bubbled up consuming
  301. // the available gas with an `invalid` opcode.
  302. await expect(
  303. this.forwarder.executeBatch(this.requests, ethers.ZeroAddress, {
  304. gasLimit,
  305. value: requestsValue(this.requests),
  306. }),
  307. ).to.be.revertedWithoutReason();
  308. const { gasUsed } = await ethers.provider
  309. .getBlock('latest')
  310. .then(block => block.getTransaction(0))
  311. .then(tx => ethers.provider.getTransactionReceipt(tx.hash));
  312. // We assert that indeed the gas was totally consumed.
  313. expect(gasUsed).to.equal(gasLimit);
  314. });
  315. });
  316. });
  317. });