Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: read fee params from diamond proxy storage #44

Merged
merged 4 commits into from
Aug 12, 2024
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
64 changes: 50 additions & 14 deletions libs/metrics/src/l1/l1MetricsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
encodeFunctionData,
erc20Abi,
formatUnits,
Hex,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Oooh didn't know viem had this type. A little bit more semantically correct for some values than Address

parseEther,
parseUnits,
zeroAddress,
Expand All @@ -23,7 +24,7 @@ import {
sharedBridgeAbi,
stateTransitionManagerAbi,
} from "@zkchainhub/metrics/l1/abis";
import { AssetTvl, GasInfo } from "@zkchainhub/metrics/types";
import { AssetTvl, FeeParams, feeParamsFieldHexDigits, GasInfo } from "@zkchainhub/metrics/types";
import { IPricingService, PRICING_PROVIDER } from "@zkchainhub/pricing";
import { EvmProviderService } from "@zkchainhub/providers";
import { BatchesInfo, ChainId, Chains, ChainType, vitalikAddress } from "@zkchainhub/shared";
Expand All @@ -38,6 +39,7 @@ import { Token } from "@zkchainhub/shared/types";
import { isNativeToken } from "@zkchainhub/shared/utils";

const ONE_ETHER = parseEther("1");
const FEE_PARAMS_SLOT: Hex = `0x26`;

/**
* Acts as a wrapper around Viem library to provide methods to interact with an EVM-based blockchain.
Expand Down Expand Up @@ -370,20 +372,54 @@ export class L1MetricsService {
});
}

//TODO: Implement feeParams.
async feeParams(_chainId: ChainId): Promise<{
batchOverheadL1Gas: number;
maxPubdataPerBatch: number;
maxL2GasPerBatch: number;
priorityTxMaxPubdata: number;
minimalL2GasPrice: number;
}> {
/**
* Retrieves the fee parameters for a specific chain.
*
* @param chainId - The ID of the chain.
* @returns A Promise that resolves to a FeeParams object containing the fee parameters.
* @throws {L1MetricsServiceException} If the fee parameters cannot be retrieved from L1.
*/
async feeParams(chainId: ChainId): Promise<FeeParams> {
const diamondProxyAddress = await this.fetchDiamondProxyAddress(chainId);

// Read the storage at the target slot;
const feeParamsData = await this.evmProviderService.getStorageAt(
diamondProxyAddress,
FEE_PARAMS_SLOT,
);
if (!feeParamsData) {
throw new L1MetricsServiceException("Failed to get fee params from L1.");
}

const strippedParamsData = feeParamsData.replace(/^0x/, "");
let cursor = strippedParamsData.length;
const values: string[] = [];

//read fields from Right to Left
for (const digits of feeParamsFieldHexDigits) {
const hexValue = strippedParamsData.slice(cursor - digits, cursor);
assert(hexValue, "Error parsing fee params");
values.push(hexValue);
cursor -= digits;
}

const [
pubdataPricingMode,
batchOverheadL1Gas,
maxPubdataPerBatch,
maxL2GasPerBatch,
priorityTxMaxPubdata,
minimalL2GasPrice,
] = values as [string, string, string, string, string, string];

// Convert hex to decimal
return {
batchOverheadL1Gas: 50000,
maxPubdataPerBatch: 120000,
maxL2GasPerBatch: 10000000,
priorityTxMaxPubdata: 15000,
minimalL2GasPrice: 10000000,
pubdataPricingMode: parseInt(pubdataPricingMode, 16),
batchOverheadL1Gas: parseInt(batchOverheadL1Gas, 16),
maxPubdataPerBatch: parseInt(maxPubdataPerBatch, 16),
maxL2GasPerBatch: parseInt(maxL2GasPerBatch, 16),
priorityTxMaxPubdata: parseInt(priorityTxMaxPubdata, 16),
minimalL2GasPrice: BigInt(`0x${minimalL2GasPrice}`),
};
}
}
22 changes: 22 additions & 0 deletions libs/metrics/src/types/feeParams.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//See: https://github.com/matter-labs/era-contracts/blob/8a70bbbc48125f5bde6189b4e3c6a3ee79631678/l1-contracts/contracts/state-transition/chain-deps/ZkSyncHyperchainStorage.sol#L52
export type FeeParams = {
pubdataPricingMode: number;
batchOverheadL1Gas: number;
maxPubdataPerBatch: number;
maxL2GasPerBatch: number;
priorityTxMaxPubdata: number;
minimalL2GasPrice?: bigint;
};

// Define the lengths for each field (in hex digits, each byte is 2 hex digits)
/*
{
pubdataPricingMode: uint8 -> 1 byte -> 2 hex digits
batchOverheadL1Gas: uint32 -> 4 bytes -> 8 hex digits
maxPubdataPerBatch: uint32 -> 4 bytes -> 8 hex digits
maxL2GasPerBatch: uint32 -> 4 bytes -> 8 hex digits
priorityTxMaxPubdata: uint32 -> 4 bytes -> 8 hex digits
minimalL2GasPrice: uint64 -> 8 bytes -> 16 hex digits
}
*/
export const feeParamsFieldHexDigits = [2, 8, 8, 8, 8, 16] as const;
Comment on lines +1 to +22
Copy link
Collaborator

Choose a reason for hiding this comment

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

👍

1 change: 1 addition & 0 deletions libs/metrics/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./gasInfo.type";
export * from "./tvl.type";
export * from "./feeParams.type";
49 changes: 41 additions & 8 deletions libs/metrics/test/unit/l1/l1MetricsService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -859,15 +859,48 @@ describe("L1MetricsService", () => {
});

describe("feeParams", () => {
it("return feeParams", async () => {
const result = await l1MetricsService.feeParams(1n);
expect(result).toEqual({
batchOverheadL1Gas: 50000,
it("should retrieve the fee parameters for a specific chain", async () => {
// Mock the dependencies
const chainId = 324n; // this is ZKsyncEra chain id
const mockedDiamondProxyAddress = "0x1234567890123456789012345678901234567890";
const mockFeeParamsRawData =
"0x00000000000000000000000ee6b280000182b804c4b4000001d4c0000f424000";

const mockFeeParams = {
pubdataPricingMode: 0,
batchOverheadL1Gas: 1000000,
maxPubdataPerBatch: 120000,
maxL2GasPerBatch: 10000000,
priorityTxMaxPubdata: 15000,
minimalL2GasPrice: 10000000,
});
maxL2GasPerBatch: 80000000,
priorityTxMaxPubdata: 99000,
minimalL2GasPrice: 250000000n,
};

l1MetricsService["diamondContracts"].set(chainId, mockedDiamondProxyAddress);
jest.spyOn(mockEvmProviderService, "getStorageAt").mockResolvedValue(
mockFeeParamsRawData,
);

const result = await l1MetricsService.feeParams(chainId);

expect(mockEvmProviderService.getStorageAt).toHaveBeenCalledWith(
mockedDiamondProxyAddress,
`0x26`,
);

expect(result).toEqual(mockFeeParams);
});

it("should throw an exception if the fee parameters cannot be retrieved from L1", async () => {
// Mock the dependencies
const chainId = 324n; // this is ZKsyncEra chain id
const mockedDiamondProxyAddress = "0x1234567890123456789012345678901234567890";
l1MetricsService["diamondContracts"].set(chainId, mockedDiamondProxyAddress);

jest.spyOn(mockEvmProviderService, "getStorageAt").mockResolvedValue(undefined);

await expect(l1MetricsService.feeParams(chainId)).rejects.toThrow(
L1MetricsServiceException,
);
});
});
});
6 changes: 3 additions & 3 deletions libs/providers/src/providers/evmProvider.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,16 @@ export class EvmProviderService {
* @returns {Promise<Hex>} A Promise that resolves to the value of the storage slot.
* @throws {InvalidArgumentException} If the slot is not a positive integer.
*/
async getStorageAt(address: Address, slot: number): Promise<Hex | undefined> {
if (slot <= 0 || !Number.isInteger(slot)) {
async getStorageAt(address: Address, slot: number | Hex): Promise<Hex | undefined> {
if (typeof slot === "number" && (slot <= 0 || !Number.isInteger(slot))) {
throw new InvalidArgumentException(
`Slot must be a positive integer number. Received: ${slot}`,
);
}

return this.client.getStorageAt({
address,
slot: toHex(slot),
slot: typeof slot === "string" ? slot : toHex(slot),
});
}

Expand Down
12 changes: 12 additions & 0 deletions libs/providers/test/unit/providers/evmProvider.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,18 @@ describe("EvmProviderService", () => {
expect(mockClient.getStorageAt).toHaveBeenCalledWith({ address, slot: "0x1" });
});

it("should return the value of the storage slot at the given address and slot value", async () => {
const address = "0x123456789";
const slot = "0x12";
const expectedValue = "0xabcdef";
jest.spyOn(mockClient, "getStorageAt").mockResolvedValue(expectedValue);

const value = await viemProvider.getStorageAt(address, slot);

expect(value).toBe(expectedValue);
expect(mockClient.getStorageAt).toHaveBeenCalledWith({ address, slot: "0x12" });
});

it("should throw an error if the slot is not a positive integer", async () => {
const address = "0x123456789";
const slot = -1;
Expand Down