This commit is contained in:
dexorder
2024-10-17 02:42:28 -04:00
commit 25def69c66
878 changed files with 112489 additions and 0 deletions

View File

@@ -0,0 +1,874 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const time = require('../helpers/time');
const { shouldSupportInterfaces } = require('../utils/introspection/SupportsInterface.behavior');
const DEFAULT_ADMIN_ROLE = ethers.ZeroHash;
const ROLE = ethers.id('ROLE');
const OTHER_ROLE = ethers.id('OTHER_ROLE');
function shouldBehaveLikeAccessControl() {
beforeEach(async function () {
[this.authorized, this.other, this.otherAdmin] = this.accounts;
});
shouldSupportInterfaces(['AccessControl']);
describe('default admin', function () {
it('deployer has default admin role', async function () {
expect(await this.mock.hasRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin)).to.be.true;
});
it("other roles's admin is the default admin role", async function () {
expect(await this.mock.getRoleAdmin(ROLE)).to.equal(DEFAULT_ADMIN_ROLE);
});
it("default admin role's admin is itself", async function () {
expect(await this.mock.getRoleAdmin(DEFAULT_ADMIN_ROLE)).to.equal(DEFAULT_ADMIN_ROLE);
});
});
describe('granting', function () {
beforeEach(async function () {
await this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.authorized);
});
it('non-admin cannot grant role to other accounts', async function () {
await expect(this.mock.connect(this.other).grantRole(ROLE, this.authorized))
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.other, DEFAULT_ADMIN_ROLE);
});
it('accounts can be granted a role multiple times', async function () {
await this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.authorized);
await expect(this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.authorized)).to.not.emit(
this.mock,
'RoleGranted',
);
});
});
describe('revoking', function () {
it('roles that are not had can be revoked', async function () {
expect(await this.mock.hasRole(ROLE, this.authorized)).to.be.false;
await expect(this.mock.connect(this.defaultAdmin).revokeRole(ROLE, this.authorized)).to.not.emit(
this.mock,
'RoleRevoked',
);
});
describe('with granted role', function () {
beforeEach(async function () {
await this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.authorized);
});
it('admin can revoke role', async function () {
await expect(this.mock.connect(this.defaultAdmin).revokeRole(ROLE, this.authorized))
.to.emit(this.mock, 'RoleRevoked')
.withArgs(ROLE, this.authorized, this.defaultAdmin);
expect(await this.mock.hasRole(ROLE, this.authorized)).to.be.false;
});
it('non-admin cannot revoke role', async function () {
await expect(this.mock.connect(this.other).revokeRole(ROLE, this.authorized))
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.other, DEFAULT_ADMIN_ROLE);
});
it('a role can be revoked multiple times', async function () {
await this.mock.connect(this.defaultAdmin).revokeRole(ROLE, this.authorized);
await expect(this.mock.connect(this.defaultAdmin).revokeRole(ROLE, this.authorized)).to.not.emit(
this.mock,
'RoleRevoked',
);
});
});
});
describe('renouncing', function () {
it('roles that are not had can be renounced', async function () {
await expect(this.mock.connect(this.authorized).renounceRole(ROLE, this.authorized)).to.not.emit(
this.mock,
'RoleRevoked',
);
});
describe('with granted role', function () {
beforeEach(async function () {
await this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.authorized);
});
it('bearer can renounce role', async function () {
await expect(this.mock.connect(this.authorized).renounceRole(ROLE, this.authorized))
.to.emit(this.mock, 'RoleRevoked')
.withArgs(ROLE, this.authorized, this.authorized);
expect(await this.mock.hasRole(ROLE, this.authorized)).to.be.false;
});
it('only the sender can renounce their roles', async function () {
await expect(
this.mock.connect(this.defaultAdmin).renounceRole(ROLE, this.authorized),
).to.be.revertedWithCustomError(this.mock, 'AccessControlBadConfirmation');
});
it('a role can be renounced multiple times', async function () {
await this.mock.connect(this.authorized).renounceRole(ROLE, this.authorized);
await expect(this.mock.connect(this.authorized).renounceRole(ROLE, this.authorized)).not.to.emit(
this.mock,
'RoleRevoked',
);
});
});
});
describe('setting role admin', function () {
beforeEach(async function () {
await expect(this.mock.$_setRoleAdmin(ROLE, OTHER_ROLE))
.to.emit(this.mock, 'RoleAdminChanged')
.withArgs(ROLE, DEFAULT_ADMIN_ROLE, OTHER_ROLE);
await this.mock.connect(this.defaultAdmin).grantRole(OTHER_ROLE, this.otherAdmin);
});
it("a role's admin role can be changed", async function () {
expect(await this.mock.getRoleAdmin(ROLE)).to.equal(OTHER_ROLE);
});
it('the new admin can grant roles', async function () {
await expect(this.mock.connect(this.otherAdmin).grantRole(ROLE, this.authorized))
.to.emit(this.mock, 'RoleGranted')
.withArgs(ROLE, this.authorized, this.otherAdmin);
});
it('the new admin can revoke roles', async function () {
await this.mock.connect(this.otherAdmin).grantRole(ROLE, this.authorized);
await expect(this.mock.connect(this.otherAdmin).revokeRole(ROLE, this.authorized))
.to.emit(this.mock, 'RoleRevoked')
.withArgs(ROLE, this.authorized, this.otherAdmin);
});
it("a role's previous admins no longer grant roles", async function () {
await expect(this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.authorized))
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.defaultAdmin, OTHER_ROLE);
});
it("a role's previous admins no longer revoke roles", async function () {
await expect(this.mock.connect(this.defaultAdmin).revokeRole(ROLE, this.authorized))
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.defaultAdmin, OTHER_ROLE);
});
});
describe('onlyRole modifier', function () {
beforeEach(async function () {
await this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.authorized);
});
it('do not revert if sender has role', async function () {
await this.mock.connect(this.authorized).$_checkRole(ROLE);
});
it("revert if sender doesn't have role #1", async function () {
await expect(this.mock.connect(this.other).$_checkRole(ROLE))
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.other, ROLE);
});
it("revert if sender doesn't have role #2", async function () {
await expect(this.mock.connect(this.authorized).$_checkRole(OTHER_ROLE))
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.authorized, OTHER_ROLE);
});
});
describe('internal functions', function () {
describe('_grantRole', function () {
it('return true if the account does not have the role', async function () {
await expect(this.mock.$_grantRole(ROLE, this.authorized))
.to.emit(this.mock, 'return$_grantRole')
.withArgs(true);
});
it('return false if the account has the role', async function () {
await this.mock.$_grantRole(ROLE, this.authorized);
await expect(this.mock.$_grantRole(ROLE, this.authorized))
.to.emit(this.mock, 'return$_grantRole')
.withArgs(false);
});
});
describe('_revokeRole', function () {
it('return true if the account has the role', async function () {
await this.mock.$_grantRole(ROLE, this.authorized);
await expect(this.mock.$_revokeRole(ROLE, this.authorized))
.to.emit(this.mock, 'return$_revokeRole')
.withArgs(true);
});
it('return false if the account does not have the role', async function () {
await expect(this.mock.$_revokeRole(ROLE, this.authorized))
.to.emit(this.mock, 'return$_revokeRole')
.withArgs(false);
});
});
});
}
function shouldBehaveLikeAccessControlEnumerable() {
beforeEach(async function () {
[this.authorized, this.other, this.otherAdmin, this.otherAuthorized] = this.accounts;
});
shouldSupportInterfaces(['AccessControlEnumerable']);
describe('enumerating', function () {
it('role bearers can be enumerated', async function () {
await this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.authorized);
await this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.other);
await this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.otherAuthorized);
await this.mock.connect(this.defaultAdmin).revokeRole(ROLE, this.other);
const expectedMembers = [this.authorized.address, this.otherAuthorized.address];
const memberCount = await this.mock.getRoleMemberCount(ROLE);
const members = [];
for (let i = 0; i < memberCount; ++i) {
members.push(await this.mock.getRoleMember(ROLE, i));
}
expect(memberCount).to.equal(expectedMembers.length);
expect(members).to.deep.equal(expectedMembers);
expect(await this.mock.getRoleMembers(ROLE)).to.deep.equal(expectedMembers);
});
it('role enumeration should be in sync after renounceRole call', async function () {
expect(await this.mock.getRoleMemberCount(ROLE)).to.equal(0);
await this.mock.connect(this.defaultAdmin).grantRole(ROLE, this.defaultAdmin);
expect(await this.mock.getRoleMemberCount(ROLE)).to.equal(1);
await this.mock.connect(this.defaultAdmin).renounceRole(ROLE, this.defaultAdmin);
expect(await this.mock.getRoleMemberCount(ROLE)).to.equal(0);
});
});
}
function shouldBehaveLikeAccessControlDefaultAdminRules() {
shouldSupportInterfaces(['AccessControlDefaultAdminRules']);
beforeEach(async function () {
[this.newDefaultAdmin, this.other] = this.accounts;
});
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.mock[getter]();
expect(value).to.equal(this.defaultAdmin);
expect(await this.mock.hasRole(DEFAULT_ADMIN_ROLE, value)).to.be.true;
});
it('changes if the default admin changes', async function () {
// Starts an admin transfer
await this.mock.connect(this.defaultAdmin).beginDefaultAdminTransfer(this.newDefaultAdmin);
// Wait for acceptance
await time.increaseBy.timestamp(this.delay + 1n, false);
await this.mock.connect(this.newDefaultAdmin).acceptDefaultAdminTransfer();
const value = await this.mock[getter]();
expect(value).to.equal(this.newDefaultAdmin);
});
});
}
describe('pendingDefaultAdmin()', function () {
it('returns 0 if no pending default admin transfer', async function () {
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(ethers.ZeroAddress);
expect(schedule).to.equal(0);
});
describe('when there is a scheduled default admin transfer', function () {
beforeEach('begins admin transfer', async function () {
await this.mock.connect(this.defaultAdmin).beginDefaultAdminTransfer(this.newDefaultAdmin);
});
for (const [fromSchedule, tag] of [
[-1n, 'before'],
[0n, 'exactly when'],
[1n, 'after'],
]) {
it(`returns pending admin and schedule ${tag} it passes if not accepted`, async function () {
// Wait until schedule + fromSchedule
const { schedule: firstSchedule } = await this.mock.pendingDefaultAdmin();
await time.increaseTo.timestamp(firstSchedule + fromSchedule);
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(this.newDefaultAdmin);
expect(schedule).to.equal(firstSchedule);
});
}
it('returns 0 after schedule passes and the transfer was accepted', async function () {
// Wait after schedule
const { schedule: firstSchedule } = await this.mock.pendingDefaultAdmin();
await time.increaseTo.timestamp(firstSchedule + 1n, false);
// Accepts
await this.mock.connect(this.newDefaultAdmin).acceptDefaultAdminTransfer();
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(ethers.ZeroAddress);
expect(schedule).to.equal(0);
});
});
});
describe('defaultAdminDelay()', function () {
it('returns the current delay', async function () {
expect(await this.mock.defaultAdminDelay()).to.equal(this.delay);
});
describe('when there is a scheduled delay change', function () {
const newDelay = 0x1337n; // Any change
beforeEach('begins delay change', async function () {
await this.mock.connect(this.defaultAdmin).changeDefaultAdminDelay(newDelay);
});
for (const [fromSchedule, tag, expectNew, delayTag] of [
[-1n, 'before', false, 'old'],
[0n, 'exactly when', false, 'old'],
[1n, 'after', true, 'new'],
]) {
it(`returns ${delayTag} delay ${tag} delay schedule passes`, async function () {
// Wait until schedule + fromSchedule
const { schedule } = await this.mock.pendingDefaultAdminDelay();
await time.increaseTo.timestamp(schedule + fromSchedule);
const currentDelay = await this.mock.defaultAdminDelay();
expect(currentDelay).to.equal(expectNew ? newDelay : this.delay);
});
}
});
});
describe('pendingDefaultAdminDelay()', function () {
it('returns 0 if not set', async function () {
const { newDelay, schedule } = await this.mock.pendingDefaultAdminDelay();
expect(newDelay).to.equal(0);
expect(schedule).to.equal(0);
});
describe('when there is a scheduled delay change', function () {
const newDelay = 0x1337n; // Any change
beforeEach('begins admin transfer', async function () {
await this.mock.connect(this.defaultAdmin).changeDefaultAdminDelay(newDelay);
});
for (const [fromSchedule, tag, expectedDelay, delayTag, expectZeroSchedule] of [
[-1n, 'before', newDelay, 'new'],
[0n, 'exactly when', newDelay, 'new'],
[1n, 'after', 0, 'zero', true],
]) {
it(`returns ${delayTag} delay ${tag} delay schedule passes`, async function () {
// Wait until schedule + fromSchedule
const { schedule: firstSchedule } = await this.mock.pendingDefaultAdminDelay();
await time.increaseTo.timestamp(firstSchedule + fromSchedule);
const { newDelay, schedule } = await this.mock.pendingDefaultAdminDelay();
expect(newDelay).to.equal(expectedDelay);
expect(schedule).to.equal(expectZeroSchedule ? 0 : firstSchedule);
});
}
});
});
describe('defaultAdminDelayIncreaseWait()', function () {
it('should return 5 days (default)', async function () {
expect(await this.mock.defaultAdminDelayIncreaseWait()).to.equal(time.duration.days(5));
});
});
it('should revert if granting default admin role', async function () {
await expect(
this.mock.connect(this.defaultAdmin).grantRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin),
).to.be.revertedWithCustomError(this.mock, 'AccessControlEnforcedDefaultAdminRules');
});
it('should revert if revoking default admin role', async function () {
await expect(
this.mock.connect(this.defaultAdmin).revokeRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin),
).to.be.revertedWithCustomError(this.mock, 'AccessControlEnforcedDefaultAdminRules');
});
it("should revert if defaultAdmin's admin is changed", async function () {
await expect(this.mock.$_setRoleAdmin(DEFAULT_ADMIN_ROLE, OTHER_ROLE)).to.be.revertedWithCustomError(
this.mock,
'AccessControlEnforcedDefaultAdminRules',
);
});
it('should not grant the default admin role twice', async function () {
await expect(this.mock.$_grantRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin)).to.be.revertedWithCustomError(
this.mock,
'AccessControlEnforcedDefaultAdminRules',
);
});
describe('begins a default admin transfer', function () {
it('reverts if called by non default admin accounts', async function () {
await expect(this.mock.connect(this.other).beginDefaultAdminTransfer(this.newDefaultAdmin))
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.other, DEFAULT_ADMIN_ROLE);
});
describe('when there is no pending delay nor pending admin transfer', function () {
it('should set pending default admin and schedule', async function () {
const nextBlockTimestamp = (await time.clock.timestamp()) + 1n;
const acceptSchedule = nextBlockTimestamp + this.delay;
await time.increaseTo.timestamp(nextBlockTimestamp, false); // set timestamp but don't mine the block yet
await expect(this.mock.connect(this.defaultAdmin).beginDefaultAdminTransfer(this.newDefaultAdmin))
.to.emit(this.mock, 'DefaultAdminTransferScheduled')
.withArgs(this.newDefaultAdmin, acceptSchedule);
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(this.newDefaultAdmin);
expect(schedule).to.equal(acceptSchedule);
});
});
describe('when there is a pending admin transfer', function () {
beforeEach('sets a pending default admin transfer', async function () {
await this.mock.connect(this.defaultAdmin).beginDefaultAdminTransfer(this.newDefaultAdmin);
this.acceptSchedule = (await time.clock.timestamp()) + this.delay;
});
for (const [fromSchedule, tag] of [
[-1n, 'before'],
[0n, 'exactly when'],
[1n, 'after'],
]) {
it(`should be able to begin a transfer again ${tag} acceptSchedule passes`, async function () {
// Wait until schedule + fromSchedule
await time.increaseTo.timestamp(this.acceptSchedule + fromSchedule, false);
// defaultAdmin changes its mind and begin again to another address
await expect(this.mock.connect(this.defaultAdmin).beginDefaultAdminTransfer(this.other)).to.emit(
this.mock,
'DefaultAdminTransferCanceled', // Cancellation is always emitted since it was never accepted
);
const newSchedule = (await time.clock.timestamp()) + this.delay;
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(this.other);
expect(schedule).to.equal(newSchedule);
});
}
it('should not emit a cancellation event if the new default admin accepted', async function () {
// Wait until the acceptSchedule has passed
await time.increaseTo.timestamp(this.acceptSchedule + 1n, false);
// Accept and restart
await this.mock.connect(this.newDefaultAdmin).acceptDefaultAdminTransfer();
await expect(this.mock.connect(this.newDefaultAdmin).beginDefaultAdminTransfer(this.other)).to.not.emit(
this.mock,
'DefaultAdminTransferCanceled',
);
});
});
describe('when there is a pending delay', function () {
const newDelay = time.duration.hours(3);
beforeEach('schedule a delay change', async function () {
await this.mock.connect(this.defaultAdmin).changeDefaultAdminDelay(newDelay);
({ schedule: this.effectSchedule } = await this.mock.pendingDefaultAdminDelay());
});
for (const [fromSchedule, schedulePassed, expectNewDelay] of [
[-1n, 'before', false],
[0n, 'exactly when', false],
[1n, 'after', true],
]) {
it(`should set the ${
expectNewDelay ? 'new' : 'old'
} delay and apply it to next default admin transfer schedule ${schedulePassed} effectSchedule passed`, async function () {
// Wait until the expected fromSchedule time
const nextBlockTimestamp = this.effectSchedule + fromSchedule;
await time.increaseTo.timestamp(nextBlockTimestamp, false);
// Start the new default admin transfer and get its schedule
const expectedDelay = expectNewDelay ? newDelay : this.delay;
const expectedAcceptSchedule = nextBlockTimestamp + expectedDelay;
await expect(this.mock.connect(this.defaultAdmin).beginDefaultAdminTransfer(this.newDefaultAdmin))
.to.emit(this.mock, 'DefaultAdminTransferScheduled')
.withArgs(this.newDefaultAdmin, expectedAcceptSchedule);
// Check that the schedule corresponds with the new delay
const { newAdmin, schedule: transferSchedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(this.newDefaultAdmin);
expect(transferSchedule).to.equal(expectedAcceptSchedule);
});
}
});
});
describe('accepts transfer admin', function () {
beforeEach(async function () {
await this.mock.connect(this.defaultAdmin).beginDefaultAdminTransfer(this.newDefaultAdmin);
this.acceptSchedule = (await time.clock.timestamp()) + this.delay;
});
it('should revert if caller is not pending default admin', async function () {
await time.increaseTo.timestamp(this.acceptSchedule + 1n, false);
await expect(this.mock.connect(this.other).acceptDefaultAdminTransfer())
.to.be.revertedWithCustomError(this.mock, 'AccessControlInvalidDefaultAdmin')
.withArgs(this.other);
});
describe('when caller is pending default admin and delay has passed', function () {
beforeEach(async function () {
await time.increaseTo.timestamp(this.acceptSchedule + 1n, false);
});
it('accepts a transfer and changes default admin', async function () {
// Emit events
await expect(this.mock.connect(this.newDefaultAdmin).acceptDefaultAdminTransfer())
.to.emit(this.mock, 'RoleRevoked')
.withArgs(DEFAULT_ADMIN_ROLE, this.defaultAdmin, this.newDefaultAdmin)
.to.emit(this.mock, 'RoleGranted')
.withArgs(DEFAULT_ADMIN_ROLE, this.newDefaultAdmin, this.newDefaultAdmin);
// Storage changes
expect(await this.mock.hasRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin)).to.be.false;
expect(await this.mock.hasRole(DEFAULT_ADMIN_ROLE, this.newDefaultAdmin)).to.be.true;
expect(await this.mock.owner()).to.equal(this.newDefaultAdmin);
// Resets pending default admin and schedule
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(ethers.ZeroAddress);
expect(schedule).to.equal(0);
});
});
describe('schedule not passed', function () {
for (const [fromSchedule, tag] of [
[-1n, 'less'],
[0n, 'equal'],
]) {
it(`should revert if block.timestamp is ${tag} to schedule`, async function () {
await time.increaseTo.timestamp(this.acceptSchedule + fromSchedule, false);
await expect(this.mock.connect(this.newDefaultAdmin).acceptDefaultAdminTransfer())
.to.be.revertedWithCustomError(this.mock, 'AccessControlEnforcedDefaultAdminDelay')
.withArgs(this.acceptSchedule);
});
}
});
});
describe('cancels a default admin transfer', function () {
it('reverts if called by non default admin accounts', async function () {
await expect(this.mock.connect(this.other).cancelDefaultAdminTransfer())
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.other, DEFAULT_ADMIN_ROLE);
});
describe('when there is a pending default admin transfer', function () {
beforeEach(async function () {
await this.mock.connect(this.defaultAdmin).beginDefaultAdminTransfer(this.newDefaultAdmin);
this.acceptSchedule = (await time.clock.timestamp()) + this.delay;
});
for (const [fromSchedule, tag] of [
[-1n, 'before'],
[0n, 'exactly when'],
[1n, 'after'],
]) {
it(`resets pending default admin and schedule ${tag} transfer schedule passes`, async function () {
// Advance until passed delay
await time.increaseTo.timestamp(this.acceptSchedule + fromSchedule, false);
await expect(this.mock.connect(this.defaultAdmin).cancelDefaultAdminTransfer()).to.emit(
this.mock,
'DefaultAdminTransferCanceled',
);
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(ethers.ZeroAddress);
expect(schedule).to.equal(0);
});
}
it('should revert if the previous default admin tries to accept', async function () {
await this.mock.connect(this.defaultAdmin).cancelDefaultAdminTransfer();
// Advance until passed delay
await time.increaseTo.timestamp(this.acceptSchedule + 1n, false);
// Previous pending default admin should not be able to accept after cancellation.
await expect(this.mock.connect(this.newDefaultAdmin).acceptDefaultAdminTransfer())
.to.be.revertedWithCustomError(this.mock, 'AccessControlInvalidDefaultAdmin')
.withArgs(this.newDefaultAdmin);
});
});
describe('when there is no pending default admin transfer', function () {
it('should succeed without changes', async function () {
await expect(this.mock.connect(this.defaultAdmin).cancelDefaultAdminTransfer()).to.not.emit(
this.mock,
'DefaultAdminTransferCanceled',
);
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(ethers.ZeroAddress);
expect(schedule).to.equal(0);
});
});
});
describe('renounces admin', function () {
beforeEach(async function () {
await this.mock.connect(this.defaultAdmin).beginDefaultAdminTransfer(ethers.ZeroAddress);
this.expectedSchedule = (await time.clock.timestamp()) + this.delay;
});
it('reverts if caller is not default admin', async function () {
await time.increaseBy.timestamp(this.delay + 1n, false);
await expect(
this.mock.connect(this.defaultAdmin).renounceRole(DEFAULT_ADMIN_ROLE, this.other),
).to.be.revertedWithCustomError(this.mock, 'AccessControlBadConfirmation');
});
it("renouncing the admin role when not an admin doesn't affect the schedule", async function () {
await time.increaseBy.timestamp(this.delay + 1n, false);
await this.mock.connect(this.other).renounceRole(DEFAULT_ADMIN_ROLE, this.other);
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(ethers.ZeroAddress);
expect(schedule).to.equal(this.expectedSchedule);
});
it('keeps defaultAdmin consistent with hasRole if another non-defaultAdmin user renounces the DEFAULT_ADMIN_ROLE', async function () {
await time.increaseBy.timestamp(this.delay + 1n, false);
// This passes because it's a noop
await this.mock.connect(this.other).renounceRole(DEFAULT_ADMIN_ROLE, this.other);
expect(await this.mock.hasRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin)).to.be.true;
expect(await this.mock.defaultAdmin()).to.equal(this.defaultAdmin);
});
it('renounces role', async function () {
await time.increaseBy.timestamp(this.delay + 1n, false);
await expect(this.mock.connect(this.defaultAdmin).renounceRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin))
.to.emit(this.mock, 'RoleRevoked')
.withArgs(DEFAULT_ADMIN_ROLE, this.defaultAdmin, this.defaultAdmin);
expect(await this.mock.hasRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin)).to.be.false;
expect(await this.mock.defaultAdmin()).to.equal(ethers.ZeroAddress);
expect(await this.mock.owner()).to.equal(ethers.ZeroAddress);
const { newAdmin, schedule } = await this.mock.pendingDefaultAdmin();
expect(newAdmin).to.equal(ethers.ZeroAddress);
expect(schedule).to.equal(0);
});
it('allows to recover access using the internal _grantRole', async function () {
await time.increaseBy.timestamp(this.delay + 1n, false);
await this.mock.connect(this.defaultAdmin).renounceRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin);
await expect(this.mock.connect(this.defaultAdmin).$_grantRole(DEFAULT_ADMIN_ROLE, this.other))
.to.emit(this.mock, 'RoleGranted')
.withArgs(DEFAULT_ADMIN_ROLE, this.other, this.defaultAdmin);
});
describe('schedule not passed', function () {
for (const [fromSchedule, tag] of [
[-1n, 'less'],
[0n, 'equal'],
]) {
it(`reverts if block.timestamp is ${tag} to schedule`, async function () {
await time.increaseBy.timestamp(this.delay + fromSchedule, false);
await expect(this.mock.connect(this.defaultAdmin).renounceRole(DEFAULT_ADMIN_ROLE, this.defaultAdmin))
.to.be.revertedWithCustomError(this.mock, 'AccessControlEnforcedDefaultAdminDelay')
.withArgs(this.expectedSchedule);
});
}
});
});
describe('changes delay', function () {
it('reverts if called by non default admin accounts', async function () {
await expect(this.mock.connect(this.other).changeDefaultAdminDelay(time.duration.hours(4)))
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.other, DEFAULT_ADMIN_ROLE);
});
for (const [delayDifference, delayChangeType] of [
[time.duration.hours(-1), 'decreased'],
[time.duration.hours(1), 'increased'],
[time.duration.days(5), 'increased to more than 5 days'],
]) {
describe(`when the delay is ${delayChangeType}`, function () {
beforeEach(function () {
this.newDefaultAdminDelay = this.delay + delayDifference;
});
it('begins the delay change to the new delay', async function () {
// Calculate expected values
const capWait = await this.mock.defaultAdminDelayIncreaseWait();
const minWait = capWait < this.newDefaultAdminDelay ? capWait : this.newDefaultAdminDelay;
const changeDelay =
this.newDefaultAdminDelay <= this.delay ? this.delay - this.newDefaultAdminDelay : minWait;
const nextBlockTimestamp = (await time.clock.timestamp()) + 1n;
const effectSchedule = nextBlockTimestamp + changeDelay;
await time.increaseTo.timestamp(nextBlockTimestamp, false);
// Begins the change
await expect(this.mock.connect(this.defaultAdmin).changeDefaultAdminDelay(this.newDefaultAdminDelay))
.to.emit(this.mock, 'DefaultAdminDelayChangeScheduled')
.withArgs(this.newDefaultAdminDelay, effectSchedule);
// Assert
const { newDelay, schedule } = await this.mock.pendingDefaultAdminDelay();
expect(newDelay).to.equal(this.newDefaultAdminDelay);
expect(schedule).to.equal(effectSchedule);
});
describe('scheduling again', function () {
beforeEach('schedule once', async function () {
await this.mock.connect(this.defaultAdmin).changeDefaultAdminDelay(this.newDefaultAdminDelay);
});
for (const [fromSchedule, tag] of [
[-1n, 'before'],
[0n, 'exactly when'],
[1n, 'after'],
]) {
const passed = fromSchedule > 0;
it(`succeeds ${tag} the delay schedule passes`, async function () {
// Wait until schedule + fromSchedule
const { schedule: firstSchedule } = await this.mock.pendingDefaultAdminDelay();
const nextBlockTimestamp = firstSchedule + fromSchedule;
await time.increaseTo.timestamp(nextBlockTimestamp, false);
// Calculate expected values
const anotherNewDefaultAdminDelay = this.newDefaultAdminDelay + time.duration.hours(2);
const capWait = await this.mock.defaultAdminDelayIncreaseWait();
const minWait = capWait < anotherNewDefaultAdminDelay ? capWait : anotherNewDefaultAdminDelay;
const effectSchedule = nextBlockTimestamp + minWait;
// Default admin changes its mind and begins another delay change
await expect(this.mock.connect(this.defaultAdmin).changeDefaultAdminDelay(anotherNewDefaultAdminDelay))
.to.emit(this.mock, 'DefaultAdminDelayChangeScheduled')
.withArgs(anotherNewDefaultAdminDelay, effectSchedule);
// Assert
const { newDelay, schedule } = await this.mock.pendingDefaultAdminDelay();
expect(newDelay).to.equal(anotherNewDefaultAdminDelay);
expect(schedule).to.equal(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.mock.pendingDefaultAdminDelay();
await time.increaseTo.timestamp(firstSchedule + fromSchedule, false);
// Default admin changes its mind and begins another delay change
const anotherNewDefaultAdminDelay = this.newDefaultAdminDelay + time.duration.hours(2);
const expected = expect(
this.mock.connect(this.defaultAdmin).changeDefaultAdminDelay(anotherNewDefaultAdminDelay),
);
if (passed) {
await expected.to.not.emit(this.mock, 'DefaultAdminDelayChangeCanceled');
} else {
await expected.to.emit(this.mock, 'DefaultAdminDelayChangeCanceled');
}
});
}
});
});
}
});
describe('rollbacks a delay change', function () {
it('reverts if called by non default admin accounts', async function () {
await expect(this.mock.connect(this.other).rollbackDefaultAdminDelay())
.to.be.revertedWithCustomError(this.mock, 'AccessControlUnauthorizedAccount')
.withArgs(this.other, DEFAULT_ADMIN_ROLE);
});
describe('when there is a pending delay', function () {
beforeEach('set pending delay', async function () {
await this.mock.connect(this.defaultAdmin).changeDefaultAdminDelay(time.duration.hours(12));
});
for (const [fromSchedule, tag] of [
[-1n, 'before'],
[0n, 'exactly when'],
[1n, '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.mock.pendingDefaultAdminDelay();
await time.increaseTo.timestamp(firstSchedule + fromSchedule, false);
await this.mock.connect(this.defaultAdmin).rollbackDefaultAdminDelay();
const { newDelay, schedule } = await this.mock.pendingDefaultAdminDelay();
expect(newDelay).to.equal(0);
expect(schedule).to.equal(0);
});
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.mock.pendingDefaultAdminDelay();
await time.increaseTo.timestamp(firstSchedule + fromSchedule, false);
const expected = expect(this.mock.connect(this.defaultAdmin).rollbackDefaultAdminDelay());
if (passed) {
await expected.to.not.emit(this.mock, 'DefaultAdminDelayChangeCanceled');
} else {
await expected.to.emit(this.mock, 'DefaultAdminDelayChangeCanceled');
}
});
}
});
describe('when there is no pending delay', function () {
it('succeeds without changes', async function () {
await this.mock.connect(this.defaultAdmin).rollbackDefaultAdminDelay();
const { newDelay, schedule } = await this.mock.pendingDefaultAdminDelay();
expect(newDelay).to.equal(0);
expect(schedule).to.equal(0);
});
});
});
}
module.exports = {
DEFAULT_ADMIN_ROLE,
shouldBehaveLikeAccessControl,
shouldBehaveLikeAccessControlEnumerable,
shouldBehaveLikeAccessControlDefaultAdminRules,
};

View File

@@ -0,0 +1,19 @@
const { ethers } = require('hardhat');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const { DEFAULT_ADMIN_ROLE, shouldBehaveLikeAccessControl } = require('./AccessControl.behavior');
async function fixture() {
const [defaultAdmin, ...accounts] = await ethers.getSigners();
const mock = await ethers.deployContract('$AccessControl');
await mock.$_grantRole(DEFAULT_ADMIN_ROLE, defaultAdmin);
return { mock, defaultAdmin, accounts };
}
describe('AccessControl', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
shouldBehaveLikeAccessControl();
});

View File

@@ -0,0 +1,79 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
async function fixture() {
const [owner, other] = await ethers.getSigners();
const ownable = await ethers.deployContract('$Ownable', [owner]);
return { owner, other, ownable };
}
describe('Ownable', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
it('emits ownership transfer events during construction', async function () {
await expect(this.ownable.deploymentTransaction())
.to.emit(this.ownable, 'OwnershipTransferred')
.withArgs(ethers.ZeroAddress, this.owner);
});
it('rejects zero address for initialOwner', async function () {
await expect(ethers.deployContract('$Ownable', [ethers.ZeroAddress]))
.to.be.revertedWithCustomError({ interface: this.ownable.interface }, 'OwnableInvalidOwner')
.withArgs(ethers.ZeroAddress);
});
it('has an owner', async function () {
expect(await this.ownable.owner()).to.equal(this.owner);
});
describe('transfer ownership', function () {
it('changes owner after transfer', async function () {
await expect(this.ownable.connect(this.owner).transferOwnership(this.other))
.to.emit(this.ownable, 'OwnershipTransferred')
.withArgs(this.owner, this.other);
expect(await this.ownable.owner()).to.equal(this.other);
});
it('prevents non-owners from transferring', async function () {
await expect(this.ownable.connect(this.other).transferOwnership(this.other))
.to.be.revertedWithCustomError(this.ownable, 'OwnableUnauthorizedAccount')
.withArgs(this.other);
});
it('guards ownership against stuck state', async function () {
await expect(this.ownable.connect(this.owner).transferOwnership(ethers.ZeroAddress))
.to.be.revertedWithCustomError(this.ownable, 'OwnableInvalidOwner')
.withArgs(ethers.ZeroAddress);
});
});
describe('renounce ownership', function () {
it('loses ownership after renouncement', async function () {
await expect(this.ownable.connect(this.owner).renounceOwnership())
.to.emit(this.ownable, 'OwnershipTransferred')
.withArgs(this.owner, ethers.ZeroAddress);
expect(await this.ownable.owner()).to.equal(ethers.ZeroAddress);
});
it('prevents non-owners from renouncement', async function () {
await expect(this.ownable.connect(this.other).renounceOwnership())
.to.be.revertedWithCustomError(this.ownable, 'OwnableUnauthorizedAccount')
.withArgs(this.other);
});
it('allows to recover access using the internal _transferOwnership', async function () {
await this.ownable.connect(this.owner).renounceOwnership();
await expect(this.ownable.$_transferOwnership(this.other))
.to.emit(this.ownable, 'OwnershipTransferred')
.withArgs(ethers.ZeroAddress, this.other);
expect(await this.ownable.owner()).to.equal(this.other);
});
});
});

View File

@@ -0,0 +1,85 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
async function fixture() {
const [owner, accountA, accountB] = await ethers.getSigners();
const ownable2Step = await ethers.deployContract('$Ownable2Step', [owner]);
return {
ownable2Step,
owner,
accountA,
accountB,
};
}
describe('Ownable2Step', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
describe('transfer ownership', function () {
it('starting a transfer does not change owner', async function () {
await expect(this.ownable2Step.connect(this.owner).transferOwnership(this.accountA))
.to.emit(this.ownable2Step, 'OwnershipTransferStarted')
.withArgs(this.owner, this.accountA);
expect(await this.ownable2Step.owner()).to.equal(this.owner);
expect(await this.ownable2Step.pendingOwner()).to.equal(this.accountA);
});
it('changes owner after transfer', async function () {
await this.ownable2Step.connect(this.owner).transferOwnership(this.accountA);
await expect(this.ownable2Step.connect(this.accountA).acceptOwnership())
.to.emit(this.ownable2Step, 'OwnershipTransferred')
.withArgs(this.owner, this.accountA);
expect(await this.ownable2Step.owner()).to.equal(this.accountA);
expect(await this.ownable2Step.pendingOwner()).to.equal(ethers.ZeroAddress);
});
it('guards transfer against invalid user', async function () {
await this.ownable2Step.connect(this.owner).transferOwnership(this.accountA);
await expect(this.ownable2Step.connect(this.accountB).acceptOwnership())
.to.be.revertedWithCustomError(this.ownable2Step, 'OwnableUnauthorizedAccount')
.withArgs(this.accountB);
});
});
describe('renouncing ownership', function () {
it('changes owner after renouncing ownership', async function () {
await expect(this.ownable2Step.connect(this.owner).renounceOwnership())
.to.emit(this.ownable2Step, 'OwnershipTransferred')
.withArgs(this.owner, ethers.ZeroAddress);
// If renounceOwnership is removed from parent an alternative is needed ...
// without it is difficult to cleanly renounce with the two step process
// see: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3620#discussion_r957930388
expect(await this.ownable2Step.owner()).to.equal(ethers.ZeroAddress);
});
it('pending owner resets after renouncing ownership', async function () {
await this.ownable2Step.connect(this.owner).transferOwnership(this.accountA);
expect(await this.ownable2Step.pendingOwner()).to.equal(this.accountA);
await this.ownable2Step.connect(this.owner).renounceOwnership();
expect(await this.ownable2Step.pendingOwner()).to.equal(ethers.ZeroAddress);
await expect(this.ownable2Step.connect(this.accountA).acceptOwnership())
.to.be.revertedWithCustomError(this.ownable2Step, 'OwnableUnauthorizedAccount')
.withArgs(this.accountA);
});
it('allows to recover access using the internal _transferOwnership', async function () {
await this.ownable2Step.connect(this.owner).renounceOwnership();
await expect(this.ownable2Step.$_transferOwnership(this.accountA))
.to.emit(this.ownable2Step, 'OwnershipTransferred')
.withArgs(ethers.ZeroAddress, this.accountA);
expect(await this.ownable2Step.owner()).to.equal(this.accountA);
});
});
});

View File

@@ -0,0 +1,32 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const time = require('../../helpers/time');
const {
shouldBehaveLikeAccessControl,
shouldBehaveLikeAccessControlDefaultAdminRules,
} = require('../AccessControl.behavior');
async function fixture() {
const delay = time.duration.hours(10);
const [defaultAdmin, ...accounts] = await ethers.getSigners();
const mock = await ethers.deployContract('$AccessControlDefaultAdminRules', [delay, defaultAdmin]);
return { mock, defaultAdmin, delay, accounts };
}
describe('AccessControlDefaultAdminRules', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
it('initial admin not zero', async function () {
await expect(ethers.deployContract('$AccessControlDefaultAdminRules', [this.delay, ethers.ZeroAddress]))
.to.be.revertedWithCustomError(this.mock, 'AccessControlInvalidDefaultAdmin')
.withArgs(ethers.ZeroAddress);
});
shouldBehaveLikeAccessControl();
shouldBehaveLikeAccessControlDefaultAdminRules();
});

View File

@@ -0,0 +1,24 @@
const { ethers } = require('hardhat');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const {
DEFAULT_ADMIN_ROLE,
shouldBehaveLikeAccessControl,
shouldBehaveLikeAccessControlEnumerable,
} = require('../AccessControl.behavior');
async function fixture() {
const [defaultAdmin, ...accounts] = await ethers.getSigners();
const mock = await ethers.deployContract('$AccessControlEnumerable');
await mock.$_grantRole(DEFAULT_ADMIN_ROLE, defaultAdmin);
return { mock, defaultAdmin, accounts };
}
describe('AccessControlEnumerable', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
shouldBehaveLikeAccessControl();
shouldBehaveLikeAccessControlEnumerable();
});

View File

@@ -0,0 +1,146 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const { impersonate } = require('../../helpers/account');
const time = require('../../helpers/time');
async function fixture() {
const [admin, roleMember, other] = await ethers.getSigners();
const authority = await ethers.deployContract('$AccessManager', [admin]);
const managed = await ethers.deployContract('$AccessManagedTarget', [authority]);
const anotherAuthority = await ethers.deployContract('$AccessManager', [admin]);
const authorityObserveIsConsuming = await ethers.deployContract('$AuthorityObserveIsConsuming');
await impersonate(authority.target);
const authorityAsSigner = await ethers.getSigner(authority.target);
return {
roleMember,
other,
authorityAsSigner,
authority,
managed,
authorityObserveIsConsuming,
anotherAuthority,
};
}
describe('AccessManaged', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
it('sets authority and emits AuthorityUpdated event during construction', async function () {
await expect(this.managed.deploymentTransaction())
.to.emit(this.managed, 'AuthorityUpdated')
.withArgs(this.authority);
});
describe('restricted modifier', function () {
beforeEach(async function () {
this.selector = this.managed.fnRestricted.getFragment().selector;
this.role = 42n;
await this.authority.$_setTargetFunctionRole(this.managed, this.selector, this.role);
await this.authority.$_grantRole(this.role, this.roleMember, 0, 0);
});
it('succeeds when role is granted without execution delay', async function () {
await this.managed.connect(this.roleMember)[this.selector]();
});
it('reverts when role is not granted', async function () {
await expect(this.managed.connect(this.other)[this.selector]())
.to.be.revertedWithCustomError(this.managed, 'AccessManagedUnauthorized')
.withArgs(this.other);
});
it('panics in short calldata', async function () {
// We avoid adding the `restricted` modifier to the fallback function because other tests may depend on it
// being accessible without restrictions. We check for the internal `_checkCanCall` instead.
await expect(this.managed.$_checkCanCall(this.roleMember, '0x1234')).to.be.reverted;
});
describe('when role is granted with execution delay', function () {
beforeEach(async function () {
const executionDelay = 911n;
await this.authority.$_grantRole(this.role, this.roleMember, 0, executionDelay);
});
it('reverts if the operation is not scheduled', async function () {
const fn = this.managed.interface.getFunction(this.selector);
const calldata = this.managed.interface.encodeFunctionData(fn, []);
const opId = await this.authority.hashOperation(this.roleMember, this.managed, calldata);
await expect(this.managed.connect(this.roleMember)[this.selector]())
.to.be.revertedWithCustomError(this.authority, 'AccessManagerNotScheduled')
.withArgs(opId);
});
it('succeeds if the operation is scheduled', async function () {
// Arguments
const delay = time.duration.hours(12);
const fn = this.managed.interface.getFunction(this.selector);
const calldata = this.managed.interface.encodeFunctionData(fn, []);
// Schedule
const scheduledAt = (await time.clock.timestamp()) + 1n;
const when = scheduledAt + delay;
await time.increaseTo.timestamp(scheduledAt, false);
await this.authority.connect(this.roleMember).schedule(this.managed, calldata, when);
// Set execution date
await time.increaseTo.timestamp(when, false);
// Shouldn't revert
await this.managed.connect(this.roleMember)[this.selector]();
});
});
});
describe('setAuthority', function () {
it('reverts if the caller is not the authority', async function () {
await expect(this.managed.connect(this.other).setAuthority(this.other))
.to.be.revertedWithCustomError(this.managed, 'AccessManagedUnauthorized')
.withArgs(this.other);
});
it('reverts if the new authority is not a valid authority', async function () {
await expect(this.managed.connect(this.authorityAsSigner).setAuthority(this.other))
.to.be.revertedWithCustomError(this.managed, 'AccessManagedInvalidAuthority')
.withArgs(this.other);
});
it('sets authority and emits AuthorityUpdated event', async function () {
await expect(this.managed.connect(this.authorityAsSigner).setAuthority(this.anotherAuthority))
.to.emit(this.managed, 'AuthorityUpdated')
.withArgs(this.anotherAuthority);
expect(await this.managed.authority()).to.equal(this.anotherAuthority);
});
});
describe('isConsumingScheduledOp', function () {
beforeEach(async function () {
await this.managed.connect(this.authorityAsSigner).setAuthority(this.authorityObserveIsConsuming);
});
it('returns bytes4(0) when not consuming operation', async function () {
expect(await this.managed.isConsumingScheduledOp()).to.equal('0x00000000');
});
it('returns isConsumingScheduledOp selector when consuming operation', async function () {
const isConsumingScheduledOp = this.managed.interface.getFunction('isConsumingScheduledOp()');
const fnRestricted = this.managed.fnRestricted.getFragment();
await expect(this.managed.connect(this.other).fnRestricted())
.to.emit(this.authorityObserveIsConsuming, 'ConsumeScheduledOpCalled')
.withArgs(
this.other,
this.managed.interface.encodeFunctionData(fnRestricted, []),
isConsumingScheduledOp.selector,
);
});
});
});

View File

@@ -0,0 +1,201 @@
const { expect } = require('chai');
const {
LIKE_COMMON_IS_EXECUTING,
LIKE_COMMON_GET_ACCESS,
LIKE_COMMON_SCHEDULABLE,
testAsSchedulableOperation,
testAsRestrictedOperation,
testAsDelayedOperation,
testAsCanCall,
testAsHasRole,
} = require('./AccessManager.predicate');
// ============ ADMIN OPERATION ============
/**
* @requires this.{manager,roles,calldata,role}
*/
function shouldBehaveLikeDelayedAdminOperation() {
const getAccessPath = LIKE_COMMON_GET_ACCESS;
testAsDelayedOperation.mineDelay = true;
getAccessPath.requiredRoleIsGranted.roleGrantingIsDelayed.callerHasAnExecutionDelay.afterGrantDelay =
testAsDelayedOperation;
getAccessPath.requiredRoleIsGranted.roleGrantingIsNotDelayed.callerHasAnExecutionDelay = function () {
beforeEach('set execution delay', async function () {
this.scheduleIn = this.executionDelay; // For testAsDelayedOperation
});
testAsSchedulableOperation(LIKE_COMMON_SCHEDULABLE);
};
beforeEach('set target as manager', function () {
this.target = this.manager;
});
testAsRestrictedOperation({
callerIsTheManager: LIKE_COMMON_IS_EXECUTING,
callerIsNotTheManager() {
testAsHasRole({
publicRoleIsRequired() {
it('reverts as AccessManagerUnauthorizedAccount', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.target, 'AccessManagerUnauthorizedAccount')
.withArgs(
this.caller,
this.roles.ADMIN.id, // Although PUBLIC is required, target function role doesn't apply to admin ops
);
});
},
specificRoleIsRequired: getAccessPath,
});
},
});
}
/**
* @requires this.{manager,roles,calldata,role}
*/
function shouldBehaveLikeNotDelayedAdminOperation() {
const getAccessPath = LIKE_COMMON_GET_ACCESS;
function testScheduleOperation(mineDelay) {
return function self() {
self.mineDelay = mineDelay;
beforeEach('set execution delay', async function () {
this.scheduleIn = this.executionDelay; // For testAsSchedulableOperation
});
testAsSchedulableOperation(LIKE_COMMON_SCHEDULABLE);
};
}
getAccessPath.requiredRoleIsGranted.roleGrantingIsDelayed.callerHasAnExecutionDelay.afterGrantDelay =
testScheduleOperation(true);
getAccessPath.requiredRoleIsGranted.roleGrantingIsNotDelayed.callerHasAnExecutionDelay = testScheduleOperation(false);
beforeEach('set target as manager', function () {
this.target = this.manager;
});
testAsRestrictedOperation({
callerIsTheManager: LIKE_COMMON_IS_EXECUTING,
callerIsNotTheManager() {
testAsHasRole({
publicRoleIsRequired() {
it('reverts as AccessManagerUnauthorizedAccount', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.target, 'AccessManagerUnauthorizedAccount')
.withArgs(
this.caller,
this.roles.ADMIN.id, // Although PUBLIC_ROLE is required, admin ops are not subject to target function roles
);
});
},
specificRoleIsRequired: getAccessPath,
});
},
});
}
/**
* @requires this.{manager,roles,calldata,role}
*/
function shouldBehaveLikeRoleAdminOperation(roleAdmin) {
const getAccessPath = LIKE_COMMON_GET_ACCESS;
function afterGrantDelay() {
afterGrantDelay.mineDelay = true;
beforeEach('set execution delay', async function () {
this.scheduleIn = this.executionDelay; // For testAsSchedulableOperation
});
testAsSchedulableOperation(LIKE_COMMON_SCHEDULABLE);
}
getAccessPath.requiredRoleIsGranted.roleGrantingIsDelayed.callerHasAnExecutionDelay.afterGrantDelay = afterGrantDelay;
getAccessPath.requiredRoleIsGranted.roleGrantingIsNotDelayed.callerHasAnExecutionDelay = afterGrantDelay;
beforeEach('set target as manager', function () {
this.target = this.manager;
});
testAsRestrictedOperation({
callerIsTheManager: LIKE_COMMON_IS_EXECUTING,
callerIsNotTheManager() {
testAsHasRole({
publicRoleIsRequired() {
it('reverts as AccessManagerUnauthorizedAccount', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.target, 'AccessManagerUnauthorizedAccount')
.withArgs(this.caller, roleAdmin);
});
},
specificRoleIsRequired: getAccessPath,
});
},
});
}
// ============ RESTRICTED OPERATION ============
/**
* @requires this.{manager,roles,calldata,role}
*/
function shouldBehaveLikeAManagedRestrictedOperation() {
function revertUnauthorized() {
it('reverts as AccessManagedUnauthorized', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.target, 'AccessManagedUnauthorized')
.withArgs(this.caller);
});
}
const getAccessPath = LIKE_COMMON_GET_ACCESS;
getAccessPath.requiredRoleIsGranted.roleGrantingIsDelayed.callerHasAnExecutionDelay.beforeGrantDelay =
revertUnauthorized;
getAccessPath.requiredRoleIsGranted.roleGrantingIsDelayed.callerHasNoExecutionDelay.beforeGrantDelay =
revertUnauthorized;
getAccessPath.requiredRoleIsNotGranted = revertUnauthorized;
function testScheduleOperation(mineDelay) {
return function self() {
self.mineDelay = mineDelay;
beforeEach('sets execution delay', async function () {
this.scheduleIn = this.executionDelay; // For testAsSchedulableOperation
});
testAsSchedulableOperation(LIKE_COMMON_SCHEDULABLE);
};
}
getAccessPath.requiredRoleIsGranted.roleGrantingIsDelayed.callerHasAnExecutionDelay.afterGrantDelay =
testScheduleOperation(true);
getAccessPath.requiredRoleIsGranted.roleGrantingIsNotDelayed.callerHasAnExecutionDelay = testScheduleOperation(false);
const isExecutingPath = LIKE_COMMON_IS_EXECUTING;
isExecutingPath.notExecuting = revertUnauthorized;
testAsCanCall({
closed: revertUnauthorized,
open: {
callerIsTheManager: isExecutingPath,
callerIsNotTheManager: {
publicRoleIsRequired() {
it('succeeds called directly', async function () {
await this.caller.sendTransaction({ to: this.target, data: this.calldata });
});
it('succeeds via execute', async function () {
await this.manager.connect(this.caller).execute(this.target, this.calldata);
});
},
specificRoleIsRequired: getAccessPath,
},
},
});
}
module.exports = {
shouldBehaveLikeDelayedAdminOperation,
shouldBehaveLikeNotDelayedAdminOperation,
shouldBehaveLikeRoleAdminOperation,
shouldBehaveLikeAManagedRestrictedOperation,
};

View File

@@ -0,0 +1,456 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { setStorageAt } = require('@nomicfoundation/hardhat-network-helpers');
const { EXECUTION_ID_STORAGE_SLOT, EXPIRATION, prepareOperation } = require('../../helpers/access-manager');
const { impersonate } = require('../../helpers/account');
const time = require('../../helpers/time');
// ============ COMMON PREDICATES ============
const LIKE_COMMON_IS_EXECUTING = {
executing() {
it('succeeds', async function () {
await this.caller.sendTransaction({ to: this.target, data: this.calldata });
});
},
notExecuting() {
it('reverts as AccessManagerUnauthorizedAccount', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.manager, 'AccessManagerUnauthorizedAccount')
.withArgs(this.caller, this.role.id);
});
},
};
const LIKE_COMMON_GET_ACCESS = {
requiredRoleIsGranted: {
roleGrantingIsDelayed: {
callerHasAnExecutionDelay: {
beforeGrantDelay() {
it('reverts as AccessManagerUnauthorizedAccount', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.manager, 'AccessManagerUnauthorizedAccount')
.withArgs(this.caller, this.role.id);
});
},
afterGrantDelay: undefined, // Diverges if there's an operation delay or not
},
callerHasNoExecutionDelay: {
beforeGrantDelay() {
it('reverts as AccessManagerUnauthorizedAccount', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.manager, 'AccessManagerUnauthorizedAccount')
.withArgs(this.caller, this.role.id);
});
},
afterGrantDelay() {
it('succeeds called directly', async function () {
await this.caller.sendTransaction({ to: this.target, data: this.calldata });
});
it('succeeds via execute', async function () {
await this.manager.connect(this.caller).execute(this.target, this.calldata);
});
},
},
},
roleGrantingIsNotDelayed: {
callerHasAnExecutionDelay: undefined, // Diverges if there's an operation to schedule or not
callerHasNoExecutionDelay() {
it('succeeds called directly', async function () {
await this.caller.sendTransaction({ to: this.target, data: this.calldata });
});
it('succeeds via execute', async function () {
await this.manager.connect(this.caller).execute(this.target, this.calldata);
});
},
},
},
requiredRoleIsNotGranted() {
it('reverts as AccessManagerUnauthorizedAccount', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.manager, 'AccessManagerUnauthorizedAccount')
.withArgs(this.caller, this.role.id);
});
},
};
const LIKE_COMMON_SCHEDULABLE = {
scheduled: {
before() {
it('reverts as AccessManagerNotReady', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.manager, 'AccessManagerNotReady')
.withArgs(this.operationId);
});
},
after() {
it('succeeds called directly', async function () {
await this.caller.sendTransaction({ to: this.target, data: this.calldata });
});
it('succeeds via execute', async function () {
await this.manager.connect(this.caller).execute(this.target, this.calldata);
});
},
expired() {
it('reverts as AccessManagerExpired', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.manager, 'AccessManagerExpired')
.withArgs(this.operationId);
});
},
},
notScheduled() {
it('reverts as AccessManagerNotScheduled', async function () {
await expect(this.caller.sendTransaction({ to: this.target, data: this.calldata }))
.to.be.revertedWithCustomError(this.manager, 'AccessManagerNotScheduled')
.withArgs(this.operationId);
});
},
};
// ============ MODE ============
/**
* @requires this.{manager,target}
*/
function testAsClosable({ closed, open }) {
describe('when the manager is closed', function () {
beforeEach('close', async function () {
await this.manager.$_setTargetClosed(this.target, true);
});
closed();
});
describe('when the manager is open', function () {
beforeEach('open', async function () {
await this.manager.$_setTargetClosed(this.target, false);
});
open();
});
}
// ============ DELAY ============
/**
* @requires this.{delay}
*/
function testAsDelay(type, { before, after }) {
beforeEach('define timestamp when delay takes effect', async function () {
const timestamp = await time.clock.timestamp();
this.delayEffect = timestamp + this.delay;
});
describe(`when ${type} delay has not taken effect yet`, function () {
beforeEach(`set next block timestamp before ${type} takes effect`, async function () {
await time.increaseTo.timestamp(this.delayEffect - 1n, !!before.mineDelay);
});
before();
});
describe(`when ${type} delay has taken effect`, function () {
beforeEach(`set next block timestamp when ${type} takes effect`, async function () {
await time.increaseTo.timestamp(this.delayEffect, !!after.mineDelay);
});
after();
});
}
// ============ OPERATION ============
/**
* @requires this.{manager,scheduleIn,caller,target,calldata}
*/
function testAsSchedulableOperation({ scheduled: { before, after, expired }, notScheduled }) {
describe('when operation is scheduled', function () {
beforeEach('schedule operation', async function () {
if (this.caller.target) {
await impersonate(this.caller.target);
this.caller = await ethers.getSigner(this.caller.target);
}
const { operationId, schedule } = await prepareOperation(this.manager, {
caller: this.caller,
target: this.target,
calldata: this.calldata,
delay: this.scheduleIn,
});
await schedule();
this.operationId = operationId;
});
describe('when operation is not ready for execution', function () {
beforeEach('set next block time before operation is ready', async function () {
this.scheduledAt = await time.clock.timestamp();
const schedule = await this.manager.getSchedule(this.operationId);
await time.increaseTo.timestamp(schedule - 1n, !!before.mineDelay);
});
before();
});
describe('when operation is ready for execution', function () {
beforeEach('set next block time when operation is ready for execution', async function () {
this.scheduledAt = await time.clock.timestamp();
const schedule = await this.manager.getSchedule(this.operationId);
await time.increaseTo.timestamp(schedule, !!after.mineDelay);
});
after();
});
describe('when operation has expired', function () {
beforeEach('set next block time when operation expired', async function () {
this.scheduledAt = await time.clock.timestamp();
const schedule = await this.manager.getSchedule(this.operationId);
await time.increaseTo.timestamp(schedule + EXPIRATION, !!expired.mineDelay);
});
expired();
});
});
describe('when operation is not scheduled', function () {
beforeEach('set expected operationId', async function () {
this.operationId = await this.manager.hashOperation(this.caller, this.target, this.calldata);
// Assert operation is not scheduled
expect(await this.manager.getSchedule(this.operationId)).to.equal(0n);
});
notScheduled();
});
}
/**
* @requires this.{manager,roles,target,calldata}
*/
function testAsRestrictedOperation({ callerIsTheManager: { executing, notExecuting }, callerIsNotTheManager }) {
describe('when the call comes from the manager (msg.sender == manager)', function () {
beforeEach('define caller as manager', async function () {
this.caller = this.manager;
if (this.caller.target) {
await impersonate(this.caller.target);
this.caller = await ethers.getSigner(this.caller.target);
}
});
describe('when _executionId is in storage for target and selector', function () {
beforeEach('set _executionId flag from calldata and target', async function () {
const executionId = ethers.keccak256(
ethers.AbiCoder.defaultAbiCoder().encode(
['address', 'bytes4'],
[this.target.target, this.calldata.substring(0, 10)],
),
);
await setStorageAt(this.manager.target, EXECUTION_ID_STORAGE_SLOT, executionId);
});
executing();
});
describe('when _executionId does not match target and selector', notExecuting);
});
describe('when the call does not come from the manager (msg.sender != manager)', function () {
beforeEach('define non manager caller', function () {
this.caller = this.roles.SOME.members[0];
});
callerIsNotTheManager();
});
}
/**
* @requires this.{manager,scheduleIn,caller,target,calldata,executionDelay}
*/
function testAsDelayedOperation() {
describe('with operation delay', function () {
describe('when operation delay is greater than execution delay', function () {
beforeEach('set operation delay', async function () {
this.operationDelay = this.executionDelay + time.duration.hours(1);
await this.manager.$_setTargetAdminDelay(this.target, this.operationDelay);
this.scheduleIn = this.operationDelay; // For testAsSchedulableOperation
});
testAsSchedulableOperation(LIKE_COMMON_SCHEDULABLE);
});
describe('when operation delay is shorter than execution delay', function () {
beforeEach('set operation delay', async function () {
this.operationDelay = this.executionDelay - time.duration.hours(1);
await this.manager.$_setTargetAdminDelay(this.target, this.operationDelay);
this.scheduleIn = this.executionDelay; // For testAsSchedulableOperation
});
testAsSchedulableOperation(LIKE_COMMON_SCHEDULABLE);
});
});
describe('without operation delay', function () {
beforeEach('set operation delay', async function () {
this.operationDelay = 0n;
await this.manager.$_setTargetAdminDelay(this.target, this.operationDelay);
this.scheduleIn = this.executionDelay; // For testAsSchedulableOperation
});
testAsSchedulableOperation(LIKE_COMMON_SCHEDULABLE);
});
}
// ============ METHOD ============
/**
* @requires this.{manager,roles,role,target,calldata}
*/
function testAsCanCall({
closed,
open: {
callerIsTheManager,
callerIsNotTheManager: { publicRoleIsRequired, specificRoleIsRequired },
},
}) {
testAsClosable({
closed,
open() {
testAsRestrictedOperation({
callerIsTheManager,
callerIsNotTheManager() {
testAsHasRole({
publicRoleIsRequired,
specificRoleIsRequired,
});
},
});
},
});
}
/**
* @requires this.{target,calldata,roles,role}
*/
function testAsHasRole({ publicRoleIsRequired, specificRoleIsRequired }) {
describe('when the function requires the caller to be granted with the PUBLIC_ROLE', function () {
beforeEach('set target function role as PUBLIC_ROLE', async function () {
this.role = this.roles.PUBLIC;
await this.manager
.connect(this.roles.ADMIN.members[0])
.$_setTargetFunctionRole(this.target, this.calldata.substring(0, 10), this.role.id);
});
publicRoleIsRequired();
});
describe('when the function requires the caller to be granted with a role other than PUBLIC_ROLE', function () {
beforeEach('set target function role as PUBLIC_ROLE', async function () {
await this.manager
.connect(this.roles.ADMIN.members[0])
.$_setTargetFunctionRole(this.target, this.calldata.substring(0, 10), this.role.id);
});
testAsGetAccess(specificRoleIsRequired);
});
}
/**
* @requires this.{manager,role,caller}
*/
function testAsGetAccess({
requiredRoleIsGranted: {
roleGrantingIsDelayed: {
// Because both grant and execution delay are set within the same $_grantRole call
// it's not possible to create a set of tests that diverge between grant and execution delay.
// Therefore, the testAsDelay arguments are renamed for clarity:
// before => beforeGrantDelay
// after => afterGrantDelay
callerHasAnExecutionDelay: { beforeGrantDelay: case1, afterGrantDelay: case2 },
callerHasNoExecutionDelay: { beforeGrantDelay: case3, afterGrantDelay: case4 },
},
roleGrantingIsNotDelayed: { callerHasAnExecutionDelay: case5, callerHasNoExecutionDelay: case6 },
},
requiredRoleIsNotGranted,
}) {
describe('when the required role is granted to the caller', function () {
describe('when role granting is delayed', function () {
beforeEach('define delay', function () {
this.grantDelay = time.duration.minutes(3);
this.delay = this.grantDelay; // For testAsDelay
});
describe('when caller has an execution delay', function () {
beforeEach('set role and delay', async function () {
this.executionDelay = time.duration.hours(10);
this.delay = this.grantDelay;
await this.manager.$_grantRole(this.role.id, this.caller, this.grantDelay, this.executionDelay);
});
testAsDelay('grant', { before: case1, after: case2 });
});
describe('when caller has no execution delay', function () {
beforeEach('set role and delay', async function () {
this.executionDelay = 0n;
await this.manager.$_grantRole(this.role.id, this.caller, this.grantDelay, this.executionDelay);
});
testAsDelay('grant', { before: case3, after: case4 });
});
});
describe('when role granting is not delayed', function () {
beforeEach('define delay', function () {
this.grantDelay = 0n;
});
describe('when caller has an execution delay', function () {
beforeEach('set role and delay', async function () {
this.executionDelay = time.duration.hours(10);
await this.manager.$_grantRole(this.role.id, this.caller, this.grantDelay, this.executionDelay);
});
case5();
});
describe('when caller has no execution delay', function () {
beforeEach('set role and delay', async function () {
this.executionDelay = 0n;
await this.manager.$_grantRole(this.role.id, this.caller, this.grantDelay, this.executionDelay);
});
case6();
});
});
});
describe('when role is not granted', function () {
// Because this helper can be composed with other helpers, it's possible
// that role has been set already by another helper.
// Although this is highly unlikely, we check for it here to avoid false positives.
beforeEach('assert role is unset', async function () {
const { since } = await this.manager.getAccess(this.role.id, this.caller);
expect(since).to.equal(0n);
});
requiredRoleIsNotGranted();
});
}
module.exports = {
LIKE_COMMON_IS_EXECUTING,
LIKE_COMMON_GET_ACCESS,
LIKE_COMMON_SCHEDULABLE,
testAsClosable,
testAsDelay,
testAsSchedulableOperation,
testAsRestrictedOperation,
testAsDelayedOperation,
testAsCanCall,
testAsHasRole,
testAsGetAccess,
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,102 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
async function fixture() {
const [user, other] = await ethers.getSigners();
const mock = await ethers.deployContract('$AuthorityUtils');
const notAuthorityMock = await ethers.deployContract('NotAuthorityMock');
const authorityNoDelayMock = await ethers.deployContract('AuthorityNoDelayMock');
const authorityDelayMock = await ethers.deployContract('AuthorityDelayMock');
const authorityNoResponse = await ethers.deployContract('AuthorityNoResponse');
return {
user,
other,
mock,
notAuthorityMock,
authorityNoDelayMock,
authorityDelayMock,
authorityNoResponse,
};
}
describe('AuthorityUtils', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
describe('canCallWithDelay', function () {
describe('when authority does not have a canCall function', function () {
beforeEach(async function () {
this.authority = this.notAuthorityMock;
});
it('returns (immediate = 0, delay = 0)', async function () {
const { immediate, delay } = await this.mock.$canCallWithDelay(
this.authority,
this.user,
this.other,
'0x12345678',
);
expect(immediate).to.be.false;
expect(delay).to.equal(0n);
});
});
describe('when authority has no delay', function () {
beforeEach(async function () {
this.authority = this.authorityNoDelayMock;
this.immediate = true;
await this.authority._setImmediate(this.immediate);
});
it('returns (immediate, delay = 0)', async function () {
const { immediate, delay } = await this.mock.$canCallWithDelay(
this.authority,
this.user,
this.other,
'0x12345678',
);
expect(immediate).to.equal(this.immediate);
expect(delay).to.equal(0n);
});
});
describe('when authority replies with a delay', function () {
beforeEach(async function () {
this.authority = this.authorityDelayMock;
});
for (const immediate of [true, false]) {
for (const delay of [0n, 42n]) {
it(`returns (immediate=${immediate}, delay=${delay})`, async function () {
await this.authority._setImmediate(immediate);
await this.authority._setDelay(delay);
const result = await this.mock.$canCallWithDelay(this.authority, this.user, this.other, '0x12345678');
expect(result.immediate).to.equal(immediate);
expect(result.delay).to.equal(delay);
});
}
}
});
describe('when authority replies with empty data', function () {
beforeEach(async function () {
this.authority = this.authorityNoResponse;
});
it('returns (immediate = 0, delay = 0)', async function () {
const { immediate, delay } = await this.mock.$canCallWithDelay(
this.authority,
this.user,
this.other,
'0x12345678',
);
expect(immediate).to.be.false;
expect(delay).to.equal(0n);
});
});
});
});