ReentrancyGuard.test.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. return { name, mock };
  10. }
  11. beforeEach(async function () {
  12. Object.assign(this, await loadFixture(fixture));
  13. });
  14. it('nonReentrant function can be called', async function () {
  15. expect(await this.mock.counter()).to.equal(0n);
  16. await this.mock.callback();
  17. expect(await this.mock.counter()).to.equal(1n);
  18. });
  19. it('does not allow remote callback', async function () {
  20. const attacker = await ethers.deployContract('ReentrancyAttack');
  21. await expect(this.mock.countAndCall(attacker)).to.be.revertedWith('ReentrancyAttack: failed call');
  22. });
  23. it('_reentrancyGuardEntered should be true when guarded', async function () {
  24. await this.mock.guardedCheckEntered();
  25. });
  26. it('_reentrancyGuardEntered should be false when unguarded', async function () {
  27. await this.mock.unguardedCheckNotEntered();
  28. });
  29. // The following are more side-effects than intended behavior:
  30. // I put them here as documentation, and to monitor any changes
  31. // in the side-effects.
  32. it('does not allow local recursion', async function () {
  33. await expect(this.mock.countLocalRecursive(10n)).to.be.revertedWithCustomError(
  34. this.mock,
  35. 'ReentrancyGuardReentrantCall',
  36. );
  37. });
  38. it('does not allow indirect local recursion', async function () {
  39. await expect(this.mock.countThisRecursive(10n)).to.be.revertedWith(`${this.name}: failed call`);
  40. });
  41. });
  42. }