import {z} from 'zod' export type GetApiV1ChainNameBlockV2BlockHeightArgs = {chainName: string, blockHeight: string}; export type GetApiV1ChainNameBlockV2BlockHeightOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiV1ChainNameBlockV2BlockHeightResponse = z.object({updated_at: z.string().optional(), chain_id: z.number().int().optional(), chain_name: z.string().optional(), items: z.array(z.object({block_hash: z.string().optional(), signed_at: z.string().optional(), height: z.number().int().optional(), block_parent_hash: z.string().optional(), extra_data: z.string().optional(), miner_address: z.string().optional(), mining_cost: z.number().int().optional(), gas_used: z.number().int().optional(), gas_limit: z.number().int().optional(), transactions_link: z.string().optional()})).optional()}); 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 }; /** * Fetches a single block, for example to render it in a block explorer. * * GET /v1/{chainName}/block_v2/{blockHeight}/ */ export const getApiV1ChainNameBlockV2BlockHeight = async (args: GetApiV1ChainNameBlockV2BlockHeightArgs, options?: GetApiV1ChainNameBlockV2BlockHeightOptions) => { const {baseUrl = "https://api.covalenthq.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/${encodeURIComponent(String(args.chainName))}/block_v2/${encodeURIComponent(String(args.blockHeight))}/${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiV1ChainNameBlockV2BlockHeightResponse, await res.json()) };