import {z} from 'zod' export type CreateTradeStrategyRebalanceBody = {allocations: Array<{underlying_currency: string, weight: string}>, participants?: Array<{participant_code: string}> | undefined}; export type CreateApiStrategiesStrategyIdRebalanceArgs = {'X-SCX-SIGNED': string, 'X-SCX-TIMESTAMP': string, strategy_id: string, body: CreateTradeStrategyRebalanceBody}; export type CreateApiStrategiesStrategyIdRebalanceOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, apiPassphrase?: string | undefined, fetch?: typeof fetch | undefined}; export const tradeStrategyOperationResponse = z.object({message: z.object({id: z.string().optional(), strategy_id: z.string().optional(), request_id: z.string().optional(), type: z.enum(["enrollment", "top_up", "partial_sell", "rebalance", "liquidation"]).optional(), status: z.enum(["validating", "pricing", "settling", "settled", "skipped", "failed"]).optional(), status_reason: z.string().optional(), allocations: z.array(z.object({underlying_currency: z.string(), weight: z.string()})).optional(), created_at: z.string().optional(), updated_at: z.string().optional()}).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 }; /** * Rebalance * * POST /strategies/{strategy_id}/rebalance */ export const createApiStrategiesStrategyIdRebalance = async (args: CreateApiStrategiesStrategyIdRebalanceArgs, options?: CreateApiStrategiesStrategyIdRebalanceOptions) => { const {baseUrl = "https://api.cert.zerohash.com", fetch: fetchFn = fetch, apiKey, apiPassphrase} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-SCX-SIGNED'] != null) headers.set("X-SCX-SIGNED", String(args['X-SCX-SIGNED'])) if (args['X-SCX-TIMESTAMP'] != null) headers.set("X-SCX-TIMESTAMP", String(args['X-SCX-TIMESTAMP'])) if (apiKey !== undefined) headers.set("X-SCX-API-KEY", apiKey) if (apiPassphrase !== undefined) headers.set("X-SCX-PASSPHRASE", apiPassphrase) const url = `${baseUrl.replace(/\/+$/, '')}/strategies/${encodeURIComponent(String(args.strategy_id))}/rebalance${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(tradeStrategyOperationResponse, await res.json()) };