import {z} from 'zod' export type PostRunesPSBTOrderCreateRequestSchema = {side: 'sell', rune: string, makerRunesPublicKey: string | string, makerRunesAddress: string | string | string, makerReceiveAddress: string | string | string, utxos: Array<{location: string, priceSats: number}>, expiresAt: string}; export type CreateApiV2OrdBtcRunesPsbtOrderCreateArgs = {body: PostRunesPSBTOrderCreateRequestSchema}; export type CreateApiV2OrdBtcRunesPsbtOrderCreateOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const unsignedRBFProtectedPSBTSchema = z.object({unsignedPSBTBase64: z.string().optional(), toSignInputs: z.array(z.number()).optional(), toSignSigHash: z.number().optional()}); export const postRunesPSBTOrderCreateResultSchema = z.object({orderPsbtBase64: z.string(), unsignedRBFProtectedPsbts: z.array(unsignedRBFProtectedPSBTSchema)}); 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 an unsigned PSBT for creating a rune sell order * * POST /v2/ord/btc/runes/psbt/order/create */ export const createApiV2OrdBtcRunesPsbtOrderCreate = async (args: CreateApiV2OrdBtcRunesPsbtOrderCreateArgs, options?: CreateApiV2OrdBtcRunesPsbtOrderCreateOptions) => { const {baseUrl = "https://api-mainnet.magiceden.dev/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v2/ord/btc/runes/psbt/order/create${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(postRunesPSBTOrderCreateResultSchema, await res.json()) };