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: chain type #42

Merged
merged 6 commits into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
3 changes: 3 additions & 0 deletions libs/metrics/src/exceptions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from "./invalidChainId.exception";
export * from "./l1MetricsService.exception";
export * from "./invalidChainType.exception";
6 changes: 6 additions & 0 deletions libs/metrics/src/exceptions/invalidChainId.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export class InvalidChainId extends Error {
constructor(message: string) {
super(message);
this.name = "InvalidChainId";
}
}
11 changes: 11 additions & 0 deletions libs/metrics/src/exceptions/invalidChainType.exception.ts
Copy link
Collaborator

Choose a reason for hiding this comment

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

💯

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Chains } from "@zkchainhub/shared";

export class InvalidChainType extends Error {
constructor(index: number) {
super(`Current supported types are [${Chains.join(
", ",
)}], but received index ${index}. Verify if supported chains are consistent with https://github.com/matter-labs/era-contracts/blob/8a70bbbc48125f5bde6189b4e3c6a3ee79631678/l1-contracts/contracts/state-transition/chain-deps/ZkSyncHyperchainStorage.sol#L39
`);
this.name = "InvalidChainType";
}
}
6 changes: 6 additions & 0 deletions libs/metrics/src/exceptions/l1MetricsService.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export class L1MetricsServiceException extends Error {
constructor(message: string) {
super(message);
this.name = "L1MetricsServiceException";
}
}
13 changes: 0 additions & 13 deletions libs/metrics/src/exceptions/provider.exception.ts

This file was deleted.

117 changes: 93 additions & 24 deletions libs/metrics/src/l1/l1MetricsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,24 @@ import {
zeroAddress,
} from "viem";

import { L1ProviderException } from "@zkchainhub/metrics/exceptions/provider.exception";
import { bridgeHubAbi, sharedBridgeAbi } from "@zkchainhub/metrics/l1/abis";
import {
InvalidChainId,
InvalidChainType,
L1MetricsServiceException,
} from "@zkchainhub/metrics/exceptions";
import { bridgeHubAbi, diamondProxyAbi, sharedBridgeAbi } from "@zkchainhub/metrics/l1/abis";
import { AssetTvl, GasInfo } from "@zkchainhub/metrics/types";
import { IPricingService, PRICING_PROVIDER } from "@zkchainhub/pricing";
import { EvmProviderService } from "@zkchainhub/providers";
import { AbiWithAddress, ChainId, L1_CONTRACTS, vitalikAddress } from "@zkchainhub/shared";
import { ETH_TOKEN_ADDRESS } from "@zkchainhub/shared/constants/addresses";
import {
BatchesInfo,
ChainId,
Chains,
ChainType,
L1_CONTRACTS,
vitalikAddress,
} from "@zkchainhub/shared";
import { ETH_TOKEN_ADDRESS } from "@zkchainhub/shared/constants";
import {
erc20Tokens,
isNativeToken,
Expand All @@ -34,15 +45,15 @@ const ONE_ETHER = parseEther("1");
*/
@Injectable()
export class L1MetricsService {
private readonly bridgeHub: Readonly<AbiWithAddress> = {
private readonly bridgeHub = {
abi: bridgeHubAbi,
address: L1_CONTRACTS.BRIDGE_HUB,
};
private readonly sharedBridge: Readonly<AbiWithAddress> = {
private readonly sharedBridge = {
abi: sharedBridgeAbi,
address: L1_CONTRACTS.SHARED_BRIDGE,
};
private readonly diamondContracts: Map<ChainId, AbiWithAddress> = new Map();
private readonly diamondContracts: Map<ChainId, Address> = new Map();

constructor(
private readonly evmProviderService: EvmProviderService,
Expand Down Expand Up @@ -143,18 +154,44 @@ export class L1MetricsService {
return { ethBalance: ethBalance, addressesBalance: balances };
}

//TODO: Implement getBatchesInfo.
async getBatchesInfo(
_chainId: number,
): Promise<{ commited: number; verified: number; proved: number }> {
return { commited: 100, verified: 100, proved: 100 };
/**
* Retrieves the information about the batches from L2 chain
* @param chainId - The chain id for which to get the batches info
* @returns commits, verified and executed batches
*/
async getBatchesInfo(chainId: bigint): Promise<BatchesInfo> {
const diamondProxyAddress = await this.fetchDiamondProxyAddress(chainId);
const [commited, verified, executed] = await this.evmProviderService.multicall({
contracts: [
{
address: diamondProxyAddress,
abi: diamondProxyAbi,
functionName: "getTotalBatchesCommitted",
args: [],
} as const,
{
address: diamondProxyAddress,
abi: diamondProxyAbi,
functionName: "getTotalBatchesVerified",
args: [],
} as const,
{
address: diamondProxyAddress,
abi: diamondProxyAbi,
functionName: "getTotalBatchesExecuted",
args: [],
} as const,
],
allowFailure: false,
});
return { commited, verified, executed };
}

/**
* Retrieves the Total Value Locked for {chainId} by L1 token
* @returns A Promise that resolves to an array of AssetTvl objects representing the TVL for each asset.
*/
async tvl(chainId: number): Promise<AssetTvl[]> {
async tvl(chainId: ChainId): Promise<AssetTvl[]> {
const erc20Addresses = erc20Tokens.map((token) => token.contractAddress);

const balances = await this.fetchTokenBalancesByChain(chainId, erc20Addresses);
Expand All @@ -173,23 +210,22 @@ export class L1MetricsService {
* @param addresses - An array of addresses for which to fetch the token balances.
* @returns A promise that resolves to an object containing the ETH balance and an array of address balances.
*/
private async fetchTokenBalancesByChain(chainId: number, addresses: Address[]) {
const chainIdBn = BigInt(chainId);
private async fetchTokenBalancesByChain(chainId: ChainId, addresses: Address[]) {
const balances = await this.evmProviderService.multicall({
contracts: [
...addresses.map((tokenAddress) => {
return {
address: this.sharedBridge.address,
abi: sharedBridgeAbi,
abi: this.sharedBridge.abi,
functionName: "chainBalance",
args: [chainIdBn, tokenAddress],
args: [chainId, tokenAddress],
} as const;
}),
{
address: this.sharedBridge.address,
abi: sharedBridgeAbi,
abi: this.sharedBridge.abi,
functionName: "chainBalance",
args: [chainIdBn, ETH_TOKEN_ADDRESS],
args: [chainId, ETH_TOKEN_ADDRESS],
} as const,
],
allowFailure: false,
Expand All @@ -198,9 +234,42 @@ export class L1MetricsService {
return { ethBalance: balances[addresses.length]!, addressesBalance: balances.slice(0, -1) };
}

//TODO: Implement chainType.
async chainType(_chainId: number): Promise<"validium" | "rollup"> {
return "rollup";
async chainType(chainId: ChainId): Promise<ChainType> {
const diamondProxyAddress = await this.fetchDiamondProxyAddress(chainId);
const chainTypeIndex = await this.evmProviderService.readContract(
diamondProxyAddress,
diamondProxyAbi,
"getPubdataPricingMode",
[],
);
const chainType = Chains[chainTypeIndex];
if (!chainType) {
throw new InvalidChainType(chainTypeIndex);
}
return chainType;
}

/**
* Fetches the diamond proxy address for the given chain id and caches it for future use.
* @param chainId - The chain id for which to fetch the diamond proxy address.
* @returns Diamond proxy address.
*/
private async fetchDiamondProxyAddress(chainId: ChainId): Promise<Address> {
let diamondProxyAddress: Address | undefined = this.diamondContracts.get(chainId);

if (!diamondProxyAddress) {
diamondProxyAddress = await this.evmProviderService.readContract(
this.bridgeHub.address,
this.bridgeHub.abi,
"getHyperchain",
[chainId],
);
if (diamondProxyAddress == zeroAddress) {
throw new InvalidChainId(`Chain ID ${chainId} doesn't exist on the ecosystem`);
}
this.diamondContracts.set(chainId, diamondProxyAddress);
}
return diamondProxyAddress;
}

/**
Expand Down Expand Up @@ -251,12 +320,12 @@ export class L1MetricsService {
if (isNativeError(e)) {
this.logger.error(`Failed to get gas information: ${e.message}`);
}
throw new L1ProviderException("Failed to get gas information from L1.");
throw new L1MetricsServiceException("Failed to get gas information from L1.");
}
}

//TODO: Implement feeParams.
async feeParams(_chainId: number): Promise<{
async feeParams(_chainId: ChainId): Promise<{
batchOverheadL1Gas: number;
maxPubdataPerBatch: number;
maxL2GasPerBatch: number;
Expand Down
Loading