// The HTTP surface of the Idle GPU cloud, kept free of sockets so it can be tested with plain objects. // // Public // GET /v1/health what is open and what is not, and why // GET /v1/gpus the rates: the provider's live prices plus Idle's margin when a provider is // configured, otherwise the target rate card with `available: 0` // GET /v1/quote what `seconds` on one GPU costs ?gpu=h100&seconds=1200 // GET /v1/market the live facts: HYPE, Nvidia on HyperCore, the head of Elysium, USDC and EQNVDA on Elysium // GET /v1/credits/quote what an amount of USDC or EQNVDA would buy in credits ?token=EQNVDA&amount=1.5 // GET /v1/offers whole Nvidia GPUs on offer on the market (Runpod list prices, Vast.ai live offers) // GET /v1/route idle/auto: the offer that fits, by a stated rule ?minVram=24&prefer=cheapest // GET /v1/openapi.json every route, as an OpenAPI 3.1 document generated from routes.mjs // POST /mcp the MCP server for agents (mcp.mjs): each tool is one of the routes here // POST /v1/auth/challenge {address} -> a message for the wallet to sign // POST /v1/auth/verify {address, signature} -> a session token, good for 24 hours // POST /rpc the scoped relayer: Elysium reads, and USDC or EQNVDA transfers to the treasury // Signed in (Authorization: Bearer , or where marked *) // GET /v1/me * credits, SSH keys, API keys, instances // POST /v1/ssh-keys {name, publicKey} // DELETE /v1/ssh-keys/:id // POST /v1/instances * {gpu, sshKeyIds?} -> the instance // GET /v1/instances * GET /v1/instances/:id * // POST /v1/instances/:id/end * -> the receipt // POST /v1/credits/claim * {txHash} a USDC or an EQNVDA transfer to the treasury // GET /v1/ledger * // POST /v1/api-keys {name, capUsdPerDay} -> the key, with its secret shown once // POST /v1/api-keys/:id/stop DELETE /v1/api-keys/:id // Operator // GET /v1/tick Authorization: Bearer . Settles, asks the provider, releases machines. // // The routes themselves are listed once, in routes.mjs: the router below dispatches from that table and refuses // to start if a row has no handler or a handler has no row. // // It never claims what it does not have. With nothing configured it is the rate card and the live figures, and // every other route answers 503 `not-open`. `rentals` is true only with a real provider, a treasury, a session // secret and a durable state store. Errors are JSON: {error: "", message}. import { timingSafeEqual } from "node:crypto"; import { getAddress } from "ethers"; import { GPUS, findGpu, quote } from "./rates.mjs"; import * as E from "./engine.mjs"; import { transact } from "./store.mjs"; import { API_KEY_PREFIX, challenge, hashApiKey, newApiKey, normalAddress, readSession, verifySignIn } from "./auth.mjs"; import { formatAmount, parseAmount, priceEquity, readTopup } from "./credits.mjs"; import { ELYSIUM } from "./market.mjs"; import { ROUTES, matchRoute, openapi } from "./routes.mjs"; import { PREFER, SOURCES, TIER_ORDER, chooseOffer, filterOffers } from "./offers.mjs"; import { MCP_VERSIONS, createMcp } from "./mcp.mjs"; const VERSION = "0.4.0"; import { createRelayer } from "./relayer.mjs"; import { ELYSIUM_CREDITS, readCredits, readCreditsAccount } from "./contract.mjs"; function limiter(max, windowMs, now) { const hits = new Map(); return (key) => { const t = now(); const list = (hits.get(key) ?? []).filter((x) => t - x < windowMs); if (list.length >= max) { hits.set(key, list); return false; } list.push(t); hits.set(key, list); if (hits.size > 5000) for (const [k, v] of hits) if (!v.some((x) => t - x < windowMs)) hits.delete(k); return true; }; } const CLOSED = "No GPU is listed yet. Rentals are not open."; const round = (x, d) => Math.round(x * 10 ** d) / 10 ** d; const usd = (micro) => micro / 1e6; // The HTTP status each error code travels with. const STATUS = { invalid: 400, "bad-json": 400, "unknown-gpu": 400, "no-ssh-key": 400, moved: 400, unauthorized: 401, "insufficient-credits": 402, "key-cap": 402, "key-stopped": 403, "session-required": 403, "not-found": 404, "tx-not-found": 404, "no-offer": 404, limit: 409, duplicate: 409, "already-claimed": 409, "no-capacity": 409, unconfirmed: 409, "too-large": 413, "tx-reverted": 422, "wrong-token": 422, "wrong-sender": 422, "wrong-recipient": 422, "no-transfer": 422, "too-old": 422, "ambiguous-transfer": 422, "too-small": 422, "price-unstable": 409, "rate-limited": 429, "server-error": 500, provider: 502, "chain-unreachable": 502, "sources-unavailable": 502, "not-open": 503, busy: 503, starting: 503, "price-unavailable": 503, }; /** * @param {object} cfg * origins, readsPer10s, writesPerMinute, sendsPerMinute, mcpPerMinute CORS and rate limits * apiBase, mcpAllowOrigin the public address of the API; which Origin may call /mcp * sessionSecret, treasury, cronSecret the secrets and the address that open the engine * usdc, chainId, marginBps, minConfirmations, claimMinBlock, domain, podPrefix, tickMaxAgeMs, inbox * eqnvda, equityHaircutBps, equityMaxGapBps paying with tokenized Nvidia (credits.mjs) * @param {object} deps * market() the live figures (market.mjs) * offers() the market offers (offers.mjs) * store {load, save} (store.mjs) * provider a provider (provider.mjs) * chain(method, params) a JSON-RPC call to Elysium * post(raw) posts a signed transaction into the inbox; absent without a gas account * now, log, random, sleep */ export function createApp(cfg, deps) { const now = deps.now ?? Date.now; const log = deps.log ?? (() => {}); const provider = deps.provider ?? null; const store = deps.store ?? null; const chainId = cfg.chainId ?? 99901; const usdc = (cfg.usdc ?? ELYSIUM.usdc).toLowerCase(); const eqnvda = (cfg.eqnvda ?? ELYSIUM.eqnvda).toLowerCase(); const haircutBps = cfg.equityHaircutBps ?? 100; const maxGapBps = cfg.equityMaxGapBps ?? 300; const PRICED_BY = "min of the Uniswap v4 pool on Elysium and Hyperliquid's xyz:NVDA"; const treasury = normalAddress(cfg.treasury); // The credits contract (IdleCredits). Absent from a configuration, nothing about it is served or carried. const credits = normalAddress(cfg.credits); const creditsCfg = credits ? { address: credits, tokens: [{ symbol: "USDC", address: usdc, decimals: 6 }, { symbol: "EQNVDA", address: eqnvda, decimals: cfg.eqnvdaDecimals ?? 8 }] } : null; const CONTRACT_NOTE = "The contract is deployed and takes deposits and withdrawals. The rental engine does not read or charge these balances yet: a balance held here cannot be spent on a rental today, and can always be withdrawn after the delay. Not audited."; const marginBps = cfg.marginBps ?? 2000; const minConfirmations = cfg.minConfirmations ?? 2; const domain = cfg.domain ?? "idle-elysium.vercel.app"; const prefix = cfg.podPrefix ?? "idle"; const tickMaxAgeMs = cfg.tickMaxAgeMs ?? 300_000; const missing = [ !provider && "a GPU provider (RUNPOD_API_KEY)", !cfg.sessionSecret && "SESSION_SECRET", !treasury && "TREASURY_ADDRESS", !store && "a state store (BLOB_READ_WRITE_TOKEN)", !deps.chain && "an Elysium RPC", ].filter(Boolean); const open = missing.length === 0; const mode = !open ? "closed" : provider.real ? "live" : "test"; const rentals = mode === "live"; const readLimit = limiter(cfg.readsPer10s ?? 120, 10_000, now); const writeLimit = limiter(cfg.writesPerMinute ?? 60, 60_000, now); const sendLimit = limiter(cfg.sendsPerMinute ?? 10, 60_000, now); const mcpLimit = limiter(cfg.mcpPerMinute ?? 120, 60_000, now); const relayer = deps.chain ? createRelayer({ chainId, usdc, eqnvda, treasury, credits }, { upstream: deps.chain, post: deps.post ?? null, allowRead: readLimit, allowSend: sendLimit, log }) : null; const tx = (fn) => transact(store, fn, { sleep: deps.sleep }); const fail = (error, message, extra = {}) => ({ ok: false, error, message, ...extra }); // ---- Rates: the provider's price plus the margin, read at most once a minute ---- let rates = null; const targetCard = (error) => ({ source: "target", error: error ?? null, gpus: GPUS.map((g) => ({ ...g, rate: Math.round(g.usdPerHour * 1e6), available: 0, stock: "none" })) }); async function catalogue() { if (!open) return targetCard(); const t = now(); if (rates && t - rates.at < 60_000) return rates; let list; try { list = await provider.listGpus(); } catch (e) { log({ event: "provider-error", call: "listGpus", code: e?.code, detail: e?.detail ?? String(e?.message ?? e) }); return targetCard("the GPU provider did not answer; these are target rates"); } rates = { at: t, source: "provider", error: null, gpus: GPUS.map((g) => { const p = list.find((x) => x.id === g.id); // A GPU the provider does not list keeps its target rate and cannot be rented. if (!p) return { ...g, rate: Math.round(g.usdPerHour * 1e6), available: 0, stock: "none", listed: false }; const rate = E.rateFor(p.usdPerHour, marginBps); return { id: g.id, name: g.name, vram: p.vramGb ?? g.vram, usdPerHour: usd(rate), rate, available: p.available ? 1 : 0, stock: p.stock ?? (p.available ? "high" : "none"), listed: true }; }), }; return rates; } const row = (g, hypeMid) => ({ id: g.id, name: g.name, vram: g.vram, vramGb: g.vram, usdPerHour: g.usdPerHour, usdPerSecond: round(g.usdPerHour / 3600, 8), hypePerHour: hypeMid > 0 ? round(g.usdPerHour / hypeMid, 6) : null, available: g.available, stock: g.stock, }); /** The live figures, or null. A source that is down never becomes a guess. */ async function figures() { try { return await deps.market(); } catch { return null; } } /** The credits contract as the chain describes it, read at most once every ten seconds. Null when it cannot be read. */ let contractSeen = null; async function contract() { if (!creditsCfg || !deps.chain) return null; if (contractSeen && now() - contractSeen.at < 10_000) return contractSeen.value; try { const value = { ...(await readCredits(deps.chain, creditsCfg)), asOf: new Date(now()).toISOString() }; contractSeen = { at: now(), value }; return value; } catch { return null; } } /** EQNVDA as the chain and Hyperliquid describe it right now, when it is the token this app is configured for. */ const equityIn = (m) => (m?.equity && String(m.equity.token).toLowerCase() === eqnvda ? m.equity : null); const priceOf = (eq, amount) => priceEquity({ amount, decimals: eq?.decimals, poolPriceUsd: eq?.poolPriceUsd ?? null, markUsd: eq?.markUsd ?? null, haircutBps, maxGapBps }); // ---- Who is asking ---- const bearer = (auth) => (typeof auth === "string" && /^Bearer\s+\S+$/i.test(auth.trim()) ? auth.trim().split(/\s+/)[1] : null); /** Returns {ok, check(state)}: `check` names the caller inside a transaction, on the state it reads. */ function caller(auth, { sessionOnly = false } = {}) { const token = bearer(auth); if (!token) return fail("unauthorized", "Sign in first: send Authorization: Bearer ."); if (token.startsWith(API_KEY_PREFIX)) { if (sessionOnly) return fail("session-required", "This needs the wallet's own session, not an API key."); const hash = hashApiKey(token); return { ok: true, check(state) { const r = E.resolveApiKey(state, hash); if (!r) return fail("unauthorized", "Unknown API key."); if (r.key.stopped) return fail("key-stopped", "This API key is stopped."); return { ok: true, address: r.address, keyId: r.key.id, via: "api-key" }; }, }; } const address = readSession(cfg.sessionSecret, token, now()); if (!address) return fail("unauthorized", "The session is invalid or has expired. Sign in again."); return { ok: true, check: () => ({ ok: true, address, keyId: null, via: "session" }) }; } // ---- Talking to the provider after the state says what is owed ---- /** Asks the provider about `work.poll`, writes what it says, then terminates what is ended. `rerun` recomputes an answer on the fresh state. */ async function sync(work, { address = null, rerun = null } = {}) { const seen = ( await Promise.all( work.poll.map(async (p) => { try { return { id: p.id, obs: await provider.get(p.providerId) }; } catch (e) { log({ event: "provider-error", call: "get", id: p.id, code: e?.code, detail: e?.detail ?? String(e?.message ?? e) }); return null; } }), ) ).filter(Boolean); let release = work.release; let res; if (seen.length) { const t = now(); const r = await tx((state) => { for (const s of seen) E.observe(state, { id: s.id, obs: s.obs, now: t }); return { release: E.pending(state, { address }).release, res: rerun ? rerun(state, t) : undefined }; }); release = r.release; res = r.res; } const done = ( await Promise.all( release.map(async (r) => { try { await provider.terminate(r.providerId); return r.id; } catch (e) { log({ event: "provider-error", call: "terminate", id: r.id, code: e?.code, detail: e?.detail ?? String(e?.message ?? e) }); return null; } }), ) ).filter(Boolean); if (done.length) { const t = now(); await tx((state) => { for (const id of done) E.released(state, { id, now: t }); }); } return { res, polled: seen.length, released: done.length }; } /** * One signed-in request: name the caller, settle everything up to now, run `fn` on the state, then do with the * provider whatever the state now asks for. `refresh` reruns `fn` after the provider answered (for reads). */ async function signedIn(auth, opts, fn) { if (!open) return fail("not-open", CLOSED); const who = caller(auth, opts); if (!who.ok) return who; const t = now(); let me = null; const first = await tx((state) => { me = who.check(state); if (!me.ok) return { res: me, work: { poll: [], release: [] } }; E.settle(state, t); E.expire(state, t); return { res: fn(state, me, t), work: E.pending(state, { address: me.address, now: t, minGapMs: 4000 }) }; }); if (first.work.poll.length === 0 && first.work.release.length === 0) return first.res; const again = await sync(first.work, { address: me.address, rerun: opts.refresh && first.res?.ok !== false ? (state, t2) => fn(state, me, t2) : null }); return again.res ?? first.res; } const mine = (state, me, id) => { const inst = state.instances[id]; return inst && inst.address === me.address ? inst : null; }; const zeroReceipt = (inst) => ({ id: null, at: new Date(inst.endedAt ?? inst.createdAt).toISOString(), type: "charge", usd: 0, deltaUsd: 0, instanceId: inst.id, gpu: inst.gpu, secondsBilled: 0, reason: inst.reason, ratePerHourUsd: usd(inst.rate), startedAt: null, endedAt: new Date(inst.endedAt ?? inst.createdAt).toISOString() }); // ---- Routes that need more than one step ---- async function rentRoute(auth, body) { if (!open) return fail("not-open", CLOSED); const who = caller(auth); if (!who.ok) return who; const cat = await catalogue(); const g = cat.gpus.find((x) => x.id === String(body.gpu ?? "").toLowerCase()); if (!g) return fail("unknown-gpu", "Unknown GPU.", { gpus: GPUS.map((x) => x.id) }); if (cat.source !== "provider") return fail("provider", "The GPU provider did not answer, so there is no price to rent at. Try again in a moment."); if (!g.listed || g.available === 0) return fail("no-capacity", `No ${g.name} is available right now.`); const t = now(); let me = null; const booked = await tx((state) => { me = who.check(state); if (!me.ok) return me; E.settle(state, t); E.expire(state, t); // No rental starts unless the meter runs: without a regular tick nothing would stop a machine whose // renter ran out of credits. if (tickMaxAgeMs > 0 && t - (state.tickAt ?? 0) > tickMaxAgeMs) return fail("not-open", "The meter is not running (no settlement tick in the last minutes), so no rental can start."); return E.rent(state, { address: me.address, gpu: g.id, gpuName: g.name, rate: g.rate, sshKeyIds: body.sshKeyIds, keyId: me.keyId, now: t }); }); if (!booked.ok) return booked; const id = booked.instance.id; let created; try { created = await provider.create({ gpuId: g.id, sshPublicKeys: booked.publicKeys, name: `${prefix}-${id}` }); } catch (e) { log({ event: "provider-error", call: "create", id, code: e?.code, detail: e?.detail ?? String(e?.message ?? e) }); const code = e?.code === "no-capacity" ? "no-capacity" : "provider"; const t2 = now(); await tx((state) => E.failInstance(state, { id, reason: code, now: t2 })); return fail(code, code === "no-capacity" ? `No ${g.name} could be placed right now. Nothing was charged.` : "The GPU provider refused the request. Nothing was charged.", { instanceId: id }); } const t3 = now(); const attached = await tx((state) => { const r = E.attach(state, { id, providerId: created.providerId, now: t3 }); return { live: r.live, view: E.viewInstance(state.instances[id]), work: E.pending(state, { address: me.address }) }; }); if (!attached.live) await sync({ poll: [], release: attached.work.release }, { address: me.address }); log({ event: "rented", id, gpu: g.id, address: me.address, rate: g.rate }); return { ok: true, status: 201, body: attached.view }; } async function claimRoute(auth, body) { if (!open) return fail("not-open", CLOSED); const who = caller(auth); if (!who.ok) return who; // An API key is named by the state; a session names itself. const me = await tx((state) => who.check(state)); if (!me.ok) return me; const top = await readTopup({ rpc: deps.chain, txHash: body.txHash, from: me.address, treasury, usdc, equity: eqnvda, chainId, minConfirmations, minBlock: cfg.claimMinBlock ?? 0 }); if (!top.ok) return top; // USDC is its own price: one base unit is one micro-dollar. EQNVDA is priced now, at the lower of the pool // and the mark, less the haircut; if it cannot be priced the claim is refused and can be made again later. let micro = Number(top.amount); let paid = { token: "USDC", amount: formatAmount(top.amount, 6), priceUsd: 1 }; if (top.token === "EQNVDA") { const eq = equityIn(await figures()); const p = priceOf(eq, top.amount); if (!p.ok) return p; if (p.micro <= 0) return fail("too-small", "This amount of EQNVDA is worth less than a millionth of a dollar. Nothing was credited."); micro = p.micro; paid = { token: "EQNVDA", amount: formatAmount(top.amount, eq.decimals), poolPriceUsd: p.poolPriceUsd, markUsd: p.markUsd, priceUsd: p.priceUsd, haircutBps: p.haircutBps }; } const txHash = String(body.txHash).toLowerCase(); const t = now(); const r = await tx((state) => { const c = E.claim(state, { address: me.address, txHash, micro, block: top.block, now: t, paid }); return c.ok ? { ok: true, body: { ok: true, txHash, token: paid.token, amount: paid.amount, priceUsd: paid.priceUsd, creditedUsd: usd(micro), creditsUsd: usd(c.credits), block: top.block, confirmations: top.confirmations, entry: E.viewEntry(c.entry) } } : c; }); if (r.ok) log({ event: "claimed", address: me.address, txHash, token: paid.token, amount: paid.amount, micro }); return r; } async function tickRoute(auth) { if (!cfg.cronSecret) return fail("not-open", "CRON_SECRET is not set: the tick is closed."); const got = Buffer.from(bearer(auth) ?? ""); const want = Buffer.from(cfg.cronSecret); if (got.length !== want.length || !timingSafeEqual(got, want)) return fail("unauthorized", "Wrong tick secret."); if (!open) return { ok: true, body: { ok: true, mode, note: "Nothing to settle: the engine is not open." } }; const t = now(); const first = await tx((state) => { const s = E.settle(state, t); const x = E.expire(state, t); const p = E.prune(state, t); E.markTick(state, t); return { ended: s.ended.length, expired: x.failed.length, pruned: p.pruned, work: E.pending(state, { running: true }) }; }); // Machines on the provider account that the state does not track: a request that died between creating // the machine and recording its id leaves one. Such a machine is tied back to its instance (and from there // polled or released like any other); one that no instance ever knew is terminated once it is 15 minutes old. // This is what keeps a lost write from leaving a paid machine running. let work = first.work; let adopted = 0; let unowned = []; try { const pods = await provider.list(); const t2 = now(); const rec = await tx((state) => { const r = E.reconcile(state, { pods, prefix, now: t2 }); for (const a of r.adopt) E.attach(state, { id: a.id, providerId: a.providerId, now: t2 }); return { ...r, work: E.pending(state, { running: true }) }; }); adopted = rec.adopt.length; unowned = rec.terminate; work = rec.work; } catch (e) { if (e?.code === "state-missing" || e?.code === "busy") throw e; log({ event: "provider-error", call: "list", code: e?.code, detail: e?.detail ?? String(e?.message ?? e) }); } const s = await sync(work); let orphans = 0; for (const providerId of unowned) { try { await provider.terminate(providerId); orphans++; log({ event: "orphan-terminated", providerId }); } catch (e) { log({ event: "provider-error", call: "terminate", providerId, code: e?.code, detail: e?.detail ?? String(e?.message ?? e) }); } } const after = await tx((state) => { const all = Object.values(state.instances); return { starting: all.filter((i) => i.status === "starting" || i.status === "requested").length, running: all.filter((i) => i.status === "running").length, unreleased: E.pending(state).release.length }; }); return { ok: true, body: { ok: true, mode, at: new Date(t).toISOString(), endedBySettlement: first.ended, expired: first.expired, pruned: first.pruned, polled: s.polled, released: s.released, adopted, orphansTerminated: orphans, instances: after } }; } // ---- Market offers and routing (public, and the same whether rentals are open or not) ---- const readOffers = deps.offers ?? (async () => ({ offers: [], sources: [], errors: ["offers: no source is configured"], asOf: null })); const NOT_IDLES = "These are market offers read from the named sources, not Idle's machines: Idle holds no GPU of its own."; /** The constraints of /v1/offers and /v1/route, read from the query string. */ function constraints(query) { const c = { gpu: null, minVram: 0, secure: null, limit: 50, prefer: "cheapest" }; if (query.gpu !== undefined && query.gpu !== "") { const g = findGpu(query.gpu); if (!g) return fail("unknown-gpu", "Unknown GPU.", { gpus: GPUS.map((x) => x.id) }); c.gpu = g.id; } if (query.minVram !== undefined && query.minVram !== "") { c.minVram = Number(query.minVram); if (!Number.isFinite(c.minVram) || c.minVram < 0 || c.minVram > 4096) return fail("invalid", "minVram must be a number of GB, 0 or more."); } if (query.secure !== undefined && query.secure !== "") { const s = String(query.secure).toLowerCase(); if (!["true", "false", "1", "0"].includes(s)) return fail("invalid", "secure must be true or false."); c.secure = s === "true" || s === "1"; } if (query.limit !== undefined && query.limit !== "") { c.limit = Number(query.limit); if (!Number.isInteger(c.limit) || c.limit < 1 || c.limit > 200) return fail("invalid", "limit must be a whole number from 1 to 200."); } if (query.prefer !== undefined && query.prefer !== "") { c.prefer = String(query.prefer).toLowerCase(); if (!PREFER.includes(c.prefer)) return fail("invalid", "prefer must be one of " + PREFER.join(", ") + ".", { prefer: PREFER }); } return { ok: true, ...c }; } // ---- The MCP server: every tool is one call to a route below, made without the per-address limits ---- const serverInfo = { name: "idle-gpu", title: "Idle, the GPU cloud on Elysium", version: VERSION }; const mcp = createMcp({ info: serverInfo, log, status: () => ({ open, missing }), allowOrigin: cfg.mcpAllowOrigin ?? (cfg.origins?.length ? (o) => cfg.origins.includes(o) : () => true), rest: async (r) => { const x = await dispatch({ ...r, ip: "mcp" }, false); return { status: x.status, body: x.body ? JSON.parse(x.body) : null }; }, }); const openTools = () => mcp.tools.filter((t) => open || !mcp.accountTools.includes(t)); // ---- The routes: one handler per row of routes.mjs ---- // A handler gets {params, query, json, body, auth, ip, origin, headers, out, refuse, answer, noStore, raw}. const signIn = (c) => { c.noStore(); if (!open) return c.refuse("not-open", CLOSED); const address = normalAddress(c.json.address); if (!address) return c.refuse("invalid", "address must be a wallet address (0x and 40 hex characters)."); return address; }; const viaMcp = (httpMethod) => async (c) => { c.noStore(); const r = await mcp.handle({ httpMethod, headers: c.headers, body: c.body, auth: c.auth, origin: c.origin }); return c.raw(r.status, r.body === null ? "" : JSON.stringify(r.body), r.headers); }; const handlers = { "POST /v1/rent": async (c) => (open ? c.refuse("moved", "Rent with POST /v1/instances.") : c.out(503, { error: "not-open", message: CLOSED, rentals })), // The relayer speaks JSON-RPC, errors included. "POST /rpc": async (c) => { c.noStore(); const rpcErr = (code, message) => c.out(200, { jsonrpc: "2.0", id: null, error: { code, message } }); if (!relayer) return rpcErr(-32000, "not-open: no Elysium RPC is configured"); let json = c.body; if (typeof c.body === "string") { try { json = JSON.parse(c.body); } catch { return rpcErr(-32700, "parse error"); } } return c.out(200, await relayer.rpc(json, c.ip)); }, "POST /mcp": viaMcp("POST"), "GET /mcp": viaMcp("GET"), "DELETE /mcp": viaMcp("DELETE"), // ---- Sign-in ---- "POST /v1/auth/challenge": async (c) => { const address = signIn(c); return typeof address === "string" ? c.out(200, challenge({ secret: cfg.sessionSecret, address, now: now(), domain, chainId })) : address; }, "POST /v1/auth/verify": async (c) => { const address = signIn(c); if (typeof address !== "string") return address; const r = verifySignIn({ secret: cfg.sessionSecret, address, signature: c.json.signature, now: now(), domain, chainId }); if (!r.ok) return c.refuse("unauthorized", "The signature does not match a current challenge for this address. Ask for a new challenge and sign it."); return c.out(200, { token: r.token, address: r.address, expiresAt: r.expiresAt }); }, // ---- The account ---- "GET /v1/me": async (c) => c.answer(await signedIn(c.auth, { refresh: true }, (state, me, t) => ({ ...E.viewAccount(state, me.address, t), via: me.via, apiKeyId: me.keyId, mode, limits: { instances: E.LIMITS.instances, sshKeys: E.LIMITS.sshKeys, apiKeys: E.LIMITS.apiKeys } }))), "POST /v1/ssh-keys": async (c) => c.answer( await signedIn(c.auth, { sessionOnly: true }, (state, me, t) => { const r = E.addSshKey(state, { address: me.address, name: c.json.name, publicKey: c.json.publicKey, now: t }); return r.ok ? { id: r.key.id, name: r.key.name, type: r.key.type, fingerprint: r.key.fingerprint, addedAt: new Date(r.key.addedAt).toISOString() } : r; }), 201, ), "DELETE /v1/ssh-keys/{id}": async (c) => c.answer(await signedIn(c.auth, { sessionOnly: true }, (state, me) => E.removeSshKey(state, { address: me.address, id: c.params.id }))), // ---- Instances ---- "POST /v1/instances": async (c) => c.answer(await rentRoute(c.auth, c.json), 201), "GET /v1/instances": async (c) => c.answer(await signedIn(c.auth, { refresh: true }, (state, me) => ({ instances: E.viewAccount(state, me.address, now()).instances }))), "GET /v1/instances/{id}": async (c) => c.answer( await signedIn(c.auth, { refresh: true }, (state, me) => { const inst = mine(state, me, c.params.id); if (!inst) return fail("not-found", "No such instance."); const receipt = E.receiptOf(state, inst); return { ...E.viewInstance(inst), receipt: receipt ? E.viewEntry(receipt) : null }; }), ), "POST /v1/instances/{id}/end": async (c) => c.answer( await signedIn(c.auth, {}, (state, me, t) => { const r = E.end(state, { address: me.address, id: c.params.id, now: t }); if (!r.ok) return r; return { ...(r.receipt ? E.viewEntry(r.receipt) : zeroReceipt(r.instance)), alreadyEnded: r.already, instance: E.viewInstance(r.instance) }; }), ), // ---- Credits ---- "POST /v1/credits/claim": async (c) => c.answer(await claimRoute(c.auth, c.json)), "GET /v1/ledger": async (c) => { const limit = Math.min(500, Math.max(1, Number(c.query.limit) || 100)); return c.answer(await signedIn(c.auth, {}, (state, me, t) => ({ address: me.address, creditsUsd: E.viewAccount(state, me.address, t).creditsUsd, entries: E.viewLedger(state, me.address, limit) }))); }, // ---- API keys ---- "POST /v1/api-keys": async (c) => { const cap = Number(c.json.capUsdPerDay); if (!(cap > 0) || !Number.isFinite(cap)) return c.refuse("invalid", "capUsdPerDay must be a positive number of USD."); const fresh = newApiKey(deps.random); return c.answer( await signedIn(c.auth, { sessionOnly: true }, (state, me, t) => { const r = E.addApiKey(state, { address: me.address, name: c.json.name, capMicro: Math.round(cap * 1e6), hash: fresh.hash, prefix: fresh.prefix, now: t }); return r.ok ? { ...E.viewApiKey(r.key, t), secret: fresh.secret, note: "This secret is shown once. Idle keeps only its hash." } : r; }), 201, ); }, "POST /v1/api-keys/{id}/stop": async (c) => c.answer( await signedIn(c.auth, { sessionOnly: true }, (state, me, t) => { const r = E.stopApiKey(state, { address: me.address, id: c.params.id, now: t }); return r.ok ? { ...E.viewApiKey(r.key, t), ended: r.ended.map(E.viewEntry) } : r; }), ), "DELETE /v1/api-keys/{id}": async (c) => c.answer( await signedIn(c.auth, { sessionOnly: true }, (state, me, t) => { const r = E.deleteApiKey(state, { address: me.address, id: c.params.id, now: t }); return r.ok ? { ok: true, id: r.id, ended: r.ended.map(E.viewEntry) } : r; }), ), "GET /v1/tick": async (c) => c.answer(await tickRoute(c.auth)), // ---- Public reads ---- "GET /v1/health": async (c) => { const cat = open ? await catalogue() : null; const eq = equityIn(await figures()); // for EQNVDA's decimals, which are read on chain and never assumed let meter = null; if (open) { try { const tickAt = (await store.load()).data.tickAt ?? 0; meter = { lastTickAt: tickAt ? new Date(tickAt).toISOString() : null, running: tickMaxAgeMs <= 0 || now() - tickAt <= tickMaxAgeMs }; } catch (e) { meter = { lastTickAt: null, running: false, error: e?.code ?? "unreadable" }; } } return c.out(200, { ok: true, product: "Idle, the GPU cloud on Elysium", chainId, rentals, mode, // "closed" | "test" (a mock provider: no real machine, no real money) | "live" provider: provider?.name ?? null, gpusListed: cat?.source === "provider" ? cat.gpus.filter((g) => g.available > 0).length : 0, gpuModelsOnTheRateCard: GPUS.length, signIn: open, credits: { token: "USDC", address: usdc, decimals: 6, treasury: treasury ? getAddress(treasury) : null, minConfirmations, hype: false, tokens: [ { symbol: "USDC", address: usdc, decimals: 6 }, { symbol: "EQNVDA", address: eqnvda, decimals: eq?.decimals ?? null, haircutBps, maxGapBps, pricedBy: PRICED_BY }, ], }, relayer: { path: "/rpc", carries: relayer?.carries ?? ["USDC.transfer(treasury, amount)", "EQNVDA.transfer(treasury, amount)"], canSend: relayer?.canSend() ?? false, inbox: cfg.inbox ?? null }, // The contract that holds prepaid credits on Elysium. Read it at /v1/contract. contract: credits ? { name: "IdleCredits", address: getAddress(credits), path: "/v1/contract", wiredToRentals: false } : null, marginBps: open ? marginBps : null, limits: { instances: E.LIMITS.instances, sshKeys: E.LIMITS.sshKeys, apiKeys: E.LIMITS.apiKeys, minSecondsOfCredits: E.LIMITS.minSeconds, readyTimeoutSeconds: E.LIMITS.readyTimeoutMs / 1000 }, meter, // What an agent can use today. `openTools` are the ones that work on this deployment as it is now; // the others are listed by the server and answer a `not-open` tool error. mcp: { path: "/mcp", transport: "streamable-http", protocolVersions: MCP_VERSIONS, tools: mcp.tools, openTools: openTools() }, // idle/auto: where the offers come from, and the rules /v1/route can apply. routing: { path: "/v1/route", sources: SOURCES.map((s) => ({ name: s.name, kind: s.kind, what: s.what })), rule: PREFER, tierOrder: TIER_ORDER }, missing: open ? [] : missing, note: mode === "closed" ? CLOSED : mode === "test" ? "Test mode: the provider is a mock. No machine is real and no money moves." : "Rentals are open. Machines are rented from a GPU provider and resold by the second.", }); }, "GET /v1/openapi.json": async (c) => c.out(200, openapi({ base: cfg.apiBase || `https://${domain}/api`, mode, version: VERSION })), "GET /v1/offers": async (c) => { const q = constraints(c.query); if (!q.ok) return c.answerPublic(q); const read = await readOffers(); const matching = filterOffers(read.offers, q); return c.out(200, { offers: matching.slice(0, q.limit), count: Math.min(matching.length, q.limit), total: matching.length, constraints: { gpu: q.gpu, minVram: q.minVram, secure: q.secure, limit: q.limit }, sources: read.sources, errors: read.errors, asOf: read.asOf, note: NOT_IDLES + " A list price is a published rate, not a promise of stock; a live offer was rentable when it was read." }); }, "GET /v1/route": async (c) => { const q = constraints(c.query); if (!q.ok) return c.answerPublic(q); const read = await readOffers(); const asked = { minVram: q.minVram, prefer: q.prefer, gpu: q.gpu }; const choice = chooseOffer(read.offers, asked); if (!choice.pick) { if (read.offers.length === 0) return c.refuse("sources-unavailable", "No source of offers answered, so nothing can be routed right now.", { constraints: asked, sources: read.sources, errors: read.errors }); return c.refuse("no-offer", "No offer on the market meets these constraints right now.", { constraints: asked, rule: choice.rule, considered: 0, sources: read.sources, errors: read.errors }); } const rate = E.rateFor(choice.pick.usdPerHour, marginBps); // Idle can rent the pick only when it is live and the pick is something its own provider serves: // the same source, its secure cloud (the adapter uses nothing else), one of Idle's seven GPUs. const rentableThroughIdle = mode === "live" && choice.pick.source === provider.name && choice.pick.secure === true && choice.pick.gpu !== null; return c.out(200, { ...choice, marginBps, idleUsdPerHour: usd(rate), idleUsdPerSecond: round(rate / 3600 / 1e6, 8), rentableThroughIdle, rentals, mode, sources: read.sources, errors: read.errors, asOf: read.asOf, note: NOT_IDLES + ` The pick is the ${choice.pick.kind === "list-price" ? "published rate" : "live offer"} of ${choice.pick.source}; idleUsdPerHour is that price plus Idle's margin of ${marginBps / 100} %. ` + (rentableThroughIdle ? `Idle can rent this one for you now: POST /v1/instances {"gpu": "${choice.pick.gpu}"}.` : mode === "live" ? "Idle cannot rent this pick itself: it only serves its own provider's secure cloud." : "Idle's rentals are not open on this deployment, so nothing can be rented through Idle yet."), }); }, // The credits contract, read on Elysium now: what it holds, who can charge, how long a withdrawal waits. "GET /v1/contract": async (c) => { if (!credits) return c.out(200, { deployed: false, note: "No credits contract is configured on this deployment." }); const k = await contract(); if (!k) return c.refuse("chain-unreachable", "Elysium did not answer."); const known = getAddress(credits) === ELYSIUM_CREDITS.address ? { deployer: ELYSIUM_CREDITS.deployer, txHash: ELYSIUM_CREDITS.txHash, inboxTxHash: ELYSIUM_CREDITS.inboxTxHash, block: ELYSIUM_CREDITS.block, sourceVerifiedOnExplorer: ELYSIUM_CREDITS.sourceVerifiedOn } : null; return c.out(200, { name: "IdleCredits", chainId, ...k, explorer: ELYSIUM.explorer + "/address/" + k.address, deployment: known, source: "/source/IdleCredits.sol", audited: false, wiredToRentals: false, relayer: { path: "/rpc", canSend: relayer?.canSend() ?? false, carries: (relayer?.carries ?? []).filter((x) => /credits/.test(x)) }, readFrom: "Elysium, at request time", note: k.deployed ? CONTRACT_NOTE : "No code at this address on Elysium.", }); }, // What one address holds in the contract, in its wallet, and what it has asked to withdraw. "GET /v1/contract/account": async (c) => { if (!credits) return c.refuse("not-open", "No credits contract is configured on this deployment."); const who = normalAddress(String(c.query.address ?? "")); if (!who) return c.refuse("invalid", "address must be a wallet address (0x and 40 hexadecimal characters)."); const k = await contract(); if (!k?.deployed) return c.refuse("chain-unreachable", "The contract could not be read on Elysium."); try { const a = await readCreditsAccount(deps.chain, creditsCfg, who); return c.out(200, { ...a, withdrawalDelaySeconds: k.withdrawalDelaySeconds, wiredToRentals: false, asOf: new Date(now()).toISOString() }); } catch { return c.refuse("chain-unreachable", "Elysium did not answer."); } }, "GET /v1/market": async (c) => { const m = await figures(); if (!m) return c.refuse("chain-unreachable", "The sources did not answer."); const { at, ...rest } = m; return c.out(200, rest); }, "GET /v1/gpus": async (c) => { const m = await figures(); const cat = await catalogue(); return c.out(200, { rentals, mode, source: cat.source, // "provider": live prices plus the margin. "target": the rate card, nothing to rent. rates: cat.source === "provider" ? "live rates in USD per GPU hour, billed per second" : "target rates in USD per GPU hour, billed per second", marginBps: cat.source === "provider" ? marginBps : null, hypeMid: m?.hypeMid ?? null, asOf: m?.asOf ?? null, errors: cat.error ? [cat.error] : [], gpus: cat.gpus.map((g) => row(g, m?.hypeMid ?? null)), }); }, "GET /v1/quote": async (c) => { const m = await figures(); if (!findGpu(c.query.gpu)) return c.refuse("unknown-gpu", "Unknown GPU.", { gpus: GPUS.map((g) => g.id) }); const cat = await catalogue(); const g = cat.gpus.find((x) => x.id === String(c.query.gpu).toLowerCase()); try { const q = quote(g, Number(c.query.seconds), m?.hypeMid ?? null); // With a live rate the figure is the engine's own: what the meter would charge for that many seconds. if (cat.source === "provider") { q.usd = usd(E.dueMicro(g.rate, q.seconds)); q.hype = m?.hypeMid > 0 ? round(q.usd / m.hypeMid, 6) : null; } const live = cat.source === "provider"; return c.out(200, { ...q, hypeMid: m?.hypeMid ?? null, rentals, mode, source: cat.source, note: live ? undefined : "A target price. " + CLOSED }); } catch (e) { return c.refuse("invalid", String(e?.message ?? e)); } }, // What an amount of USDC or EQNVDA would buy. Read-only, and it answers while rentals are closed too: // it is a price, not an offer. A claim prices again, at the moment it is made. "GET /v1/credits/quote": async (c) => { const m = await figures(); const token = String(c.query.token ?? "").toUpperCase(); const text = String(c.query.amount ?? ""); if (token !== "USDC" && token !== "EQNVDA") return c.refuse("invalid", "token must be USDC or EQNVDA.", { tokens: ["USDC", "EQNVDA"] }); const tail = { rentals, mode, asOf: m?.asOf ?? null }; if (token === "USDC") { const amount = parseAmount(text, 6); if (amount === null) return c.refuse("invalid", "amount must be a positive number of USDC with at most 6 decimals."); return c.out(200, { token, amount: formatAmount(amount, 6), poolPriceUsd: null, markUsd: null, priceUsd: 1, haircutBps: 0, creditsUsd: usd(Number(amount)), ...tail }); } if (!/^\d+(\.\d+)?$/.test(text) || !(Number(text) > 0)) return c.refuse("invalid", "amount must be a positive number of EQNVDA."); const eq = equityIn(m); if (!eq) return c.refuse("price-unavailable", "EQNVDA cannot be priced right now: the token or its pool on Elysium could not be read.", { poolPriceUsd: null, markUsd: m?.nvda ?? null }); const amount = parseAmount(text, eq.decimals); if (amount === null) return c.refuse("invalid", `amount must be a positive number of EQNVDA with at most ${eq.decimals} decimals.`); const p = priceOf(eq, amount); if (!p.ok) { const { ok, error, message, ...extra } = p; return c.refuse(error, message, extra); } return c.out(200, { token, amount: formatAmount(amount, eq.decimals), poolPriceUsd: p.poolPriceUsd, markUsd: p.markUsd, priceUsd: p.priceUsd, haircutBps: p.haircutBps, creditsUsd: usd(p.micro), gapBps: p.gapBps, maxGapBps, pricedBy: PRICED_BY, ...tail }); }, }; // The table and the handlers must be the same set: a route cannot be served unlisted, nor listed unserved. for (const r of ROUTES) if (!handlers[r.id]) throw new Error("routes.mjs lists " + r.id + " but app.mjs has no handler for it"); for (const id of Object.keys(handlers)) if (!ROUTES.some((r) => r.id === id)) throw new Error("app.mjs handles " + id + " but routes.mjs does not list it"); /** * One request. `limited` is false only for the calls the MCP server makes on a caller's behalf, which were * already counted once at the MCP endpoint. * @returns {Promise<{status:number, headers:object, body:string}>} */ async function dispatch({ method, path, query = {}, ip = "?", origin, body, auth, headers: sent = {} }, limited) { const allow = !cfg.origins?.length ? "*" : cfg.origins.includes(origin) ? origin : cfg.origins[0]; const headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": allow, "Access-Control-Allow-Headers": "Content-Type, Authorization, Accept, MCP-Protocol-Version, Mcp-Method, Mcp-Name, Mcp-Session-Id, Last-Event-ID", "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS", Vary: "Origin", }; const out = (status, obj) => ({ status, headers, body: JSON.stringify(obj) }); const raw = (status, text, extra = {}) => ({ status, headers: Object.assign(headers, extra), body: text }); const refuse = (error, message, extra = {}) => out(STATUS[error] ?? 400, { error, message, ...extra }); const noStore = () => (headers["Cache-Control"] = "no-store"); // What a route gives back: {ok:false, error, message, ...} or {ok:true, body, status?} or a plain object to send. const answerPublic = (r) => { const { ok, error, message, ...extra } = r; return refuse(error, message, extra); }; const answer = (r, okStatus = 200) => { noStore(); if (r?.ok === false) return answerPublic(r); return r?.ok === true && "body" in r ? out(r.status ?? okStatus, r.body) : out(okStatus, r); }; if (method === "OPTIONS") return { status: 204, headers, body: "" }; try { const hit = matchRoute(method, path); const limit = hit ? hit.route.limit : method === "GET" ? "read" : "write"; if (limited) { if (limit === "read" && !readLimit(ip)) return refuse("rate-limited", "Too many requests."); if (limit === "write" && !writeLimit(ip)) return refuse("rate-limited", "Too many requests. Wait a minute."); if (limit === "mcp" && !mcpLimit(ip)) return out(429, { jsonrpc: "2.0", error: { code: 429, message: "Too many requests. Wait a minute." } }); } // Everything that is not a GET carries a small JSON object, unless the route reads its body itself. let json = {}; if ((hit ? hit.route.body : method === "GET" ? "none" : "json") === "json") { if (typeof body === "string" && body.trim()) { if (body.length > 16_384) return refuse("too-large", "Request too large."); try { json = JSON.parse(body); } catch { return refuse("bad-json", "The body is not JSON."); } } else if (body && typeof body === "object") json = body; if (!json || typeof json !== "object" || Array.isArray(json)) return refuse("bad-json", "The body must be a JSON object."); } if (!hit) return refuse("not-found", "No such route."); return await handlers[hit.route.id]({ params: hit.params, query, json, body, auth, ip, origin, headers: sent, out, raw, refuse, answer, answerPublic, noStore }); } catch (e) { noStore(); if (e?.code === "state-missing") return refuse("starting", "The state store is not initialised yet. Nothing was changed."); if (e?.code === "busy") return refuse("busy", "The engine is busy. Nothing was changed; try again in a moment."); log({ event: "error", path, error: String(e?.stack ?? e) }); return refuse("server-error", "Something went wrong. Nothing is known to have changed."); } } return { handle: (req) => dispatch(req, true), mode, open, rentals }; }