import {z} from 'zod' export type MetricParams = {createdAfter?: string | undefined, createdBefore?: string | undefined, calculationInterval?: ('day' | 'week' | 'month' | 'quarter' | 'year') | undefined, userIds?: Array | undefined, transactionTypes?: (Array<'onramp' | 'offramp' | 'transfer'>) | undefined, transactionStatuses?: (Array<'AWAITING_FUNDS' | 'COMPLETED' | 'CRYPTO_FAILED' | 'CRYPTO_INITIATED' | 'CRYPTO_PENDING' | 'FAILED' | 'FIAT_FAILED' | 'FIAT_INITIATED' | 'FIAT_PENDING' | 'FIAT_PROCESSED' | 'FIAT_RETURNED' | 'INITIATED' | 'NOT_INITIATED' | 'PENDING' | 'QUOTE_FAILED' | 'REJECTED'>) | undefined, breakdowns?: (Array<'transactionType' | 'transactionStatus' | 'userId'>) | undefined, limit?: number | undefined} | {[key: string]: unknown}; export type CreateMetricRequest = {template: 'GROSS_VOLUME' | 'TRANSACTION_COUNT' | 'NEW_USERS', name: string, params: MetricParams}; export type CreateApiV2ReportingMetricsArgs = {body: CreateMetricRequest}; export type CreateApiV2ReportingMetricsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const metricParams = z.object({createdAfter: z.string().optional(), createdBefore: z.string().optional(), calculationInterval: z.enum(["day", "week", "month", "quarter", "year"]).optional(), userIds: z.array(z.string()).optional(), transactionTypes: z.array(z.enum(["onramp", "offramp", "transfer"])).optional(), transactionStatuses: z.array(z.enum(["AWAITING_FUNDS", "COMPLETED", "CRYPTO_FAILED", "CRYPTO_INITIATED", "CRYPTO_PENDING", "FAILED", "FIAT_FAILED", "FIAT_INITIATED", "FIAT_PENDING", "FIAT_PROCESSED", "FIAT_RETURNED", "INITIATED", "NOT_INITIATED", "PENDING", "QUOTE_FAILED", "REJECTED"])).optional(), breakdowns: z.array(z.enum(["transactionType", "transactionStatus", "userId"])).optional(), limit: z.number().int().gte(1).lte(500).optional()}).and(z.record(z.string(), z.unknown())); export const metric = z.object({id: z.string(), profileId: z.string(), template: z.enum(["GROSS_VOLUME", "TRANSACTION_COUNT", "NEW_USERS"]), name: z.string(), params: metricParams, createdAt: z.string(), updatedAt: z.string()}); export const metricResponse = z.object({status: z.literal("success").optional(), data: metric.optional(), metadata: z.object({}).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 }; /** * Create Saved Metric * * POST /v2/reporting/metrics */ export const createApiV2ReportingMetrics = async (args: CreateApiV2ReportingMetricsArgs, options?: CreateApiV2ReportingMetricsOptions) => { const {baseUrl = "https://production.hifibridge.com", 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 (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/reporting/metrics${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(metricResponse, await res.json()) };