import {z} from 'zod' export type ApiTransactionsCustomFee = {fixed_fee?: string | undefined, percentage_fee?: number | undefined, min_percentage_fee_fixed?: string | undefined, max_percentage_fee_fixed?: string | undefined}; export type ApiTokenAddress = {blockchain: string, address: string}; export type ApiTokenVerification = 'whitelisted' | 'blacklisted' | 'community' | 'unknown'; export type ApiTokenMetadata = {name: string, symbol: string, decimals: number, image_url?: string | undefined, listed: boolean, verification: ApiTokenVerification}; export type ApiToken = {address: ApiTokenAddress, metadata: ApiTokenMetadata}; export type ApiSwapResult = 'fully_fulfilled' | 'partially_fulfilled' | 'unavailable'; export type ApiPoolReserves = Array; export type ApiSwap = {result: ApiSwapResult, input_amount: number, output_amount: number, before_reserves: ApiPoolReserves, after_reserves: ApiPoolReserves, reason?: string | undefined, left_amount?: number | undefined}; export type ApiRoutingStep = {blockchain: string, dex: string, pool_address: string, input_token: ApiToken, output_token: ApiToken, swap: ApiSwap, recommended_gas: number, average_gas: number, next?: Array | undefined}; export type ApiTransactionsRequest = {sender_address: string, slippage?: number | undefined, dynamic_slippage?: boolean | undefined, referral_name?: string | undefined, custom_fee?: ApiTransactionsCustomFee | undefined, mev_protection?: boolean | undefined, paths: Array}; export type CreateApiV2RouteTransactionsArgs = {body: ApiTransactionsRequest}; export type CreateApiV2RouteTransactionsOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const apiSwapTransaction = z.object({address: z.string(), value: z.string(), cell: z.string(), stateInit: z.string().optional(), send_mode: z.number().int(), query_id: z.number().int()}); export const apiTransactionsResponse = z.object({route_id: z.number().int(), transactions: z.array(apiSwapTransaction)}); 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 }; /** * Returns pre-built transactions for the given route. It is assumed that transactions will be signed and sent by the sender via wallet * * POST /v2/route/transactions */ export const createApiV2RouteTransactions = async (args: CreateApiV2RouteTransactionsArgs, options?: CreateApiV2RouteTransactionsOptions) => { const {baseUrl = "https://backend.swap.coffee", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set("X-Api-Key", ApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v2/route/transactions${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(apiTransactionsResponse, await res.json()) };