82 lines
2.1 KiB
TypeScript
82 lines
2.1 KiB
TypeScript
import type { WalletTransaction } from "@/lib/types"
|
|
|
|
import { httpJson } from "./http"
|
|
|
|
type Paginated<T> = {
|
|
items: T[] | null
|
|
meta: {
|
|
total: number
|
|
offset: number
|
|
limit: number
|
|
}
|
|
}
|
|
|
|
export type ListWalletTransactionsOptions = {
|
|
offset?: number
|
|
limit?: number
|
|
}
|
|
|
|
function withOffsetLimit(path: string, options?: ListWalletTransactionsOptions): string {
|
|
const offset = options?.offset ?? 0
|
|
const limit = options?.limit ?? 100
|
|
const searchParams = new URLSearchParams({
|
|
offset: String(offset),
|
|
limit: String(limit),
|
|
})
|
|
return `${path}?${searchParams.toString()}`
|
|
}
|
|
|
|
type WalletBalanceResponse = {
|
|
balance: string
|
|
frozenBalance?: string
|
|
}
|
|
|
|
function parseBalance(value: unknown): number | undefined {
|
|
if (typeof value !== "object" || value === null) return undefined
|
|
const v = value as WalletBalanceResponse
|
|
if (typeof v.balance === "string") return Number(v.balance)
|
|
if (typeof v.balance === "number") return v.balance
|
|
return undefined
|
|
}
|
|
|
|
export async function getWalletBalance(): Promise<number> {
|
|
const res = await httpJson<unknown>("/api/v1/wallet/balance", { cache: "no-store" })
|
|
const balance = parseBalance(res)
|
|
if (balance === undefined) {
|
|
throw new Error("Invalid wallet balance response")
|
|
}
|
|
return balance
|
|
}
|
|
|
|
export async function listWalletTransactions(
|
|
options?: ListWalletTransactionsOptions,
|
|
): Promise<WalletTransaction[]> {
|
|
const res = await httpJson<Paginated<WalletTransaction>>(
|
|
withOffsetLimit("/api/v1/wallet/transactions", options),
|
|
{
|
|
cache: "no-store",
|
|
},
|
|
)
|
|
return res.items ?? []
|
|
}
|
|
|
|
export async function topUpWallet(input: { amount: number; method?: string }): Promise<void> {
|
|
await httpJson<unknown>("/api/v1/wallet/topup", {
|
|
method: "POST",
|
|
json: {
|
|
amount: String(input.amount),
|
|
method: input.method ?? "dev",
|
|
},
|
|
})
|
|
}
|
|
|
|
export async function withdrawWallet(input: { amount: number; method?: string }): Promise<void> {
|
|
await httpJson<unknown>("/api/v1/wallet/withdraw", {
|
|
method: "POST",
|
|
json: {
|
|
amount: String(input.amount),
|
|
method: input.method ?? "dev",
|
|
},
|
|
})
|
|
}
|