Update docs

This commit is contained in:
github-actions
2023-09-19 19:19:10 +00:00
commit dbe796d542
624 changed files with 107720 additions and 0 deletions

View File

@ -0,0 +1,136 @@
const { expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const DummyImplementation = artifacts.require('DummyImplementation');
module.exports = function shouldBehaveLikeClone(createClone) {
before('deploy implementation', async function () {
this.implementation = web3.utils.toChecksumAddress((await DummyImplementation.new()).address);
});
const assertProxyInitialization = function ({ value, balance }) {
it('initializes the proxy', async function () {
const dummy = new DummyImplementation(this.proxy);
expect(await dummy.value()).to.be.bignumber.equal(value.toString());
});
it('has expected balance', async function () {
expect(await web3.eth.getBalance(this.proxy)).to.be.bignumber.equal(balance.toString());
});
};
describe('initialization without parameters', function () {
describe('non payable', function () {
const expectedInitializedValue = 10;
const initializeData = new DummyImplementation('').contract.methods['initializeNonPayable()']().encodeABI();
describe('when not sending balance', function () {
beforeEach('creating proxy', async function () {
this.proxy = (await createClone(this.implementation, initializeData)).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: 0,
});
});
describe('when sending some balance', function () {
const value = 10e5;
it('reverts', async function () {
await expectRevert.unspecified(createClone(this.implementation, initializeData, { value }));
});
});
});
describe('payable', function () {
const expectedInitializedValue = 100;
const initializeData = new DummyImplementation('').contract.methods['initializePayable()']().encodeABI();
describe('when not sending balance', function () {
beforeEach('creating proxy', async function () {
this.proxy = (await createClone(this.implementation, initializeData)).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: 0,
});
});
describe('when sending some balance', function () {
const value = 10e5;
beforeEach('creating proxy', async function () {
this.proxy = (await createClone(this.implementation, initializeData, { value })).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: value,
});
});
});
});
describe('initialization with parameters', function () {
describe('non payable', function () {
const expectedInitializedValue = 10;
const initializeData = new DummyImplementation('').contract.methods
.initializeNonPayableWithValue(expectedInitializedValue)
.encodeABI();
describe('when not sending balance', function () {
beforeEach('creating proxy', async function () {
this.proxy = (await createClone(this.implementation, initializeData)).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: 0,
});
});
describe('when sending some balance', function () {
const value = 10e5;
it('reverts', async function () {
await expectRevert.unspecified(createClone(this.implementation, initializeData, { value }));
});
});
});
describe('payable', function () {
const expectedInitializedValue = 42;
const initializeData = new DummyImplementation('').contract.methods
.initializePayableWithValue(expectedInitializedValue)
.encodeABI();
describe('when not sending balance', function () {
beforeEach('creating proxy', async function () {
this.proxy = (await createClone(this.implementation, initializeData)).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: 0,
});
});
describe('when sending some balance', function () {
const value = 10e5;
beforeEach('creating proxy', async function () {
this.proxy = (await createClone(this.implementation, initializeData, { value })).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: value,
});
});
});
});
};

62
test/proxy/Clones.test.js Normal file
View File

@ -0,0 +1,62 @@
const { expectEvent } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const { computeCreate2Address } = require('../helpers/create');
const { expectRevertCustomError } = require('../helpers/customError');
const shouldBehaveLikeClone = require('./Clones.behaviour');
const Clones = artifacts.require('$Clones');
contract('Clones', function (accounts) {
const [deployer] = accounts;
describe('clone', function () {
shouldBehaveLikeClone(async (implementation, initData, opts = {}) => {
const factory = await Clones.new();
const receipt = await factory.$clone(implementation);
const address = receipt.logs.find(({ event }) => event === 'return$clone').args.instance;
await web3.eth.sendTransaction({ from: deployer, to: address, value: opts.value, data: initData });
return { address };
});
});
describe('cloneDeterministic', function () {
shouldBehaveLikeClone(async (implementation, initData, opts = {}) => {
const salt = web3.utils.randomHex(32);
const factory = await Clones.new();
const receipt = await factory.$cloneDeterministic(implementation, salt);
const address = receipt.logs.find(({ event }) => event === 'return$cloneDeterministic').args.instance;
await web3.eth.sendTransaction({ from: deployer, to: address, value: opts.value, data: initData });
return { address };
});
it('address already used', async function () {
const implementation = web3.utils.randomHex(20);
const salt = web3.utils.randomHex(32);
const factory = await Clones.new();
// deploy once
expectEvent(await factory.$cloneDeterministic(implementation, salt), 'return$cloneDeterministic');
// deploy twice
await expectRevertCustomError(factory.$cloneDeterministic(implementation, salt), 'ERC1167FailedCreateClone', []);
});
it('address prediction', async function () {
const implementation = web3.utils.randomHex(20);
const salt = web3.utils.randomHex(32);
const factory = await Clones.new();
const predicted = await factory.$predictDeterministicAddress(implementation, salt);
const creationCode = [
'0x3d602d80600a3d3981f3363d3d373d3d3d363d73',
implementation.replace(/0x/, '').toLowerCase(),
'5af43d82803e903d91602b57fd5bf3',
].join('');
expect(computeCreate2Address(salt, creationCode, factory.address)).to.be.equal(predicted);
expectEvent(await factory.$cloneDeterministic(implementation, salt), 'return$cloneDeterministic', {
instance: predicted,
});
});
});
});

View File

@ -0,0 +1,12 @@
const shouldBehaveLikeProxy = require('../Proxy.behaviour');
const ERC1967Proxy = artifacts.require('ERC1967Proxy');
contract('ERC1967Proxy', function (accounts) {
// `undefined`, `null` and other false-ish opts will not be forwarded.
const createProxy = async function (implementation, initData, opts) {
return ERC1967Proxy.new(implementation, initData, ...[opts].filter(Boolean));
};
shouldBehaveLikeProxy(createProxy, accounts);
});

View File

@ -0,0 +1,172 @@
const { expectEvent, constants } = require('@openzeppelin/test-helpers');
const { expectRevertCustomError } = require('../../helpers/customError');
const { getAddressInSlot, setSlot, ImplementationSlot, AdminSlot, BeaconSlot } = require('../../helpers/erc1967');
const { ZERO_ADDRESS } = constants;
const ERC1967Utils = artifacts.require('$ERC1967Utils');
const V1 = artifacts.require('DummyImplementation');
const V2 = artifacts.require('CallReceiverMock');
const UpgradeableBeaconMock = artifacts.require('UpgradeableBeaconMock');
const UpgradeableBeaconReentrantMock = artifacts.require('UpgradeableBeaconReentrantMock');
contract('ERC1967Utils', function (accounts) {
const [, admin, anotherAccount] = accounts;
const EMPTY_DATA = '0x';
beforeEach('setup', async function () {
this.utils = await ERC1967Utils.new();
this.v1 = await V1.new();
this.v2 = await V2.new();
});
describe('IMPLEMENTATION_SLOT', function () {
beforeEach('set v1 implementation', async function () {
await setSlot(this.utils, ImplementationSlot, this.v1.address);
});
describe('getImplementation', function () {
it('returns current implementation and matches implementation slot value', async function () {
expect(await this.utils.$getImplementation()).to.equal(this.v1.address);
expect(await getAddressInSlot(this.utils.address, ImplementationSlot)).to.equal(this.v1.address);
});
});
describe('upgradeToAndCall', function () {
it('sets implementation in storage and emits event', async function () {
const newImplementation = this.v2.address;
const receipt = await this.utils.$upgradeToAndCall(newImplementation, EMPTY_DATA);
expect(await getAddressInSlot(this.utils.address, ImplementationSlot)).to.equal(newImplementation);
expectEvent(receipt, 'Upgraded', { implementation: newImplementation });
});
it('reverts when implementation does not contain code', async function () {
await expectRevertCustomError(
this.utils.$upgradeToAndCall(anotherAccount, EMPTY_DATA),
'ERC1967InvalidImplementation',
[anotherAccount],
);
});
describe('when data is empty', function () {
it('reverts when value is sent', async function () {
await expectRevertCustomError(
this.utils.$upgradeToAndCall(this.v2.address, EMPTY_DATA, { value: 1 }),
'ERC1967NonPayable',
[],
);
});
});
describe('when data is not empty', function () {
it('delegates a call to the new implementation', async function () {
const initializeData = this.v2.contract.methods.mockFunction().encodeABI();
const receipt = await this.utils.$upgradeToAndCall(this.v2.address, initializeData);
await expectEvent.inTransaction(receipt.tx, await V2.at(this.utils.address), 'MockFunctionCalled');
});
});
});
});
describe('ADMIN_SLOT', function () {
beforeEach('set admin', async function () {
await setSlot(this.utils, AdminSlot, admin);
});
describe('getAdmin', function () {
it('returns current admin and matches admin slot value', async function () {
expect(await this.utils.$getAdmin()).to.equal(admin);
expect(await getAddressInSlot(this.utils.address, AdminSlot)).to.equal(admin);
});
});
describe('changeAdmin', function () {
it('sets admin in storage and emits event', async function () {
const newAdmin = anotherAccount;
const receipt = await this.utils.$changeAdmin(newAdmin);
expect(await getAddressInSlot(this.utils.address, AdminSlot)).to.equal(newAdmin);
expectEvent(receipt, 'AdminChanged', { previousAdmin: admin, newAdmin: newAdmin });
});
it('reverts when setting the address zero as admin', async function () {
await expectRevertCustomError(this.utils.$changeAdmin(ZERO_ADDRESS), 'ERC1967InvalidAdmin', [ZERO_ADDRESS]);
});
});
});
describe('BEACON_SLOT', function () {
beforeEach('set beacon', async function () {
this.beacon = await UpgradeableBeaconMock.new(this.v1.address);
await setSlot(this.utils, BeaconSlot, this.beacon.address);
});
describe('getBeacon', function () {
it('returns current beacon and matches beacon slot value', async function () {
expect(await this.utils.$getBeacon()).to.equal(this.beacon.address);
expect(await getAddressInSlot(this.utils.address, BeaconSlot)).to.equal(this.beacon.address);
});
});
describe('upgradeBeaconToAndCall', function () {
it('sets beacon in storage and emits event', async function () {
const newBeacon = await UpgradeableBeaconMock.new(this.v2.address);
const receipt = await this.utils.$upgradeBeaconToAndCall(newBeacon.address, EMPTY_DATA);
expect(await getAddressInSlot(this.utils.address, BeaconSlot)).to.equal(newBeacon.address);
expectEvent(receipt, 'BeaconUpgraded', { beacon: newBeacon.address });
});
it('reverts when beacon does not contain code', async function () {
await expectRevertCustomError(
this.utils.$upgradeBeaconToAndCall(anotherAccount, EMPTY_DATA),
'ERC1967InvalidBeacon',
[anotherAccount],
);
});
it("reverts when beacon's implementation does not contain code", async function () {
const newBeacon = await UpgradeableBeaconMock.new(anotherAccount);
await expectRevertCustomError(
this.utils.$upgradeBeaconToAndCall(newBeacon.address, EMPTY_DATA),
'ERC1967InvalidImplementation',
[anotherAccount],
);
});
describe('when data is empty', function () {
it('reverts when value is sent', async function () {
const newBeacon = await UpgradeableBeaconMock.new(this.v2.address);
await expectRevertCustomError(
this.utils.$upgradeBeaconToAndCall(newBeacon.address, EMPTY_DATA, { value: 1 }),
'ERC1967NonPayable',
[],
);
});
});
describe('when data is not empty', function () {
it('delegates a call to the new implementation', async function () {
const initializeData = this.v2.contract.methods.mockFunction().encodeABI();
const newBeacon = await UpgradeableBeaconMock.new(this.v2.address);
const receipt = await this.utils.$upgradeBeaconToAndCall(newBeacon.address, initializeData);
await expectEvent.inTransaction(receipt.tx, await V2.at(this.utils.address), 'MockFunctionCalled');
});
});
describe('reentrant beacon implementation() call', function () {
it('sees the new beacon implementation', async function () {
const newBeacon = await UpgradeableBeaconReentrantMock.new();
await expectRevertCustomError(
this.utils.$upgradeBeaconToAndCall(newBeacon.address, '0x'),
'BeaconProxyBeaconSlotAddress',
[newBeacon.address],
);
});
});
});
});
});

View File

@ -0,0 +1,182 @@
const { expectRevert } = require('@openzeppelin/test-helpers');
const { getSlot, ImplementationSlot } = require('../helpers/erc1967');
const { expect } = require('chai');
const { expectRevertCustomError } = require('../helpers/customError');
const DummyImplementation = artifacts.require('DummyImplementation');
module.exports = function shouldBehaveLikeProxy(createProxy, accounts) {
it('cannot be initialized with a non-contract address', async function () {
const nonContractAddress = accounts[0];
const initializeData = Buffer.from('');
await expectRevert.unspecified(createProxy(nonContractAddress, initializeData));
});
before('deploy implementation', async function () {
this.implementation = web3.utils.toChecksumAddress((await DummyImplementation.new()).address);
});
const assertProxyInitialization = function ({ value, balance }) {
it('sets the implementation address', async function () {
const implementationSlot = await getSlot(this.proxy, ImplementationSlot);
const implementationAddress = web3.utils.toChecksumAddress(implementationSlot.substr(-40));
expect(implementationAddress).to.be.equal(this.implementation);
});
it('initializes the proxy', async function () {
const dummy = new DummyImplementation(this.proxy);
expect(await dummy.value()).to.be.bignumber.equal(value.toString());
});
it('has expected balance', async function () {
expect(await web3.eth.getBalance(this.proxy)).to.be.bignumber.equal(balance.toString());
});
};
describe('without initialization', function () {
const initializeData = Buffer.from('');
describe('when not sending balance', function () {
beforeEach('creating proxy', async function () {
this.proxy = (await createProxy(this.implementation, initializeData)).address;
});
assertProxyInitialization({ value: 0, balance: 0 });
});
describe('when sending some balance', function () {
const value = 10e5;
it('reverts', async function () {
await expectRevertCustomError(
createProxy(this.implementation, initializeData, { value }),
'ERC1967NonPayable',
[],
);
});
});
});
describe('initialization without parameters', function () {
describe('non payable', function () {
const expectedInitializedValue = 10;
const initializeData = new DummyImplementation('').contract.methods['initializeNonPayable()']().encodeABI();
describe('when not sending balance', function () {
beforeEach('creating proxy', async function () {
this.proxy = (await createProxy(this.implementation, initializeData)).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: 0,
});
});
describe('when sending some balance', function () {
const value = 10e5;
it('reverts', async function () {
await expectRevert.unspecified(createProxy(this.implementation, initializeData, { value }));
});
});
});
describe('payable', function () {
const expectedInitializedValue = 100;
const initializeData = new DummyImplementation('').contract.methods['initializePayable()']().encodeABI();
describe('when not sending balance', function () {
beforeEach('creating proxy', async function () {
this.proxy = (await createProxy(this.implementation, initializeData)).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: 0,
});
});
describe('when sending some balance', function () {
const value = 10e5;
beforeEach('creating proxy', async function () {
this.proxy = (await createProxy(this.implementation, initializeData, { value })).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: value,
});
});
});
});
describe('initialization with parameters', function () {
describe('non payable', function () {
const expectedInitializedValue = 10;
const initializeData = new DummyImplementation('').contract.methods
.initializeNonPayableWithValue(expectedInitializedValue)
.encodeABI();
describe('when not sending balance', function () {
beforeEach('creating proxy', async function () {
this.proxy = (await createProxy(this.implementation, initializeData)).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: 0,
});
});
describe('when sending some balance', function () {
const value = 10e5;
it('reverts', async function () {
await expectRevert.unspecified(createProxy(this.implementation, initializeData, { value }));
});
});
});
describe('payable', function () {
const expectedInitializedValue = 42;
const initializeData = new DummyImplementation('').contract.methods
.initializePayableWithValue(expectedInitializedValue)
.encodeABI();
describe('when not sending balance', function () {
beforeEach('creating proxy', async function () {
this.proxy = (await createProxy(this.implementation, initializeData)).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: 0,
});
});
describe('when sending some balance', function () {
const value = 10e5;
beforeEach('creating proxy', async function () {
this.proxy = (await createProxy(this.implementation, initializeData, { value })).address;
});
assertProxyInitialization({
value: expectedInitializedValue,
balance: value,
});
});
});
describe('reverting initialization', function () {
const initializeData = new DummyImplementation('').contract.methods.reverts().encodeABI();
it('reverts', async function () {
await expectRevert(createProxy(this.implementation, initializeData), 'DummyImplementation reverted');
});
});
});
};

View File

@ -0,0 +1,152 @@
const { expectRevert } = require('@openzeppelin/test-helpers');
const { getSlot, BeaconSlot } = require('../../helpers/erc1967');
const { expectRevertCustomError } = require('../../helpers/customError');
const { expect } = require('chai');
const UpgradeableBeacon = artifacts.require('UpgradeableBeacon');
const BeaconProxy = artifacts.require('BeaconProxy');
const DummyImplementation = artifacts.require('DummyImplementation');
const DummyImplementationV2 = artifacts.require('DummyImplementationV2');
const BadBeaconNoImpl = artifacts.require('BadBeaconNoImpl');
const BadBeaconNotContract = artifacts.require('BadBeaconNotContract');
contract('BeaconProxy', function (accounts) {
const [upgradeableBeaconAdmin, anotherAccount] = accounts;
describe('bad beacon is not accepted', async function () {
it('non-contract beacon', async function () {
await expectRevertCustomError(BeaconProxy.new(anotherAccount, '0x'), 'ERC1967InvalidBeacon', [anotherAccount]);
});
it('non-compliant beacon', async function () {
const beacon = await BadBeaconNoImpl.new();
await expectRevert.unspecified(BeaconProxy.new(beacon.address, '0x'));
});
it('non-contract implementation', async function () {
const beacon = await BadBeaconNotContract.new();
const implementation = await beacon.implementation();
await expectRevertCustomError(BeaconProxy.new(beacon.address, '0x'), 'ERC1967InvalidImplementation', [
implementation,
]);
});
});
before('deploy implementation', async function () {
this.implementationV0 = await DummyImplementation.new();
this.implementationV1 = await DummyImplementationV2.new();
});
describe('initialization', function () {
before(function () {
this.assertInitialized = async ({ value, balance }) => {
const beaconSlot = await getSlot(this.proxy, BeaconSlot);
const beaconAddress = web3.utils.toChecksumAddress(beaconSlot.substr(-40));
expect(beaconAddress).to.equal(this.beacon.address);
const dummy = new DummyImplementation(this.proxy.address);
expect(await dummy.value()).to.bignumber.eq(value);
expect(await web3.eth.getBalance(this.proxy.address)).to.bignumber.eq(balance);
};
});
beforeEach('deploy beacon', async function () {
this.beacon = await UpgradeableBeacon.new(this.implementationV0.address, upgradeableBeaconAdmin);
});
it('no initialization', async function () {
const data = Buffer.from('');
this.proxy = await BeaconProxy.new(this.beacon.address, data);
await this.assertInitialized({ value: '0', balance: '0' });
});
it('non-payable initialization', async function () {
const value = '55';
const data = this.implementationV0.contract.methods.initializeNonPayableWithValue(value).encodeABI();
this.proxy = await BeaconProxy.new(this.beacon.address, data);
await this.assertInitialized({ value, balance: '0' });
});
it('payable initialization', async function () {
const value = '55';
const data = this.implementationV0.contract.methods.initializePayableWithValue(value).encodeABI();
const balance = '100';
this.proxy = await BeaconProxy.new(this.beacon.address, data, { value: balance });
await this.assertInitialized({ value, balance });
});
it('reverting initialization due to value', async function () {
const data = Buffer.from('');
await expectRevertCustomError(
BeaconProxy.new(this.beacon.address, data, { value: '1' }),
'ERC1967NonPayable',
[],
);
});
it('reverting initialization function', async function () {
const data = this.implementationV0.contract.methods.reverts().encodeABI();
await expectRevert(BeaconProxy.new(this.beacon.address, data), 'DummyImplementation reverted');
});
});
it('upgrade a proxy by upgrading its beacon', async function () {
const beacon = await UpgradeableBeacon.new(this.implementationV0.address, upgradeableBeaconAdmin);
const value = '10';
const data = this.implementationV0.contract.methods.initializeNonPayableWithValue(value).encodeABI();
const proxy = await BeaconProxy.new(beacon.address, data);
const dummy = new DummyImplementation(proxy.address);
// test initial values
expect(await dummy.value()).to.bignumber.eq(value);
// test initial version
expect(await dummy.version()).to.eq('V1');
// upgrade beacon
await beacon.upgradeTo(this.implementationV1.address, { from: upgradeableBeaconAdmin });
// test upgraded version
expect(await dummy.version()).to.eq('V2');
});
it('upgrade 2 proxies by upgrading shared beacon', async function () {
const value1 = '10';
const value2 = '42';
const beacon = await UpgradeableBeacon.new(this.implementationV0.address, upgradeableBeaconAdmin);
const proxy1InitializeData = this.implementationV0.contract.methods
.initializeNonPayableWithValue(value1)
.encodeABI();
const proxy1 = await BeaconProxy.new(beacon.address, proxy1InitializeData);
const proxy2InitializeData = this.implementationV0.contract.methods
.initializeNonPayableWithValue(value2)
.encodeABI();
const proxy2 = await BeaconProxy.new(beacon.address, proxy2InitializeData);
const dummy1 = new DummyImplementation(proxy1.address);
const dummy2 = new DummyImplementation(proxy2.address);
// test initial values
expect(await dummy1.value()).to.bignumber.eq(value1);
expect(await dummy2.value()).to.bignumber.eq(value2);
// test initial version
expect(await dummy1.version()).to.eq('V1');
expect(await dummy2.version()).to.eq('V1');
// upgrade beacon
await beacon.upgradeTo(this.implementationV1.address, { from: upgradeableBeaconAdmin });
// test upgraded version
expect(await dummy1.version()).to.eq('V2');
expect(await dummy2.version()).to.eq('V2');
});
});

View File

@ -0,0 +1,54 @@
const { expectEvent } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const { expectRevertCustomError } = require('../../helpers/customError');
const UpgradeableBeacon = artifacts.require('UpgradeableBeacon');
const Implementation1 = artifacts.require('Implementation1');
const Implementation2 = artifacts.require('Implementation2');
contract('UpgradeableBeacon', function (accounts) {
const [owner, other] = accounts;
it('cannot be created with non-contract implementation', async function () {
await expectRevertCustomError(UpgradeableBeacon.new(other, owner), 'BeaconInvalidImplementation', [other]);
});
context('once deployed', async function () {
beforeEach('deploying beacon', async function () {
this.v1 = await Implementation1.new();
this.beacon = await UpgradeableBeacon.new(this.v1.address, owner);
});
it('emits Upgraded event to the first implementation', async function () {
const beacon = await UpgradeableBeacon.new(this.v1.address, owner);
await expectEvent.inTransaction(beacon.contract.transactionHash, beacon, 'Upgraded', {
implementation: this.v1.address,
});
});
it('returns implementation', async function () {
expect(await this.beacon.implementation()).to.equal(this.v1.address);
});
it('can be upgraded by the owner', async function () {
const v2 = await Implementation2.new();
const receipt = await this.beacon.upgradeTo(v2.address, { from: owner });
expectEvent(receipt, 'Upgraded', { implementation: v2.address });
expect(await this.beacon.implementation()).to.equal(v2.address);
});
it('cannot be upgraded to a non-contract', async function () {
await expectRevertCustomError(this.beacon.upgradeTo(other, { from: owner }), 'BeaconInvalidImplementation', [
other,
]);
});
it('cannot be upgraded by other account', async function () {
const v2 = await Implementation2.new();
await expectRevertCustomError(this.beacon.upgradeTo(v2.address, { from: other }), 'OwnableUnauthorizedAccount', [
other,
]);
});
});
});

View File

@ -0,0 +1,103 @@
const { expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const ImplV1 = artifacts.require('DummyImplementation');
const ImplV2 = artifacts.require('DummyImplementationV2');
const ProxyAdmin = artifacts.require('ProxyAdmin');
const TransparentUpgradeableProxy = artifacts.require('TransparentUpgradeableProxy');
const ITransparentUpgradeableProxy = artifacts.require('ITransparentUpgradeableProxy');
const { getAddressInSlot, ImplementationSlot } = require('../../helpers/erc1967');
const { expectRevertCustomError } = require('../../helpers/customError');
const { computeCreateAddress } = require('../../helpers/create');
contract('ProxyAdmin', function (accounts) {
const [proxyAdminOwner, anotherAccount] = accounts;
before('set implementations', async function () {
this.implementationV1 = await ImplV1.new();
this.implementationV2 = await ImplV2.new();
});
beforeEach(async function () {
const initializeData = Buffer.from('');
const proxy = await TransparentUpgradeableProxy.new(this.implementationV1.address, proxyAdminOwner, initializeData);
const proxyNonce = await web3.eth.getTransactionCount(proxy.address);
const proxyAdminAddress = computeCreateAddress(proxy.address, proxyNonce - 1); // Nonce already used
this.proxyAdmin = await ProxyAdmin.at(proxyAdminAddress);
this.proxy = await ITransparentUpgradeableProxy.at(proxy.address);
});
it('has an owner', async function () {
expect(await this.proxyAdmin.owner()).to.equal(proxyAdminOwner);
});
it('has an interface version', async function () {
expect(await this.proxyAdmin.UPGRADE_INTERFACE_VERSION()).to.equal('5.0.0');
});
describe('without data', function () {
context('with unauthorized account', function () {
it('fails to upgrade', async function () {
await expectRevertCustomError(
this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, '0x', {
from: anotherAccount,
}),
'OwnableUnauthorizedAccount',
[anotherAccount],
);
});
});
context('with authorized account', function () {
it('upgrades implementation', async function () {
await this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, '0x', {
from: proxyAdminOwner,
});
const implementationAddress = await getAddressInSlot(this.proxy, ImplementationSlot);
expect(implementationAddress).to.be.equal(this.implementationV2.address);
});
});
});
describe('with data', function () {
context('with unauthorized account', function () {
it('fails to upgrade', async function () {
const callData = new ImplV1('').contract.methods.initializeNonPayableWithValue(1337).encodeABI();
await expectRevertCustomError(
this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, {
from: anotherAccount,
}),
'OwnableUnauthorizedAccount',
[anotherAccount],
);
});
});
context('with authorized account', function () {
context('with invalid callData', function () {
it('fails to upgrade', async function () {
const callData = '0x12345678';
await expectRevert.unspecified(
this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, {
from: proxyAdminOwner,
}),
);
});
});
context('with valid callData', function () {
it('upgrades implementation', async function () {
const callData = new ImplV1('').contract.methods.initializeNonPayableWithValue(1337).encodeABI();
await this.proxyAdmin.upgradeAndCall(this.proxy.address, this.implementationV2.address, callData, {
from: proxyAdminOwner,
});
const implementationAddress = await getAddressInSlot(this.proxy, ImplementationSlot);
expect(implementationAddress).to.be.equal(this.implementationV2.address);
});
});
});
});
});

View File

@ -0,0 +1,413 @@
const { BN, expectRevert, expectEvent, constants } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { getAddressInSlot, ImplementationSlot, AdminSlot } = require('../../helpers/erc1967');
const { expectRevertCustomError } = require('../../helpers/customError');
const { expect } = require('chai');
const { web3 } = require('hardhat');
const { computeCreateAddress } = require('../../helpers/create');
const { impersonate } = require('../../helpers/account');
const Implementation1 = artifacts.require('Implementation1');
const Implementation2 = artifacts.require('Implementation2');
const Implementation3 = artifacts.require('Implementation3');
const Implementation4 = artifacts.require('Implementation4');
const MigratableMockV1 = artifacts.require('MigratableMockV1');
const MigratableMockV2 = artifacts.require('MigratableMockV2');
const MigratableMockV3 = artifacts.require('MigratableMockV3');
const InitializableMock = artifacts.require('InitializableMock');
const DummyImplementation = artifacts.require('DummyImplementation');
const ClashingImplementation = artifacts.require('ClashingImplementation');
const Ownable = artifacts.require('Ownable');
module.exports = function shouldBehaveLikeTransparentUpgradeableProxy(createProxy, initialOwner, accounts) {
const [anotherAccount] = accounts;
async function createProxyWithImpersonatedProxyAdmin(logic, initData, opts = undefined) {
const proxy = await createProxy(logic, initData, opts);
// Expect proxy admin to be the first and only contract created by the proxy
const proxyAdminAddress = computeCreateAddress(proxy.address, 1);
await impersonate(proxyAdminAddress);
return {
proxy,
proxyAdminAddress,
};
}
before(async function () {
this.implementationV0 = (await DummyImplementation.new()).address;
this.implementationV1 = (await DummyImplementation.new()).address;
});
beforeEach(async function () {
const initializeData = Buffer.from('');
const { proxy, proxyAdminAddress } = await createProxyWithImpersonatedProxyAdmin(
this.implementationV0,
initializeData,
);
this.proxy = proxy;
this.proxyAdminAddress = proxyAdminAddress;
});
describe('implementation', function () {
it('returns the current implementation address', async function () {
const implementationAddress = await getAddressInSlot(this.proxy, ImplementationSlot);
expect(implementationAddress).to.be.equal(this.implementationV0);
});
it('delegates to the implementation', async function () {
const dummy = new DummyImplementation(this.proxy.address);
const value = await dummy.get();
expect(value).to.equal(true);
});
});
describe('proxy admin', function () {
it('emits AdminChanged event during construction', async function () {
await expectEvent.inConstruction(this.proxy, 'AdminChanged', {
previousAdmin: ZERO_ADDRESS,
newAdmin: this.proxyAdminAddress,
});
});
it('sets the proxy admin in storage with the correct initial owner', async function () {
expect(await getAddressInSlot(this.proxy, AdminSlot)).to.be.equal(this.proxyAdminAddress);
const proxyAdmin = await Ownable.at(this.proxyAdminAddress);
expect(await proxyAdmin.owner()).to.be.equal(initialOwner);
});
it('can overwrite the admin by the implementation', async function () {
const dummy = new DummyImplementation(this.proxy.address);
await dummy.unsafeOverrideAdmin(anotherAccount);
const ERC1967AdminSlotValue = await getAddressInSlot(this.proxy, AdminSlot);
expect(ERC1967AdminSlotValue).to.be.equal(anotherAccount);
// Still allows previous admin to execute admin operations
expect(ERC1967AdminSlotValue).to.not.equal(this.proxyAdminAddress);
expectEvent(
await this.proxy.upgradeToAndCall(this.implementationV1, '0x', { from: this.proxyAdminAddress }),
'Upgraded',
{
implementation: this.implementationV1,
},
);
});
});
describe('upgradeToAndCall', function () {
describe('without migrations', function () {
beforeEach(async function () {
this.behavior = await InitializableMock.new();
});
describe('when the call does not fail', function () {
const initializeData = new InitializableMock('').contract.methods['initializeWithX(uint256)'](42).encodeABI();
describe('when the sender is the admin', function () {
const value = 1e5;
beforeEach(async function () {
this.receipt = await this.proxy.upgradeToAndCall(this.behavior.address, initializeData, {
from: this.proxyAdminAddress,
value,
});
});
it('upgrades to the requested implementation', async function () {
const implementationAddress = await getAddressInSlot(this.proxy, ImplementationSlot);
expect(implementationAddress).to.be.equal(this.behavior.address);
});
it('emits an event', function () {
expectEvent(this.receipt, 'Upgraded', { implementation: this.behavior.address });
});
it('calls the initializer function', async function () {
const migratable = new InitializableMock(this.proxy.address);
const x = await migratable.x();
expect(x).to.be.bignumber.equal('42');
});
it('sends given value to the proxy', async function () {
const balance = await web3.eth.getBalance(this.proxy.address);
expect(balance.toString()).to.be.bignumber.equal(value.toString());
});
it('uses the storage of the proxy', async function () {
// storage layout should look as follows:
// - 0: Initializable storage ++ initializerRan ++ onlyInitializingRan
// - 1: x
const storedValue = await web3.eth.getStorageAt(this.proxy.address, 1);
expect(parseInt(storedValue)).to.eq(42);
});
});
describe('when the sender is not the admin', function () {
it('reverts', async function () {
await expectRevert.unspecified(
this.proxy.upgradeToAndCall(this.behavior.address, initializeData, { from: anotherAccount }),
);
});
});
});
describe('when the call does fail', function () {
const initializeData = new InitializableMock('').contract.methods.fail().encodeABI();
it('reverts', async function () {
await expectRevert.unspecified(
this.proxy.upgradeToAndCall(this.behavior.address, initializeData, { from: this.proxyAdminAddress }),
);
});
});
});
describe('with migrations', function () {
describe('when the sender is the admin', function () {
const value = 1e5;
describe('when upgrading to V1', function () {
const v1MigrationData = new MigratableMockV1('').contract.methods.initialize(42).encodeABI();
beforeEach(async function () {
this.behaviorV1 = await MigratableMockV1.new();
this.balancePreviousV1 = new BN(await web3.eth.getBalance(this.proxy.address));
this.receipt = await this.proxy.upgradeToAndCall(this.behaviorV1.address, v1MigrationData, {
from: this.proxyAdminAddress,
value,
});
});
it('upgrades to the requested version and emits an event', async function () {
const implementation = await getAddressInSlot(this.proxy, ImplementationSlot);
expect(implementation).to.be.equal(this.behaviorV1.address);
expectEvent(this.receipt, 'Upgraded', { implementation: this.behaviorV1.address });
});
it("calls the 'initialize' function and sends given value to the proxy", async function () {
const migratable = new MigratableMockV1(this.proxy.address);
const x = await migratable.x();
expect(x).to.be.bignumber.equal('42');
const balance = await web3.eth.getBalance(this.proxy.address);
expect(new BN(balance)).to.be.bignumber.equal(this.balancePreviousV1.addn(value));
});
describe('when upgrading to V2', function () {
const v2MigrationData = new MigratableMockV2('').contract.methods.migrate(10, 42).encodeABI();
beforeEach(async function () {
this.behaviorV2 = await MigratableMockV2.new();
this.balancePreviousV2 = new BN(await web3.eth.getBalance(this.proxy.address));
this.receipt = await this.proxy.upgradeToAndCall(this.behaviorV2.address, v2MigrationData, {
from: this.proxyAdminAddress,
value,
});
});
it('upgrades to the requested version and emits an event', async function () {
const implementation = await getAddressInSlot(this.proxy, ImplementationSlot);
expect(implementation).to.be.equal(this.behaviorV2.address);
expectEvent(this.receipt, 'Upgraded', { implementation: this.behaviorV2.address });
});
it("calls the 'migrate' function and sends given value to the proxy", async function () {
const migratable = new MigratableMockV2(this.proxy.address);
const x = await migratable.x();
expect(x).to.be.bignumber.equal('10');
const y = await migratable.y();
expect(y).to.be.bignumber.equal('42');
const balance = new BN(await web3.eth.getBalance(this.proxy.address));
expect(balance).to.be.bignumber.equal(this.balancePreviousV2.addn(value));
});
describe('when upgrading to V3', function () {
const v3MigrationData = new MigratableMockV3('').contract.methods['migrate()']().encodeABI();
beforeEach(async function () {
this.behaviorV3 = await MigratableMockV3.new();
this.balancePreviousV3 = new BN(await web3.eth.getBalance(this.proxy.address));
this.receipt = await this.proxy.upgradeToAndCall(this.behaviorV3.address, v3MigrationData, {
from: this.proxyAdminAddress,
value,
});
});
it('upgrades to the requested version and emits an event', async function () {
const implementation = await getAddressInSlot(this.proxy, ImplementationSlot);
expect(implementation).to.be.equal(this.behaviorV3.address);
expectEvent(this.receipt, 'Upgraded', { implementation: this.behaviorV3.address });
});
it("calls the 'migrate' function and sends given value to the proxy", async function () {
const migratable = new MigratableMockV3(this.proxy.address);
const x = await migratable.x();
expect(x).to.be.bignumber.equal('42');
const y = await migratable.y();
expect(y).to.be.bignumber.equal('10');
const balance = new BN(await web3.eth.getBalance(this.proxy.address));
expect(balance).to.be.bignumber.equal(this.balancePreviousV3.addn(value));
});
});
});
});
});
describe('when the sender is not the admin', function () {
const from = anotherAccount;
it('reverts', async function () {
const behaviorV1 = await MigratableMockV1.new();
const v1MigrationData = new MigratableMockV1('').contract.methods.initialize(42).encodeABI();
await expectRevert.unspecified(this.proxy.upgradeToAndCall(behaviorV1.address, v1MigrationData, { from }));
});
});
});
});
describe('transparent proxy', function () {
beforeEach('creating proxy', async function () {
const initializeData = Buffer.from('');
this.clashingImplV0 = (await ClashingImplementation.new()).address;
this.clashingImplV1 = (await ClashingImplementation.new()).address;
const { proxy, proxyAdminAddress } = await createProxyWithImpersonatedProxyAdmin(
this.clashingImplV0,
initializeData,
);
this.proxy = proxy;
this.proxyAdminAddress = proxyAdminAddress;
this.clashing = new ClashingImplementation(this.proxy.address);
});
it('proxy admin cannot call delegated functions', async function () {
await expectRevertCustomError(
this.clashing.delegatedFunction({ from: this.proxyAdminAddress }),
'ProxyDeniedAdminAccess',
[],
);
});
describe('when function names clash', function () {
it('executes the proxy function if the sender is the admin', async function () {
const receipt = await this.proxy.upgradeToAndCall(this.clashingImplV1, '0x', {
from: this.proxyAdminAddress,
});
expectEvent(receipt, 'Upgraded', { implementation: this.clashingImplV1 });
});
it('delegates the call to implementation when sender is not the admin', async function () {
const receipt = await this.proxy.upgradeToAndCall(this.clashingImplV1, '0x', {
from: anotherAccount,
});
expectEvent.notEmitted(receipt, 'Upgraded');
expectEvent.inTransaction(receipt.tx, this.clashing, 'ClashingImplementationCall');
});
});
});
describe('regression', () => {
const initializeData = Buffer.from('');
it('should add new function', async () => {
const instance1 = await Implementation1.new();
const { proxy, proxyAdminAddress } = await createProxyWithImpersonatedProxyAdmin(
instance1.address,
initializeData,
);
const proxyInstance1 = new Implementation1(proxy.address);
await proxyInstance1.setValue(42);
const instance2 = await Implementation2.new();
await proxy.upgradeToAndCall(instance2.address, '0x', { from: proxyAdminAddress });
const proxyInstance2 = new Implementation2(proxy.address);
const res = await proxyInstance2.getValue();
expect(res.toString()).to.eq('42');
});
it('should remove function', async () => {
const instance2 = await Implementation2.new();
const { proxy, proxyAdminAddress } = await createProxyWithImpersonatedProxyAdmin(
instance2.address,
initializeData,
);
const proxyInstance2 = new Implementation2(proxy.address);
await proxyInstance2.setValue(42);
const res = await proxyInstance2.getValue();
expect(res.toString()).to.eq('42');
const instance1 = await Implementation1.new();
await proxy.upgradeToAndCall(instance1.address, '0x', { from: proxyAdminAddress });
const proxyInstance1 = new Implementation2(proxy.address);
await expectRevert.unspecified(proxyInstance1.getValue());
});
it('should change function signature', async () => {
const instance1 = await Implementation1.new();
const { proxy, proxyAdminAddress } = await createProxyWithImpersonatedProxyAdmin(
instance1.address,
initializeData,
);
const proxyInstance1 = new Implementation1(proxy.address);
await proxyInstance1.setValue(42);
const instance3 = await Implementation3.new();
await proxy.upgradeToAndCall(instance3.address, '0x', { from: proxyAdminAddress });
const proxyInstance3 = new Implementation3(proxy.address);
const res = await proxyInstance3.getValue(8);
expect(res.toString()).to.eq('50');
});
it('should add fallback function', async () => {
const initializeData = Buffer.from('');
const instance1 = await Implementation1.new();
const { proxy, proxyAdminAddress } = await createProxyWithImpersonatedProxyAdmin(
instance1.address,
initializeData,
);
const instance4 = await Implementation4.new();
await proxy.upgradeToAndCall(instance4.address, '0x', { from: proxyAdminAddress });
const proxyInstance4 = new Implementation4(proxy.address);
const data = '0x';
await web3.eth.sendTransaction({ to: proxy.address, from: anotherAccount, data });
const res = await proxyInstance4.getValue();
expect(res.toString()).to.eq('1');
});
it('should remove fallback function', async () => {
const instance4 = await Implementation4.new();
const { proxy, proxyAdminAddress } = await createProxyWithImpersonatedProxyAdmin(
instance4.address,
initializeData,
);
const instance2 = await Implementation2.new();
await proxy.upgradeToAndCall(instance2.address, '0x', { from: proxyAdminAddress });
const data = '0x';
await expectRevert.unspecified(web3.eth.sendTransaction({ to: proxy.address, from: anotherAccount, data }));
const proxyInstance2 = new Implementation2(proxy.address);
const res = await proxyInstance2.getValue();
expect(res.toString()).to.eq('0');
});
});
};

View File

@ -0,0 +1,24 @@
const shouldBehaveLikeProxy = require('../Proxy.behaviour');
const shouldBehaveLikeTransparentUpgradeableProxy = require('./TransparentUpgradeableProxy.behaviour');
const TransparentUpgradeableProxy = artifacts.require('TransparentUpgradeableProxy');
const ITransparentUpgradeableProxy = artifacts.require('ITransparentUpgradeableProxy');
contract('TransparentUpgradeableProxy', function (accounts) {
const [owner, ...otherAccounts] = accounts;
// `undefined`, `null` and other false-ish opts will not be forwarded.
const createProxy = async function (logic, initData, opts = undefined) {
const { address, transactionHash } = await TransparentUpgradeableProxy.new(
logic,
owner,
initData,
...[opts].filter(Boolean),
);
const instance = await ITransparentUpgradeableProxy.at(address);
return { ...instance, transactionHash };
};
shouldBehaveLikeProxy(createProxy, otherAccounts);
shouldBehaveLikeTransparentUpgradeableProxy(createProxy, owner, otherAccounts);
});

View File

@ -0,0 +1,220 @@
const { expectEvent } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const { expectRevertCustomError } = require('../../helpers/customError');
const { MAX_UINT64 } = require('../../helpers/constants');
const InitializableMock = artifacts.require('InitializableMock');
const ConstructorInitializableMock = artifacts.require('ConstructorInitializableMock');
const ChildConstructorInitializableMock = artifacts.require('ChildConstructorInitializableMock');
const ReinitializerMock = artifacts.require('ReinitializerMock');
const SampleChild = artifacts.require('SampleChild');
const DisableBad1 = artifacts.require('DisableBad1');
const DisableBad2 = artifacts.require('DisableBad2');
const DisableOk = artifacts.require('DisableOk');
contract('Initializable', function () {
describe('basic testing without inheritance', function () {
beforeEach('deploying', async function () {
this.contract = await InitializableMock.new();
});
describe('before initialize', function () {
it('initializer has not run', async function () {
expect(await this.contract.initializerRan()).to.equal(false);
});
it('_initializing returns false before initialization', async function () {
expect(await this.contract.isInitializing()).to.equal(false);
});
});
describe('after initialize', function () {
beforeEach('initializing', async function () {
await this.contract.initialize();
});
it('initializer has run', async function () {
expect(await this.contract.initializerRan()).to.equal(true);
});
it('_initializing returns false after initialization', async function () {
expect(await this.contract.isInitializing()).to.equal(false);
});
it('initializer does not run again', async function () {
await expectRevertCustomError(this.contract.initialize(), 'InvalidInitialization', []);
});
});
describe('nested under an initializer', function () {
it('initializer modifier reverts', async function () {
await expectRevertCustomError(this.contract.initializerNested(), 'InvalidInitialization', []);
});
it('onlyInitializing modifier succeeds', async function () {
await this.contract.onlyInitializingNested();
expect(await this.contract.onlyInitializingRan()).to.equal(true);
});
});
it('cannot call onlyInitializable function outside the scope of an initializable function', async function () {
await expectRevertCustomError(this.contract.initializeOnlyInitializing(), 'NotInitializing', []);
});
});
it('nested initializer can run during construction', async function () {
const contract2 = await ConstructorInitializableMock.new();
expect(await contract2.initializerRan()).to.equal(true);
expect(await contract2.onlyInitializingRan()).to.equal(true);
});
it('multiple constructor levels can be initializers', async function () {
const contract2 = await ChildConstructorInitializableMock.new();
expect(await contract2.initializerRan()).to.equal(true);
expect(await contract2.childInitializerRan()).to.equal(true);
expect(await contract2.onlyInitializingRan()).to.equal(true);
});
describe('reinitialization', function () {
beforeEach('deploying', async function () {
this.contract = await ReinitializerMock.new();
});
it('can reinitialize', async function () {
expect(await this.contract.counter()).to.be.bignumber.equal('0');
await this.contract.initialize();
expect(await this.contract.counter()).to.be.bignumber.equal('1');
await this.contract.reinitialize(2);
expect(await this.contract.counter()).to.be.bignumber.equal('2');
await this.contract.reinitialize(3);
expect(await this.contract.counter()).to.be.bignumber.equal('3');
});
it('can jump multiple steps', async function () {
expect(await this.contract.counter()).to.be.bignumber.equal('0');
await this.contract.initialize();
expect(await this.contract.counter()).to.be.bignumber.equal('1');
await this.contract.reinitialize(128);
expect(await this.contract.counter()).to.be.bignumber.equal('2');
});
it('cannot nest reinitializers', async function () {
expect(await this.contract.counter()).to.be.bignumber.equal('0');
await expectRevertCustomError(this.contract.nestedReinitialize(2, 2), 'InvalidInitialization', []);
await expectRevertCustomError(this.contract.nestedReinitialize(2, 3), 'InvalidInitialization', []);
await expectRevertCustomError(this.contract.nestedReinitialize(3, 2), 'InvalidInitialization', []);
});
it('can chain reinitializers', async function () {
expect(await this.contract.counter()).to.be.bignumber.equal('0');
await this.contract.chainReinitialize(2, 3);
expect(await this.contract.counter()).to.be.bignumber.equal('2');
});
it('_getInitializedVersion returns right version', async function () {
await this.contract.initialize();
expect(await this.contract.getInitializedVersion()).to.be.bignumber.equal('1');
await this.contract.reinitialize(12);
expect(await this.contract.getInitializedVersion()).to.be.bignumber.equal('12');
});
describe('contract locking', function () {
it('prevents initialization', async function () {
await this.contract.disableInitializers();
await expectRevertCustomError(this.contract.initialize(), 'InvalidInitialization', []);
});
it('prevents re-initialization', async function () {
await this.contract.disableInitializers();
await expectRevertCustomError(this.contract.reinitialize(255), 'InvalidInitialization', []);
});
it('can lock contract after initialization', async function () {
await this.contract.initialize();
await this.contract.disableInitializers();
await expectRevertCustomError(this.contract.reinitialize(255), 'InvalidInitialization', []);
});
});
});
describe('events', function () {
it('constructor initialization emits event', async function () {
const contract = await ConstructorInitializableMock.new();
await expectEvent.inTransaction(contract.transactionHash, contract, 'Initialized', { version: '1' });
});
it('initialization emits event', async function () {
const contract = await ReinitializerMock.new();
const { receipt } = await contract.initialize();
expect(receipt.logs.filter(({ event }) => event === 'Initialized').length).to.be.equal(1);
expectEvent(receipt, 'Initialized', { version: '1' });
});
it('reinitialization emits event', async function () {
const contract = await ReinitializerMock.new();
const { receipt } = await contract.reinitialize(128);
expect(receipt.logs.filter(({ event }) => event === 'Initialized').length).to.be.equal(1);
expectEvent(receipt, 'Initialized', { version: '128' });
});
it('chained reinitialization emits multiple events', async function () {
const contract = await ReinitializerMock.new();
const { receipt } = await contract.chainReinitialize(2, 3);
expect(receipt.logs.filter(({ event }) => event === 'Initialized').length).to.be.equal(2);
expectEvent(receipt, 'Initialized', { version: '2' });
expectEvent(receipt, 'Initialized', { version: '3' });
});
});
describe('complex testing with inheritance', function () {
const mother = '12';
const gramps = '56';
const father = '34';
const child = '78';
beforeEach('deploying', async function () {
this.contract = await SampleChild.new();
});
beforeEach('initializing', async function () {
await this.contract.initialize(mother, gramps, father, child);
});
it('initializes human', async function () {
expect(await this.contract.isHuman()).to.be.equal(true);
});
it('initializes mother', async function () {
expect(await this.contract.mother()).to.be.bignumber.equal(mother);
});
it('initializes gramps', async function () {
expect(await this.contract.gramps()).to.be.bignumber.equal(gramps);
});
it('initializes father', async function () {
expect(await this.contract.father()).to.be.bignumber.equal(father);
});
it('initializes child', async function () {
expect(await this.contract.child()).to.be.bignumber.equal(child);
});
});
describe('disabling initialization', function () {
it('old and new patterns in bad sequence', async function () {
await expectRevertCustomError(DisableBad1.new(), 'InvalidInitialization', []);
await expectRevertCustomError(DisableBad2.new(), 'InvalidInitialization', []);
});
it('old and new patterns in good sequence', async function () {
const ok = await DisableOk.new();
await expectEvent.inConstruction(ok, 'Initialized', { version: '1' });
await expectEvent.inConstruction(ok, 'Initialized', { version: MAX_UINT64 });
});
});
});

View File

@ -0,0 +1,131 @@
const { expectEvent } = require('@openzeppelin/test-helpers');
const { getAddressInSlot, ImplementationSlot } = require('../../helpers/erc1967');
const { expectRevertCustomError } = require('../../helpers/customError');
const ERC1967Proxy = artifacts.require('ERC1967Proxy');
const UUPSUpgradeableMock = artifacts.require('UUPSUpgradeableMock');
const UUPSUpgradeableUnsafeMock = artifacts.require('UUPSUpgradeableUnsafeMock');
const NonUpgradeableMock = artifacts.require('NonUpgradeableMock');
const UUPSUnsupportedProxiableUUID = artifacts.require('UUPSUnsupportedProxiableUUID');
const Clones = artifacts.require('$Clones');
contract('UUPSUpgradeable', function () {
before(async function () {
this.implInitial = await UUPSUpgradeableMock.new();
this.implUpgradeOk = await UUPSUpgradeableMock.new();
this.implUpgradeUnsafe = await UUPSUpgradeableUnsafeMock.new();
this.implUpgradeNonUUPS = await NonUpgradeableMock.new();
this.implUnsupportedUUID = await UUPSUnsupportedProxiableUUID.new();
// Used for testing non ERC1967 compliant proxies (clones are proxies that don't use the ERC1967 implementation slot)
this.cloneFactory = await Clones.new();
});
beforeEach(async function () {
const { address } = await ERC1967Proxy.new(this.implInitial.address, '0x');
this.instance = await UUPSUpgradeableMock.at(address);
});
it('has an interface version', async function () {
expect(await this.instance.UPGRADE_INTERFACE_VERSION()).to.equal('5.0.0');
});
it('upgrade to upgradeable implementation', async function () {
const { receipt } = await this.instance.upgradeToAndCall(this.implUpgradeOk.address, '0x');
expect(receipt.logs.filter(({ event }) => event === 'Upgraded').length).to.be.equal(1);
expectEvent(receipt, 'Upgraded', { implementation: this.implUpgradeOk.address });
expect(await getAddressInSlot(this.instance, ImplementationSlot)).to.be.equal(this.implUpgradeOk.address);
});
it('upgrade to upgradeable implementation with call', async function () {
expect(await this.instance.current()).to.be.bignumber.equal('0');
const { receipt } = await this.instance.upgradeToAndCall(
this.implUpgradeOk.address,
this.implUpgradeOk.contract.methods.increment().encodeABI(),
);
expect(receipt.logs.filter(({ event }) => event === 'Upgraded').length).to.be.equal(1);
expectEvent(receipt, 'Upgraded', { implementation: this.implUpgradeOk.address });
expect(await getAddressInSlot(this.instance, ImplementationSlot)).to.be.equal(this.implUpgradeOk.address);
expect(await this.instance.current()).to.be.bignumber.equal('1');
});
it('calling upgradeTo on the implementation reverts', async function () {
await expectRevertCustomError(
this.implInitial.upgradeToAndCall(this.implUpgradeOk.address, '0x'),
'UUPSUnauthorizedCallContext',
[],
);
});
it('calling upgradeToAndCall on the implementation reverts', async function () {
await expectRevertCustomError(
this.implInitial.upgradeToAndCall(
this.implUpgradeOk.address,
this.implUpgradeOk.contract.methods.increment().encodeABI(),
),
'UUPSUnauthorizedCallContext',
[],
);
});
it('calling upgradeTo from a contract that is not an ERC1967 proxy (with the right implementation) reverts', async function () {
const receipt = await this.cloneFactory.$clone(this.implUpgradeOk.address);
const instance = await UUPSUpgradeableMock.at(
receipt.logs.find(({ event }) => event === 'return$clone').args.instance,
);
await expectRevertCustomError(
instance.upgradeToAndCall(this.implUpgradeUnsafe.address, '0x'),
'UUPSUnauthorizedCallContext',
[],
);
});
it('calling upgradeToAndCall from a contract that is not an ERC1967 proxy (with the right implementation) reverts', async function () {
const receipt = await this.cloneFactory.$clone(this.implUpgradeOk.address);
const instance = await UUPSUpgradeableMock.at(
receipt.logs.find(({ event }) => event === 'return$clone').args.instance,
);
await expectRevertCustomError(
instance.upgradeToAndCall(this.implUpgradeUnsafe.address, '0x'),
'UUPSUnauthorizedCallContext',
[],
);
});
it('rejects upgrading to an unsupported UUID', async function () {
await expectRevertCustomError(
this.instance.upgradeToAndCall(this.implUnsupportedUUID.address, '0x'),
'UUPSUnsupportedProxiableUUID',
[web3.utils.keccak256('invalid UUID')],
);
});
it('upgrade to and unsafe upgradeable implementation', async function () {
const { receipt } = await this.instance.upgradeToAndCall(this.implUpgradeUnsafe.address, '0x');
expectEvent(receipt, 'Upgraded', { implementation: this.implUpgradeUnsafe.address });
expect(await getAddressInSlot(this.instance, ImplementationSlot)).to.be.equal(this.implUpgradeUnsafe.address);
});
// delegate to a non existing upgradeTo function causes a low level revert
it('reject upgrade to non uups implementation', async function () {
await expectRevertCustomError(
this.instance.upgradeToAndCall(this.implUpgradeNonUUPS.address, '0x'),
'ERC1967InvalidImplementation',
[this.implUpgradeNonUUPS.address],
);
});
it('reject proxy address as implementation', async function () {
const { address } = await ERC1967Proxy.new(this.implInitial.address, '0x');
const otherInstance = await UUPSUpgradeableMock.at(address);
await expectRevertCustomError(
this.instance.upgradeToAndCall(otherInstance.address, '0x'),
'ERC1967InvalidImplementation',
[otherInstance.address],
);
});
});