ReentrancyGuard.test.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const { ethers } = require('hardhat');
  2. const { expect } = require('chai');
  3. const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
  4. for (const variant of ['', 'Transient']) {
  5. describe(`Reentrancy${variant}Guard`, function () {
  6. async function fixture() {
  7. const name = `Reentrancy${variant}Mock`;
  8. const mock = await ethers.deployContract(name);
  9. const attacker = await ethers.deployContract('ReentrancyAttack');
  10. return { name, mock, attacker };
  11. }
  12. beforeEach(async function () {
  13. Object.assign(this, await loadFixture(fixture));
  14. });
  15. it('nonReentrant function can be called', async function () {
  16. expect(await this.mock.counter()).to.equal(0n);
  17. await this.mock.callback();
  18. expect(await this.mock.counter()).to.equal(1n);
  19. });
  20. it('nonReentrantView function can be called', async function () {
  21. await this.mock.viewCallback();
  22. });
  23. it('does not allow remote callback to nonReentrant function', async function () {
  24. await expect(this.mock.countAndCall(this.attacker)).to.be.revertedWith('ReentrancyAttack: failed call');
  25. });
  26. it('does not allow remote callback to nonReentrantView function', async function () {
  27. await expect(this.mock.countAndCallView(this.attacker)).to.be.revertedWith('ReentrancyAttack: failed call');
  28. });
  29. it('_reentrancyGuardEntered should be true when guarded', async function () {
  30. await this.mock.guardedCheckEntered();
  31. });
  32. it('_reentrancyGuardEntered should be false when unguarded', async function () {
  33. await this.mock.unguardedCheckNotEntered();
  34. });
  35. // The following are more side-effects than intended behavior:
  36. // I put them here as documentation, and to monitor any changes
  37. // in the side-effects.
  38. it('does not allow local recursion', async function () {
  39. await expect(this.mock.countLocalRecursive(10n)).to.be.revertedWithCustomError(
  40. this.mock,
  41. 'ReentrancyGuardReentrantCall',
  42. );
  43. });
  44. it('does not allow indirect local recursion', async function () {
  45. await expect(this.mock.countThisRecursive(10n)).to.be.revertedWith(`${this.name}: failed call`);
  46. });
  47. });
  48. }