import {z} from 'zod' export type ResolveRequest = {intent: string}; export type CreateApiResolveArgs = {body: ResolveRequest}; export type CreateApiResolveOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const parameter = z.object({type: z.string(), required: z.boolean()}); export const passthroughRequest = z.object({method: z.string(), url: z.string(), body: z.string().optional()}); export const paymentEntry = z.object({scheme: z.literal("exact"), network: z.string(), asset: z.string(), amount: z.string()}); export const payment = z.object({accepts: z.array(paymentEntry)}); export const candidate = z.object({listing: z.string(), airnode: z.string(), operation: z.string(), address: z.string(), attestation: z.enum(["first-party", "third-party"]), parameters: z.record(z.string(), parameter), example: z.record(z.string(), z.unknown()), passthrough: passthroughRequest, returns: z.record(z.string(), z.string()), payment: payment.nullable(), why: z.string()}); export const unresolvedInput = z.object({requirement: z.string(), needed: z.string(), reason: z.enum(["missing", "unverified", "unsupported", "noIntent"])}); export const resolution = z.object({intent: z.string(), candidates: z.array(candidate), unresolvedInputs: z.array(unresolvedInput)}); 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 }; /** * Find Airnode operations for an intent * * POST /resolve */ export const createApiResolve = async (args: CreateApiResolveArgs, options?: CreateApiResolveOptions) => { const {baseUrl = "https://airnodehub.api3.org", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/resolve${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(resolution, await res.json()) };