// Optisol SDK: options on Solana, with a floor, hedged on Pacifica. One file, needs viem, tweetnacl and bs58. // import { Keypair } from '@solana/web3.js' // import { Optisol } from './optisol' // const op = new Optisol() // https://optisol.cfd // const kp = Keypair.fromSecretKey(secret) // or any { publicKey, secretKey } ed25519 pair // const user = kp.publicKey.toBase58() // const q = await op.quote({ coin: 'SOL', preset: 'call', strikePct: 100, days: 7, budget: 50 }) // const req = op.request('open', user, { coin: 'SOL', preset: 'call', strikePct: 100, days: 7, budget: 50 }) // const signature = op.sign(req, kp.secretKey) // base58; in a browser: bs58.encode(await wallet.signMessage(messageBytes(req))) // const { intent } = await op.open(req, signature); await op.waitIntent(intent) import { keccak256, stringToBytes, type Hex } from 'viem' import nacl from 'tweetnacl' import bs58 from 'bs58' export type Preset = 'call' | 'put' | 'call_spread' | 'put_spread' | 'straddle' | 'strangle' | 'custom' export interface Leg { kind: 'call' | 'put'; strike: number; qty: number } export interface QuoteRequest { coin: string; preset: Preset; strikePct?: number; widthPct?: number; legs?: Leg[]; days: number; budget: number } export type Action = 'open' | 'close' | 'agent' /** user: the wallet's Solana address, base58 (case-sensitive: send it as it is). */ export interface Envelope { action: Action; user: string; nonce: number; deadline: number; body: Record } export const DOMAIN = { name: 'Optisol', version: '1', chain: 'solana:mainnet' } as const /** Canonical JSON: sorted keys, no spaces; integers only (write other numbers as decimal strings). */ export function canonicalJson(v: unknown): string { if (v === null) return 'null' if (typeof v === 'string' || typeof v === 'boolean') return JSON.stringify(v) if (typeof v === 'number') { if (!Number.isSafeInteger(v)) throw new TypeError('write non-integer numbers as decimal strings') return String(v) } if (Array.isArray(v)) return '[' + v.map(canonicalJson).join(',') + ']' if (typeof v === 'object') { const o = v as Record return '{' + Object.keys(o).filter((k) => o[k] !== undefined).sort().map((k) => JSON.stringify(k) + ':' + canonicalJson(o[k])).join(',') + '}' } throw new TypeError('unsupported value') } /** Non-integer numbers → decimal strings, undefined fields dropped. */ export function signable(body: T): T { const walk = (v: unknown): unknown => { if (typeof v === 'number') return Number.isSafeInteger(v) ? v : String(v) if (Array.isArray(v)) return v.map(walk) if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined).map(([k, x]) => [k, walk(x)])) return v } return walk(body) as T } export const payloadHash = (body: unknown): Hex => keccak256(stringToBytes(canonicalJson(body))) /** The exact text the wallet signs. Every field is on its own line, in this order. */ export function messageText(r: Envelope) { return [ `${DOMAIN.name} request v${DOMAIN.version}`, `chain: ${DOMAIN.chain}`, `action: ${r.action}`, `user: ${r.user}`, `payload: ${payloadHash(r.body)}`, `nonce: ${r.nonce}`, `deadline: ${r.deadline}`, ].join('\n') } /** The UTF-8 bytes of messageText: what a wallet's signMessage takes. */ export const messageBytes = (r: Envelope) => new TextEncoder().encode(messageText(r)) /** Signs any message with a 64-byte ed25519 secret key (a Solana Keypair's secretKey); returns base58. */ export const signBytes = (msg: Uint8Array, secretKey: Uint8Array) => bs58.encode(nacl.sign.detached(msg, secretKey)) /** Pacifica's signed message: compact JSON of { data, expiry_window, timestamp, type } with every object's keys sorted. */ export function sortKeys(v: unknown): unknown { if (Array.isArray(v)) return v.map(sortKeys) if (v && typeof v === 'object') { const o: Record = {} for (const k of Object.keys(v as Record).sort()) { const x = (v as Record)[k] if (x !== undefined) o[k] = sortKeys(x) } return o } return v } /** Pacifica's bind_agent_wallet message for the trading key Optisol made for this wallet. */ export function bindMessage(agentWallet: string, timestamp = Date.now(), expiryWindow = 5000) { return JSON.stringify(sortKeys({ type: 'bind_agent_wallet', timestamp, expiry_window: expiryWindow, data: { agent_wallet: agentWallet } })) } /** A decision's leaf hash: keccak256("optisol.leaf.v1" ‖ json). */ export const leafHash = (json: string): Hex => keccak256(stringToBytes('optisol.leaf.v1' + json)) /** A seal memo: "optisol.root.v1 m= r= n=", found in a seal transaction's log messages. */ export function parseMemo(s: string) { const m = s.match(/optisol\.root\.v1 m=(\d+) r=(0x[0-9a-f]{64}) n=(\d+)/) return m ? { minute: Number(m[1]) * 1000, root: m[2] as Hex, count: Number(m[3]) } : null } export class OptisolError extends Error { constructor(message: string, readonly status: number) { super(message) } } export class Optisol { constructor(readonly base = 'https://optisol.cfd') {} private async call(path: string, init?: RequestInit): Promise { const res = await fetch(this.base + path, { ...init, headers: { 'content-type': 'application/json', ...(init?.headers ?? {}) } }) const j = (await res.json().catch(() => ({}))) as { data?: T; error?: string } if (!res.ok || j.error) throw new OptisolError(j.error ?? 'HTTP ' + res.status, res.status) return j.data as T } status() { return this.call>('/api/v1/status') } markets() { return this.call>>('/api/v1/markets') } board(sort = 'move', group = 'all') { return this.call>('/api/v1/board?sort=' + sort + '&group=' + group) } protect(user?: string, days = 7) { return this.call>('/api/v1/protect?days=' + days + (user ? '&user=' + user : '')) } replay(p: { coin?: string; preset?: 'call' | 'put' | 'straddle'; budget?: number; start?: string; days?: number } = {}) { const q = new URLSearchParams(Object.entries(p).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])) return this.call>('/api/v1/replay?' + q.toString()) } surface(coin: string) { return this.call>('/api/v1/surface/' + encodeURIComponent(coin)) } quote(q: QuoteRequest) { return this.call>('/api/v1/quote', { method: 'POST', body: JSON.stringify(q) }) } book() { return this.call>('/api/v1/book') } position(id: string) { return this.call>('/api/v1/positions/' + encodeURIComponent(id)) } record(limit = 30) { return this.call>>('/api/v1/record?limit=' + limit) } proof(leaf: Hex) { return this.call>('/api/v1/proof/' + leaf) } rules() { return this.call>('/api/v1/rules') } me(user: string) { return this.call>('/api/v1/me?user=' + user) } intent(id: number) { return this.call<{ id: number; status: 'new' | 'taken' | 'done' | 'failed'; result: unknown; error: string | null }>('/api/v1/intents/' + id) } /** A request to sign: nonce = now (ms), deadline = now + 4 minutes. */ request(action: Action, user: string, body: Record = {}): Envelope { const now = Date.now() return { action, user, nonce: now, deadline: Math.floor(now / 1000) + 240, body: signable(body) } } /** The text to sign (wallet signMessage takes messageBytes(r)). */ message(r: Envelope) { return messageText(r) } /** Signs the request with a Solana Keypair's 64-byte secretKey (ed25519); returns the base58 signature. */ sign(r: Envelope, secretKey: Uint8Array) { return signBytes(messageBytes(r), secretKey) } agent(r: Envelope, signature: string) { return this.call<{ intent: number }>('/api/v1/agent', { method: 'POST', body: JSON.stringify({ request: r, signature }) }) } open(r: Envelope, signature: string) { return this.call<{ intent: number }>('/api/v1/positions', { method: 'POST', body: JSON.stringify({ request: r, signature }) }) } close(id: string, r: Envelope, signature: string) { return this.call<{ intent: number }>('/api/v1/positions/' + encodeURIComponent(id) + '/close', { method: 'POST', body: JSON.stringify({ request: r, signature }) }) } /** Relays a wallet-signed bind_agent_wallet to Pacifica (signature: base58 of the wallet's signature of bindMessage). */ bind(b: { account: string; agent_wallet: string; signature: string; timestamp: number; expiry_window: number }) { return this.call<{ agent: { address: string | null; approved: boolean } }>('/api/v1/agent/bind', { method: 'POST', body: JSON.stringify(b) }) } /** * Approves trading once, with a Keypair: creates the wallet's trading key (an "agent" request), then signs * Pacifica's bind_agent_wallet for it and relays it. The key can trade the Pacifica account, never withdraw. */ async approveTrading(kp: { publicKey: { toBase58(): string }; secretKey: Uint8Array }) { const user = kp.publicKey.toBase58() const req = this.request('agent', user) const { intent } = await this.agent(req, this.sign(req, kp.secretKey)) const res = (await this.waitIntent(intent)) as { agent: string; approved: boolean } if (res.approved) return res const timestamp = Date.now(), expiry_window = 5000 const signature = signBytes(new TextEncoder().encode(bindMessage(res.agent, timestamp, expiry_window)), kp.secretKey) return this.bind({ account: user, agent_wallet: res.agent, signature, timestamp, expiry_window }) } /** Polls an intent until it is done or failed (default 60 s). */ async waitIntent(id: number, timeoutMs = 60_000) { const end = Date.now() + timeoutMs for (;;) { const it = await this.intent(id) if (it.status === 'done') return it.result if (it.status === 'failed') throw new OptisolError(it.error ?? 'failed', 400) if (Date.now() > end) throw new OptisolError('timed out waiting for the engine', 408) await new Promise((r) => setTimeout(r, 1000)) } } }