import {z} from 'zod' export type GetApiV2FeesArgs = {currency: unknown, amount: number, amount_extra?: number | undefined, amount_postage?: number | undefined, payment_method?: string | undefined, fees_config?: number | undefined}; export type GetApiV2FeesOptions = {baseUrl?: string | undefined, APIKey?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const v2TransactionsFees = z.object({buyer: z.number().int(), config: z.number().int(), seller: z.number().int()}); 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 }; /** * Get the Trustap fee for a transaction * * GET /v2/fees * * Also accepts auth: OAuth2 */ export const getApiV2Fees = async (args: GetApiV2FeesArgs, options?: GetApiV2FeesOptions) => { const {baseUrl = "https://api.test.trustap.com", fetch: fetchFn = fetch, APIKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.currency != null) query.append("currency", String(args.currency)) if (args.amount != null) query.append("amount", String(args.amount)) if (args.amount_extra != null) query.append("amount_extra", String(args.amount_extra)) if (args.amount_postage != null) query.append("amount_postage", String(args.amount_postage)) if (args.payment_method != null) query.append("payment_method", String(args.payment_method)) if (args.fees_config != null) query.append("fees_config", String(args.fees_config)) if (APIKey !== undefined) headers.set('authorization', `Basic ${btoa(`${APIKey.username}:${APIKey.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/fees${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(v2TransactionsFees, await res.json()) };