solid-grinder 0.4.0

A CLI that goes along with building blocks of smart contract. Along with our front-end snippets, this toolbox can reduce L2 gas cost by encoding calldata for dApps development to use as little bytes of calldata as possible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
const { expectEvent, expectRevert, constants, BN } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');

const { time } = require('@nomicfoundation/hardhat-network-helpers');

const { shouldSupportInterfaces } = require('../utils/introspection/SupportsInterface.behavior');
const { network } = require('hardhat');
const { ZERO_ADDRESS } = require('@openzeppelin/test-helpers/src/constants');

const DEFAULT_ADMIN_ROLE = '0x0000000000000000000000000000000000000000000000000000000000000000';
const ROLE = web3.utils.soliditySha3('ROLE');
const OTHER_ROLE = web3.utils.soliditySha3('OTHER_ROLE');
const ZERO = web3.utils.toBN(0);

function shouldBehaveLikeAccessControl(errorPrefix, admin, authorized, other, otherAdmin) {
  shouldSupportInterfaces(['AccessControl']);

  describe('default admin', function () {
    it('deployer has default admin role', async function () {
      expect(await this.accessControl.hasRole(DEFAULT_ADMIN_ROLE, admin)).to.equal(true);
    });

    it("other roles's admin is the default admin role", async function () {
      expect(await this.accessControl.getRoleAdmin(ROLE)).to.equal(DEFAULT_ADMIN_ROLE);
    });

    it("default admin role's admin is itself", async function () {
      expect(await this.accessControl.getRoleAdmin(DEFAULT_ADMIN_ROLE)).to.equal(DEFAULT_ADMIN_ROLE);
    });
  });

  describe('granting', function () {
    beforeEach(async function () {
      await this.accessControl.grantRole(ROLE, authorized, { from: admin });
    });

    it('non-admin cannot grant role to other accounts', async function () {
      await expectRevert(
        this.accessControl.grantRole(ROLE, authorized, { from: other }),
        `${errorPrefix}: account ${other.toLowerCase()} is missing role ${DEFAULT_ADMIN_ROLE}`,
      );
    });

    it('accounts can be granted a role multiple times', async function () {
      await this.accessControl.grantRole(ROLE, authorized, { from: admin });
      const receipt = await this.accessControl.grantRole(ROLE, authorized, { from: admin });
      expectEvent.notEmitted(receipt, 'RoleGranted');
    });
  });

  describe('revoking', function () {
    it('roles that are not had can be revoked', async function () {
      expect(await this.accessControl.hasRole(ROLE, authorized)).to.equal(false);

      const receipt = await this.accessControl.revokeRole(ROLE, authorized, { from: admin });
      expectEvent.notEmitted(receipt, 'RoleRevoked');
    });

    context('with granted role', function () {
      beforeEach(async function () {
        await this.accessControl.grantRole(ROLE, authorized, { from: admin });
      });

      it('admin can revoke role', async function () {
        const receipt = await this.accessControl.revokeRole(ROLE, authorized, { from: admin });
        expectEvent(receipt, 'RoleRevoked', { account: authorized, role: ROLE, sender: admin });

        expect(await this.accessControl.hasRole(ROLE, authorized)).to.equal(false);
      });

      it('non-admin cannot revoke role', async function () {
        await expectRevert(
          this.accessControl.revokeRole(ROLE, authorized, { from: other }),
          `${errorPrefix}: account ${other.toLowerCase()} is missing role ${DEFAULT_ADMIN_ROLE}`,
        );
      });

      it('a role can be revoked multiple times', async function () {
        await this.accessControl.revokeRole(ROLE, authorized, { from: admin });

        const receipt = await this.accessControl.revokeRole(ROLE, authorized, { from: admin });
        expectEvent.notEmitted(receipt, 'RoleRevoked');
      });
    });
  });

  describe('renouncing', function () {
    it('roles that are not had can be renounced', async function () {
      const receipt = await this.accessControl.renounceRole(ROLE, authorized, { from: authorized });
      expectEvent.notEmitted(receipt, 'RoleRevoked');
    });

    context('with granted role', function () {
      beforeEach(async function () {
        await this.accessControl.grantRole(ROLE, authorized, { from: admin });
      });

      it('bearer can renounce role', async function () {
        const receipt = await this.accessControl.renounceRole(ROLE, authorized, { from: authorized });
        expectEvent(receipt, 'RoleRevoked', { account: authorized, role: ROLE, sender: authorized });

        expect(await this.accessControl.hasRole(ROLE, authorized)).to.equal(false);
      });

      it('only the sender can renounce their roles', async function () {
        await expectRevert(
          this.accessControl.renounceRole(ROLE, authorized, { from: admin }),
          `${errorPrefix}: can only renounce roles for self`,
        );
      });

      it('a role can be renounced multiple times', async function () {
        await this.accessControl.renounceRole(ROLE, authorized, { from: authorized });

        const receipt = await this.accessControl.renounceRole(ROLE, authorized, { from: authorized });
        expectEvent.notEmitted(receipt, 'RoleRevoked');
      });
    });
  });

  describe('setting role admin', function () {
    beforeEach(async function () {
      const receipt = await this.accessControl.$_setRoleAdmin(ROLE, OTHER_ROLE);
      expectEvent(receipt, 'RoleAdminChanged', {
        role: ROLE,
        previousAdminRole: DEFAULT_ADMIN_ROLE,
        newAdminRole: OTHER_ROLE,
      });

      await this.accessControl.grantRole(OTHER_ROLE, otherAdmin, { from: admin });
    });

    it("a role's admin role can be changed", async function () {
      expect(await this.accessControl.getRoleAdmin(ROLE)).to.equal(OTHER_ROLE);
    });

    it('the new admin can grant roles', async function () {
      const receipt = await this.accessControl.grantRole(ROLE, authorized, { from: otherAdmin });
      expectEvent(receipt, 'RoleGranted', { account: authorized, role: ROLE, sender: otherAdmin });
    });

    it('the new admin can revoke roles', async function () {
      await this.accessControl.grantRole(ROLE, authorized, { from: otherAdmin });
      const receipt = await this.accessControl.revokeRole(ROLE, authorized, { from: otherAdmin });
      expectEvent(receipt, 'RoleRevoked', { account: authorized, role: ROLE, sender: otherAdmin });
    });

    it("a role's previous admins no longer grant roles", async function () {
      await expectRevert(
        this.accessControl.grantRole(ROLE, authorized, { from: admin }),
        `${errorPrefix}: account ${admin.toLowerCase()} is missing role ${OTHER_ROLE}`,
      );
    });

    it("a role's previous admins no longer revoke roles", async function () {
      await expectRevert(
        this.accessControl.revokeRole(ROLE, authorized, { from: admin }),
        `${errorPrefix}: account ${admin.toLowerCase()} is missing role ${OTHER_ROLE}`,
      );
    });
  });

  describe('onlyRole modifier', function () {
    beforeEach(async function () {
      await this.accessControl.grantRole(ROLE, authorized, { from: admin });
    });

    it('do not revert if sender has role', async function () {
      await this.accessControl.methods['$_checkRole(bytes32)'](ROLE, { from: authorized });
    });

    it("revert if sender doesn't have role #1", async function () {
      await expectRevert(
        this.accessControl.methods['$_checkRole(bytes32)'](ROLE, { from: other }),
        `${errorPrefix}: account ${other.toLowerCase()} is missing role ${ROLE}`,
      );
    });

    it("revert if sender doesn't have role #2", async function () {
      await expectRevert(
        this.accessControl.methods['$_checkRole(bytes32)'](OTHER_ROLE, { from: authorized }),
        `${errorPrefix}: account ${authorized.toLowerCase()} is missing role ${OTHER_ROLE}`,
      );
    });
  });
}

function shouldBehaveLikeAccessControlEnumerable(errorPrefix, admin, authorized, other, otherAdmin, otherAuthorized) {
  shouldSupportInterfaces(['AccessControlEnumerable']);

  describe('enumerating', function () {
    it('role bearers can be enumerated', async function () {
      await this.accessControl.grantRole(ROLE, authorized, { from: admin });
      await this.accessControl.grantRole(ROLE, other, { from: admin });
      await this.accessControl.grantRole(ROLE, otherAuthorized, { from: admin });
      await this.accessControl.revokeRole(ROLE, other, { from: admin });

      const memberCount = await this.accessControl.getRoleMemberCount(ROLE);
      expect(memberCount).to.bignumber.equal('2');

      const bearers = [];
      for (let i = 0; i < memberCount; ++i) {
        bearers.push(await this.accessControl.getRoleMember(ROLE, i));
      }

      expect(bearers).to.have.members([authorized, otherAuthorized]);
    });
    it('role enumeration should be in sync after renounceRole call', async function () {
      expect(await this.accessControl.getRoleMemberCount(ROLE)).to.bignumber.equal('0');
      await this.accessControl.grantRole(ROLE, admin, { from: admin });
      expect(await this.accessControl.getRoleMemberCount(ROLE)).to.bignumber.equal('1');
      await this.accessControl.renounceRole(ROLE, admin, { from: admin });
      expect(await this.accessControl.getRoleMemberCount(ROLE)).to.bignumber.equal('0');
    });
  });
}

function shouldBehaveLikeAccessControlDefaultAdminRules(errorPrefix, delay, defaultAdmin, newDefaultAdmin, other) {
  shouldSupportInterfaces(['AccessControlDefaultAdminRules']);

  function expectNoEvent(receipt, eventName) {
    try {
      expectEvent(receipt, eventName);
      throw new Error(`${eventName} event found`);
    } catch (err) {
      expect(err.message).to.eq(`No '${eventName}' events found: expected false to equal true`);
    }
  }

  for (const getter of ['owner', 'defaultAdmin']) {
    describe(`${getter}()`, function () {
      it('has a default set to the initial default admin', async function () {
        const value = await this.accessControl[getter]();
        expect(value).to.equal(defaultAdmin);
        expect(await this.accessControl.hasRole(DEFAULT_ADMIN_ROLE, value)).to.be.true;
      });

      it('changes if the default admin changes', async function () {
        // Starts an admin transfer
        await this.accessControl.beginDefaultAdminTransfer(newDefaultAdmin, { from: defaultAdmin });

        // Wait for acceptance
        const acceptSchedule = web3.utils.toBN(await time.latest()).add(delay);
        await time.setNextBlockTimestamp(acceptSchedule.addn(1));
        await this.accessControl.acceptDefaultAdminTransfer({ from: newDefaultAdmin });

        const value = await this.accessControl[getter]();
        expect(value).to.equal(newDefaultAdmin);
      });
    });
  }

  describe('pendingDefaultAdmin()', function () {
    it('returns 0 if no pending default admin transfer', async function () {
      const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
      expect(newAdmin).to.eq(ZERO_ADDRESS);
      expect(schedule).to.be.bignumber.eq(ZERO);
    });

    describe('when there is a scheduled default admin transfer', function () {
      beforeEach('begins admin transfer', async function () {
        await this.accessControl.beginDefaultAdminTransfer(newDefaultAdmin, { from: defaultAdmin });
      });

      for (const [fromSchedule, tag] of [
        [-1, 'before'],
        [0, 'exactly when'],
        [1, 'after'],
      ]) {
        it(`returns pending admin and schedule ${tag} it passes if not accepted`, async function () {
          // Wait until schedule + fromSchedule
          const { schedule: firstSchedule } = await this.accessControl.pendingDefaultAdmin();
          await time.setNextBlockTimestamp(firstSchedule.toNumber() + fromSchedule);
          await network.provider.send('evm_mine'); // Mine a block to force the timestamp

          const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
          expect(newAdmin).to.eq(newDefaultAdmin);
          expect(schedule).to.be.bignumber.eq(firstSchedule);
        });
      }

      it('returns 0 after schedule passes and the transfer was accepted', async function () {
        // Wait after schedule
        const { schedule: firstSchedule } = await this.accessControl.pendingDefaultAdmin();
        await time.setNextBlockTimestamp(firstSchedule.addn(1));

        // Accepts
        await this.accessControl.acceptDefaultAdminTransfer({ from: newDefaultAdmin });

        const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
        expect(newAdmin).to.eq(ZERO_ADDRESS);
        expect(schedule).to.be.bignumber.eq(ZERO);
      });
    });
  });

  describe('defaultAdminDelay()', function () {
    it('returns the current delay', async function () {
      expect(await this.accessControl.defaultAdminDelay()).to.be.bignumber.eq(delay);
    });

    describe('when there is a scheduled delay change', function () {
      const newDelay = web3.utils.toBN(0xdead); // Any change

      beforeEach('begins delay change', async function () {
        await this.accessControl.changeDefaultAdminDelay(newDelay, { from: defaultAdmin });
      });

      for (const [fromSchedule, tag, expectedDelay, delayTag] of [
        [-1, 'before', delay, 'old'],
        [0, 'exactly when', delay, 'old'],
        [1, 'after', newDelay, 'new'],
      ]) {
        it(`returns ${delayTag} delay ${tag} delay schedule passes`, async function () {
          // Wait until schedule + fromSchedule
          const { schedule } = await this.accessControl.pendingDefaultAdminDelay();
          await time.setNextBlockTimestamp(schedule.toNumber() + fromSchedule);
          await network.provider.send('evm_mine'); // Mine a block to force the timestamp

          const currentDelay = await this.accessControl.defaultAdminDelay();
          expect(currentDelay).to.be.bignumber.eq(expectedDelay);
        });
      }
    });
  });

  describe('pendingDefaultAdminDelay()', function () {
    it('returns 0 if not set', async function () {
      const { newDelay, schedule } = await this.accessControl.pendingDefaultAdminDelay();
      expect(newDelay).to.be.bignumber.eq(ZERO);
      expect(schedule).to.be.bignumber.eq(ZERO);
    });

    describe('when there is a scheduled delay change', function () {
      const newDelay = web3.utils.toBN(0xdead); // Any change

      beforeEach('begins admin transfer', async function () {
        await this.accessControl.changeDefaultAdminDelay(newDelay, { from: defaultAdmin });
      });

      for (const [fromSchedule, tag, expectedDelay, delayTag, expectZeroSchedule] of [
        [-1, 'before', newDelay, 'new'],
        [0, 'exactly when', newDelay, 'new'],
        [1, 'after', ZERO, 'zero', true],
      ]) {
        it(`returns ${delayTag} delay ${tag} delay schedule passes`, async function () {
          // Wait until schedule + fromSchedule
          const { schedule: firstSchedule } = await this.accessControl.pendingDefaultAdminDelay();
          await time.setNextBlockTimestamp(firstSchedule.toNumber() + fromSchedule);
          await network.provider.send('evm_mine'); // Mine a block to force the timestamp

          const { newDelay, schedule } = await this.accessControl.pendingDefaultAdminDelay();
          expect(newDelay).to.be.bignumber.eq(expectedDelay);
          expect(schedule).to.be.bignumber.eq(expectZeroSchedule ? ZERO : firstSchedule);
        });
      }
    });
  });

  describe('defaultAdminDelayIncreaseWait()', function () {
    it('should return 5 days (default)', async function () {
      expect(await this.accessControl.defaultAdminDelayIncreaseWait()).to.be.bignumber.eq(
        web3.utils.toBN(time.duration.days(5)),
      );
    });
  });

  it('should revert if granting default admin role', async function () {
    await expectRevert(
      this.accessControl.grantRole(DEFAULT_ADMIN_ROLE, defaultAdmin, { from: defaultAdmin }),
      `${errorPrefix}: can't directly grant default admin role`,
    );
  });

  it('should revert if revoking default admin role', async function () {
    await expectRevert(
      this.accessControl.revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin, { from: defaultAdmin }),
      `${errorPrefix}: can't directly revoke default admin role`,
    );
  });

  it("should revert if defaultAdmin's admin is changed", async function () {
    await expectRevert(
      this.accessControl.$_setRoleAdmin(DEFAULT_ADMIN_ROLE, defaultAdmin),
      `${errorPrefix}: can't violate default admin rules`,
    );
  });

  it('should not grant the default admin role twice', async function () {
    await expectRevert(
      this.accessControl.$_grantRole(DEFAULT_ADMIN_ROLE, defaultAdmin),
      `${errorPrefix}: default admin already granted`,
    );
  });

  describe('begins a default admin transfer', function () {
    let receipt;
    let acceptSchedule;

    it('reverts if called by non default admin accounts', async function () {
      await expectRevert(
        this.accessControl.beginDefaultAdminTransfer(newDefaultAdmin, { from: other }),
        `${errorPrefix}: account ${other.toLowerCase()} is missing role ${DEFAULT_ADMIN_ROLE}`,
      );
    });

    describe('when there is no pending delay nor pending admin transfer', function () {
      beforeEach('begins admin transfer', async function () {
        receipt = await this.accessControl.beginDefaultAdminTransfer(newDefaultAdmin, { from: defaultAdmin });
        acceptSchedule = web3.utils.toBN(await time.latest()).add(delay);
      });

      it('should set pending default admin and schedule', async function () {
        const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
        expect(newAdmin).to.equal(newDefaultAdmin);
        expect(schedule).to.be.bignumber.equal(acceptSchedule);
        expectEvent(receipt, 'DefaultAdminTransferScheduled', {
          newAdmin,
          acceptSchedule,
        });
      });
    });

    describe('when there is a pending admin transfer', function () {
      beforeEach('sets a pending default admin transfer', async function () {
        await this.accessControl.beginDefaultAdminTransfer(newDefaultAdmin, { from: defaultAdmin });
        acceptSchedule = web3.utils.toBN(await time.latest()).add(delay);
      });

      for (const [fromSchedule, tag] of [
        [-1, 'before'],
        [0, 'exactly when'],
        [1, 'after'],
      ]) {
        it(`should be able to begin a transfer again ${tag} acceptSchedule passes`, async function () {
          // Wait until schedule + fromSchedule
          await time.setNextBlockTimestamp(acceptSchedule.toNumber() + fromSchedule);

          // defaultAdmin changes its mind and begin again to another address
          const receipt = await this.accessControl.beginDefaultAdminTransfer(other, { from: defaultAdmin });
          const newSchedule = web3.utils.toBN(await time.latest()).add(delay);
          const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
          expect(newAdmin).to.equal(other);
          expect(schedule).to.be.bignumber.equal(newSchedule);

          // Cancellation is always emitted since it was never accepted
          expectEvent(receipt, 'DefaultAdminTransferCanceled');
        });
      }

      it('should not emit a cancellation event if the new default admin accepted', async function () {
        // Wait until the acceptSchedule has passed
        await time.setNextBlockTimestamp(acceptSchedule.addn(1));

        // Accept and restart
        await this.accessControl.acceptDefaultAdminTransfer({ from: newDefaultAdmin });
        const receipt = await this.accessControl.beginDefaultAdminTransfer(other, { from: newDefaultAdmin });

        expectNoEvent(receipt, 'DefaultAdminTransferCanceled');
      });
    });

    describe('when there is a pending delay', function () {
      const newDelay = web3.utils.toBN(time.duration.hours(3));

      beforeEach('schedule a delay change', async function () {
        await this.accessControl.changeDefaultAdminDelay(newDelay, { from: defaultAdmin });
        const pendingDefaultAdminDelay = await this.accessControl.pendingDefaultAdminDelay();
        acceptSchedule = pendingDefaultAdminDelay.schedule;
      });

      for (const [fromSchedule, schedulePassed, expectedDelay, delayTag] of [
        [-1, 'before', delay, 'old'],
        [0, 'exactly when', delay, 'old'],
        [1, 'after', newDelay, 'new'],
      ]) {
        it(`should set the ${delayTag} delay and apply it to next default admin transfer schedule ${schedulePassed} acceptSchedule passed`, async function () {
          // Wait until the expected fromSchedule time
          await time.setNextBlockTimestamp(acceptSchedule.toNumber() + fromSchedule);

          // Start the new default admin transfer and get its schedule
          const receipt = await this.accessControl.beginDefaultAdminTransfer(newDefaultAdmin, { from: defaultAdmin });
          const expectedAcceptSchedule = web3.utils.toBN(await time.latest()).add(expectedDelay);

          // Check that the schedule corresponds with the new delay
          const { newAdmin, schedule: transferSchedule } = await this.accessControl.pendingDefaultAdmin();
          expect(newAdmin).to.equal(newDefaultAdmin);
          expect(transferSchedule).to.be.bignumber.equal(expectedAcceptSchedule);

          expectEvent(receipt, 'DefaultAdminTransferScheduled', {
            newAdmin,
            acceptSchedule: expectedAcceptSchedule,
          });
        });
      }
    });
  });

  describe('accepts transfer admin', function () {
    let acceptSchedule;

    beforeEach(async function () {
      await this.accessControl.beginDefaultAdminTransfer(newDefaultAdmin, { from: defaultAdmin });
      acceptSchedule = web3.utils.toBN(await time.latest()).add(delay);
    });

    it('should revert if caller is not pending default admin', async function () {
      await time.setNextBlockTimestamp(acceptSchedule.addn(1));
      await expectRevert(
        this.accessControl.acceptDefaultAdminTransfer({ from: other }),
        `${errorPrefix}: pending admin must accept`,
      );
    });

    describe('when caller is pending default admin and delay has passed', function () {
      beforeEach(async function () {
        await time.setNextBlockTimestamp(acceptSchedule.addn(1));
      });

      it('accepts a transfer and changes default admin', async function () {
        const receipt = await this.accessControl.acceptDefaultAdminTransfer({ from: newDefaultAdmin });

        // Storage changes
        expect(await this.accessControl.hasRole(DEFAULT_ADMIN_ROLE, defaultAdmin)).to.be.false;
        expect(await this.accessControl.hasRole(DEFAULT_ADMIN_ROLE, newDefaultAdmin)).to.be.true;
        expect(await this.accessControl.owner()).to.equal(newDefaultAdmin);

        // Emit events
        expectEvent(receipt, 'RoleRevoked', {
          role: DEFAULT_ADMIN_ROLE,
          account: defaultAdmin,
        });
        expectEvent(receipt, 'RoleGranted', {
          role: DEFAULT_ADMIN_ROLE,
          account: newDefaultAdmin,
        });

        // Resets pending default admin and schedule
        const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
        expect(newAdmin).to.equal(constants.ZERO_ADDRESS);
        expect(schedule).to.be.bignumber.equal(ZERO);
      });
    });

    describe('schedule not passed', function () {
      for (const [fromSchedule, tag] of [
        [-1, 'less'],
        [0, 'equal'],
      ]) {
        it(`should revert if block.timestamp is ${tag} to schedule`, async function () {
          await time.setNextBlockTimestamp(acceptSchedule.toNumber() + fromSchedule);
          await expectRevert(
            this.accessControl.acceptDefaultAdminTransfer({ from: newDefaultAdmin }),
            `${errorPrefix}: transfer delay not passed`,
          );
        });
      }
    });
  });

  describe('cancels a default admin transfer', function () {
    it('reverts if called by non default admin accounts', async function () {
      await expectRevert(
        this.accessControl.cancelDefaultAdminTransfer({ from: other }),
        `${errorPrefix}: account ${other.toLowerCase()} is missing role ${DEFAULT_ADMIN_ROLE}`,
      );
    });

    describe('when there is a pending default admin transfer', function () {
      let acceptSchedule;

      beforeEach(async function () {
        await this.accessControl.beginDefaultAdminTransfer(newDefaultAdmin, { from: defaultAdmin });
        acceptSchedule = web3.utils.toBN(await time.latest()).add(delay);
      });

      for (const [fromSchedule, tag] of [
        [-1, 'before'],
        [0, 'exactly when'],
        [1, 'after'],
      ]) {
        it(`resets pending default admin and schedule ${tag} transfer schedule passes`, async function () {
          // Advance until passed delay
          await time.setNextBlockTimestamp(acceptSchedule.toNumber() + fromSchedule);

          const receipt = await this.accessControl.cancelDefaultAdminTransfer({ from: defaultAdmin });

          const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
          expect(newAdmin).to.equal(constants.ZERO_ADDRESS);
          expect(schedule).to.be.bignumber.equal(ZERO);

          expectEvent(receipt, 'DefaultAdminTransferCanceled');
        });
      }

      it('should revert if the previous default admin tries to accept', async function () {
        await this.accessControl.cancelDefaultAdminTransfer({ from: defaultAdmin });

        // Advance until passed delay
        await time.setNextBlockTimestamp(acceptSchedule.addn(1));

        // Previous pending default admin should not be able to accept after cancellation.
        await expectRevert(
          this.accessControl.acceptDefaultAdminTransfer({ from: newDefaultAdmin }),
          `${errorPrefix}: pending admin must accept`,
        );
      });
    });

    describe('when there is no pending default admin transfer', async function () {
      it('should succeed without changes', async function () {
        const receipt = await this.accessControl.cancelDefaultAdminTransfer({ from: defaultAdmin });

        const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
        expect(newAdmin).to.equal(constants.ZERO_ADDRESS);
        expect(schedule).to.be.bignumber.equal(ZERO);

        expectNoEvent(receipt, 'DefaultAdminTransferCanceled');
      });
    });
  });

  describe('renounces admin', function () {
    let expectedSchedule;
    let delayPassed;
    let delayNotPassed;

    beforeEach(async function () {
      await this.accessControl.beginDefaultAdminTransfer(constants.ZERO_ADDRESS, { from: defaultAdmin });
      expectedSchedule = web3.utils.toBN(await time.latest()).add(delay);
      delayNotPassed = expectedSchedule;
      delayPassed = expectedSchedule.addn(1);
    });

    it('reverts if caller is not default admin', async function () {
      await time.setNextBlockTimestamp(delayPassed);
      await expectRevert(
        this.accessControl.renounceRole(DEFAULT_ADMIN_ROLE, other, { from: defaultAdmin }),
        `${errorPrefix}: can only renounce roles for self`,
      );
    });

    it("renouncing the admin role when not an admin doesn't affect the schedule", async function () {
      await time.setNextBlockTimestamp(delayPassed);
      await this.accessControl.renounceRole(DEFAULT_ADMIN_ROLE, other, { from: other });

      const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
      expect(newAdmin).to.equal(constants.ZERO_ADDRESS);
      expect(schedule).to.be.bignumber.equal(expectedSchedule);
    });

    it('keeps defaultAdmin consistent with hasRole if another non-defaultAdmin user renounces the DEFAULT_ADMIN_ROLE', async function () {
      await time.setNextBlockTimestamp(delayPassed);

      // This passes because it's a noop
      await this.accessControl.renounceRole(DEFAULT_ADMIN_ROLE, other, { from: other });

      expect(await this.accessControl.hasRole(DEFAULT_ADMIN_ROLE, defaultAdmin)).to.be.true;
      expect(await this.accessControl.defaultAdmin()).to.be.equal(defaultAdmin);
    });

    it('renounces role', async function () {
      await time.setNextBlockTimestamp(delayPassed);
      const receipt = await this.accessControl.renounceRole(DEFAULT_ADMIN_ROLE, defaultAdmin, { from: defaultAdmin });

      expect(await this.accessControl.hasRole(DEFAULT_ADMIN_ROLE, defaultAdmin)).to.be.false;
      expect(await this.accessControl.defaultAdmin()).to.be.equal(constants.ZERO_ADDRESS);
      expectEvent(receipt, 'RoleRevoked', {
        role: DEFAULT_ADMIN_ROLE,
        account: defaultAdmin,
      });
      expect(await this.accessControl.owner()).to.equal(constants.ZERO_ADDRESS);
      const { newAdmin, schedule } = await this.accessControl.pendingDefaultAdmin();
      expect(newAdmin).to.eq(ZERO_ADDRESS);
      expect(schedule).to.be.bignumber.eq(ZERO);
    });

    it('allows to recover access using the internal _grantRole', async function () {
      await time.setNextBlockTimestamp(delayPassed);
      await this.accessControl.renounceRole(DEFAULT_ADMIN_ROLE, defaultAdmin, { from: defaultAdmin });

      const grantRoleReceipt = await this.accessControl.$_grantRole(DEFAULT_ADMIN_ROLE, other);
      expectEvent(grantRoleReceipt, 'RoleGranted', {
        role: DEFAULT_ADMIN_ROLE,
        account: other,
      });
    });

    describe('schedule not passed', function () {
      for (const [fromSchedule, tag] of [
        [-1, 'less'],
        [0, 'equal'],
      ]) {
        it(`reverts if block.timestamp is ${tag} to schedule`, async function () {
          await time.setNextBlockTimestamp(delayNotPassed.toNumber() + fromSchedule);
          await expectRevert(
            this.accessControl.renounceRole(DEFAULT_ADMIN_ROLE, defaultAdmin, { from: defaultAdmin }),
            `${errorPrefix}: only can renounce in two delayed steps`,
          );
        });
      }
    });
  });

  describe('changes delay', function () {
    it('reverts if called by non default admin accounts', async function () {
      await expectRevert(
        this.accessControl.changeDefaultAdminDelay(time.duration.hours(4), {
          from: other,
        }),
        `${errorPrefix}: account ${other.toLowerCase()} is missing role ${DEFAULT_ADMIN_ROLE}`,
      );
    });

    for (const [newDefaultAdminDelay, delayChangeType] of [
      [web3.utils.toBN(delay).subn(time.duration.hours(1)), 'decreased'],
      [web3.utils.toBN(delay).addn(time.duration.hours(1)), 'increased'],
      [web3.utils.toBN(delay).addn(time.duration.days(5)), 'increased to more than 5 days'],
    ]) {
      describe(`when the delay is ${delayChangeType}`, function () {
        it('begins the delay change to the new delay', async function () {
          // Begins the change
          const receipt = await this.accessControl.changeDefaultAdminDelay(newDefaultAdminDelay, {
            from: defaultAdmin,
          });

          // Calculate expected values
          const cap = await this.accessControl.defaultAdminDelayIncreaseWait();
          const changeDelay = newDefaultAdminDelay.lte(delay)
            ? delay.sub(newDefaultAdminDelay)
            : BN.min(newDefaultAdminDelay, cap);
          const timestamp = web3.utils.toBN(await time.latest());
          const effectSchedule = timestamp.add(changeDelay);

          // Assert
          const { newDelay, schedule } = await this.accessControl.pendingDefaultAdminDelay();
          expect(newDelay).to.be.bignumber.eq(newDefaultAdminDelay);
          expect(schedule).to.be.bignumber.eq(effectSchedule);
          expectEvent(receipt, 'DefaultAdminDelayChangeScheduled', {
            newDelay,
            effectSchedule,
          });
        });

        describe('scheduling again', function () {
          beforeEach('schedule once', async function () {
            await this.accessControl.changeDefaultAdminDelay(newDefaultAdminDelay, { from: defaultAdmin });
          });

          for (const [fromSchedule, tag] of [
            [-1, 'before'],
            [0, 'exactly when'],
            [1, 'after'],
          ]) {
            const passed = fromSchedule > 0;

            it(`succeeds ${tag} the delay schedule passes`, async function () {
              // Wait until schedule + fromSchedule
              const { schedule: firstSchedule } = await this.accessControl.pendingDefaultAdminDelay();
              await time.setNextBlockTimestamp(firstSchedule.toNumber() + fromSchedule);

              // Default admin changes its mind and begins another delay change
              const anotherNewDefaultAdminDelay = newDefaultAdminDelay.addn(time.duration.hours(2));
              const receipt = await this.accessControl.changeDefaultAdminDelay(anotherNewDefaultAdminDelay, {
                from: defaultAdmin,
              });

              // Calculate expected values
              const cap = await this.accessControl.defaultAdminDelayIncreaseWait();
              const timestamp = web3.utils.toBN(await time.latest());
              const effectSchedule = timestamp.add(BN.min(cap, anotherNewDefaultAdminDelay));

              // Assert
              const { newDelay, schedule } = await this.accessControl.pendingDefaultAdminDelay();
              expect(newDelay).to.be.bignumber.eq(anotherNewDefaultAdminDelay);
              expect(schedule).to.be.bignumber.eq(effectSchedule);
              expectEvent(receipt, 'DefaultAdminDelayChangeScheduled', {
                newDelay,
                effectSchedule,
              });
            });

            const emit = passed ? 'not emit' : 'emit';
            it(`should ${emit} a cancellation event ${tag} the delay schedule passes`, async function () {
              // Wait until schedule + fromSchedule
              const { schedule: firstSchedule } = await this.accessControl.pendingDefaultAdminDelay();
              await time.setNextBlockTimestamp(firstSchedule.toNumber() + fromSchedule);

              // Default admin changes its mind and begins another delay change
              const anotherNewDefaultAdminDelay = newDefaultAdminDelay.addn(time.duration.hours(2));
              const receipt = await this.accessControl.changeDefaultAdminDelay(anotherNewDefaultAdminDelay, {
                from: defaultAdmin,
              });

              const eventMatcher = passed ? expectNoEvent : expectEvent;
              eventMatcher(receipt, 'DefaultAdminDelayChangeCanceled');
            });
          }
        });
      });
    }
  });

  describe('rollbacks a delay change', function () {
    it('reverts if called by non default admin accounts', async function () {
      await expectRevert(
        this.accessControl.rollbackDefaultAdminDelay({ from: other }),
        `${errorPrefix}: account ${other.toLowerCase()} is missing role ${DEFAULT_ADMIN_ROLE}`,
      );
    });

    describe('when there is a pending delay', function () {
      beforeEach('set pending delay', async function () {
        await this.accessControl.changeDefaultAdminDelay(time.duration.hours(12), { from: defaultAdmin });
      });

      for (const [fromSchedule, tag] of [
        [-1, 'before'],
        [0, 'exactly when'],
        [1, 'after'],
      ]) {
        const passed = fromSchedule > 0;

        it(`resets pending delay and schedule ${tag} delay change schedule passes`, async function () {
          // Wait until schedule + fromSchedule
          const { schedule: firstSchedule } = await this.accessControl.pendingDefaultAdminDelay();
          await time.setNextBlockTimestamp(firstSchedule.toNumber() + fromSchedule);

          await this.accessControl.rollbackDefaultAdminDelay({ from: defaultAdmin });

          const { newDelay, schedule } = await this.accessControl.pendingDefaultAdminDelay();
          expect(newDelay).to.be.bignumber.eq(ZERO);
          expect(schedule).to.be.bignumber.eq(ZERO);
        });

        const emit = passed ? 'not emit' : 'emit';
        it(`should ${emit} a cancellation event ${tag} the delay schedule passes`, async function () {
          // Wait until schedule + fromSchedule
          const { schedule: firstSchedule } = await this.accessControl.pendingDefaultAdminDelay();
          await time.setNextBlockTimestamp(firstSchedule.toNumber() + fromSchedule);

          const receipt = await this.accessControl.rollbackDefaultAdminDelay({ from: defaultAdmin });

          const eventMatcher = passed ? expectNoEvent : expectEvent;
          eventMatcher(receipt, 'DefaultAdminDelayChangeCanceled');
        });
      }
    });

    describe('when there is no pending delay', function () {
      it('succeeds without changes', async function () {
        await this.accessControl.rollbackDefaultAdminDelay({ from: defaultAdmin });

        const { newDelay, schedule } = await this.accessControl.pendingDefaultAdminDelay();
        expect(newDelay).to.be.bignumber.eq(ZERO);
        expect(schedule).to.be.bignumber.eq(ZERO);
      });
    });
  });
}

module.exports = {
  DEFAULT_ADMIN_ROLE,
  shouldBehaveLikeAccessControl,
  shouldBehaveLikeAccessControlEnumerable,
  shouldBehaveLikeAccessControlDefaultAdminRules,
};