Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/bright-blocks-validate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@perfect-abstractions/compose-cli": minor
---

Validate deployed diamond facet bytecode against the source-derived virtual storage layout.
1 change: 1 addition & 0 deletions cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@inquirer/select": "5.2.1",
"@perfect-abstractions/compose": "0.0.6",
"commander": "^13.1.0",
"compose-bytecode-validator": "0.1.2",
"dotenv": "^16.4.7",
"fs-extra": "^11.3.3",
"picocolors": "^1.1.1",
Expand Down
54 changes: 54 additions & 0 deletions cli/src/adapters/IBytecodeValidatorAdapter/adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { validateStorage } from "compose-bytecode-validator";
import type {
BytecodeValidationInput,
BytecodeValidationReport,
BytecodeStorageLocation,
IBytecodeValidatorAdapter,
} from "./interface";

const PLAIN_BYTE_ARRAY = /Plain\(\[([\d,\s]+)\]\)/g;

export function formatSymbolicStoragePath(path: string): string {
return path.replace(PLAIN_BYTE_ARRAY, (match, values: string) => {
const bytes = values.split(",").map((value) => Number(value.trim()));
if (bytes.length !== 32 || bytes.some((byte) => !Number.isInteger(byte) || byte < 0 || byte > 255)) {
return match;
}
return `Plain(0x${bytes.map((byte) => byte.toString(16).padStart(2, "0")).join("")})`;
});
}

function normalizeLocation(location: BytecodeStorageLocation): BytecodeStorageLocation {
return {
...location,
symbolicPath: formatSymbolicStoragePath(location.symbolicPath),
};
}

function normalizeReport(report: BytecodeValidationReport): BytecodeValidationReport {
return {
collisions: report.collisions.map((collision) => ({
...collision,
location: normalizeLocation(collision.location),
})),
validatedVariables: report.validatedVariables.map((variable) => ({
...variable,
location: normalizeLocation(variable.location),
})),
uncertainScopes: report.uncertainScopes.map((scope) => ({
...scope,
location: normalizeLocation(scope.location),
})),
diagnostics: report.diagnostics.map((diagnostic) => ({
...diagnostic,
symbolicPath: formatSymbolicStoragePath(diagnostic.symbolicPath),
})),
delegatecallWarnings: report.delegatecallWarnings,
};
}

export const BytecodeValidatorAdapter: IBytecodeValidatorAdapter = {
validate(input: BytecodeValidationInput): BytecodeValidationReport {
return normalizeReport(validateStorage(input) as BytecodeValidationReport);
},
};
82 changes: 82 additions & 0 deletions cli/src/adapters/IBytecodeValidatorAdapter/interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import type { Hex } from "viem";

export type BytecodeStorageLocation = {
slot: string;
offset: number;
selector: string;
pc?: number;
symbolicPath: string;
};

export type BytecodeStorageCollision = {
location: BytecodeStorageLocation;
virtualPath: string;
sourceNames?: string[];
expectedType: string;
observedType: string;
reason: string;
};

export type BytecodeValidatedVariable = {
location: BytecodeStorageLocation;
virtualPath: string;
sourceNames?: string[];
expectedType: string;
observedType: string;
};

export type BytecodeUncertainScope = {
location: BytecodeStorageLocation;
virtualPath?: string;
sourceNames?: string[];
reason: string;
};

export type BytecodeStorageDiagnostic = {
selector: string;
pc?: number;
symbolicPath: string;
message: string;
};

export type BytecodeDelegateCallWarning = {
callerSelector: string;
pc: number;
target: string;
selector?: string;
reason: string;
};

export type BytecodeValidationReport = {
collisions: BytecodeStorageCollision[];
validatedVariables: BytecodeValidatedVariable[];
uncertainScopes: BytecodeUncertainScope[];
diagnostics: BytecodeStorageDiagnostic[];
delegatecallWarnings: BytecodeDelegateCallWarning[];
};

export type BytecodeVirtualStorageRecord = {
id: string;
virtualPath: string;
parentVirtualPath?: string;
kind: "normal" | "immutable";
codeWidth: number;
layout: string[];
serializedLayout: string[];
slots: number[][];
source: "erc8042" | "erc7201" | "slot-assignment" | "implicit-state";
sourceName: string;
contractName: string;
structName?: string;
diamondName?: string;
};

export type BytecodeValidationInput = {
bytecode: Hex;
virtualStorageLayout: { records: BytecodeVirtualStorageRecord[] };
};

/** Stable CLI boundary around the external WASM validator package. */
export interface IBytecodeValidatorAdapter {
validate(input: BytecodeValidationInput): BytecodeValidationReport;
}
3 changes: 3 additions & 0 deletions cli/src/adapters/IBytecodeValidatorAdapter/package.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
declare module "compose-bytecode-validator" {
export function validateStorage(input: unknown): unknown;
}
15 changes: 12 additions & 3 deletions cli/src/adapters/IRPCAdapter/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,17 @@ export async function createRPCAdapter(options: RPCAdapterOptions): Promise<IRPC
* @returns Deployed bytecode, or `undefined` when no bytecode exists.
* @throws {RPCAdapterError} If the RPC request fails.
*/
async function getCode(address: Address): Promise<Hex | undefined> {
async function getBlockNumber(): Promise<bigint> {
try {
return await retryRPC(() => client.getCode({ address }));
return await retryRPC(() => client.getBlockNumber());
} catch (error) {
throw requestError("getBlockNumber", options.chainId, error);
}
}

async function getCode(address: Address, blockNumber?: bigint): Promise<Hex | undefined> {
try {
return await retryRPC(() => client.getCode({ address, blockNumber }));
} catch (error) {
throw requestError("getCode", options.chainId, error);
}
Expand All @@ -89,7 +97,7 @@ export async function createRPCAdapter(options: RPCAdapterOptions): Promise<IRPC
chainId: options.chainId,
});
}
const code = await getCode(getAddress(parameters.address));
const code = await getCode(getAddress(parameters.address), parameters.blockNumber);
if (!code || code === "0x") {
throw new RPCAdapterError("RPC_CONTRACT_NOT_FOUND", `No contract code found at ${parameters.address}`, {
operation: "readContract",
Expand All @@ -105,6 +113,7 @@ export async function createRPCAdapter(options: RPCAdapterOptions): Promise<IRPC
}

return {
getBlockNumber,
readContract,
getCode,
};
Expand Down
5 changes: 4 additions & 1 deletion cli/src/adapters/IRPCAdapter/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@ export type RPCReadContractOptions = {

/** Generic read-only RPC boundary used by CLI modules. */
export interface IRPCAdapter {
/** Return the current block number so related reads can be pinned consistently. */
getBlockNumber(): Promise<bigint>;

/** Read a view or pure contract function and return its decoded value. */
readContract<T>(
parameters: ReadContractParameters<Abi>,
options?: RPCReadContractOptions,
): Promise<T>;

/** Return deployed bytecode, or undefined when the account has no code. */
getCode(address: Address): Promise<Hex | undefined>;
getCode(address: Address, blockNumber?: bigint): Promise<Hex | undefined>;
}
2 changes: 1 addition & 1 deletion cli/src/comander.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function buildProgram(): Command {

program
.command("inspect")
.description("Inspect a deployed diamond's facets and selectors via Loupe")
.description("Inspect a deployed diamond's facets and selectors")
.argument("<address>", "Diamond contract address")
.option("--chain <chain-key>", "Chain key from compose.json", "local")

Expand Down
Loading
Loading