import {z} from 'zod' export type Chain = 'mainnet' | 'hoodi'; export type ValidatorIndex = number; export type ValidatorPublicKey = string; export type ValidatorIndexPublicKey = ValidatorIndex | ValidatorPublicKey; export type ValidatorIndexPublicKeys = Array; export type ValidatorsByIdentifiers = {validator_identifiers: ValidatorIndexPublicKeys}; export type DashboardID = number; export type DashboardGroupID = number | null; export type ValidatorsByDashboard = {dashboard_id: DashboardID, group_id?: DashboardGroupID | undefined}; export type ExecutionLayerAddress = string; export type ValidatorsByDeposit = {deposit_address: ExecutionLayerAddress}; export type AddressOrCredential = string; export type ValidatorsByWithdrawal = {withdrawal: AddressOrCredential}; export type ValidatorsByEntity = {entity: string, sub_entity?: string | undefined}; export type ValidatorsSelector = ValidatorsByIdentifiers | ValidatorsByDashboard | ValidatorsByDeposit | ValidatorsByWithdrawal | ValidatorsByEntity; export type EvaluationWindow = '24h' | '7d' | '30d' | '90d' | 'all_time'; export type TimeRangeSelectorWithWindow = {evaluation_window: EvaluationWindow}; export type ValidatorChainEvaluationWindow = {chain?: Chain | undefined, validator: ValidatorsSelector, range: TimeRangeSelectorWithWindow}; export type CreateApiApiV2EthereumValidatorsApyRoiArgs = {body: ValidatorChainEvaluationWindow}; export type CreateApiApiV2EthereumValidatorsApyRoiOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const roiApyMetricsRoi = z.object({total: z.number(), missed: z.number().lte(0)}); export const roiApyMetricsApy = z.object({total: z.number(), missed: z.number().lte(0)}); export const roiApyMetrics = z.object({roi: roiApyMetricsRoi, apy: roiApyMetricsApy}); export const finalityParamsOnlyFinalized = z.literal("finalized"); export const validatorApyRoiData = z.object({execution_layer: roiApyMetrics, consensus_layer: roiApyMetrics, combined: roiApyMetrics, finality: finalityParamsOnlyFinalized}); export const slot = z.number().int().gte(0); export const slotRange = z.object({start: slot, end: slot}); export const epoch = z.number().int().gte(0); export const epochRange = z.object({start: epoch, end: epoch}); export const timestamp = z.number().int().gte(0); export const timeRange = z.object({start: timestamp, end: timestamp}); export const resultRange = z.object({slot: slotRange, epoch: epochRange, timestamp: timeRange}); export const validatorApyRoiContainer = z.object({data: validatorApyRoiData, range: resultRange}); 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 }; /** * APY & ROI * * POST /api/v2/ethereum/validators/apy-roi */ export const createApiApiV2EthereumValidatorsApyRoi = async (args: CreateApiApiV2EthereumValidatorsApyRoiArgs, options?: CreateApiApiV2EthereumValidatorsApyRoiOptions) => { 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/validators/apy-roi${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(validatorApyRoiContainer, await res.json()) };