Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## vNEXT

- Migrate proxy to Diamond pattern (ERC-2535):
- Add Diamond contract unit tests (#224)
- Fix `fallback` and `receive` (#223)
- Migrate contracts (#222)
- Add Github Action CI in order to publish NPM package
Expand Down
7 changes: 5 additions & 2 deletions contracts/Diamond.sol
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2025 IEXEC BLOCKCHAIN TECH <contact@iex.ec>
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

//*************************************************************************************\
Expand All @@ -8,8 +10,9 @@ pragma solidity ^0.8.0;
//* Implementation of a diamond.
//*************************************************************************************/

// Diamond proxy implementation adapted from Mudgen's to re-direct
// Diamond proxy implementation adapted from Mudgen's to redirect
// `receive` and `fallback` calls to the implementations in facets.
// See diff at: https://github.com/iExecBlockchainComputing/PoCo/pull/223/commits/0562f982

import { LibDiamond } from "@mudgen/diamond-1/contracts/libraries/LibDiamond.sol";
import { IDiamondCut } from "@mudgen/diamond-1/contracts/interfaces/IDiamondCut.sol";
Expand Down
43 changes: 0 additions & 43 deletions contracts/tools/Migrations.sol

This file was deleted.

15 changes: 5 additions & 10 deletions deploy/0_deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { FactoryDeployer } from '../utils/FactoryDeployer';
import config from '../utils/config';
import { getFunctionSelectors, linkContractToProxy } from '../utils/proxy-tools';
import { DiamondArgsStruct } from '../typechain/@mudgen/diamond-1/contracts/Diamond';
import { getLibDiamondConfigOrEmpty } from '../utils/tools';

let factoryDeployer: FactoryDeployer;

Expand Down Expand Up @@ -72,7 +73,7 @@ export default async function deploy() {
throw new Error('Failed to prepare transferOwnership data');
});
const erc1538ProxyAddress = await deployDiamondProxyWithDefaultFacets(
owner.address,
owner,
// transferOwnershipCall, //TODO
);
const erc1538 = DiamondCutFacet__factory.connect(erc1538ProxyAddress, owner);
Expand Down Expand Up @@ -248,18 +249,12 @@ async function getOrDeployRlc(token: string, owner: SignerWithAddress) {
* @returns The address of the deployed Diamond proxy contract.
*/
async function deployDiamondProxyWithDefaultFacets(
ownerAddress: string,
owner: SignerWithAddress,
// transferOwnershipCall: string, // TODO
): Promise<string> {
const initAddress = await factoryDeployer.deployContract(new DiamondInit__factory());
const initCalldata = DiamondInit__factory.createInterface().encodeFunctionData('init');
// Deploy LibDiamond and link it to fix coverage task issue.
const libDiamondAddress =
(hre as any).__SOLIDITY_COVERAGE_RUNNING &&
(await factoryDeployer.deployContract(new LibDiamond__factory()));
const libDiamondConfig = (hre as any).__SOLIDITY_COVERAGE_RUNNING && {
['@mudgen/diamond-1/contracts/libraries/LibDiamond.sol:LibDiamond']: libDiamondAddress,
};
const libDiamondConfig = await getLibDiamondConfigOrEmpty(owner);
// Deploy required proxy facets.
const facetFactories = [
new DiamondCutFacet__factory(libDiamondConfig),
Expand All @@ -278,7 +273,7 @@ async function deployDiamondProxyWithDefaultFacets(
}
// Set diamond constructor arguments
const diamondArgs: DiamondArgsStruct = {
owner: ownerAddress,
owner: owner.address,
init: initAddress,
initCalldata: initCalldata,
};
Expand Down
96 changes: 96 additions & 0 deletions test/byContract/Diamond.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// SPDX-FileCopyrightText: 2025 IEXEC BLOCKCHAIN TECH <contact@iex.ec>
// SPDX-License-Identifier: Apache-2.0

import { SignerWithAddress } from '@nomicfoundation/hardhat-ethers/signers';
import { getStorageAt } from '@nomicfoundation/hardhat-network-helpers';
import { expect } from 'chai';
import { ZeroAddress } from 'ethers';
import { ethers } from 'hardhat';
import { FacetCutAction } from 'hardhat-deploy/dist/types';
import { Diamond__factory, DiamondLoupeFacet__factory, IDiamond } from '../../typechain';
import { DiamondArgsStruct } from '../../typechain/contracts/Diamond';
import { getFunctionSelectors } from '../../utils/proxy-tools';
import { getLibDiamondConfigOrEmpty } from '../../utils/tools';

const DIAMOND_STORAGE_POSITION = ethers.id('diamond.standard.diamond.storage');

describe('Diamond', async () => {
let deployer: SignerWithAddress;
let owner: SignerWithAddress;

beforeEach('Deploy', async () => {
[deployer, owner] = await ethers.getSigners();
});

describe('Deployment', () => {
it('Should set owner at deployment', async () => {
const diamond = await _deployDiamond([]); // No facets
const diamondAddress = await diamond.getAddress();
// Check the owner.
const ownerSlotPosition = ethers.toBeHex(BigInt(DIAMOND_STORAGE_POSITION) + 3n);
const actualOwnerAddress = await getStorageAt(diamondAddress, ownerSlotPosition);
const expectedOwnerAddress = ethers.zeroPadValue(owner.address, 32); // Padded to 32 bytes.
expect(actualOwnerAddress).to.equal(expectedOwnerAddress);
// Check `DiamondCut` event with empty facet cuts.
await expect(diamond.deploymentTransaction())
.to.emit(diamond, 'DiamondCut')
.withArgs([], ZeroAddress, '0x');
});

it('Should apply diamond cuts at deployment', async () => {
// Deploy any facet.
const facet = await new DiamondLoupeFacet__factory()
.connect(deployer)
.deploy()
.then((tx) => tx.waitForDeployment());
const facetCuts = [
{
facetAddress: await facet.getAddress(),
action: FacetCutAction.Add,
functionSelectors: getFunctionSelectors(new DiamondLoupeFacet__factory()),
},
];
const diamond = await _deployDiamond(facetCuts);
await expect(diamond.deploymentTransaction())
.to.emit(diamond, 'DiamondCut')
.withArgs(
[Object.values(facetCuts[0])], // Convert object to array for deep comparison.
ZeroAddress,
'0x',
);
});
});

describe('Delegatecall', () => {
it.skip('[TODO] Should delegate `fallback` call', async () => {});

it.skip('[TODO] Should delegate `receive` call', async () => {});

it.skip('[TODO] Should delegate any function call', async () => {});

it('Should revert when function not found', async () => {
const diamond = await _deployDiamond([]);
const randomData = ethers.id('0xrandom');
const tx = owner.sendTransaction({
to: await diamond.getAddress(),
value: 0,
data: randomData,
});
await expect(tx)
.to.be.revertedWithCustomError(diamond, 'FunctionNotFound')
.withArgs(randomData.slice(0, 10)); // First 4 bytes.
});
});

async function _deployDiamond(facetCuts: IDiamond.FacetCutStruct[]) {
const libDiamondConfig = await getLibDiamondConfigOrEmpty(deployer);
return await new Diamond__factory(libDiamondConfig)
.connect(deployer)
.deploy(facetCuts, {
owner: owner.address,
init: ZeroAddress,
initCalldata: '0x',
} as DiamondArgsStruct)
.then((tx) => tx.waitForDeployment());
}
});
28 changes: 27 additions & 1 deletion utils/tools.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
// SPDX-FileCopyrightText: 2020-2025 IEXEC BLOCKCHAIN TECH <contact@iex.ec>
// SPDX-License-Identifier: Apache-2.0

import { SignerWithAddress } from '@nomicfoundation/hardhat-ethers/signers';
import { Signature } from 'ethers';
import { ethers } from 'hardhat';
import hre, { ethers } from 'hardhat';
import { LibDiamond__factory } from '../typechain';

export function compactSignature(signature: string): string {
return Signature.from(signature).compactSerialized;
Expand All @@ -19,3 +21,27 @@ export function minBigInt(a: bigint, b: bigint) {
export function maxBigInt(a: bigint, b: bigint) {
return a > b ? a : b;
}

/**
* Deploys the `LibDiamond` library if running coverage task and returns
* the linking configuration. Returns an empty config if not running coverage
* task.
* This fixes an issue with the coverage task that requires the library to be
* deployed and linked to contracts where it is used.
* @param deployer Signer to deploy the library.
* @returns The library configuration or an empty object.
*/
export async function getLibDiamondConfigOrEmpty(deployer: SignerWithAddress): Promise<any> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it possible to type the promise output ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It generates a typing error so I use the generic type any.

// No need to deploy the library if not running coverage task.
if (!(hre as any).__SOLIDITY_COVERAGE_RUNNING) {
return {};
}
const libDiamondAddress = await new LibDiamond__factory()
.connect(deployer)
.deploy()
.then((contract) => contract.waitForDeployment())
.then((contract) => contract.getAddress());
return {
['@mudgen/diamond-1/contracts/libraries/LibDiamond.sol:LibDiamond']: libDiamondAddress,
};
}