// The rental engine of the Idle GPU cloud: accounts, credits, SSH keys, API keys, instances, the meter, the ledger. // Everything here is a plain function over one state object. No clock, no network, no randomness: the caller // passes `now`, the provider's observations and any secret. A host reads the state, runs one of these functions, // and writes the state back only if nobody else changed it meanwhile (see store.mjs), so two requests at the same // instant can never both spend the same credits. // // What the engine guarantees: // - 1 credit is 1 USD. All money is whole micro-dollars (1e-6 USD), never a fraction. // - An instance is billed per second from the moment the provider showed the machine running with SSH open, // never from the request. What an instance owes after s seconds is ceil(rate * s / 3600): rounded up to the // micro-dollar at each settlement, and never more than s seconds at its rate plus one micro-dollar in total. // - A rental starts only if the credits cover 10 minutes of it, on top of 10 minutes of everything already live. // - A machine that is not ready within 10 minutes is given up and costs nothing. // - When an account cannot cover the next 60 seconds of what it runs, its newest instances are ended until it can. // - Ending writes one receipt in the ledger. Ending twice, or a tick after an end, charges nothing more. // - If the provider lost a machine, billing stops at the last time the provider confirmed it; anything charged // past that moment is given back as a refund entry. import { parsePublicKey } from "./sshkey.mjs"; export const LIMITS = { instances: 3, // live instances per account sshKeys: 10, apiKeys: 10, minSeconds: 600, // credits must cover this much to start lookaheadSeconds: 60, // credits must cover this much to keep running readyTimeoutMs: 600_000, // a machine not ready by then is given up, at no charge requestTimeoutMs: 180_000, // a request the provider never acknowledged lostAfterMs: 300_000, // a running machine the provider stopped confirming keepEndedMs: 7 * 86_400_000, // ended instances stay listed this long; their receipt stays in the ledger maxCapMicro: 1_000_000_000_000, }; export const emptyState = () => ({ v: 1, seq: 0, tickAt: 0, accounts: {}, instances: {}, ledger: [], claimed: {}, keyIndex: {} }); const no = (error, message, extra = {}) => ({ ok: false, error, message, ...extra }); const usd = (micro) => micro / 1e6; /** Micro-dollars as a decimal string, without trailing zeros: 2500000 is "2.5". */ function formatUsd(micro) { const frac = String(micro % 1e6).padStart(6, "0").replace(/0+$/, ""); return Math.floor(micro / 1e6) + (frac ? "." + frac : ""); } const iso = (t) => (t ? new Date(t).toISOString() : null); const utcDay = (t) => new Date(t).toISOString().slice(0, 10); const isLive = (i) => i.status === "requested" || i.status === "starting" || i.status === "running"; const nextId = (state, prefix) => prefix + (++state.seq).toString(36).padStart(4, "0"); export const isAddress = (a) => typeof a === "string" && /^0x[0-9a-f]{40}$/.test(a); /** What `seconds` at `rate` (micro-dollars per hour) owes, rounded up to the micro-dollar. */ export const dueMicro = (rate, seconds) => Number((BigInt(rate) * BigInt(seconds) + 3599n) / 3600n); /** The rate Idle charges for a provider price: the price plus the margin, rounded up to the micro-dollar per hour. */ export const rateFor = (usdPerHour, marginBps) => Number((BigInt(Math.round(usdPerHour * 1e6)) * BigInt(10_000 + marginBps) + 9_999n) / 10_000n); function account(state, address, now) { return (state.accounts[address] ??= { credits: 0, sshKeys: [], apiKeys: [], createdAt: now }); } function entry(state, e) { const row = { id: nextId(state, "e"), ...e }; state.ledger.push(row); return row; } const instancesOf = (state, address) => Object.values(state.instances).filter((i) => i.address === address); const byAge = (a, b) => a.n - b.n; // ---- API keys: the spend of a key counts per UTC day ---- function capLeft(key, now) { return Math.max(0, key.cap - (key.day === utcDay(now) ? key.spent : 0)); } function keySpend(key, micro, now) { const day = utcDay(now); if (key.day !== day) { key.day = day; key.spent = 0; } key.spent = Math.max(0, key.spent + micro); } const keyOf = (state, inst) => (inst.keyId ? state.accounts[inst.address]?.apiKeys.find((k) => k.id === inst.keyId) ?? null : null); // ---- The meter ---- /** Charges one running instance for the whole seconds up to `upTo`. Returns what was charged now. */ function meter(state, inst, upTo) { if (inst.status !== "running") return 0; const seconds = Math.floor((upTo - inst.startedAt) / 1000); if (!(seconds > inst.seconds)) return 0; // same moment, or a clock that went back: nothing to do const due = dueMicro(inst.rate, seconds); const delta = due - inst.due; const acct = state.accounts[inst.address]; const key = keyOf(state, inst); // An account never goes below zero and a key never past its cap. What could not be charged is kept as `unpaid`: // it is the operator's loss, and it only happens when settlements came late. const pay = Math.min(delta, acct.credits, key ? capLeft(key, upTo) : Infinity); acct.credits -= pay; if (key) keySpend(key, pay, upTo); inst.seconds = seconds; inst.due = due; inst.charged += pay; inst.unpaid += delta - pay; inst.settledAt = upTo; return pay; } /** Stops billing at `at`, writes the receipt, and leaves the machine to be released by the host. */ function close(state, inst, at, reason) { const acct = state.accounts[inst.address]; const was = inst.status; let stop = at; if (was === "running") { stop = Math.max(inst.startedAt, at); meter(state, inst, stop); } inst.status = "ended"; inst.endedAt = stop; inst.reason = reason; const receipt = entry(state, { t: stop, address: inst.address, type: "charge", micro: inst.charged, instanceId: inst.id, gpu: inst.gpu, seconds: inst.seconds, rate: inst.rate, startedAt: inst.startedAt, endedAt: stop, reason, }); inst.receiptId = receipt.id; if (was === "running") { // Billed further than the machine is known to have lived (the provider lost it between two checks): // the seconds after `stop` are given back. const kept = Math.floor((stop - inst.startedAt) / 1000); if (kept < inst.seconds) { const refund = Math.max(0, inst.charged - dueMicro(inst.rate, kept)); if (refund > 0) { acct.credits += refund; const key = keyOf(state, inst); if (key && key.day === utcDay(inst.settledAt)) keySpend(key, -refund, inst.settledAt); inst.refunded = refund; inst.refundedSeconds = inst.seconds - kept; entry(state, { t: stop, address: inst.address, type: "refund", micro: refund, instanceId: inst.id, gpu: inst.gpu, seconds: inst.refundedSeconds, reason }); } } } return receipt; } /** A start that did not happen. Nothing was charged; the ledger says so when a machine had been asked for. */ function failStart(state, inst, at, reason, note) { inst.status = "failed"; inst.endedAt = at; inst.reason = reason; if (note) inst.note = String(note).slice(0, 200); if (inst.providerId || reason === "never-ready") { entry(state, { t: at, address: inst.address, type: "refund", micro: 0, instanceId: inst.id, gpu: inst.gpu, seconds: 0, reason, note: "The machine never became ready. Nothing was charged." }); } } /** * Charges every running instance up to `now`, then ends what its account (or its API key) can no longer carry * for the next 60 seconds, newest first. Calling it twice with the same `now` changes nothing the second time. * @returns {{ended: object[]}} the receipts written */ export function settle(state, now) { const ended = []; const running = Object.values(state.instances).filter((i) => i.status === "running").sort(byAge); for (const inst of running) meter(state, inst, now); const next = (list) => list.reduce((s, i) => s + dueMicro(i.rate, LIMITS.lookaheadSeconds), 0); for (const address of new Set(running.map((i) => i.address))) { const acct = state.accounts[address]; let mine = running.filter((i) => i.address === address); while (mine.length && acct.credits < next(mine)) ended.push(close(state, mine.pop(), now, "out-of-credits")); for (const key of acct.apiKeys) { const ofKey = mine.filter((i) => i.keyId === key.id); while (ofKey.length && capLeft(key, now) < next(ofKey)) { const inst = ofKey.pop(); mine = mine.filter((i) => i !== inst); ended.push(close(state, inst, now, "key-cap")); } } } return { ended }; } // ---- Credits ---- /** * Credits a top-up that the host has verified on Elysium. A transaction hash is credited once, ever. * `micro` is what it is worth. `paid` says what was sent, for the ledger: {token, amount} (amount as a decimal * string), and for a token that had to be priced {poolPriceUsd, markUsd, priceUsd, haircutBps}. */ export function claim(state, { address, txHash, micro, block = null, now, paid = null }) { if (!isAddress(address)) return no("invalid", "Not an address."); if (!/^0x[0-9a-f]{64}$/.test(txHash ?? "")) return no("invalid", "Not a transaction hash."); if (!Number.isSafeInteger(micro) || micro <= 0) return no("invalid", "Nothing to credit."); const detail = {}; if (paid) { if (!/^[A-Z0-9]{2,12}$/.test(paid.token ?? "") || !/^\d+(\.\d+)?$/.test(paid.amount ?? "")) return no("invalid", "Bad payment detail."); Object.assign(detail, { token: paid.token, amount: paid.amount }); for (const k of ["poolPriceUsd", "markUsd", "priceUsd", "haircutBps"]) if (Number.isFinite(paid[k])) detail[k] = paid[k]; } if (state.claimed[txHash]) return no("already-claimed", "This transaction was already credited."); const acct = account(state, address, now); acct.credits += micro; state.claimed[txHash] = { address, micro, t: now }; const e = entry(state, { t: now, address, type: "topup", micro, txHash, block, ...detail }); return { ok: true, entry: e, credits: acct.credits }; } // ---- SSH keys ---- export function addSshKey(state, { address, name, publicKey, now }) { if (!isAddress(address)) return no("invalid", "Not an address."); const label = String(name ?? "").trim(); if (!label || label.length > 60) return no("invalid", "A key needs a name of 1 to 60 characters."); const k = parsePublicKey(publicKey); if (!k.ok) return no("invalid", "Not a usable SSH public key: " + k.reason + "."); const acct = account(state, address, now); if (acct.sshKeys.some((x) => x.fingerprint === k.fingerprint)) return no("duplicate", "This key is already on the account."); if (acct.sshKeys.length >= LIMITS.sshKeys) return no("limit", `At most ${LIMITS.sshKeys} SSH keys per account.`); const row = { id: nextId(state, "k"), name: label, type: k.type, publicKey: k.publicKey, fingerprint: k.fingerprint, addedAt: now }; acct.sshKeys.push(row); return { ok: true, key: row }; } /** Removes a key from the account. Machines that already carry it keep it until they end. */ export function removeSshKey(state, { address, id }) { const acct = state.accounts[address]; const i = acct?.sshKeys.findIndex((k) => k.id === id) ?? -1; if (i < 0) return no("not-found", "No such SSH key."); acct.sshKeys.splice(i, 1); return { ok: true, id }; } // ---- API keys ---- /** `hash` is the SHA-256 of the secret, made by the host; the secret itself is never stored. */ export function addApiKey(state, { address, name, capMicro, hash, prefix, now }) { if (!isAddress(address)) return no("invalid", "Not an address."); const label = String(name ?? "").trim(); if (!label || label.length > 60) return no("invalid", "A key needs a name of 1 to 60 characters."); if (!Number.isSafeInteger(capMicro) || capMicro <= 0 || capMicro > LIMITS.maxCapMicro) return no("invalid", "capUsdPerDay must be a positive amount."); if (!/^[0-9a-f]{64}$/.test(hash ?? "") || state.keyIndex[hash]) return no("invalid", "Bad key material."); const acct = account(state, address, now); if (acct.apiKeys.length >= LIMITS.apiKeys) return no("limit", `At most ${LIMITS.apiKeys} API keys per account.`); const row = { id: nextId(state, "a"), name: label, hash, prefix: String(prefix ?? ""), cap: capMicro, day: utcDay(now), spent: 0, stopped: false, createdAt: now }; acct.apiKeys.push(row); state.keyIndex[hash] = address; return { ok: true, key: row }; } /** Whose key this is, or null. */ export function resolveApiKey(state, hash) { const address = state.keyIndex[hash]; const key = address ? state.accounts[address]?.apiKeys.find((k) => k.hash === hash) : null; return key ? { address, key } : null; } function endAllOfKey(state, address, keyId, now, reason) { return instancesOf(state, address).filter((i) => i.keyId === keyId && isLive(i)).sort(byAge).map((i) => close(state, i, now, reason)); } /** Stops a key for good: it is refused from now on and every instance it started is ended. */ export function stopApiKey(state, { address, id, now }) { const key = state.accounts[address]?.apiKeys.find((k) => k.id === id); if (!key) return no("not-found", "No such API key."); key.stopped = true; return { ok: true, key, ended: endAllOfKey(state, address, id, now, "key-stopped") }; } /** Deletes a key. The instances it started are ended first: nothing keeps spending under a key that is gone. */ export function deleteApiKey(state, { address, id, now }) { const acct = state.accounts[address]; const key = acct?.apiKeys.find((k) => k.id === id); if (!key) return no("not-found", "No such API key."); const ended = endAllOfKey(state, address, id, now, "key-deleted"); acct.apiKeys = acct.apiKeys.filter((k) => k !== key); delete state.keyIndex[key.hash]; return { ok: true, id, ended }; } // ---- Instances ---- /** * Books an instance. Nothing is asked of the provider here: the host does that next, then calls attach() * or failInstance(). `rate` is micro-dollars per hour and stays fixed for the life of the instance. * @returns {{ok:true, instance:object, publicKeys:string[]} | {ok:false, error:string, message:string}} */ export function rent(state, { address, gpu, gpuName, rate, sshKeyIds, keyId = null, now }) { if (!isAddress(address)) return no("invalid", "Not an address."); if (!Number.isSafeInteger(rate) || rate <= 0) return no("invalid", "No rate for this GPU."); const acct = state.accounts[address]; if (!acct) return no("no-ssh-key", "Add an SSH public key first: it is the only way into the machine."); const key = keyId ? acct.apiKeys.find((k) => k.id === keyId) : null; if (keyId && !key) return no("not-found", "No such API key."); if (key?.stopped) return no("key-stopped", "This API key is stopped."); if (sshKeyIds != null && (!Array.isArray(sshKeyIds) || sshKeyIds.length === 0)) return no("invalid", "sshKeyIds must be a list of key ids."); const keys = sshKeyIds ? sshKeyIds.map((id) => acct.sshKeys.find((k) => k.id === id)) : acct.sshKeys; if (keys.some((k) => !k)) return no("not-found", "One of the SSH keys is not on this account."); if (keys.length === 0) return no("no-ssh-key", "Add an SSH public key first: it is the only way into the machine."); const live = instancesOf(state, address).filter(isLive); if (live.length >= LIMITS.instances) return no("limit", `At most ${LIMITS.instances} live instances per account.`); const min = (list) => list.reduce((s, i) => s + dueMicro(i.rate, LIMITS.minSeconds), 0); const need = dueMicro(rate, LIMITS.minSeconds) + min(live); if (acct.credits < need) { return no("insufficient-credits", `Credits must cover 10 minutes of every live instance: ${usd(need)} USD needed, ${usd(acct.credits)} USD on the account.`, { neededUsd: usd(need), creditsUsd: usd(acct.credits) }); } if (key) { const keyNeed = dueMicro(rate, LIMITS.minSeconds) + min(live.filter((i) => i.keyId === key.id)); if (capLeft(key, now) < keyNeed) return no("key-cap", "This API key has not enough left of its daily cap for 10 minutes of this GPU.", { neededUsd: usd(keyNeed), leftTodayUsd: usd(capLeft(key, now)) }); } const n = ++state.seq; const inst = { id: "i" + n.toString(36).padStart(4, "0"), n, address, gpu, gpuName: gpuName ?? gpu, rate, keyId, sshKeyIds: keys.map((k) => k.id), status: "requested", reason: null, providerId: null, ssh: null, createdAt: now, startedAt: null, seenAt: null, polledAt: null, settledAt: null, endedAt: null, releasedAt: null, seconds: 0, due: 0, charged: 0, unpaid: 0, refunded: 0, refundedSeconds: 0, receiptId: null, }; state.instances[inst.id] = inst; return { ok: true, instance: inst, publicKeys: keys.map((k) => k.publicKey) }; } /** * Records the provider's id for a booked instance. If the instance was ended meanwhile, the id is still kept, * so the machine gets released. */ export function attach(state, { id, providerId, now }) { const inst = state.instances[id]; if (!inst) return no("not-found", "No such instance."); inst.providerId ??= providerId; if (inst.status !== "requested") return { ok: true, instance: inst, live: false }; inst.status = "starting"; inst.polledAt = now; return { ok: true, instance: inst, live: true }; } /** The provider refused or failed the request: the instance never existed and costs nothing. */ export function failInstance(state, { id, reason, note, now }) { const inst = state.instances[id]; if (!inst) return no("not-found", "No such instance."); if (inst.status === "requested" || inst.status === "starting") failStart(state, inst, now, reason, note); return { ok: true, instance: inst }; } /** * What the provider says about one instance, seen at `now`. * `obs` is {status: "starting"|"running"|"gone", ssh: {host, port, user} | null}. */ export function observe(state, { id, obs, now }) { const inst = state.instances[id]; if (!inst) return no("not-found", "No such instance."); inst.polledAt = now; const ready = obs?.status === "running" && obs.ssh?.host && obs.ssh?.port; if (inst.status === "requested" || inst.status === "starting") { if (obs?.status === "gone") failStart(state, inst, now, "provider-lost"); else if (ready) { const acct = state.accounts[inst.address]; const key = keyOf(state, inst); const others = instancesOf(state, inst.address).filter((i) => i.status === "running"); const need = [...others, inst].reduce((s, i) => s + dueMicro(i.rate, LIMITS.lookaheadSeconds), 0); if (acct.credits < need || (key && (key.stopped || capLeft(key, now) < dueMicro(inst.rate, LIMITS.lookaheadSeconds)))) failStart(state, inst, now, "out-of-credits"); else { // Billing starts here: the moment the machine was seen running with SSH open. inst.status = "running"; inst.startedAt = now; inst.seenAt = now; inst.settledAt = now; inst.ssh = { host: String(obs.ssh.host), port: Number(obs.ssh.port), user: String(obs.ssh.user ?? "root") }; } } else if (now - inst.createdAt >= LIMITS.readyTimeoutMs) failStart(state, inst, now, "never-ready"); } else if (inst.status === "running") { if (ready) inst.seenAt = now; else if (obs?.status === "gone" || now - inst.seenAt >= LIMITS.lostAfterMs) close(state, inst, inst.seenAt, "provider-lost"); } return { ok: true, instance: inst }; } /** Gives up what the provider never acknowledged or never made ready in time. */ export function expire(state, now) { const failed = []; for (const inst of Object.values(state.instances)) { if (inst.status === "requested" && !inst.providerId && now - inst.createdAt >= LIMITS.requestTimeoutMs) failStart(state, inst, now, "provider-timeout"); else if (inst.status === "starting" && now - inst.createdAt >= LIMITS.readyTimeoutMs) failStart(state, inst, now, "never-ready"); else continue; failed.push(inst.id); } return { failed }; } /** Ends an instance for its owner: one last settlement, then the receipt. Ending again returns the same receipt. */ export function end(state, { address, id, now, reason = "user" }) { const inst = state.instances[id]; if (!inst || inst.address !== address) return no("not-found", "No such instance."); if (!isLive(inst)) return { ok: true, already: true, instance: inst, receipt: receiptOf(state, inst) }; return { ok: true, already: false, receipt: close(state, inst, now, reason), instance: inst }; } /** The provider confirmed the machine is terminated. */ export function released(state, { id, now }) { const inst = state.instances[id]; if (inst && !isLive(inst) && inst.providerId && !inst.releasedAt) inst.releasedAt = now; return { ok: true }; } /** * What the host must still do with the provider. * poll: machines to ask about (starting ones; running ones too when `running` is set) * release: machines that are ended here and not yet confirmed terminated there */ export function pending(state, { address = null, running = false, now = 0, minGapMs = 0 } = {}) { const poll = []; const release = []; for (const inst of Object.values(state.instances).sort(byAge)) { if (address && inst.address !== address) continue; if (!inst.providerId) continue; if (!isLive(inst)) { if (!inst.releasedAt) release.push({ id: inst.id, providerId: inst.providerId }); } else if ((inst.status === "starting" || (running && inst.status === "running")) && (minGapMs <= 0 || now - (inst.polledAt ?? 0) >= minGapMs)) { poll.push({ id: inst.id, providerId: inst.providerId, status: inst.status }); } } return { poll, release }; } /** * Compares the provider's machines with the state. `pods` is [{providerId, name, createdAt}] and a machine made * by Idle is named `-`. * adopt: a booked instance whose machine exists but whose id was never recorded (the host died in between) * terminate: machines carrying Idle's prefix that no live instance owns, older than `graceMs` */ export function reconcile(state, { pods, prefix, now, graceMs = 900_000 }) { const adopt = []; const terminate = []; const known = new Set(Object.values(state.instances).filter((i) => i.providerId && (isLive(i) || !i.releasedAt)).map((i) => i.providerId)); for (const pod of pods) { if (typeof pod.name !== "string" || !pod.name.startsWith(prefix + "-") || known.has(pod.providerId)) continue; const inst = state.instances[pod.name.slice(prefix.length + 1)]; if (inst && !inst.providerId) adopt.push({ id: inst.id, providerId: pod.providerId }); else if (now - (pod.createdAt ?? 0) >= graceMs) terminate.push(pod.providerId); } return { adopt, terminate }; } /** Forgets ended instances after a week, once their machine is confirmed released. Receipts stay in the ledger. */ export function prune(state, now) { let n = 0; for (const inst of Object.values(state.instances)) { if (isLive(inst) || (inst.providerId && !inst.releasedAt)) continue; if (now - (inst.endedAt ?? inst.createdAt) < LIMITS.keepEndedMs) continue; delete state.instances[inst.id]; n++; } return { pruned: n }; } export function markTick(state, now) { state.tickAt = now; } // ---- What the API shows ---- export function receiptOf(state, inst) { if (!inst?.receiptId) return null; for (let i = state.ledger.length - 1; i >= 0; i--) if (state.ledger[i].id === inst.receiptId) return state.ledger[i]; return null; } export function viewEntry(e) { const sign = e.type === "charge" ? -1 : 1; const out = { id: e.id, at: iso(e.t), type: e.type, usd: usd(e.micro), deltaUsd: e.micro === 0 ? 0 : sign * usd(e.micro) }; if (e.txHash) Object.assign(out, { txHash: e.txHash, block: e.block ?? null }); // What was sent. A top-up recorded before EQNVDA was taken carries no token: it was USDC, one for one. if (e.type === "topup") Object.assign(out, { token: e.token ?? "USDC", amount: e.amount ?? formatUsd(e.micro) }); for (const k of ["poolPriceUsd", "markUsd", "priceUsd", "haircutBps"]) if (k in e) out[k] = e[k]; if (e.instanceId) Object.assign(out, { instanceId: e.instanceId, gpu: e.gpu, secondsBilled: e.seconds ?? 0, reason: e.reason ?? null }); if (e.type === "charge") Object.assign(out, { ratePerHourUsd: usd(e.rate), startedAt: iso(e.startedAt), endedAt: iso(e.endedAt) }); if (e.open) out.open = true; if (e.note) out.note = e.note; return out; } export function viewInstance(inst) { const ssh = inst.status === "running" && inst.ssh ? { ...inst.ssh, command: `ssh ${inst.ssh.user}@${inst.ssh.host} -p ${inst.ssh.port}` } : null; return { id: inst.id, gpu: inst.gpu, gpuName: inst.gpuName, status: inst.status === "requested" ? "starting" : inst.status, // starting | running | ended | failed reason: inst.reason, note: inst.note ?? null, ratePerHourUsd: usd(inst.rate), ratePerSecondUsd: Math.round((inst.rate / 3600) * 100) / 1e8, createdAt: iso(inst.createdAt), startedAt: iso(inst.startedAt), // when billing started endedAt: iso(inst.endedAt), meteredAt: iso(inst.settledAt), secondsBilled: inst.seconds - inst.refundedSeconds, costUsd: usd(inst.charged - inst.refunded), ssh, sshCommand: ssh?.command ?? null, sshKeyIds: inst.sshKeyIds, apiKeyId: inst.keyId, receiptId: inst.receiptId, }; } export function viewApiKey(key, now) { return { id: key.id, name: key.name, prefix: key.prefix, capUsdPerDay: usd(key.cap), spentTodayUsd: usd(key.day === utcDay(now) ? key.spent : 0), stopped: key.stopped, createdAt: iso(key.createdAt) }; } /** The account as GET /v1/me shows it. An address that never did anything is an empty account, not an error. */ export function viewAccount(state, address, now) { const acct = state.accounts[address] ?? { credits: 0, sshKeys: [], apiKeys: [] }; return { address, creditsUsd: usd(acct.credits), creditsMicro: acct.credits, sshKeys: acct.sshKeys.map((k) => ({ id: k.id, name: k.name, type: k.type, fingerprint: k.fingerprint, addedAt: iso(k.addedAt) })), apiKeys: acct.apiKeys.map((k) => viewApiKey(k, now)), instances: instancesOf(state, address).sort((a, b) => b.n - a.n).map(viewInstance), }; } /** The ledger of one account, newest first. A running instance shows as an open charge: what it has cost so far. */ export function viewLedger(state, address, limit = 100) { const open = instancesOf(state, address) .filter((i) => i.status === "running") .map((i) => ({ id: "open-" + i.id, t: i.settledAt, type: "charge", micro: i.charged, instanceId: i.id, gpu: i.gpu, seconds: i.seconds, rate: i.rate, startedAt: i.startedAt, endedAt: null, reason: null, open: true })); const closed = state.ledger.filter((e) => e.address === address); return [...closed, ...open].reverse().slice(0, limit).map(viewEntry); }