import {z} from 'zod' export type UUID = string; export type GetApiV0PortfoliosArgs = {investorId: UUID}; export type GetApiV0PortfoliosOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const uUID = z.string(); export const network = z.enum(["Ethereum", "Polygon", "Base", "Arbitrum", "ArbitrumUk", "Etherlink", "Starknet", "Stellar", "Solana"]); export const evmAddress = z.string(); export const starknetAddress = z.string(); export const stellarAccountAddress = z.string(); export const stellarContractAddress = z.string(); export const solanaAddress = z.string(); export const currencyCode = z.enum(["EUR", "USD", "GBP", "CHF", "JPY", "SGD", "SEK", "NOK", "DKK", "PLN", "HUF", "CZK"]); export const nonNegativeAmount = z.object({value: z.string(), currency: currencyCode}); export const nonNegativeInt = z.number().int().gte(0).lte(9007199254740991); export const amount = z.object({value: z.string(), currency: currencyCode}); export const getApiV0PortfoliosResponse = z.object({items: z.array(z.object({investorId: uUID, accountId: uUID, shareClassId: uUID, network: network, walletAddress: z.union([evmAddress, starknetAddress, stellarAccountAddress, stellarContractAddress, solanaAddress]), totalNumberOfShares: z.string(), currentValue: nonNegativeAmount, isCustodialWallet: z.boolean(), pending: z.object({credit: z.object({numberOfSubscriptions: nonNegativeInt, amount: nonNegativeAmount, approximated: z.boolean()}), debit: z.object({numberOfRedemptions: nonNegativeInt, approximated: z.boolean(), amount: nonNegativeAmount})}), projectedBalance: nonNegativeAmount, projectedBalanceInShares: z.string(), withdrawableBalance: nonNegativeAmount, withdrawableBalanceInShares: z.string(), virtualIban: z.string().optional(), bic: z.string().optional(), depositIbanLines: z.array(z.object({label: z.string(), value: z.string(), tooltip: z.string().optional()})).optional(), cashCollectionBankAccountBeneficiaryName: z.string().min(1).optional()})), totalGainSinceStart: z.array(z.object({investorId: uUID, accountId: uUID, shareClassId: uUID, totalGainAmount: amount}))}); 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 portfolio * * GET /v0/portfolios/ */ export const getApiV0Portfolios = async (args: GetApiV0PortfoliosArgs, options?: GetApiV0PortfoliosOptions) => { const {baseUrl = "https://distributor-api.spiko.io", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.investorId != null) query.append("investorId", String(args.investorId)) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v0/portfolios/${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(getApiV0PortfoliosResponse, await res.json()) };