import {z} from 'zod' export type GetApiUserHistoriesOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const loanStruct = z.object({buyerNftId: z.string().optional(), sellerNftId: z.string().optional(), remainingPrincipal: z.string().optional(), minimumPrincipalPerPeriod: z.string().optional(), periodInterestRateBps: z.number().int().optional(), periodDuration: z.number().int().optional(), periodEndTimestamp: z.number().int().optional(), periodBeginTimestamp: z.number().int().optional()}); export const buyerExecutedLoan = z.object({type: z.literal("BUYER_EXECUTED_LOAN"), timestamp: z.number().int(), loan: loanStruct, txHash: z.string()}); export const userSentBuyerNft = z.object({type: z.literal("SENT_BUYER_NFT"), timestamp: z.number().int(), nftId: z.string(), to: z.string(), from: z.string(), txHash: z.string()}); export const userReceivedBuyerNft = z.object({type: z.literal("RECEIVED_BUYER_NFT"), timestamp: z.number().int(), nftId: z.string(), to: z.string(), from: z.string(), txHash: z.string()}); export const offerStruct = z.object({minimumPrincipalPerPeriod: z.string().optional(), periodDuration: z.number().int().optional(), creator: z.string().optional(), nftContractAddress: z.string().optional(), price: z.string().optional(), periodInterestRateBps: z.number().int().optional(), nftId: z.string().optional(), expiration: z.number().int().optional(), downPaymentAmount: z.string().optional(), collectionOfferLimit: z.string().optional()}); export const offer = z.object({offer: offerStruct.optional(), signature: z.string().optional(), createdAt: z.number().int().optional(), status: z.enum(["ACTIVE", "EXPIRED", "CANCELLED", "USED_TO_EXECUTE_LOAN", "COLLECTION_OFFER_LIMIT_REACHED"]).optional(), isCollectionOffer: z.boolean().optional(), howManyTimesUsed: z.number().int().optional()}); export const transferEventArgs = z.object({from: z.string().optional(), to: z.string().optional(), tokenId: z.string().optional()}); export const transferEvent = z.object({args: transferEventArgs.optional(), blockNumber: z.number().int().optional(), transactionHash: z.string().optional(), transactionIndex: z.number().int().optional(), logIndex: z.number().int().optional(), eventType: z.literal("Transfer").optional()}); export const nftDetails = z.object({tokenId: z.string().optional(), owner: z.string().optional(), ownerHistory: z.array(z.string()).optional(), transferEvents: z.array(transferEvent).optional()}); export const loan = z.object({loan: loanStruct.optional(), offer: offer.optional(), buyerNft: nftDetails.optional(), sellerNft: nftDetails.optional(), paymentHistory: z.array(z.unknown()).optional(), status: z.enum(["ACTIVE", "FULLY_REPAID", "ASSET_SEIZED"]).optional(), defaultStatus: z.enum(["NOT_IN_DEFAULT", "IN_DEFAULT_AND_REPAYABLE", "IN_DEFAULT_AND_NOT_REPAYABLE"]).optional()}); export const buyerMadePayment = z.object({type: z.literal("BUYER_MADE_PAYMENT"), timestamp: z.number().int(), loan: loan, amount: z.string(), interestPaid: z.string(), royaltiesPaid: z.string(), txHash: z.string()}); export const buyerPaidOffLoan = z.object({type: z.literal("BUYER_PAID_OFF_LOAN"), timestamp: z.number().int(), loan: loan, txHash: z.string()}); export const buyerDefaultedOnLoan = z.object({type: z.literal("BUYER_DEFAULTED_ON_LOAN"), timestamp: z.number().int(), loan: loan}); export const buyerAssetSeized = z.object({type: z.literal("BUYER_ASSET_SEIZED"), timestamp: z.number().int(), loan: loan, txHash: z.string()}); export const sellerCreatedOffer = z.object({type: z.literal("SELLER_CREATED_OFFERStruct"), timestamp: z.number().int(), signature: z.string(), offer: offer}); export const sellerCancelledOffer = z.object({type: z.literal("SELLER_CANCELLED_OFFERStruct"), timestamp: z.number().int(), signature: z.string(), offer: offer, txHash: z.string()}); export const sellerLoanExecuted = z.object({type: z.literal("SELLER_LOAN_EXECUTED"), timestamp: z.number().int(), loan: loanStruct, txHash: z.string()}); export const userSentSellerNft = z.object({type: z.literal("SENT_SELLER_NFT"), timestamp: z.number().int(), nftId: z.string(), to: z.string(), from: z.string(), txHash: z.string()}); export const userReceivedSellerNft = z.object({type: z.literal("RECEIVED_SELLER_NFT"), timestamp: z.number().int(), nftId: z.string(), to: z.string(), from: z.string(), txHash: z.string()}); export const sellerPaymentReceived = z.object({type: z.literal("SELLER_PAYMENT_RECEIVED"), timestamp: z.number().int(), loan: loan, amount: z.string(), interestPaid: z.string(), royaltiesPaid: z.string(), txHash: z.string()}); export const sellerLoanPaidOff = z.object({type: z.literal("SELLER_LOAN_PAID_OFF"), timestamp: z.number().int(), loan: loan, txHash: z.string()}); export const sellerLoanDefaultedOn = z.object({type: z.literal("SELLER_LOAN_DEFAULTED_ON"), timestamp: z.number().int(), loan: loan}); export const sellerSeizedAsset = z.object({type: z.literal("SELLER_SEIZED_ASSET"), timestamp: z.number().int(), loan: loan, txHash: z.string()}); export const userHistory = z.object({events: z.array(z.union([buyerExecutedLoan, userSentBuyerNft, userReceivedBuyerNft, buyerMadePayment, buyerPaidOffLoan, buyerDefaultedOnLoan, buyerAssetSeized, sellerCreatedOffer, sellerCancelledOffer, sellerLoanExecuted, userSentSellerNft, userReceivedSellerNft, sellerPaymentReceived, sellerLoanPaidOff, sellerLoanDefaultedOn, sellerSeizedAsset])).optional()}); export const getApiUserHistoriesResponse = z.record(z.string(), userHistory); 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 }; /** * Retrieves user histories * * GET /user-histories */ export const getApiUserHistories = async (options?: GetApiUserHistoriesOptions) => { const {baseUrl = "https://api.niftyapes.money/MAINNET/v1", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set("x-api-key", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/user-histories${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(getApiUserHistoriesResponse, await res.json()) };