import {z} from 'zod' export type ChainGasBalances = Record; export type Route = {routeId: string, fromAmount: string, chainGasBalances: ChainGasBalances, toAmount: string, usedBridgeNames: Array<'polygon-bridge' | 'hop' | 'anyswap-router-v4' | 'hyphen' | 'arbitrum-bridge' | 'connext'>, totalUserTx: number, totalGasFeesInUsd: number, sender: string, userTxs: Array>, serviceTime: number}; export type SingleTxDTO = {route: Route}; export type CreateApiV2BuildTxArgs = {'API-KEY'?: string | undefined, body: SingleTxDTO}; export type CreateApiV2BuildTxOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const approvalData = z.object({minimumApprovalAmount: z.string(), approvalTokenAddress: z.string(), allowanceTarget: z.string(), owner: z.string()}); export const singleTxResponse = z.object({userTxType: z.enum(["approve", "fund-movr", "claim", "dex-swap", "sign"]), txTarget: z.string(), chainId: z.enum(["ETHEREUM", "OPTIMISM", "BSC", "XDAI", "POLYGON", "FANTOM", "ARBITRUM", "AVALANCHE"]), txData: z.string(), txType: z.enum(["eth_sendTransaction", "eth_signMessage"]), value: z.string(), totalUserTx: z.number(), approvalData: approvalData}); export const singleTxOutputDTO = z.object({success: z.boolean(), result: singleTxResponse}); 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 }; /** * POST /v2/build-tx */ export const createApiV2BuildTx = async (args: CreateApiV2BuildTxArgs, options: CreateApiV2BuildTxOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['API-KEY'] != null) headers.set("API-KEY", String(args['API-KEY'])) const url = `${baseUrl.replace(/\/+$/, '')}/v2/build-tx${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(singleTxOutputDTO, await res.json()) };