import {z} from 'zod' export type Chain = 'mainnet' | 'hoodi'; export type Slot = number; export type SlotByNumber = {number: Slot}; export type ConsensusLayerBlockRoot = string; export type SlotByConsensusLayerBlockRoot = {root: ConsensusLayerBlockRoot}; export type ChainView = 'latest' | 'finalized'; export type SlotByChainView = {view: ChainView}; export type SlotSelector = SlotByNumber | SlotByConsensusLayerBlockRoot | SlotByChainView; export type CreateApiApiV2EthereumSlotArgs = {body: {chain?: Chain | undefined, slot: SlotSelector}}; export type CreateApiApiV2EthereumSlotOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const slot = z.number().int().gte(0); export const epoch = z.number().int().gte(0); export const timestamp = z.number().int().gte(0); export const block = z.number().int().gte(0); export const executionLayerBlockHash = z.string(); export const executionLayerReference = z.object({block: block, hash: executionLayerBlockHash}); export const validatorIndex = z.number().int().gte(0); export const validatorPublicKey = z.string(); export const validator = z.object({index: validatorIndex.nullable().optional(), public_key: validatorPublicKey.optional()}); export const proposalDutyStatus = z.enum(["success", "missed", "orphaned", "scheduled"]); export const consensusLayerBlockRoot = z.string(); export const hash = z.string(); export const graffiti = z.string().nullable(); export const bLSSignature = z.string(); export const syncCommitteePeriod = z.number().int().gte(0); export const validatorSyncCommitteeDutyParticipation = z.object({successful: z.number().int().gte(0), assigned: z.number().int().gte(0), missed: z.number().int().gte(0), missed_including_missed_slots: z.number().int().gte(0), scheduled: z.number().int().gte(0)}); export const validatorAttestationDutyParticipation = z.object({successful: z.number().int().gte(0), assigned: z.number().int().gte(0), missed: z.number().int().gte(0)}); export const wei = z.string(); export const clEventDetails = z.object({count: z.number().int().gte(0), amount: wei}); export const queueEventsQueued = z.object({deposit: clEventDetails, withdrawal_manual: clEventDetails, consolidation: clEventDetails}); export const queueEventsProcessed = z.object({deposit: clEventDetails, withdrawal_sweep: clEventDetails, withdrawal_manual: clEventDetails, consolidation: clEventDetails, voluntary_exit_count: z.number().int().gte(0)}); export const queueEvents = z.object({queued: queueEventsQueued, processed: queueEventsProcessed}).nullable(); export const includedSlashingCounts = z.object({proposer: validatorIndex.optional(), attestation: validatorIndex.optional()}).nullable(); export const finalityParams = z.enum(["not_finalized", "finalized"]); export const slotOverviewData = z.object({slot: slot, epoch: epoch, timestamp: timestamp, execution_reference: executionLayerReference.nullable().optional(), proposer: validator.nullable().optional(), status: proposalDutyStatus, block_root: consensusLayerBlockRoot.nullable().optional(), parent_root: consensusLayerBlockRoot.nullable().optional(), state_root: hash.nullable().optional(), graffiti: graffiti.optional(), randao_reveal: bLSSignature.nullable().optional(), signature: bLSSignature.nullable().optional(), sync_committee_period: syncCommitteePeriod.nullable(), sync_participation: validatorSyncCommitteeDutyParticipation.nullable().optional(), attestation_participation: validatorAttestationDutyParticipation.nullable().optional(), queue_events: queueEvents.optional(), bls_credential_changes_count: z.number().int().nullable().optional(), included_slashing_count: includedSlashingCounts.optional(), included_blob_commitment_count: z.number().int().nullable().optional(), finality: finalityParams.optional()}); export const slotOverviewContainer = z.object({data: slotOverviewData}); 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 }; /** * Slot * * POST /api/v2/ethereum/slot */ export const createApiApiV2EthereumSlot = async (args: CreateApiApiV2EthereumSlotArgs, options?: CreateApiApiV2EthereumSlotOptions) => { 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/slot${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(slotOverviewContainer, await res.json()) };