ERC2771Forwarder.test.js 18 KB

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