import {z} from 'zod' export type GetApiSearchArgs = {q?: string | undefined}; export type GetApiSearchOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const searchResultToken = z.object({address_hash: z.string().optional(), address_url: z.string(), exchange_rate: z.string(), icon_url: z.string(), is_smart_contract_verified: z.boolean(), name: z.string(), symbol: z.string(), token_type: z.string(), token_url: z.string(), total_supply: z.string(), type: z.string()}); export const searchResultAddressOrContract = z.object({address_hash: z.string().optional(), is_smart_contract_verified: z.boolean(), name: z.string(), type: z.string(), url: z.string()}); export const searchResultBlock = z.object({block_hash: z.string(), block_number: z.number().int(), timestamp: z.string(), type: z.string(), url: z.string()}); export const searchResultTransaction = z.object({timestamp: z.string(), transaction_hash: z.string(), type: z.string(), url: z.string()}); export const getApiSearchResponse = z.object({items: z.array(z.union([searchResultToken, searchResultAddressOrContract, searchResultBlock, searchResultTransaction])), next_page_params: z.object({})}); 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 * * GET /search * * Also accepts auth: apiKeyAuth */ export const getApiSearch = async (args: GetApiSearchArgs, options?: GetApiSearchOptions) => { const {baseUrl = "https://api.blockscout.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.q != null) query.append("q", String(args.q)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/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(getApiSearchResponse, await res.json()) };