import {z} from 'zod' export type Coin = 'BRLA' | 'USDC' | 'USDT' | 'ETH' | 'GLMR' | 'MATIC' | 'CHZ'; export type Markup = string; export type BuyPixToTokenInput = {amount: number, token: Coin, markup?: Markup | undefined, receiverAddress: string, markupAddress?: string | undefined, externalId?: string | undefined}; export type CreateApiSuperuserBuyPixToTokenArgs = {taxId: string, body: BuyPixToTokenInput}; export type CreateApiSuperuserBuyPixToTokenOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const buyPixToTokenOutput = z.object({id: z.string().optional(), due: z.string().optional(), brCode: z.string().optional(), markupBRLA: z.string().optional()}); 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 }; /** * Creates a pix-to-token ticket * * POST /superuser/buy/pix-to-token * * Also accepts auth: apiKeyAuth + apiSignatureAuth + apiTimestampAuth */ export const createApiSuperuserBuyPixToToken = async (args: CreateApiSuperuserBuyPixToTokenArgs, options?: CreateApiSuperuserBuyPixToTokenOptions) => { const {baseUrl = "https://api.brla.digital:5567/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.taxId != null) query.append("taxId", String(args.taxId)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/superuser/buy/pix-to-token${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(buyPixToTokenOutput, await res.json()) };