/** * SUNK public API, in one file with no dependencies. Works in Node 18+, Deno, Bun and browsers. * * import { Sunk } from "./sunk"; * const sunk = new Sunk("https://"); // in a browser on the site itself, new Sunk() is enough * const cfg = await sunk.config(); // house vault, $SUNK mint, launch cost, split rules * const { data, next_before } = await sunk.payouts({ limit: 50 }); * const older = await sunk.payouts({ limit: 50, before: next_before ?? undefined }); * const check = await sunk.verifyPayout(data[0]); // reads Solana directly: { ok, reason } * * Every list is newest first and paged with `before` (a created_at, in ms) and `next_before` (null on the last page). * verifyPayout() trusts nothing from SUNK: it fetches the deposit transaction from a Solana RPC and checks that it * succeeded, that the LP vault signed it, and that the pool's LP tokens were burned in it. */ export interface SunkConfig { brand: string; house_vault: string | null; sunk_mint: string | null; launch_fee_sol: number; launches_enabled: boolean; lp_engine: boolean; split: { coin_pool: number; sunk: number; locked_at_launch: boolean; schedule: string }; lock: { pumpswap: string }; accounting: { liquidity_proof: string; before_pool: string }; } export interface SunkCoin { ticker: string; name: string; mint_address: string; kind: "launch" | "linked"; lp_vault: string | null; launch_signature: string | null; created_at: number; verify: string; } export interface SunkPayout { type: "paired_deposit_lp_burn"; destination: "coin" | "sunk"; destination_ticker: string; destination_mint: string | null; vault: string; pool: string | null; lp_mint: string | null; sol_deposited: number; tokens_deposited: number; /** LP tokens burned, in base units, as a decimal string. */ lp_burned: string; /** SOL the round used, including the buy and network costs. */ sol: number; buy_signature: string | null; deposit_signature: string; created_at: number; verify_deposit: string; verify_buy: string | null; } export interface Page { data: T[]; next_before: number | null; } export interface PageOptions { limit?: number; before?: number; } export interface VerifyResult { ok: boolean; reason: string; /** What was checked. `deposit` (both pool balances went up) is informational and isn't part of `ok`. */ checks?: { success: boolean; signer: boolean; burn: boolean; deposit: boolean | null }; /** LP tokens burned in the transaction, in base units. */ burned?: string; } type Json = any; // eslint-disable-line @typescript-eslint/no-explicit-any export class Sunk { readonly baseUrl: string; private readonly fetcher: typeof fetch; constructor(baseUrl?: string, fetcher?: typeof fetch) { const here = (globalThis as Json).location?.origin as string | undefined; const url = baseUrl ?? here; if (!url) throw new Error("new Sunk(baseUrl): pass the SUNK site's address, e.g. new Sunk(\"https://example.com\")"); this.baseUrl = url.replace(/\/+$/, ""); this.fetcher = fetcher ?? globalThis.fetch.bind(globalThis); } private async get(path: string, opts: PageOptions = {}): Promise { const q = new URLSearchParams(); if (opts.limit !== undefined) q.set("limit", String(opts.limit)); if (opts.before !== undefined && opts.before !== null) q.set("before", String(opts.before)); const qs = q.toString(); const url = `${this.baseUrl}${path}${qs ? `?${qs}` : ""}`; const res = await this.fetcher(url, { headers: { accept: "application/json" } }); if (!res.ok) throw new Error(`SUNK API ${res.status} for ${path}`); return (await res.json()) as T; } /** The house vault, the $SUNK mint (null until it's set), the launch cost and the split rules. */ config(): Promise { return this.get("/api/public/v1/config"); } /** Every coin on SUNK, launched or linked, newest first. */ coins(opts: PageOptions = {}): Promise> { return this.get>("/api/public/v1/coins", opts); } /** Every confirmed paired deposit (with its LP burn), newest first. */ payouts(opts: PageOptions = {}): Promise> { return this.get>("/api/public/v1/payouts", opts); } /** * Checks one deposit against Solana itself: the transaction exists and succeeded, `p.vault` signed it, and LP tokens * of `p.lp_mint` were burned in it (a burn instruction for that mint, or that mint's LP balance going down). */ async verifyPayout(p: SunkPayout, rpcUrl = "https://api.mainnet-beta.solana.com"): Promise { if (!p || !p.deposit_signature) return { ok: false, reason: "no deposit_signature on this payout" }; if (!p.vault) return { ok: false, reason: "no vault on this payout" }; if (!p.lp_mint) return { ok: false, reason: "no lp_mint on this payout" }; let tx: Json; try { tx = await rpc(this.fetcher, rpcUrl, "getTransaction", [ p.deposit_signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "confirmed" }, ]); } catch (e) { return { ok: false, reason: `RPC error: ${(e as Error).message}` }; } if (!tx) return { ok: false, reason: "transaction not found (not confirmed yet, or this RPC keeps no history for it)" }; const meta = tx.meta ?? {}; const success = meta.err === null || meta.err === undefined; if (!success) return { ok: false, reason: `the transaction failed: ${JSON.stringify(meta.err)}`, checks: { success, signer: false, burn: false, deposit: null } }; // jsonParsed gives every account as { pubkey, signer, writable } const keys: Json[] = tx.transaction?.message?.accountKeys ?? []; const signer = keys.some((k) => (typeof k === "string" ? false : k.pubkey === p.vault && k.signer === true)); // the burn: a burn / burnChecked of the LP mint, top level or inner (SUNK burns, then closes the LP account, so the // account is often gone afterwards and the balance check below can't see it) let burned = 0n; const ixs: Json[] = [ ...(tx.transaction?.message?.instructions ?? []), ...((meta.innerInstructions ?? []) as Json[]).flatMap((x) => x.instructions ?? []), ]; for (const ix of ixs) { const t = ix?.parsed?.type; const info = ix?.parsed?.info; if ((t === "burn" || t === "burnChecked") && info?.mint === p.lp_mint) { burned += BigInt(info.amount ?? info.tokenAmount?.amount ?? "0"); } } // ...or the LP balance going down const lpBal = (list: Json[] | undefined): bigint => (list ?? []).filter((b) => b.mint === p.lp_mint).reduce((s: bigint, b: Json) => s + BigInt(b.uiTokenAmount?.amount ?? "0"), 0n); const drop = lpBal(meta.preTokenBalances) - lpBal(meta.postTokenBalances); const burn = burned > 0n || drop > 0n; // informational: both of the pool's token accounts (owned by the pool) went up let deposit: boolean | null = null; if (p.pool) { const owned = (list: Json[] | undefined) => new Map((list ?? []).filter((b) => b.owner === p.pool).map((b) => [`${b.accountIndex}`, BigInt(b.uiTokenAmount?.amount ?? "0")])); const pre = owned(meta.preTokenBalances), post = owned(meta.postTokenBalances); let up = 0; for (const [k, v] of post) if (v > (pre.get(k) ?? 0n)) up++; deposit = post.size ? up >= 2 : null; } const checks = { success, signer, burn, deposit }; const amount = (burned > 0n ? burned : drop).toString(); if (!signer) return { ok: false, reason: `not signed by the vault ${p.vault}`, checks }; if (!burn) return { ok: false, reason: `no burn of the LP mint ${p.lp_mint} in this transaction`, checks }; return { ok: true, reason: `confirmed: signed by the vault, ${amount} LP burned${deposit === false ? " (pool balances not confirmed)" : ""}`, checks, burned: amount }; } } let rpcId = 0; async function rpc(fetcher: typeof fetch, url: string, method: string, params: unknown[]): Promise { const res = await fetcher(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: ++rpcId, method, params }), }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const j = (await res.json()) as Json; if (j.error) throw new Error(j.error.message ?? JSON.stringify(j.error)); return j.result; } export default Sunk;