// Intalio SDK: options on Hyperliquid, with a floor. One file, needs viem. // import { Intalio } from './intalio' // const io = new Intalio() // https://intalio.space // const q = await io.quote({ coin: 'HYPE', preset: 'call', strikePct: 100, days: 7, budget: 50 }) // const req = io.request('open', user, { coin: 'HYPE', preset: 'call', strikePct: 100, days: 7, budget: 50 }) // const signature = await walletClient.signTypedData({ account: user, ...io.typedData(req) }) // const { intent } = await io.open(req, signature); await io.waitIntent(intent) import { keccak256, stringToBytes, type Hex } from 'viem' 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' export interface Envelope { action: Action; user: Hex; nonce: number; deadline: number; body: Record } export const DOMAIN = { name: 'Intalio', version: '1', chainId: 99901 } as const export const TYPES = { Request: [ { name: 'action', type: 'string' }, { name: 'user', type: 'address' }, { name: 'payload', type: 'bytes32' }, { name: 'nonce', type: 'uint64' }, { name: 'deadline', type: 'uint64' }, ], } 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))) export class IntalioError extends Error { constructor(message: string, readonly status: number) { super(message) } } export class Intalio { constructor(readonly base = 'https://intalio.space') {} 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 IntalioError(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') } 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<{ leaf: Hex; minute: number; root: Hex; proof: Hex[]; contract: Hex | null; tx: Hex | null }>('/api/v1/proof/' + leaf) } me(user: Hex) { 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: Hex, body: Record = {}): Envelope { const now = Date.now() return { action, user, nonce: now, deadline: Math.floor(now / 1000) + 240, body: signable(body) } } /** EIP-712 typed data for viem signTypedData / eth_signTypedData_v4. */ typedData(r: Envelope) { return { domain: DOMAIN, types: TYPES, primaryType: 'Request' as const, message: { action: r.action, user: r.user, payload: payloadHash(r.body), nonce: BigInt(r.nonce), deadline: BigInt(r.deadline) }, } } agent(r: Envelope, signature: Hex) { return this.call<{ intent: number }>('/api/v1/agent', { method: 'POST', body: JSON.stringify({ request: r, signature }) }) } open(r: Envelope, signature: Hex) { return this.call<{ intent: number }>('/api/v1/positions', { method: 'POST', body: JSON.stringify({ request: r, signature }) }) } close(id: string, r: Envelope, signature: Hex) { return this.call<{ intent: number }>('/api/v1/positions/' + encodeURIComponent(id) + '/close', { method: 'POST', body: JSON.stringify({ request: r, signature }) }) } /** 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 IntalioError(it.error ?? 'failed', 400) if (Date.now() > end) throw new IntalioError('timed out waiting for the engine', 408) await new Promise((r) => setTimeout(r, 1000)) } } }