import {z} from 'zod' export type GetApiCommitArgs = {height?: number | undefined}; export type GetApiCommitOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const blockID = z.object({hash: z.string(), parts: z.object({total: z.number().int(), hash: z.string()})}); export const blockHeader = z.object({version: z.object({block: z.string(), app: z.string()}), chain_id: z.string(), height: z.string(), time: z.string(), last_block_id: blockID, last_commit_hash: z.string(), data_hash: z.string(), validators_hash: z.string(), next_validators_hash: z.string(), consensus_hash: z.string(), app_hash: z.string(), last_results_hash: z.string(), evidence_hash: z.string(), proposer_address: z.string()}); export const commitResponse = z.object({jsonrpc: z.string(), id: z.number().int(), result: z.object({signed_header: z.object({header: blockHeader, commit: z.object({height: z.string(), round: z.number().int(), block_id: blockID, signatures: z.array(z.object({block_id_flag: z.number().int().optional(), validator_address: z.string().optional(), timestamp: z.string().optional(), signature: z.string().optional()}))})}), canonical: z.boolean()})}); 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 }; /** * Get commit results at a specified height * * GET /commit */ export const getApiCommit = async (args: GetApiCommitArgs, options?: GetApiCommitOptions) => { const {baseUrl = "http://localhost:26657", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.height != null) query.append("height", String(args.height)) const url = `${baseUrl.replace(/\/+$/, '')}/commit${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(commitResponse, await res.json()) };