// Sennet client for TypeScript / JavaScript (Node 18+, Bun, Deno). One file, no dependencies: copy it into your project. // Your keys and signer stay with you: Sennet only reserves, leases and records. export type Asset = "SOL" | "USDC" | (string & {}); export interface Reservation { id: string; worker: string; asset: string; amount: string; spent: string | null; state: "held" | "submitted" | "settled" | "released" | "expired"; signature: string | null; idem_key: string | null; nonce: string | null; memo: string | null; created_at: number; expires_at: number; updated_at: number; } export interface Reserved extends Reservation { replay: boolean; blockhash?: { blockhash: string; last_valid_block_height: number } | null; blockhash_error?: string; nonce_value?: string | null; } export interface ReserveInput { asset: Asset; amount: string | bigint | number; ttl_s?: number; idempotency_key?: string; blockhash?: boolean; nonce?: boolean; memo?: string; } export interface OnceClaim { status: "claimed"; key: string; token: string; lease_until: number; attempt: number; recovered: boolean; previous_worker?: string } export interface OnceDone { status: "done"; key: string; result: T; worker: string; done_at: number } export class SennetError extends Error { constructor(public status: number, public code: string, message: string, public body: Record) { super(message); } } export class Sennet { readonly url: string; readonly key: string; readonly worker: string; private f: typeof fetch; constructor(opts: { url: string; key: string; worker: string; fetch?: typeof fetch }) { if (!opts.url || !opts.key || !opts.worker) throw new Error("Sennet needs url, key and worker"); this.url = opts.url.replace(/\/+$/, ""); this.key = opts.key; this.worker = opts.worker; this.f = opts.fetch ?? fetch; } async request(method: string, path: string, body?: unknown): Promise { const res = await this.f(this.url + path, { method, headers: { Authorization: "Bearer " + this.key, ...(body !== undefined ? { "Content-Type": "application/json" } : {}) }, body: body === undefined ? undefined : JSON.stringify(body), }); const data = (await res.json().catch(() => ({}))) as Record; if (!res.ok) throw new SennetError(res.status, String(data.error ?? "http_" + res.status), String(data.message ?? res.statusText), data); return data as T; } state() { return this.request("GET", "/api/v1/state"); } blockhash() { return this.request<{ blockhash: string; last_valid_block_height: number }>("GET", "/api/v1/blockhash"); } sync() { return this.request("POST", "/api/v1/sync"); } /** Hold `amount` for this worker. Throws SennetError code "insufficient" when not enough is free. */ reserve(input: ReserveInput) { return this.request("POST", "/api/v1/reserve", { ...input, amount: String(input.amount), worker: this.worker }); } submit(id: string, signature: string) { return this.request("POST", `/api/v1/reservations/${id}/submit`, { signature }); } settle(id: string, opts: { spent?: string | bigint | number; signature?: string } = {}) { return this.request("POST", `/api/v1/reservations/${id}/settle`, { ...opts, ...(opts.spent !== undefined ? { spent: String(opts.spent) } : {}) }); } release(id: string) { return this.request("POST", `/api/v1/reservations/${id}/release`, {}); } reservation(id: string) { return this.request("GET", `/api/v1/reservations/${id}`); } /** Reserve, run `send` (sign + send with your own signer, return the signature), then submit. * If `send` throws, the reservation is released and the error is rethrown. */ async spend(input: ReserveInput, send: (r: Reserved) => Promise) { const r = await this.reserve(input); let sig: string; try { sig = await send(r); } catch (e) { await this.release(r.id).catch(() => {}); throw e; } return this.submit(r.id, sig); } claimOnce(key: string, ttl_s?: number) { return this.request("POST", "/api/v1/once/claim", { key, worker: this.worker, ...(ttl_s ? { ttl_s } : {}) }); } completeOnce(key: string, token: string, result?: unknown) { return this.request("POST", "/api/v1/once/complete", { key, token, result }); } abandonOnce(key: string, token: string) { return this.request("POST", "/api/v1/once/abandon", { key, token }); } /** Run `fn` once across the whole fleet for `key`. Returns the stored result if it already ran. * While another worker holds the key, waits (up to `waitMs`) for its result. * If an earlier claim lapsed unfinished, `recover` runs first: return a value to record it without * running `fn` (e.g. you found the account already exists on chain), or undefined to run `fn`. */ async once(key: string, fn: () => Promise, opts: { ttl_s?: number; waitMs?: number; recover?: (c: OnceClaim) => Promise } = {}): Promise { const deadline = Date.now() + (opts.waitMs ?? 60_000); for (let delay = 250; ; delay = Math.min(delay * 2, 4000)) { let c: OnceClaim | OnceDone; try { c = await this.claimOnce(key, opts.ttl_s); } catch (e) { if (e instanceof SennetError && e.code === "running" && Date.now() < deadline) { await new Promise((r) => setTimeout(r, delay)); continue; } throw e; } if (c.status === "done") return c.result as T; let result: T | undefined; try { if (c.recovered && opts.recover) result = await opts.recover(c); if (result === undefined) result = await fn(); } catch (e) { await this.abandonOnce(key, c.token).catch(() => {}); throw e; } await this.completeOnce(key, c.token, result ?? null); return result as T; } } leaseNonce(ttl_s?: number) { return this.request<{ address: string; token: string; lease_until: number; nonce_value: string | null }>("POST", "/api/v1/nonces/lease", { worker: this.worker, ...(ttl_s ? { ttl_s } : {}) }); } returnNonce(address: string, token: string) { return this.request("POST", "/api/v1/nonces/return", { address, token }); } }