// Asphodel SDK (was Wick Cover; the file name and the WickCover exports stay): one file, zero dependencies (fetch). buyCover/buyCoverBatch take a viem WalletClient. // import { Asphodel } from "./wickcover.ts"; // alias of WickCover // const wc = new Asphodel("http://127.0.0.1:8700/api/v1"); // const q = await wc.quote({ hlAccount, coin: "BTC", termSec: 86400, buyer }); // const { policyId } = await wc.buyCover(walletClient, q); export type Side = "long" | "short"; /** EIP-712 domain of the signed quotes: { name, version, chainId, verifyingContract: policyBook }. */ export const EIP712_DOMAIN_NAME = "Asphodel"; export const EIP712_DOMAIN_VERSION = "1"; /** The consent text a Hyperliquid account signs (personal_sign) so another buyer can get a quote for it. `buyer` must be EIP-55 checksummed. */ export const consentMessage = (buyer: string, authNonce: string | number) => `Asphodel quote for ${buyer} nonce ${authNonce}`; export interface Stats { chainId: number; policyBook: string; coverPool: string; usdc: string; navUsd: number; freeUsd: number; reservedUsd: number; pendingUsd: number; pendingPayoutsUsd: number; depositsPaused: boolean; depositsPausedReason: string | null; withdrawalsBlockedBy: number[]; sharePrice: number; totalShares: number; queuedShares: number; openCoverUsd: number; openPolicies: number; feesEarnedUsd: number; feesToPoolUsd: number; feesToTreasuryUsd: number; payoutsMadeUsd: number; payoutsCount: number; policiesCount: number; salesPaused: boolean; salesPausedReason: string | null; rule: string; chainTime: number; /** false on Elysium mainnet. */ fork?: boolean; /** On-chain PolicyBook.maxPayout in USDC: no policy pays more. */ maxPayoutUsd?: number; /** A quote is refused only when its payout, after the clip to the pool size, is below this. */ minPayoutUsd?: number; [k: string]: unknown; } export interface Deployment { chainId: number; rpcUrl: string; usdc: `0x${string}`; coverPool: `0x${string}`; policyBook: `0x${string}`; quoter: `0x${string}`; keeper: `0x${string}`; guardians: `0x${string}`[]; treasury: `0x${string}`; deployBlock: number; deployedAt: string | null; isFork: boolean; chainName?: string; /** Block explorer base URL; null on the fork. */ explorerUrl?: string | null; } export interface Position { coin: string; coinId: number | null; side: Side; size: number; entryPx: number; markPx: number; liqPx: number | null; distancePct: number | null; leverage: number; leverageType: string; marginUsd: number; coverable: boolean; reason: string | null; preview?: { termSec: number; payout: number; fee: number; feePctOfPayout: number; pTouch: number; human: string[] }; } /** On-chain Quote struct; integers as decimal strings (USDC 6 dp, prices 1e8). */ export interface QuoteStruct { hlAccount: string; coinId: number; side: number; liqPx: string; marginUsd: string; payout: string; fee: string; term: string; buyer: string; beneficiary: string; quoteExpiry: string; nonce: string; } export interface SignedQuote { source: "live" | "replay"; quote: QuoteStruct; signature: `0x${string}`; policyBook: `0x${string}`; usdc: `0x${string}`; expiresAt: number; authorisedBy: string; /** Includes payoutLimitedBy ("margin" | "maxPayout" | "pool") and payoutLimitedByPool (true = payout limited by pool size). */ breakdown: Record; human: string[]; [k: string]: unknown; } export interface QuoteRequest { hlAccount: string; coin: string; side?: Side; termSec?: 86400 | 259200 | 604800; buyer: string; beneficiary?: string; /** Optional consent: personal_sign by hlAccount of `Asphodel quote for nonce `. */ authNonce?: string | number; authSig?: `0x${string}`; } export interface BatchResult { rows: { index: number; ok: boolean; quote?: SignedQuote; error?: { code: string; message: string } }[]; ok: number; failed: number; buyCoverBatch: { quotes: QuoteStruct[]; sigs: `0x${string}`[]; totalFee: string } | null; } export interface PolicyView { id: number; status: string; state: string; source: "live" | "replay"; hlAccount: string; coin: string; side: Side; buyer: string; beneficiary: string; payoutUsd: number; feeUsd: number; start: number; end: number; claim: Record | null; votes: Record[]; evidence: Record | null; [k: string]: unknown; } export class WickCoverError extends Error { constructor(public status: number, public code: string, message: string) { super(message); } } /** Minimal shape of a viem WalletClient (so this file needs no viem import). */ export interface WalletLike { account?: { address: `0x${string}` } | null; chain?: unknown; writeContract(args: Record): Promise<`0x${string}`>; request(args: { method: string; params?: unknown }): Promise; } const QUOTE_COMPONENTS = [ { name: "hlAccount", type: "address" }, { name: "coinId", type: "uint32" }, { name: "side", type: "uint8" }, { name: "liqPx", type: "uint256" }, { name: "marginUsd", type: "uint256" }, { name: "payout", type: "uint256" }, { name: "fee", type: "uint256" }, { name: "term", type: "uint256" }, { name: "buyer", type: "address" }, { name: "beneficiary", type: "address" }, { name: "quoteExpiry", type: "uint256" }, { name: "nonce", type: "uint256" }, ] as const; export const POLICY_BOOK_ABI = [ { type: "function", name: "buyCover", stateMutability: "nonpayable", inputs: [{ name: "q", type: "tuple", components: QUOTE_COMPONENTS }, { name: "sig", type: "bytes" }], outputs: [{ name: "policyId", type: "uint256" }] }, { type: "function", name: "buyCoverBatch", stateMutability: "nonpayable", inputs: [{ name: "qs", type: "tuple[]", components: QUOTE_COMPONENTS }, { name: "sigs", type: "bytes[]" }], outputs: [{ name: "ids", type: "uint256[]" }] }, ] as const; export const ERC20_ABI = [ { type: "function", name: "approve", stateMutability: "nonpayable", inputs: [{ name: "spender", type: "address" }, { name: "amount", type: "uint256" }], outputs: [{ type: "bool" }] }, ] as const; /** keccak256("PolicyBought(uint256,address,address,address,uint32,uint8,uint256,uint256,uint256,uint256,uint64,uint64,uint256)") */ export const POLICY_BOUGHT_TOPIC = "0xd5bfc0e2e65d8c0afb52c8cefe3f678c3e35521e62b05959e80520c4b11a18f4"; const toChain = (q: QuoteStruct) => ({ ...q, liqPx: BigInt(q.liqPx), marginUsd: BigInt(q.marginUsd), payout: BigInt(q.payout), fee: BigInt(q.fee), term: BigInt(q.term), quoteExpiry: BigInt(q.quoteExpiry), nonce: BigInt(q.nonce), }); async function waitReceipt(w: WalletLike, hash: `0x${string}`, timeoutMs = 60_000): Promise<{ status: string; logs: { topics: string[]; address: string }[] }> { const t0 = Date.now(); for (;;) { const r = (await w.request({ method: "eth_getTransactionReceipt", params: [hash] })) as { status: string; logs: { topics: string[]; address: string }[] } | null; if (r) { if (r.status !== "0x1") throw new WickCoverError(0, "reverted", `transaction ${hash} reverted`); return r; } if (Date.now() - t0 > timeoutMs) throw new WickCoverError(0, "timeout", `no receipt for ${hash}`); await new Promise((res) => setTimeout(res, 500)); } } export class WickCover { constructor(public baseUrl = "http://127.0.0.1:8700/api/v1", private headers: Record = {}) { this.baseUrl = baseUrl.replace(/\/$/, ""); } private async call(path: string, body?: unknown): Promise { const res = await fetch( `${this.baseUrl}${path}`, body === undefined ? { headers: this.headers } : { method: "POST", headers: { ...this.headers, "content-type": "application/json" }, body: JSON.stringify(body) }, ); const j = (await res.json().catch(() => ({}))) as { error?: { code: string; message: string } }; if (!res.ok) throw new WickCoverError(res.status, j.error?.code ?? "http_error", j.error?.message ?? `HTTP ${res.status}`); return j as T; } getStats = () => this.call("/stats"); getDeployment = () => this.call("/deployment"); getHealth = () => this.call>("/health"); getPositions = (hlAddress: string, termSec?: number) => this.call<{ hlAccount: string; accountValue: number; positions: Position[] }>(`/positions/${hlAddress}${termSec ? `?termSec=${termSec}` : ""}`); quote = (req: QuoteRequest) => this.call("/quote", req); quoteBatch = (rows: QuoteRequest[]) => this.call("/quote/batch", { rows }); getPolicy = (id: number | string) => this.call(`/policies/${id}`); listPolicies = (f: { hl?: string; buyer?: string; beneficiary?: string; status?: string; limit?: number } = {}) => { const qs = new URLSearchParams(Object.entries(f).filter(([, v]) => v !== undefined).map(([k, v]) => [k, String(v)])).toString(); return this.call<{ policies: PolicyView[] }>(`/policies${qs ? `?${qs}` : ""}`); }; getClaims = () => this.call<{ claims: Record[] }>("/claims"); getActivity = () => this.call<{ activity: Record[] }>("/activity"); getBacktest = () => this.call>("/backtest"); /** Approve the fee and call PolicyBook.buyCover. The wallet must be quote.buyer. Returns the new policy id. */ async buyCover(wallet: WalletLike, q: SignedQuote): Promise<{ policyId: number; txHash: `0x${string}` }> { const account = wallet.account ?? undefined; const a = await wallet.writeContract({ account, chain: wallet.chain, address: q.usdc, abi: ERC20_ABI, functionName: "approve", args: [q.policyBook, BigInt(q.quote.fee)] }); await waitReceipt(wallet, a); const h = await wallet.writeContract({ account, chain: wallet.chain, address: q.policyBook, abi: POLICY_BOOK_ABI, functionName: "buyCover", args: [toChain(q.quote), q.signature], gas: 900_000n }); const r = await waitReceipt(wallet, h); const ids = await policyIdsFromLogs(wallet, r.logs, q.policyBook); return { policyId: ids[0], txHash: h }; } /** One transaction for many positions (prop firms). Every quote must have the same buyer (the wallet). */ async buyCoverBatch(wallet: WalletLike, batch: NonNullable, policyBook: `0x${string}`, usdc: `0x${string}`): Promise<{ policyIds: number[]; txHash: `0x${string}` }> { const account = wallet.account ?? undefined; const a = await wallet.writeContract({ account, chain: wallet.chain, address: usdc, abi: ERC20_ABI, functionName: "approve", args: [policyBook, BigInt(batch.totalFee)] }); await waitReceipt(wallet, a); const h = await wallet.writeContract({ account, chain: wallet.chain, address: policyBook, abi: POLICY_BOOK_ABI, functionName: "buyCoverBatch", args: [batch.quotes.map(toChain), batch.sigs], gas: BigInt(400_000 + 350_000 * batch.quotes.length) }); const r = await waitReceipt(wallet, h); return { policyIds: await policyIdsFromLogs(wallet, r.logs, policyBook), txHash: h }; } } async function policyIdsFromLogs(_w: WalletLike, logs: { topics: string[]; address: string }[], book: string): Promise { return logs .filter((l) => l.address.toLowerCase() === book.toLowerCase() && l.topics[0] === POLICY_BOUGHT_TOPIC) .map((l) => Number(BigInt(l.topics[1]))); } // New-name aliases. The old names stay exported. export { WickCover as Asphodel, WickCoverError as AsphodelError }; export default WickCover;