ReentrancyGuard.test.js 1.6 KB

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