import {z} from 'zod' export type GetApiTxSearchArgs = {query: string, prove?: boolean | undefined, page?: number | undefined, per_page?: number | undefined, order_by?: string | undefined}; export type GetApiTxSearchOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const event = z.object({key: z.string().optional(), value: z.string().optional(), index: z.boolean().optional()}); export const txSearchResponse = z.object({jsonrpc: z.string(), id: z.number().int(), result: z.object({txs: z.array(z.object({hash: z.string().optional(), height: z.string().optional(), index: z.number().int().optional(), tx_result: z.object({log: z.string(), gas_wanted: z.string(), gas_used: z.string(), tags: event}).optional(), tx: z.string().optional(), proof: z.object({RootHash: z.string(), Data: z.string(), Proof: z.object({total: z.string(), index: z.string(), leaf_hash: z.string(), aunts: z.array(z.string())})}).optional()})), total_count: 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 }; /** * Search for transactions * * GET /tx_search */ export const getApiTxSearch = async (args: GetApiTxSearchArgs, options?: GetApiTxSearchOptions) => { const {baseUrl = "http://localhost:26657", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.query != null) query.append("query", String(args.query)) if (args.prove != null) query.append("prove", String(args.prove)) if (args.page != null) query.append("page", String(args.page)) if (args.per_page != null) query.append("per_page", String(args.per_page)) if (args.order_by != null) query.append("order_by", String(args.order_by)) const url = `${baseUrl.replace(/\/+$/, '')}/tx_search${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(txSearchResponse, await res.json()) };