import {z} from 'zod' export type Chain = 'mainnet' | 'hoodi'; export type Block = number; export type BlockByNumber = {number: Block}; export type ChainView = 'latest' | 'finalized'; export type BlockByChainView = {view: ChainView}; export type BlockSelector = BlockByNumber | BlockByChainView; export type CreateApiApiV2EthereumBlockArgs = {body: {chain?: Chain | undefined, block: BlockSelector}}; export type CreateApiApiV2EthereumBlockOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const block = z.number().int().gte(0); export const timestamp = z.number().int().gte(0); export const slot = z.number().int().gte(0); export const consensusLayerBlockRoot = z.string(); export const epoch = z.number().int().gte(0); export const consensusLayerReference = z.object({slot: slot, block_root: consensusLayerBlockRoot.nullable().optional(), epoch: epoch}).nullable(); export const executionLayerBlockHash = z.string(); export const hash = z.string(); export const wei = z.string(); export const blockOverviewGas = z.object({used: z.number().int(), limit: z.number().int(), base_fee: wei.nullable().optional(), fees_burned: wei.nullable().optional()}); export const blockOverviewTransactionCount = z.object({normal: z.number().int(), blob: z.number().int().nullable().optional(), internal: z.number().int()}); export const blockOverviewTransaction = z.object({gas: blockOverviewGas, count: blockOverviewTransactionCount}); export const blockOverviewBlobGas = z.object({used: z.number().int(), excess: z.number().int()}); export const blockOverviewBlob = z.object({gas: blockOverviewBlobGas}).nullable(); export const executionLayerAddress = z.string(); export const executionLayerAddressDetails = z.object({address: executionLayerAddress, is_contract: z.boolean()}); export const blockOverviewMining = z.object({miner: executionLayerAddressDetails, difficulty: z.string(), mix_hash: hash, uncles_sha3: hash, uncles_count: z.number().int()}).nullable(); export const finalityParams = z.enum(["not_finalized", "finalized"]); export const blockOverviewData = z.object({block: block, timestamp: timestamp, consensus_reference: consensusLayerReference.optional(), hash: executionLayerBlockHash, parent_hash: executionLayerBlockHash, receipts_root: hash, state_root: hash, transaction: blockOverviewTransaction, blob: blockOverviewBlob.optional(), mining: blockOverviewMining.optional(), extra_data: z.string(), finality: finalityParams}); export const blockOverviewContainer = z.object({data: blockOverviewData}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Block * * POST /api/v2/ethereum/block */ export const createApiApiV2EthereumBlock = async (args: CreateApiApiV2EthereumBlockArgs, options?: CreateApiApiV2EthereumBlockOptions) => { const {baseUrl = "https://beaconcha.in", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set('authorization', `Bearer ${ApiKeyAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/ethereum/block${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(blockOverviewContainer, await res.json()) };