ERC2771Forwarder.test.js 19 KB

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