// The routes end to end: the real app, the real engine, the real claim code, a mock provider, a fake chain, // a store in memory and a clock moved by hand. import { test, describe } from "node:test"; import assert from "node:assert/strict"; import { Interface, Wallet } from "ethers"; import { memoryStore } from "../lib/store.mjs"; import { createMockProvider } from "../lib/provider-mock.mjs"; import { ProviderError } from "../lib/provider.mjs"; import { GPUS } from "../lib/rates.mjs"; import { ROUTES, matchRoute } from "../lib/routes.mjs"; import { readFileSync } from "node:fs"; import { sshKey, T0 } from "./helpers.mjs"; import { CRON, EQNVDA, TREASURY, USDC, world } from "./world.mjs"; describe("what is open", () => { test("with nothing configured: the rate card answers, everything else says not-open and why", async () => { const w = world({ without: ["provider", "store", "sessionSecret", "treasury", "chain"] }); const h = await w.call("GET", "/v1/health"); assert.equal(h.body.rentals, false); assert.equal(h.body.mode, "closed"); assert.equal(h.body.provider, null); assert.equal(h.body.gpusListed, 0); assert.equal(h.body.signIn, false); assert.equal(h.body.missing.length, 5); // Every field the health answer had before EQNVDA is still there, and the tokens are listed next to them. const c = h.body.credits; assert.deepEqual([c.token, c.address, c.decimals, c.treasury, c.minConfirmations, c.hype], ["USDC", USDC, 6, null, 2, false]); assert.deepEqual(c.tokens, [ { symbol: "USDC", address: USDC, decimals: 6 }, { symbol: "EQNVDA", address: EQNVDA, decimals: 8, haircutBps: 100, maxGapBps: 300, pricedBy: "min of the Uniswap v4 pool on Elysium and Hyperliquid's xyz:NVDA" }, ]); assert.deepEqual(h.body.relayer.carries, ["USDC.transfer(treasury, amount)", "EQNVDA.transfer(treasury, amount)"]); const g = await w.call("GET", "/v1/gpus"); assert.equal(g.body.source, "target"); assert.ok(g.body.gpus.every((x) => x.available === 0)); for (const [method, path] of [["POST", "/v1/auth/challenge"], ["POST", "/v1/auth/verify"], ["GET", "/v1/me"], ["POST", "/v1/ssh-keys"], ["DELETE", "/v1/ssh-keys/k1"], ["POST", "/v1/instances"], ["GET", "/v1/instances"], ["GET", "/v1/instances/i1"], ["POST", "/v1/instances/i1/end"], ["POST", "/v1/credits/claim"], ["GET", "/v1/ledger"], ["POST", "/v1/api-keys"], ["POST", "/v1/api-keys/a1/stop"], ["DELETE", "/v1/api-keys/a1"], ["POST", "/v1/rent"]]) { const r = await w.call(method, path, { body: method === "GET" ? undefined : { address: "0x" + "11".repeat(20), capUsdPerDay: 1 }, token: "ids_whatever" }); assert.equal(r.status, 503, method + " " + path); assert.equal(r.body.error, "not-open", method + " " + path); } assert.equal((await w.call("POST", "/rpc", { body: { id: 1, method: "eth_chainId" } })).body.error.code, -32000); }); test("one missing piece keeps it closed: no provider, no treasury, no secret, no store", async () => { for (const piece of ["provider", "treasury", "sessionSecret", "store"]) { const w = world({ without: [piece] }); const h = (await w.call("GET", "/v1/health")).body; assert.equal(h.mode, "closed", piece); assert.equal(h.rentals, false, piece); assert.equal(h.missing.length, 1, piece); assert.equal((await w.call("POST", "/v1/auth/challenge", { body: { address: "0x" + "11".repeat(20) } })).status, 503, piece); } }); test("with a mock provider it is a test desk: it works, and never calls itself a rental", async () => { const w = world(); await w.tick(); const h = (await w.call("GET", "/v1/health")).body; assert.equal(h.mode, "test"); assert.equal(h.rentals, false); assert.equal(h.provider, "mock"); assert.equal(h.signIn, true); assert.equal(h.gpusListed, 7); assert.match(h.note, /mock/); assert.equal(h.credits.treasury.toLowerCase(), TREASURY); assert.equal(h.credits.hype, false); assert.equal(h.meter.running, true); assert.equal((await w.call("GET", "/v1/gpus")).body.rentals, false); }); test("rentals is true only with a provider whose machines are real", async () => { const real = createMockProvider({ env: {} }); real.real = true; real.name = "runpod"; const w = world({ provider: real }); const h = (await w.call("GET", "/v1/health")).body; assert.equal(h.rentals, true); assert.equal(h.mode, "live"); assert.equal((await w.call("GET", "/v1/gpus")).body.rentals, true); assert.equal((await w.call("POST", "/v1/rent")).body.error, "moved"); }); test("the meter must run: without a recent tick no rental starts, and health says so", async () => { const w = world(); const user = await w.signIn(); await w.topUp(user, 10); await w.call("POST", "/v1/ssh-keys", { token: user.token, body: { name: "k", publicKey: sshKey() } }); assert.equal((await w.call("GET", "/v1/health")).body.meter.running, false); const r = await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } }); assert.equal(r.status, 503); assert.equal(r.body.error, "not-open"); await w.tick(); assert.equal((await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } })).status, 201); w.advance(301); assert.equal((await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } })).body.error, "not-open"); }); }); describe("rates", () => { test("the provider's live price plus the margin, with the HYPE conversion and the stock", async () => { const w = world({ mock: { stock: { h200: "none", l40s: "low" } } }); const g = (await w.call("GET", "/v1/gpus")).body; assert.equal(g.source, "provider"); assert.equal(g.marginBps, 2000); const row = (id) => g.gpus.find((x) => x.id === id); assert.deepEqual(row("rtx-4090"), { id: "rtx-4090", name: "RTX 4090", vram: 24, vramGb: 24, usdPerHour: 0.72, usdPerSecond: 0.0002, hypePerHour: 0.0144, available: 1, stock: "high" }); assert.equal(row("h200").available, 0); assert.equal(row("l40s").stock, "low"); assert.equal(g.gpus.length, GPUS.length); const q = (await w.call("GET", "/v1/quote", { query: { gpu: "rtx-4090", seconds: "1200" } })).body; assert.equal(q.usd, 0.24); assert.equal(q.hype, 0.0048); assert.equal(q.source, "provider"); assert.equal(q.note, undefined); assert.equal((await w.call("GET", "/v1/quote", { query: { gpu: "nope", seconds: "60" } })).body.error, "unknown-gpu"); assert.equal((await w.call("GET", "/v1/quote", { query: { gpu: "h100", seconds: "0" } })).status, 400); }); test("prices are read from the provider at most once a minute", async () => { const w = world(); for (let i = 0; i < 5; i++) await w.call("GET", "/v1/gpus"); assert.equal(w.provider.calls.listGpus, 1); w.advance(61); await w.call("GET", "/v1/gpus"); assert.equal(w.provider.calls.listGpus, 2); }); test("a provider that does not answer gives the target card, named as such, and nothing can be rented at a guess", async () => { const w = world(); const user = await w.renter(); w.advance(61); w.provider.listGpus = async () => { throw new ProviderError("provider", "down", "ECONNRESET"); }; const g = (await w.call("GET", "/v1/gpus")).body; assert.equal(g.source, "target"); assert.equal(g.errors.length, 1); assert.ok(g.gpus.every((x) => x.available === 0)); const r = await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } }); assert.equal(r.status, 502); assert.equal(r.body.error, "provider"); assert.equal(w.provider.calls.create, 0); }); }); describe("signing in", () => { test("a wallet signs a challenge and gets a session; without one the account routes answer 401", async () => { const w = world(); const wallet = Wallet.createRandom(); const ch = await w.call("POST", "/v1/auth/challenge", { body: { address: wallet.address } }); assert.equal(ch.status, 200); assert.equal(ch.body.address, wallet.address.toLowerCase()); assert.ok(ch.body.message.includes("idle.test wants you to sign in")); assert.ok(Date.parse(ch.body.expiresAt) > w.t); const v = await w.call("POST", "/v1/auth/verify", { body: { address: wallet.address, signature: await wallet.signMessage(ch.body.message) } }); assert.equal(v.status, 200); assert.deepEqual(Object.keys(v.body).sort(), ["address", "expiresAt", "token"]); assert.equal(v.headers["Cache-Control"], "no-store"); const me = await w.call("GET", "/v1/me", { token: v.body.token }); assert.equal(me.status, 200); assert.equal(me.body.address, wallet.address.toLowerCase()); assert.equal(me.body.creditsUsd, 0); assert.deepEqual([me.body.sshKeys, me.body.apiKeys, me.body.instances], [[], [], []]); assert.equal(me.body.via, "session"); assert.equal(me.headers["Cache-Control"], "no-store"); assert.equal(w.store.saves, 0, "signing in and looking writes nothing"); for (const token of [undefined, "", "ids_forged.sig", v.body.token.slice(0, -3) + "AAA", "idk_unknownkey"]) { const r = await w.call("GET", "/v1/me", { token }); assert.equal(r.status, 401, String(token)); assert.equal(r.body.error, "unauthorized"); } }); test("a wrong signature, a stale challenge and an expired session are refused", async () => { const w = world(); const wallet = Wallet.createRandom(); const other = Wallet.createRandom(); const ch = (await w.call("POST", "/v1/auth/challenge", { body: { address: wallet.address } })).body; const bad = await w.call("POST", "/v1/auth/verify", { body: { address: wallet.address, signature: await other.signMessage(ch.message) } }); assert.equal(bad.status, 401); assert.equal((await w.call("POST", "/v1/auth/verify", { body: { address: wallet.address } })).status, 401); assert.equal((await w.call("POST", "/v1/auth/challenge", { body: { address: "0x123" } })).body.error, "invalid"); const signature = await wallet.signMessage(ch.message); w.advance(601); assert.equal((await w.call("POST", "/v1/auth/verify", { body: { address: wallet.address, signature } })).status, 401); const user = await w.signIn(wallet); w.advance(24 * 3600 - 1); assert.equal((await w.call("GET", "/v1/me", { token: user.token })).status, 200); w.advance(1); assert.equal((await w.call("GET", "/v1/me", { token: user.token })).status, 401); }); }); describe("SSH keys over the API", () => { test("add, list, refuse a bad one, delete", async () => { const w = world(); const user = await w.signIn(); const line = sshKey("ed25519", 0, "me@laptop"); const added = await w.call("POST", "/v1/ssh-keys", { token: user.token, body: { name: "laptop", publicKey: line } }); assert.equal(added.status, 201); assert.deepEqual(Object.keys(added.body).sort(), ["addedAt", "fingerprint", "id", "name", "type"]); assert.match(added.body.fingerprint, /^SHA256:/); assert.equal((await w.call("POST", "/v1/ssh-keys", { token: user.token, body: { name: "again", publicKey: line } })).body.error, "duplicate"); const bad = await w.call("POST", "/v1/ssh-keys", { token: user.token, body: { name: "bad", publicKey: "ssh-ed25519 AAAA" } }); assert.equal(bad.status, 400); assert.equal(bad.body.error, "invalid"); assert.equal((await w.call("POST", "/v1/ssh-keys", { token: user.token, raw: "{not json" })).body.error, "bad-json"); const me = await w.me(user); assert.deepEqual(me.sshKeys.map((k) => [k.id, k.name, k.fingerprint]), [[added.body.id, "laptop", added.body.fingerprint]]); assert.equal(JSON.stringify(me).includes(line.split(" ")[1]), false); assert.equal((await w.call("DELETE", "/v1/ssh-keys/nope", { token: user.token })).status, 404); assert.equal((await w.call("DELETE", "/v1/ssh-keys/" + added.body.id, { token: user.token })).status, 200); assert.deepEqual((await w.me(user)).sshKeys, []); }); }); describe("credits over the API", () => { test("a transfer to the treasury is credited once it has 2 confirmations, and only once", async () => { const w = world(); const user = await w.signIn(); const txHash = w.chain.transfer({ from: user.address, to: TREASURY, amount: 12_500_000n }); const early = await w.call("POST", "/v1/credits/claim", { token: user.token, body: { txHash } }); assert.equal(early.status, 409); assert.equal(early.body.error, "unconfirmed"); assert.equal((await w.me(user)).creditsUsd, 0); w.chain.mine(1); const ok = await w.call("POST", "/v1/credits/claim", { token: user.token, body: { txHash } }); assert.equal(ok.status, 200); assert.equal(ok.body.creditedUsd, 12.5); assert.equal(ok.body.creditsUsd, 12.5); assert.equal(ok.body.entry.type, "topup"); const replay = await w.call("POST", "/v1/credits/claim", { token: user.token, body: { txHash: txHash.toUpperCase().replace("0X", "0x") } }); assert.equal(replay.status, 409); assert.equal(replay.body.error, "already-claimed"); assert.equal((await w.me(user)).creditsUsd, 12.5); const ledger = (await w.call("GET", "/v1/ledger", { token: user.token })).body; assert.deepEqual(ledger.entries.map((e) => [e.type, e.usd, e.txHash]), [["topup", 12.5, txHash]]); assert.equal(ledger.creditsUsd, 12.5); }); test("someone else's transfer, another token, another recipient, a reverted or unknown transaction credit nothing", async () => { const w = world(); const user = await w.signIn(); const thief = await w.signIn(); const theirs = w.chain.transfer({ from: user.address, to: TREASURY, amount: 5_000_000n }); const otherToken = w.chain.transfer({ token: "0x" + "70".repeat(20), from: user.address, to: TREASURY, amount: 5_000_000n }); const elsewhere = w.chain.transfer({ from: user.address, to: "0x" + "99".repeat(20), amount: 5_000_000n }); const reverted = w.chain.transfer({ from: user.address, to: TREASURY, amount: 5_000_000n, status: 0 }); w.chain.mine(3); const claim = (token, txHash) => w.call("POST", "/v1/credits/claim", { token, body: { txHash } }); assert.deepEqual([(await claim(thief.token, theirs)).status, (await claim(thief.token, theirs)).body.error], [422, "wrong-sender"]); assert.equal((await claim(user.token, otherToken)).body.error, "wrong-token"); assert.equal((await claim(user.token, elsewhere)).body.error, "wrong-recipient"); assert.equal((await claim(user.token, reverted)).body.error, "tx-reverted"); assert.deepEqual([(await claim(user.token, "0x" + "ab".repeat(32))).status, (await claim(user.token, "0x12")).status], [404, 400]); assert.equal((await claim(undefined, theirs)).status, 401); w.chain.down = true; assert.equal((await claim(user.token, theirs)).status, 502); w.chain.down = false; assert.equal((await w.me(thief)).creditsUsd, 0); assert.equal((await w.me(user)).creditsUsd, 0); assert.equal((await claim(user.token, theirs)).status, 200, "and the rightful sender still can"); }); test("two claims of one transaction at the same instant credit it once", async () => { const w = world(); const user = await w.signIn(); const txHash = w.chain.transfer({ from: user.address, to: TREASURY, amount: 4_000_000n }); w.chain.mine(1); const results = await Promise.all([1, 2, 3].map(() => w.call("POST", "/v1/credits/claim", { token: user.token, body: { txHash } }))); assert.deepEqual(results.map((r) => r.status).sort(), [200, 409, 409]); assert.equal((await w.me(user)).creditsUsd, 4); }); }); describe("paying with tokenized Nvidia", () => { const quote = (w, query) => w.call("GET", "/v1/credits/quote", { query }); const sendEquity = (w, user, amount) => { const txHash = w.chain.transfer({ token: EQNVDA, from: user.address, to: TREASURY, amount }); w.chain.mine(1); return txHash; }; const claim = (w, user, txHash) => w.call("POST", "/v1/credits/claim", { token: user.token, body: { txHash } }); test("a quote answers while everything is closed, signs nobody in and writes nothing", async () => { const w = world({ without: ["provider", "store", "sessionSecret", "treasury", "chain"] }); const q = await quote(w, { token: "EQNVDA", amount: "1.5" }); assert.equal(q.status, 200); assert.deepEqual( { token: q.body.token, amount: q.body.amount, poolPriceUsd: q.body.poolPriceUsd, markUsd: q.body.markUsd, priceUsd: q.body.priceUsd, haircutBps: q.body.haircutBps, creditsUsd: q.body.creditsUsd, rentals: q.body.rentals, mode: q.body.mode }, { token: "EQNVDA", amount: "1.5", poolPriceUsd: 151.368838, markUsd: 151.305, priceUsd: 151.305, haircutBps: 100, creditsUsd: 224.687925, rentals: false, mode: "closed" }, ); assert.equal(q.headers["Cache-Control"], undefined, "a public read: the host may cache it briefly"); const usdc = await quote(w, { token: "usdc", amount: "25.5" }); assert.deepEqual( { token: usdc.body.token, amount: usdc.body.amount, poolPriceUsd: usdc.body.poolPriceUsd, markUsd: usdc.body.markUsd, priceUsd: usdc.body.priceUsd, haircutBps: usdc.body.haircutBps, creditsUsd: usdc.body.creditsUsd, mode: usdc.body.mode }, { token: "USDC", amount: "25.5", poolPriceUsd: null, markUsd: null, priceUsd: 1, haircutBps: 0, creditsUsd: 25.5, mode: "closed" }, ); }); test("a quote is the lower of the pool and the mark, less the haircut, rounded down", async () => { const w = world(); assert.equal((await quote(w, { token: "EQNVDA", amount: "1" })).body.creditsUsd, 149.79195); // 151.305 less 1 % w.prices = { pool: 150, mark: 151.305 }; const low = (await quote(w, { token: "EQNVDA", amount: "1" })).body; assert.deepEqual([low.priceUsd, low.creditsUsd, low.mode], [150, 148.5, "test"]); w.prices = { pool: 155, mark: 151.305 }; // pushed up, inside the 3 %: the mark still caps it assert.equal((await quote(w, { token: "EQNVDA", amount: "1" })).body.creditsUsd, 149.79195); assert.equal((await quote(w, { token: "EQNVDA", amount: "0.00000001" })).body.creditsUsd, 0.000001); const other = world({ cfg: { equityHaircutBps: 500, equityMaxGapBps: 1000 } }); const q = (await quote(other, { token: "EQNVDA", amount: "2" })).body; assert.deepEqual([q.haircutBps, q.maxGapBps, q.creditsUsd], [500, 1000, 287.4795]); }); test("a bad token or a bad amount is a 400", async () => { const w = world(); for (const query of [{}, { token: "EQNVDA" }, { amount: "1" }, { token: "HYPE", amount: "1" }, { token: "EQNVDA", amount: "0" }, { token: "EQNVDA", amount: "-1" }, { token: "EQNVDA", amount: "1e3" }, { token: "EQNVDA", amount: "abc" }, { token: "EQNVDA", amount: "0.000000001" }, { token: "USDC", amount: "0.0000001" }, { token: "USDC", amount: "" }]) { const r = await quote(w, query); assert.deepEqual([r.status, r.body.error], [400, "invalid"], JSON.stringify(query)); } }); test("no quote without both prices, and none while they disagree by more than 3 %", async () => { const w = world(); w.prices = { pool: 151.37, mark: null }; const noMark = await quote(w, { token: "EQNVDA", amount: "1" }); assert.deepEqual([noMark.status, noMark.body.error], [503, "price-unavailable"]); w.prices = { mark: 151.305 }; // the pool could not be read: market.mjs gives no equity at all const noPool = await quote(w, { token: "EQNVDA", amount: "1" }); assert.deepEqual([noPool.status, noPool.body.error], [503, "price-unavailable"]); w.prices = { pool: 151.37, mark: 151.305, token: "0x" + "12".repeat(20) }; // a market read for some other token assert.equal((await quote(w, { token: "EQNVDA", amount: "1" })).body.error, "price-unavailable"); w.prices = { pool: 160, mark: 151.305 }; const apart = await quote(w, { token: "EQNVDA", amount: "1" }); assert.deepEqual([apart.status, apart.body.error, apart.body.maxGapBps], [409, "price-unstable", 300]); w.prices = { pool: 140, mark: 151.305 }; assert.equal((await quote(w, { token: "EQNVDA", amount: "1" })).body.error, "price-unstable"); assert.equal((await quote(w, { token: "USDC", amount: "1" })).status, 200, "USDC needs no price"); }); test("an EQNVDA transfer to the treasury is credited at that price, and the ledger keeps how", async () => { const w = world(); const user = await w.signIn(); const txHash = sendEquity(w, user, 150_000_000n); // 1.5 EQNVDA const r = await claim(w, user, txHash); assert.equal(r.status, 200, JSON.stringify(r.body)); assert.deepEqual( { ok: r.body.ok, txHash: r.body.txHash, token: r.body.token, amount: r.body.amount, priceUsd: r.body.priceUsd, creditedUsd: r.body.creditedUsd, creditsUsd: r.body.creditsUsd, confirmations: r.body.confirmations }, { ok: true, txHash, token: "EQNVDA", amount: "1.5", priceUsd: 151.305, creditedUsd: 224.687925, creditsUsd: 224.687925, confirmations: 2 }, ); assert.equal(r.body.creditedUsd, (await quote(w, { token: "EQNVDA", amount: "1.5" })).body.creditsUsd, "the claim credits what the quote said"); const [entry] = (await w.call("GET", "/v1/ledger", { token: user.token })).body.entries; assert.deepEqual( { type: entry.type, usd: entry.usd, token: entry.token, amount: entry.amount, poolPriceUsd: entry.poolPriceUsd, markUsd: entry.markUsd, priceUsd: entry.priceUsd, haircutBps: entry.haircutBps, txHash: entry.txHash }, { type: "topup", usd: 224.687925, token: "EQNVDA", amount: "1.5", poolPriceUsd: 151.368838, markUsd: 151.305, priceUsd: 151.305, haircutBps: 100, txHash }, ); assert.deepEqual(r.body.entry, entry); const replay = await claim(w, user, txHash); assert.deepEqual([replay.status, replay.body.error], [409, "already-claimed"]); assert.equal((await w.me(user)).creditsMicro, 224_687_925); // And those credits rent a machine like any other. await w.call("POST", "/v1/ssh-keys", { token: user.token, body: { name: "k", publicKey: sshKey() } }); await w.tick(); assert.equal((await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } })).status, 201); }); test("USDC is credited as before, and the answer now names the token", async () => { const w = world(); const user = await w.signIn(); const txHash = w.chain.transfer({ from: user.address, to: TREASURY, amount: 12_500_000n }); w.chain.mine(1); w.prices = { mark: null }; // no price source at all: USDC does not need one const r = await claim(w, user, txHash); assert.deepEqual([r.status, r.body.token, r.body.amount, r.body.priceUsd, r.body.creditedUsd, r.body.creditsUsd], [200, "USDC", "12.5", 1, 12.5, 12.5]); assert.deepEqual([r.body.entry.token, r.body.entry.amount, "poolPriceUsd" in r.body.entry], ["USDC", "12.5", false]); }); test("an EQNVDA claim is refused, not guessed, when a price is missing or the two disagree; it can be made again later", async () => { const w = world(); const user = await w.signIn(); const txHash = sendEquity(w, user, 100_000_000n); w.prices = { pool: 151.37, mark: null }; const noMark = await claim(w, user, txHash); assert.deepEqual([noMark.status, noMark.body.error], [503, "price-unavailable"]); w.prices = { mark: 151.305 }; assert.equal((await claim(w, user, txHash)).body.error, "price-unavailable"); w.prices = { pool: 200, mark: 151.305 }; // someone pushed the pool up by a third const pushed = await claim(w, user, txHash); assert.deepEqual([pushed.status, pushed.body.error], [409, "price-unstable"]); w.prices = { pool: 100, mark: 151.305 }; assert.equal((await claim(w, user, txHash)).body.error, "price-unstable"); assert.equal((await w.me(user)).creditsUsd, 0); assert.equal(w.store.saves, 0, "a refused claim writes nothing, so the transaction is not used up"); w.prices = { pool: 151.368838, mark: 151.305 }; assert.equal((await claim(w, user, txHash)).body.creditedUsd, 149.79195); }); test("a pool pushed up never credits more than the mark; a pool pushed down credits less", async () => { const w = world(); const user = await w.signIn(); w.prices = { pool: 155.8, mark: 151.305 }; // 2.97 % above: inside the limit assert.equal((await claim(w, user, sendEquity(w, user, 100_000_000n))).body.creditedUsd, 149.79195); w.prices = { pool: 147, mark: 151.305 }; // 2.85 % below const low = (await claim(w, user, sendEquity(w, user, 100_000_000n))).body; assert.deepEqual([low.priceUsd, low.creditedUsd], [147, 145.53]); }); test("one transfer per transaction: both tokens at once, two transfers, another sender or dust credit nothing", async () => { const w = world(); const user = await w.signIn(); const other = await w.signIn(); const pad = (a) => "0x" + a.slice(2).padStart(64, "0"); const log = (token, amount) => ({ address: token, topics: ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", pad(user.address), pad(TREASURY)], data: pad("0x" + BigInt(amount).toString(16)) }); const both = w.chain.transfer({ from: user.address, to: TREASURY, amount: 5_000_000n, extraLogs: [log(EQNVDA, 100_000_000)] }); const twice = w.chain.transfer({ token: EQNVDA, from: user.address, to: TREASURY, amount: 100_000_000n, extraLogs: [log(EQNVDA, 100_000_000)] }); w.chain.mine(2); for (const txHash of [both, twice]) { const r = await claim(w, user, txHash); assert.deepEqual([r.status, r.body.error], [422, "ambiguous-transfer"]); } const theirs = sendEquity(w, user, 100_000_000n); assert.equal((await claim(w, other, theirs)).body.error, "wrong-sender"); w.prices = { pool: 0.5, mark: 0.5 }; const dust = await claim(w, user, sendEquity(w, user, 1n)); assert.deepEqual([dust.status, dust.body.error], [422, "too-small"]); assert.equal((await w.me(user)).creditsUsd, 0); assert.equal((await w.me(other)).creditsUsd, 0); }); }); describe("renting over the API", () => { test("the whole life of an instance: booked, started, metered by the second, ended, receipted", async () => { const w = world(); const user = await w.renter(10); const r = await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "RTX-4090" } }); assert.equal(r.status, 201); const id = r.body.id; assert.deepEqual( { gpu: r.body.gpu, gpuName: r.body.gpuName, status: r.body.status, ratePerHourUsd: r.body.ratePerHourUsd, secondsBilled: r.body.secondsBilled, costUsd: r.body.costUsd, ssh: r.body.ssh, sshCommand: r.body.sshCommand }, { gpu: "rtx-4090", gpuName: "RTX 4090", status: "starting", ratePerHourUsd: 0.72, secondsBilled: 0, costUsd: 0, ssh: null, sshCommand: null }, ); // The provider was asked for one machine, named after the instance, with the renter's key and nothing else. const [pod] = w.livePods(); assert.equal(pod.name, "idle-" + id); assert.equal(pod.sshPublicKeys.length, 1); assert.match(pod.sshPublicKeys[0], /^ssh-ed25519 \S+$/); assert.equal(JSON.stringify(r.body).includes(pod.providerId), false, "the provider's id is not shown"); w.advance(20); const waiting = (await w.call("GET", "/v1/instances/" + id, { token: user.token })).body; assert.equal(waiting.status, "starting"); assert.equal(waiting.costUsd, 0); w.advance(10); // the mock is ready 30 seconds after the request const up = (await w.call("GET", "/v1/instances/" + id, { token: user.token })).body; assert.equal(up.status, "running"); assert.equal(up.startedAt, new Date(w.t).toISOString(), "billing starts when it was seen ready"); assert.equal(up.sshCommand, `ssh root@127.0.0.1 -p ${pod.port}`); assert.equal(up.secondsBilled, 0); assert.equal((await w.me(user)).creditsUsd, 10, "30 seconds of start-up cost nothing"); w.advance(90); const metered = (await w.call("GET", "/v1/instances/" + id, { token: user.token })).body; assert.equal(metered.secondsBilled, 90); assert.equal(metered.costUsd, 0.018); assert.equal((await w.me(user)).creditsUsd, 9.982); assert.deepEqual((await w.call("GET", "/v1/instances", { token: user.token })).body.instances.map((i) => [i.id, i.status]), [[id, "running"]]); const open = (await w.call("GET", "/v1/ledger", { token: user.token })).body.entries[0]; assert.deepEqual([open.type, open.open, open.deltaUsd], ["charge", true, -0.018]); w.advance(10); const end = await w.call("POST", `/v1/instances/${id}/end`, { token: user.token }); assert.equal(end.status, 200); assert.deepEqual( { type: end.body.type, instanceId: end.body.instanceId, gpu: end.body.gpu, secondsBilled: end.body.secondsBilled, usd: end.body.usd, ratePerHourUsd: end.body.ratePerHourUsd, startedAt: end.body.startedAt, endedAt: end.body.endedAt, reason: end.body.reason, alreadyEnded: end.body.alreadyEnded }, { type: "charge", instanceId: id, gpu: "rtx-4090", secondsBilled: 100, usd: 0.02, ratePerHourUsd: 0.72, startedAt: up.startedAt, endedAt: new Date(w.t).toISOString(), reason: "user", alreadyEnded: false }, ); assert.equal(end.body.instance.status, "ended"); assert.equal(end.body.instance.ssh, null); assert.deepEqual(w.livePods(), [], "the machine was terminated at the provider in the same request"); assert.ok(w.store.peek().instances[id].releasedAt); w.advance(500); const again = await w.call("POST", `/v1/instances/${id}/end`, { token: user.token }); assert.equal(again.body.id, end.body.id); assert.equal(again.body.alreadyEnded, true); await w.tick(); assert.equal((await w.me(user)).creditsUsd, 9.98, "nothing after the end"); const after = (await w.call("GET", "/v1/instances/" + id, { token: user.token })).body; assert.equal(after.receipt.id, end.body.id); assert.deepEqual((await w.call("GET", "/v1/ledger", { token: user.token })).body.entries.map((e) => [e.type, e.deltaUsd]), [["charge", -0.02], ["topup", 10]]); }); test("refusals: no session, unknown GPU, no SSH key, no credits, none in stock, more than 3", async () => { const w = world({ mock: { stock: { b200: "none" } } }); const user = await w.signIn(); await w.tick(); const rent = (body, token = user.token) => w.call("POST", "/v1/instances", { token, body }); assert.equal((await rent({ gpu: "rtx-4090" }, null)).status, 401); assert.deepEqual([(await rent({ gpu: "gtx-1080" })).status, (await rent({})).body.error], [400, "unknown-gpu"]); assert.deepEqual([(await rent({ gpu: "rtx-4090" })).status, (await rent({ gpu: "rtx-4090" })).body.error], [400, "no-ssh-key"]); await w.call("POST", "/v1/ssh-keys", { token: user.token, body: { name: "k", publicKey: sshKey() } }); const poor = await rent({ gpu: "rtx-4090" }); assert.deepEqual([poor.status, poor.body.error, poor.body.neededUsd], [402, "insufficient-credits", 0.12]); await w.topUp(user, 100); assert.deepEqual([(await rent({ gpu: "b200" })).status, (await rent({ gpu: "b200" })).body.error], [409, "no-capacity"]); assert.equal((await rent({ gpu: "rtx-4090", sshKeyIds: ["nope"] })).status, 404); assert.equal(w.provider.calls.create, 0, "none of these reached the provider"); for (let i = 0; i < 3; i++) assert.equal((await rent({ gpu: "rtx-4090" })).status, 201); const fourth = await rent({ gpu: "rtx-4090" }); assert.deepEqual([fourth.status, fourth.body.error], [409, "limit"]); assert.equal(w.livePods().length, 3); assert.equal((await w.call("GET", "/v1/instances/i9999", { token: user.token })).status, 404); const stranger = await w.signIn(); const theirs = (await w.me(user)).instances[0].id; assert.equal((await w.call("GET", "/v1/instances/" + theirs, { token: stranger.token })).status, 404); assert.equal((await w.call("POST", `/v1/instances/${theirs}/end`, { token: stranger.token })).status, 404); }); test("two requests at the same instant with credits for one: one machine, not two", async () => { const w = world(); const user = await w.renter(0.13); // 10 minutes of one RTX 4090 is 0.12 const results = await Promise.all([1, 2].map(() => w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } }))); assert.deepEqual(results.map((r) => r.status).sort(), [201, 402]); assert.equal(w.livePods().length, 1); }); test("the provider has no machine: 409, nothing charged, and the place is free again", async () => { const w = world(); const user = await w.renter(10); w.provider.failCreate = "no-capacity"; const r = await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } }); assert.deepEqual([r.status, r.body.error], [409, "no-capacity"]); w.provider.failCreate = "provider-funds"; const funds = await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } }); assert.deepEqual([funds.status, funds.body.error], [502, "provider"]); assert.ok(!/fund|balance/i.test(funds.body.message), "the state of the provider account is not a renter's business"); const me = await w.me(user); assert.equal(me.creditsUsd, 10); assert.deepEqual(me.instances.map((i) => [i.status, i.reason]), [["failed", "provider"], ["failed", "no-capacity"]]); w.provider.failCreate = null; assert.equal((await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } })).status, 201); }); test("ending before the machine is ready terminates it and costs nothing", async () => { const w = world(); const user = await w.renter(10); const { id } = (await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "h100" } })).body; w.advance(5); const end = (await w.call("POST", `/v1/instances/${id}/end`, { token: user.token })).body; assert.deepEqual([end.usd, end.secondsBilled, end.startedAt], [0, 0, null]); assert.deepEqual(w.livePods(), []); w.advance(100); await w.tick(); assert.equal((await w.me(user)).creditsUsd, 10); }); }); describe("the tick", () => { test("needs its secret", async () => { const w = world(); assert.equal((await w.call("GET", "/v1/tick")).status, 401); assert.equal((await w.call("GET", "/v1/tick", { token: "wrong" })).status, 401); assert.equal((await w.call("GET", "/v1/tick", { token: CRON + "x" })).status, 401); const ok = await w.tick(); assert.equal(ok.status, 200); assert.equal(ok.headers["Cache-Control"], "no-store"); const closed = world({ without: ["cronSecret"] }); assert.equal((await closed.call("GET", "/v1/tick", { token: "" })).status, 503); assert.equal((await closed.call("GET", "/v1/tick", { token: "undefined" })).status, 503); }); test("sees machines become ready and starts their meter, with nobody looking", async () => { const w = world(); const user = await w.renter(10); const { id } = (await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } })).body; w.advance(60); const t = (await w.tick()).body; assert.deepEqual([t.polled, t.instances.running], [1, 1]); w.advance(60); await w.tick(); const inst = (await w.call("GET", "/v1/instances/" + id, { token: user.token })).body; assert.deepEqual([inst.status, inst.secondsBilled, inst.costUsd], ["running", 60, 0.012]); }); test("an account that runs dry: its machine is ended and terminated at the provider, and the balance never goes below zero", async () => { const w = world(); const user = await w.renter(0.2); // 1000 seconds of an RTX 4090 const inst = await w.rentRunning(user); for (let i = 0; i < 15; i++) { w.advance(60); await w.tick(); } assert.equal(w.livePods().length, 1, "900 seconds in: 0.02 left covers the next minute"); w.advance(60); const t = (await w.tick()).body; assert.deepEqual([t.endedBySettlement, t.released, t.instances.running], [1, 1, 0]); assert.deepEqual(w.livePods(), []); const me = await w.me(user); assert.deepEqual([me.instances[0].status, me.instances[0].reason, me.instances[0].secondsBilled], ["ended", "out-of-credits", 960]); assert.equal(me.creditsMicro, 200_000 - 960 * 200); assert.ok(me.creditsMicro >= 0); const receipt = (await w.call("GET", "/v1/instances/" + inst.id, { token: user.token })).body.receipt; assert.deepEqual([receipt.usd, receipt.secondsBilled, receipt.reason], [0.192, 960, "out-of-credits"]); }); test("a machine that is never ready is terminated after 10 minutes and costs nothing", async () => { const w = world({ mock: { neverReady: ["h100"] } }); const user = await w.renter(10); const { id } = (await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "h100" } })).body; for (let i = 0; i < 9; i++) { w.advance(60); await w.tick(); } assert.equal(w.livePods().length, 1); w.advance(60); const t = (await w.tick()).body; assert.equal(t.released, 1); assert.deepEqual(w.livePods(), []); const inst = (await w.call("GET", "/v1/instances/" + id, { token: user.token })).body; assert.deepEqual([inst.status, inst.reason, inst.costUsd, inst.secondsBilled], ["failed", "never-ready", 0, 0]); assert.equal((await w.me(user)).creditsUsd, 10); const ledger = (await w.call("GET", "/v1/ledger", { token: user.token })).body.entries; assert.deepEqual(ledger.map((e) => [e.type, e.usd]), [["refund", 0], ["topup", 10]]); assert.match(ledger[0].note, /Nothing was charged/); assert.equal((await w.call("POST", `/v1/instances/${id}/end`, { token: user.token })).body.usd, 0); }); test("a machine the provider lost: billing stops at its last confirmation and the rest is refunded", async () => { const w = world(); const user = await w.renter(10); const inst = await w.rentRunning(user); w.advance(60); await w.tick(); // confirmed running 60 seconds in w.provider.lose([...w.provider.pods.keys()][0]); w.advance(45); assert.equal((await w.call("GET", "/v1/instances/" + inst.id, { token: user.token })).body.secondsBilled, 105, "the renter's own look still meters: nobody knows yet"); w.advance(15); await w.tick(); const after = (await w.call("GET", "/v1/instances/" + inst.id, { token: user.token })).body; assert.deepEqual([after.status, after.reason, after.secondsBilled, after.costUsd], ["ended", "provider-lost", 60, 0.012]); assert.equal((await w.me(user)).creditsUsd, 9.988); const ledger = (await w.call("GET", "/v1/ledger", { token: user.token })).body.entries; assert.deepEqual(ledger.map((e) => [e.type, e.deltaUsd]), [["refund", 0.012], ["charge", -0.024], ["topup", 10]]); }); test("machines nobody tracks are found on the provider account: adopted when a request died half-way, terminated otherwise", async () => { const w = world(); const user = await w.renter(10); // A request that booked the instance and created the machine, then died before recording the machine's id. const original = w.provider.create; let orphanId = null; w.provider.create = async (args) => { orphanId = (await original(args)).providerId; throw new Error("the function was killed here"); }; const dead = await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } }); assert.equal(dead.status, 502); w.provider.create = original; assert.equal(w.livePods().length, 1, "a paid machine with no owner"); // A machine with Idle's prefix that no instance ever knew, and one that is not Idle's at all. const stray = (await w.provider.create({ gpuId: "h100", sshPublicKeys: ["k"], name: "idle-i9999" })).providerId; const foreign = (await w.provider.create({ gpuId: "h100", sshPublicKeys: ["k"], name: "my-own-training" })).providerId; w.advance(60); const first = (await w.tick()).body; // The dead request's machine is tied back to its (failed) instance and terminated at once. assert.deepEqual([first.adopted, first.released, first.orphansTerminated], [1, 1, 0]); assert.ok(w.provider.pods.get(orphanId).gone); assert.ok(!w.provider.pods.get(stray).gone, "a machine no instance knows gets 15 minutes: a request may still be on its way"); w.advance(900); const t = (await w.tick()).body; assert.equal(t.orphansTerminated, 1); assert.ok(w.provider.pods.get(stray).gone); assert.deepEqual(w.livePods().map((p) => p.providerId), [foreign], "what does not carry Idle's prefix is never touched"); assert.equal((await w.me(user)).creditsUsd, 10); assert.deepEqual((await w.me(user)).instances.map((i) => [i.status, i.costUsd]), [["failed", 0]]); }); test("a booked instance whose machine id was lost is adopted, then runs and bills normally", async () => { const w = world(); const user = await w.renter(10); const { id } = (await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } })).body; // Put the state back to "booked, machine id never written", as after a crash between the two writes. const state = w.store.peek(); const providerId = state.instances[id].providerId; Object.assign(state.instances[id], { providerId: null, status: "requested" }); const { etag } = await w.store.load(); await w.store.save(state, etag); w.advance(60); const t = (await w.tick()).body; assert.equal(t.adopted, 1); assert.equal(w.store.peek().instances[id].providerId, providerId); w.advance(60); await w.tick(); assert.equal((await w.call("GET", "/v1/instances/" + id, { token: user.token })).body.status, "running"); assert.equal(w.livePods().length, 1); }); test("a provider that fails during a tick stops nothing: the machine is released at the next one", async () => { const w = world(); const user = await w.renter(10); const inst = await w.rentRunning(user); const terminate = w.provider.terminate; w.provider.terminate = async () => { throw new ProviderError("provider", "down", "503"); }; const end = await w.call("POST", `/v1/instances/${inst.id}/end`, { token: user.token }); assert.equal(end.status, 200, "the renter is done and stops paying, whatever the provider does"); assert.equal(w.livePods().length, 1); w.advance(60); assert.equal((await w.tick()).body.instances.unreleased, 1); w.provider.terminate = terminate; w.advance(60); const t = (await w.tick()).body; assert.deepEqual([t.released, t.instances.unreleased], [1, 0]); assert.deepEqual(w.livePods(), []); assert.equal((await w.me(user)).creditsUsd, 10, "ended the instant it was seen running"); assert.ok(w.logs.some((l) => l.event === "provider-error" && l.call === "terminate")); }); }); describe("API keys over the API", () => { const makeKey = async (w, user, capUsdPerDay = 5) => { const r = await w.call("POST", "/v1/api-keys", { token: user.token, body: { name: "agent", capUsdPerDay } }); assert.equal(r.status, 201); return r.body; }; test("the secret is shown once; the key rents and reads, and cannot touch keys", async () => { const w = world(); const user = await w.renter(10); const key = await makeKey(w, user); assert.match(key.secret, /^idk_[A-Za-z0-9_-]{43}$/); assert.deepEqual([key.capUsdPerDay, key.spentTodayUsd, key.stopped], [5, 0, false]); assert.equal(JSON.stringify(w.store.peek()).includes(key.secret), false, "the state holds the hash, not the secret"); const listed = (await w.me(user)).apiKeys; assert.deepEqual(listed.map((k) => [k.id, k.name, k.capUsdPerDay, k.spentTodayUsd, k.stopped]), [[key.id, "agent", 5, 0, false]]); assert.equal("secret" in listed[0], false); const viaKey = await w.call("GET", "/v1/me", { token: key.secret }); assert.deepEqual([viaKey.status, viaKey.body.address, viaKey.body.via, viaKey.body.apiKeyId], [200, user.address, "api-key", key.id]); for (const [method, path, body] of [["POST", "/v1/ssh-keys", { name: "x", publicKey: sshKey() }], ["DELETE", "/v1/ssh-keys/" + user.sshKeyId], ["POST", "/v1/api-keys", { name: "more", capUsdPerDay: 1 }], ["POST", `/v1/api-keys/${key.id}/stop`], ["DELETE", "/v1/api-keys/" + key.id]]) { const r = await w.call(method, path, { token: key.secret, body }); assert.deepEqual([r.status, r.body.error], [403, "session-required"], method + " " + path); } const inst = await w.rentRunning(user, "rtx-4090", key.secret); assert.equal(inst.apiKeyId, key.id); w.advance(100); assert.equal((await w.call("GET", "/v1/ledger", { token: key.secret })).body.entries[0].deltaUsd, -0.02); assert.equal((await w.me(user)).apiKeys[0].spentTodayUsd, 0.02); assert.equal((await w.call("POST", `/v1/instances/${inst.id}/end`, { token: key.secret })).body.usd, 0.02); for (const bad of [{ name: "x" }, { name: "x", capUsdPerDay: 0 }, { name: "x", capUsdPerDay: -1 }, { name: "x", capUsdPerDay: "lots" }, { name: "", capUsdPerDay: 1 }]) { assert.equal((await w.call("POST", "/v1/api-keys", { token: user.token, body: bad })).status, 400); } }); test("the daily cap ends what the key started, and the key cannot start more that day", async () => { const w = world(); const user = await w.renter(10); const key = await makeKey(w, user, 0.2); // 1000 seconds of an RTX 4090 a day await w.rentRunning(user, "rtx-4090", key.secret); for (let i = 0; i < 16; i++) { w.advance(60); await w.tick(); } const me = await w.me(user); assert.deepEqual([me.instances[0].status, me.instances[0].reason], ["ended", "key-cap"]); assert.ok(me.apiKeys[0].spentTodayUsd <= 0.2); assert.equal(me.apiKeys[0].spentTodayUsd, 0.192); assert.deepEqual(w.livePods(), []); const more = await w.call("POST", "/v1/instances", { token: key.secret, body: { gpu: "rtx-4090" } }); assert.deepEqual([more.status, more.body.error], [402, "key-cap"]); assert.equal((await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "rtx-4090" } })).status, 201, "the wallet itself is not capped"); }); test("stopping a key ends its instances, terminates their machines and shuts the key out", async () => { const w = world(); const user = await w.renter(10); const key = await makeKey(w, user); const byKey = await w.rentRunning(user, "rtx-4090", key.secret); const byWallet = await w.rentRunning(user); w.advance(50); const stop = await w.call("POST", `/v1/api-keys/${key.id}/stop`, { token: user.token }); assert.equal(stop.status, 200); assert.equal(stop.body.stopped, true); assert.deepEqual(stop.body.ended.map((e) => [e.instanceId, e.reason, e.secondsBilled]), [[byKey.id, "key-stopped", 80]]); assert.deepEqual(w.livePods().map((p) => p.name), ["idle-" + byWallet.id]); const shut = await w.call("GET", "/v1/me", { token: key.secret }); assert.deepEqual([shut.status, shut.body.error], [403, "key-stopped"]); assert.equal((await w.call("POST", "/v1/instances", { token: key.secret, body: { gpu: "rtx-4090" } })).status, 403); assert.equal((await w.call("POST", "/v1/api-keys/nope/stop", { token: user.token })).status, 404); }); test("deleting a key ends its instances and the secret stops working", async () => { const w = world(); const user = await w.renter(10); const key = await makeKey(w, user); await w.rentRunning(user, "rtx-4090", key.secret); const del = await w.call("DELETE", "/v1/api-keys/" + key.id, { token: user.token }); assert.deepEqual([del.status, del.body.ok, del.body.ended.length], [200, true, 1]); assert.deepEqual(w.livePods(), []); assert.equal((await w.call("GET", "/v1/me", { token: key.secret })).status, 401); assert.deepEqual((await w.me(user)).apiKeys, []); }); }); describe("the relayer route", () => { const erc20 = new Interface(["function transfer(address to, uint256 value) returns (bool)"]); const signed = (wallet, to) => wallet.signTransaction({ chainId: 99901, type: 2, to: USDC, data: erc20.encodeFunctionData("transfer", [to, 5_000_000n]), nonce: 0, gasLimit: 80_000n, maxFeePerGas: 1_000_000_000n, maxPriorityFeePerGas: 1_000_000_000n }); const chainWith = (w) => async (method, params) => (method === "eth_call" ? "0x" + "0".repeat(63) + "1" : method === "eth_getTransactionCount" ? "0x0" : w.chain.rpc(method, params)); test("forwards reads, carries a top-up when a gas account is there, and nothing else", async () => { const posted = []; const w = world({ deps: { post: async (raw) => (posted.push(raw), "0x" + "aa".repeat(32)) } }); const w2 = world({ deps: { chain: chainWith(w), post: async (raw) => (posted.push(raw), "0x" + "aa".repeat(32)) } }); assert.equal((await w.call("POST", "/rpc", { body: { jsonrpc: "2.0", id: 1, method: "eth_blockNumber" } })).body.result, "0x3e8"); assert.equal((await w.call("POST", "/rpc", { body: { id: 1, method: "eth_accounts" } })).body.error.code, -32601); assert.equal((await w.call("POST", "/rpc", { raw: "{nope" })).body.error.code, -32700); const wallet = Wallet.createRandom(); const good = await signed(wallet, TREASURY); const sent = await w2.call("POST", "/rpc", { body: { id: 2, method: "eth_sendRawTransaction", params: [good] } }); assert.match(sent.body.result, /^0x[0-9a-f]{64}$/); assert.deepEqual(posted, [good]); const bad = await w2.call("POST", "/rpc", { body: { id: 3, method: "eth_sendRawTransaction", params: [await signed(wallet, "0x" + "99".repeat(20))] } }); assert.match(bad.body.error.message, /^scope:/); assert.equal(posted.length, 1); assert.equal((await w2.call("GET", "/v1/health")).body.relayer.canSend, true); assert.equal(sent.headers["Cache-Control"], "no-store"); // The same for EQNVDA, and for nothing else on that token. const approve = new Interface(["function approve(address spender, uint256 value) returns (bool)"]); const equityTx = (data) => wallet.signTransaction({ chainId: 99901, type: 2, to: EQNVDA, data, nonce: 0, gasLimit: 80_000n, maxFeePerGas: 1_000_000_000n, maxPriorityFeePerGas: 1_000_000_000n }); const eq = await equityTx(erc20.encodeFunctionData("transfer", [TREASURY, 150_000_000n])); assert.match((await w2.call("POST", "/rpc", { body: { id: 4, method: "eth_sendRawTransaction", params: [eq] } })).body.result, /^0x[0-9a-f]{64}$/); assert.deepEqual(posted, [good, eq]); const away = await equityTx(erc20.encodeFunctionData("transfer", ["0x" + "99".repeat(20), 150_000_000n])); assert.match((await w2.call("POST", "/rpc", { body: { id: 5, method: "eth_sendRawTransaction", params: [away] } })).body.error.message, /^scope:/); const allowance = await equityTx(approve.encodeFunctionData("approve", [TREASURY, 150_000_000n])); assert.match((await w2.call("POST", "/rpc", { body: { id: 6, method: "eth_sendRawTransaction", params: [allowance] } })).body.error.message, /^scope:/); assert.equal(posted.length, 2); }); test("without a gas account it posts nothing, and health says it cannot send", async () => { const base = world(); const w = world({ deps: { chain: chainWith(base) } }); const r = await w.call("POST", "/rpc", { body: { id: 1, method: "eth_sendRawTransaction", params: [await signed(Wallet.createRandom(), TREASURY)] } }); assert.match(r.body.error.message, /^no-gas-account/); assert.equal((await w.call("GET", "/v1/health")).body.relayer.canSend, false); }); }); describe("the edges", () => { test("a state store that was never initialised answers 503 `starting` and changes nothing", async () => { const missing = { load: async () => { throw Object.assign(new Error("missing"), { code: "state-missing" }); }, save: async () => true }; const w = world({ store: missing }); const user = await w.signIn(); const r = await w.call("GET", "/v1/me", { token: user.token }); assert.deepEqual([r.status, r.body.error], [503, "starting"]); assert.equal((await w.call("GET", "/v1/health")).body.meter.running, false); }); test("a state that never stops moving answers 503 `busy`; an unexpected failure answers 500 and is logged", async () => { const inner = memoryStore(); const w = world({ store: { load: () => inner.load(), save: async () => false } }); const user = await w.signIn(); const r = await w.call("POST", "/v1/ssh-keys", { token: user.token, body: { name: "k", publicKey: sshKey() } }); assert.deepEqual([r.status, r.body.error], [503, "busy"]); const broken = world({ store: { load: async () => { throw new Error("disk on fire"); }, save: async () => true } }); const u2 = await broken.signIn(); const e = await broken.call("GET", "/v1/me", { token: u2.token }); assert.deepEqual([e.status, e.body.error], [500, "server-error"]); assert.ok(!e.body.message.includes("fire")); assert.ok(broken.logs.some((l) => l.event === "error" && l.error.includes("disk on fire"))); }); test("CORS lets a browser send its token, unknown routes are 404, bodies are bounded, writes are rate limited", async () => { const w = world({ cfg: { writesPerMinute: 3 } }); const pre = await w.app.handle({ method: "OPTIONS", path: "/v1/me" }); assert.equal(pre.status, 204); assert.match(pre.headers["Access-Control-Allow-Headers"], /Authorization/); assert.match(pre.headers["Access-Control-Allow-Methods"], /DELETE/); assert.equal((await w.call("GET", "/v1/nope")).status, 404); assert.equal((await w.call("POST", "/v1/nope", { ip: "a" })).status, 404); assert.equal((await w.call("POST", "/v1/auth/challenge", { ip: "b", raw: JSON.stringify({ address: "x".repeat(20_000) }) })).status, 413); assert.equal((await w.call("POST", "/v1/auth/challenge", { ip: "c", raw: "[1,2]" })).body.error, "bad-json"); for (let i = 0; i < 3; i++) assert.equal((await w.call("POST", "/v1/auth/challenge", { ip: "d", body: { address: "0x" + "11".repeat(20) } })).status, 200); const limited = await w.call("POST", "/v1/auth/challenge", { ip: "d", body: { address: "0x" + "11".repeat(20) } }); assert.deepEqual([limited.status, limited.body.error], [429, "rate-limited"]); }); test("every error is JSON with a code and a message", async () => { const w = world(); const user = await w.signIn(); for (const r of [ await w.call("GET", "/v1/me"), await w.call("GET", "/v1/nope"), await w.call("POST", "/v1/instances", { token: user.token, body: { gpu: "nope" } }), await w.call("POST", "/v1/credits/claim", { token: user.token, body: {} }), await w.call("DELETE", "/v1/api-keys/x", { token: user.token }), await w.call("GET", "/v1/tick"), ]) { assert.ok(r.status >= 400); assert.equal(typeof r.body.error, "string"); assert.match(r.body.error, /^[a-z-]+$/); assert.ok(r.body.message.length > 5); } }); }); describe("market offers and idle/auto", () => { const closed = () => world({ without: ["provider", "store", "sessionSecret", "treasury", "chain"] }); const OFFER = ["asOf", "gpu", "kind", "model", "region", "reliability", "secure", "source", "usdPerHour", "vramGb"]; test("/v1/offers answers while everything is closed: both sources, cheapest first, and says whose machines these are", async () => { const w = closed(); const r = await w.call("GET", "/v1/offers"); assert.equal(r.status, 200); assert.deepEqual(Object.keys(r.body).sort(), ["asOf", "constraints", "count", "errors", "note", "offers", "sources", "total"]); assert.deepEqual([r.body.count, r.body.offers.length, r.body.total > 50, r.body.errors], [50, 50, true, []]); for (const o of r.body.offers) assert.deepEqual(Object.keys(o).sort(), OFFER); assert.deepEqual(r.body.offers.map((o) => o.usdPerHour), r.body.offers.map((o) => o.usdPerHour).sort((a, b) => a - b)); assert.deepEqual(r.body.sources.map((x) => [x.name, x.kind, x.ok]), [["runpod", "list-price", true], ["vast", "live-offer", true]]); assert.match(r.body.note, /not Idle's machines/); assert.equal(r.headers["Cache-Control"], undefined, "a public read"); assert.equal(w.store.saves, 0); }); test("/v1/offers filters by model, memory and cloud, and refuses a bad filter", async () => { const w = closed(); const get = async (query) => (await w.call("GET", "/v1/offers", { query })).body; const h100 = await get({ gpu: "H100" }); assert.ok(h100.total >= 3 && h100.offers.every((o) => o.gpu === "h100")); assert.deepEqual(h100.offers.map((o) => [o.source, o.usdPerHour]).slice(0, 3), [["vast", 1.735556], ["vast", 1.735556], ["runpod", 2.69]]); const big = await get({ minVram: "100", secure: "true", limit: "3" }); assert.deepEqual([big.count, big.offers.every((o) => o.vramGb >= 100 && o.secure), big.constraints], [3, true, { gpu: null, minVram: 100, secure: true, limit: 3 }]); assert.ok((await get({ secure: "false" })).offers.every((o) => !o.secure)); assert.equal((await get({ limit: "200" })).count, (await get({ limit: "200" })).total); for (const query of [{ gpu: "gtx-1080" }, { minVram: "lots" }, { minVram: "-1" }, { secure: "maybe" }, { limit: "0" }, { limit: "201" }, { limit: "2.5" }]) { assert.equal((await w.call("GET", "/v1/offers", { query })).status, 400, JSON.stringify(query)); } assert.equal(w.offerCalls.runpod, 1, "all of these were one read of the sources"); }); test("/v1/route picks by the rule asked for, and prices the pick with Idle's margin", async () => { const w = closed(); const route = async (query) => (await w.call("GET", "/v1/route", { query })).body; const cheapest = await route({ minVram: "24" }); assert.deepEqual(Object.keys(cheapest).sort(), ["alternatives", "asOf", "considered", "errors", "idleUsdPerHour", "idleUsdPerSecond", "marginBps", "mode", "note", "pick", "rentableThroughIdle", "rentals", "rule", "sources"]); assert.deepEqual(cheapest.pick, { source: "runpod", kind: "list-price", gpu: null, model: "RTX A5000", vramGb: 24, usdPerHour: 0.16, secure: false, region: null, reliability: null, asOf: cheapest.pick.asOf }); // 0.16 plus the default margin of 20 %: 0.192 per hour, 0.00005333 per second. assert.deepEqual([cheapest.marginBps, cheapest.idleUsdPerHour, cheapest.idleUsdPerSecond], [2000, 0.192, 0.00005333]); assert.deepEqual([cheapest.rule.prefer, cheapest.rule.minVram, cheapest.rule.gpu, cheapest.alternatives.length, cheapest.rentableThroughIdle, cheapest.mode], ["cheapest", 24, null, 3, false, "closed"]); assert.match(cheapest.note, /market offers read from the named sources, not Idle's machines/); assert.match(cheapest.note, /rentals are not open/); const fastest = await route({ minVram: "24", prefer: "fastest" }); assert.deepEqual([fastest.pick.gpu, fastest.pick.usdPerHour, fastest.idleUsdPerHour], ["b200", 5.98, 7.176]); assert.deepEqual(fastest.rule.tierOrder, ["b200", "h200", "h100", "a100", "rtx-5090", "l40s", "rtx-4090"]); assert.match(fastest.rule.description, /highest tier/); const secure = await route({ minVram: "24", prefer: "secure" }); assert.deepEqual([secure.pick.model, secure.pick.secure, secure.pick.usdPerHour, secure.alternatives.every((o) => o.secure)], ["RTX A5000", true, 0.27, true]); const live = await route({ gpu: "h100", prefer: "cheapest" }); assert.deepEqual([live.pick.source, live.pick.kind, live.pick.region, live.pick.usdPerHour, live.idleUsdPerHour], ["vast", "live-offer", "Washington, US", 1.735556, 2.082668]); assert.match(live.note, /live offer of vast/); assert.equal((await route({})).pick.model, "Quadro P2000"); }); test("nothing fits: 404 no-offer with the constraints echoed; a bad rule: 400", async () => { const w = closed(); const none = await w.call("GET", "/v1/route", { query: { minVram: "500", prefer: "secure" } }); assert.equal(none.status, 404); assert.deepEqual([none.body.error, none.body.constraints, none.body.considered], ["no-offer", { minVram: 500, prefer: "secure", gpu: null }, 0]); assert.equal(none.body.sources.length, 2); for (const query of [{ prefer: "prettiest" }, { gpu: "nope" }, { minVram: "NaN" }]) assert.equal((await w.call("GET", "/v1/route", { query })).status, 400, JSON.stringify(query)); }); test("one source down: the other still routes and the answer names what failed; both down: 502, never a guess", async () => { const w = closed(); w.down.vast = true; const r = (await w.call("GET", "/v1/route", { query: { gpu: "h100" } })).body; assert.deepEqual([r.pick.source, r.pick.usdPerHour, r.errors], ["runpod", 2.69, ["vast: connection refused"]]); const offers = (await w.call("GET", "/v1/offers")).body; assert.deepEqual([offers.offers.every((o) => o.source === "runpod"), offers.errors.length, offers.sources[1].ok], [true, 1, false]); const dark = closed(); dark.down = { runpod: true, vast: true }; const lost = await dark.call("GET", "/v1/route", { query: { minVram: "24" } }); assert.deepEqual([lost.status, lost.body.error, lost.body.errors.length], [502, "sources-unavailable", 2]); const empty = await dark.call("GET", "/v1/offers"); assert.deepEqual([empty.status, empty.body.offers, empty.body.errors.length], [200, [], 2]); }); test("a pick is rentable through Idle only on a live deployment, from its own provider's secure cloud, for one of its GPUs", async () => { const real = createMockProvider({ env: {} }); Object.assign(real, { real: true, name: "runpod" }); const live = world({ provider: real }); const route = async (w, query) => (await w.call("GET", "/v1/route", { query })).body; const ok = await route(live, { gpu: "rtx-4090", prefer: "secure" }); assert.deepEqual([ok.pick.source, ok.pick.secure, ok.rentableThroughIdle, ok.mode], ["runpod", true, true, "live"]); assert.match(ok.note, /POST \/v1\/instances \{"gpu": "rtx-4090"\}/); assert.equal((await route(live, { gpu: "rtx-4090" })).rentableThroughIdle, false, "the cheapest 4090 is Runpod's community cloud, which Idle does not use"); assert.equal((await route(live, { gpu: "h100" })).rentableThroughIdle, false, "a Vast offer"); assert.equal((await route(live, { minVram: "24", prefer: "secure" })).rentableThroughIdle, false, "an RTX A5000 is not one of Idle's seven"); assert.equal((await route(world(), { gpu: "rtx-4090", prefer: "secure" })).rentableThroughIdle, false, "a mock provider rents nothing"); const margin = world({ cfg: { marginBps: 1000 } }); assert.deepEqual([(await route(margin, { gpu: "rtx-4090", prefer: "secure" })).idleUsdPerHour, (await route(margin, { gpu: "rtx-4090", prefer: "secure" })).marginBps], [0.979, 1000]); }); test("/v1/health says where routing reads and which rules it knows", async () => { const h = (await closed().call("GET", "/v1/health")).body; assert.deepEqual(h.routing.sources.map((x) => [x.name, x.kind]), [["runpod", "list-price"], ["vast", "live-offer"]]); assert.deepEqual([h.routing.rule, h.routing.path, h.routing.tierOrder.length], [["cheapest", "fastest", "secure"], "/v1/route", 7]); }); }); describe("the route table and the OpenAPI document", () => { // Written out by hand on purpose: taking one of these out of routes.mjs must fail a test. const PUBLIC = ["GET /v1/health", "GET /v1/gpus", "GET /v1/quote", "GET /v1/market", "GET /v1/contract", "GET /v1/contract/account", "GET /v1/credits/quote", "GET /v1/offers", "GET /v1/route", "GET /v1/openapi.json", "POST /v1/auth/challenge", "POST /v1/auth/verify", "POST /rpc", "POST /mcp", "POST /v1/rent"]; const SIGNED = ["GET /v1/me", "POST /v1/ssh-keys", "DELETE /v1/ssh-keys/{id}", "POST /v1/instances", "GET /v1/instances", "GET /v1/instances/{id}", "POST /v1/instances/{id}/end", "POST /v1/credits/claim", "GET /v1/ledger", "POST /v1/api-keys", "POST /v1/api-keys/{id}/stop", "DELETE /v1/api-keys/{id}"]; const closed = () => world({ without: ["provider", "store", "sessionSecret", "treasury", "chain"] }); const op = (doc, id) => { const [method, path] = id.split(" "); return doc.paths[path]?.[method.toLowerCase()]; }; test("the document is OpenAPI 3.1 and holds every public route", async () => { const r = await closed().call("GET", "/v1/openapi.json"); assert.equal(r.status, 200); const doc = r.body; assert.equal(doc.openapi, "3.1.0"); assert.deepEqual([doc.info.title, doc.servers, doc["x-idle-mode"]], ["Idle, the GPU cloud on Elysium", [{ url: "https://idle.test/api" }], "closed"]); for (const id of PUBLIC) { const o = op(doc, id); assert.ok(o, id + " is missing from the OpenAPI document"); assert.deepEqual([o["x-idle-access"], o.security], ["public", []], id); assert.ok(o.summary && o.description && o.responses.default, id); } assert.equal(doc.paths["/v1/route"].get.parameters.find((p) => p.name === "prefer").schema.enum.join(), "cheapest,fastest,secure"); assert.deepEqual(doc.paths["/v1/quote"].get.parameters.map((p) => [p.name, p.in, p.required]), [["gpu", "query", true], ["seconds", "query", true]]); assert.deepEqual(doc.paths["/v1/auth/verify"].post.requestBody.content["application/json"].schema.required, ["address", "signature"]); assert.equal(doc.components.schemas.Error.required.join(), "error,message"); }); test("the signed-in routes are in it too, marked closed until rentals open", async () => { const closedDoc = (await closed().call("GET", "/v1/openapi.json")).body; const openDoc = (await world().call("GET", "/v1/openapi.json")).body; for (const id of SIGNED) { const c = op(closedDoc, id); assert.ok(c, id + " is missing from the OpenAPI document"); assert.deepEqual([c["x-idle-access"], c["x-idle-status"]], ["signed-in", "closed"], id); assert.match(c.description, /Closed on this deployment: answers 503 `not-open`/); assert.ok(c.security.length >= 1 && c.security[0].session); assert.equal(op(openDoc, id)["x-idle-status"], "open", id); } assert.deepEqual(op(closedDoc, "POST /v1/instances").security, [{ session: [] }, { apiKey: [] }]); assert.deepEqual(op(closedDoc, "POST /v1/api-keys").security, [{ session: [] }], "keys are made by the wallet, not by a key"); assert.deepEqual(op(closedDoc, "GET /v1/instances/{id}").parameters.map((p) => [p.name, p.in, p.required]), [["id", "path", true]]); assert.equal(op(closedDoc, "POST /v1/auth/challenge")["x-idle-status"], "closed"); assert.equal(op(closedDoc, "GET /v1/tick")["x-idle-access"], "operator"); assert.equal(openDoc["x-idle-mode"], "test"); }); test("the document and the router are the same table: nothing served is unlisted, nothing listed is unserved", async () => { const w = closed(); const doc = (await w.call("GET", "/v1/openapi.json")).body; const listed = Object.entries(doc.paths).flatMap(([path, ops]) => Object.keys(ops).map((m) => m.toUpperCase() + " " + path)); assert.deepEqual(listed.sort(), ROUTES.map((r) => r.id).sort()); assert.deepEqual([...PUBLIC, ...SIGNED, "GET /v1/tick", "GET /mcp", "DELETE /mcp"].sort(), ROUTES.map((r) => r.id).sort(), "a route was added or removed: say so here too"); // Every listed route answers something of its own; none falls through to "no such route". for (const r of ROUTES) { const res = await w.call(r.method, r.path.replace("{id}", "x1"), { body: r.method === "GET" ? undefined : {}, ip: r.id }); assert.notEqual(res.body?.error, "not-found", r.id + " is listed but not served"); assert.ok([200, 202, 400, 401, 405, 503].includes(res.status), r.id + " answered " + res.status); } // And a path that is not in the table is not served, whatever it looks like. for (const [method, path] of [["GET", "/v1/offers/extra"], ["POST", "/v1/route"], ["GET", "/v1/instances/x1/end"], ["PUT", "/v1/me"], ["GET", "/v1"], ["GET", "/openapi.json"]]) { assert.equal((await w.call(method, path, { ip: "z" })).status, 404, method + " " + path); } assert.deepEqual(matchRoute("POST", "/v1/instances/i0007/end").params, { id: "i0007" }); assert.equal(matchRoute("GET", "/v1/nope"), null); }); test("the README names every route of the table", () => { const readme = readFileSync(new URL("../README.md", import.meta.url), "utf8"); for (const r of ROUTES) { const path = r.path.replace("{id}", ":id"); assert.ok(readme.includes(path), "the README does not mention " + path); } }); });