import {z} from 'zod' export type GetApiAbciQueryArgs = {path: string, data: string, height?: number | undefined, prove?: boolean | undefined}; export type GetApiAbciQueryOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const aBCIQueryResponse = z.object({error: z.string(), result: z.object({response: z.object({log: z.string(), height: z.string(), proof: z.string(), value: z.string(), key: z.string(), index: z.string(), code: z.string()})}), id: z.number().int(), jsonrpc: z.string()}); 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 }; /** * Query the application for some information. * * GET /abci_query */ export const getApiAbciQuery = async (args: GetApiAbciQueryArgs, options?: GetApiAbciQueryOptions) => { const {baseUrl = "http://localhost:26657", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.path != null) query.append("path", String(args.path)) if (args.data != null) query.append("data", String(args.data)) if (args.height != null) query.append("height", String(args.height)) if (args.prove != null) query.append("prove", String(args.prove)) const url = `${baseUrl.replace(/\/+$/, '')}/abci_query${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(aBCIQueryResponse, await res.json()) };