import {z} from 'zod' export type GetApiV1TradingQuoteArgs = {method: 'IN' | 'OUT', type: 'MEME' | 'NATIVE', amount: string, tokenName: string}; export type GetApiV1TradingQuoteOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const tradeQuoteFeesResponseDto = z.object({reverseBondingCurve: z.string(), transactionFees: z.string()}); export const tradeAmountResponseDto = z.object({calculatedQuantity: z.string(), extraFees: tradeQuoteFeesResponseDto}); export const getApiV1TradingQuoteResponse = z.object({error: z.literal(false), message: z.string(), status: z.number(), data: tradeAmountResponseDto}); 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 }; /** * Calculate trade quote * * GET /v1/trading/quote */ export const getApiV1TradingQuote = async (args: GetApiV1TradingQuoteArgs, options?: GetApiV1TradingQuoteOptions) => { const {baseUrl = "https://lpad-backend.stage.defi.ovh.gala.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.method != null) query.append("method", String(args.method)) if (args.type != null) query.append("type", String(args.type)) if (args.amount != null) query.append("amount", String(args.amount)) if (args.tokenName != null) query.append("tokenName", String(args.tokenName)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/trading/quote${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(getApiV1TradingQuoteResponse, await res.json()) };