File size: 13,579 Bytes
34f6aa9 0aee05c 34f6aa9 0aee05c 34f6aa9 c9248c9 34f6aa9 0aee05c 34f6aa9 c443a0e 308911d c443a0e 34f6aa9 f395b6d 7e173d8 34f6aa9 c443a0e 34f6aa9 0aee05c 34f6aa9 7e173d8 34f6aa9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | // SPDX-License-Identifier: MIT
// drAIML · the donation panel: sign in with login333 · drAIML, choose the CPU, RAM and GPU shares, confirm them, then
// watch what this computer gives (measured) and what it earns (SHAMBA LUV, 1 LUV per generated token),
// and request a payout to the signed-in wallet. Everything here runs in the page; the router only
// verifies the sign-in, keeps the ledger and records payout claims, which the drAIML operator pays.
import { donor, ensureEngine, reloadEngine } from "./bonsai.js";
import { LOGIN_KEY, login, format18 } from "./dmind.js";
const $ = (sel) => document.querySelector(sel);
const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "");
const ETHERSCAN = "https://etherscan.io/tx/";
let timer = null;
// ── login333 · drAIML ─────────────────────────────────────────────────────────────────────────────────────────────
function siweMessage(address, nonce) {
const domain = location.host, uri = location.origin, issued = new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
return `${domain} wants you to sign in with your Ethereum account:\n${address}\n\n` +
"Sign in to drAIML.dmind to receive SHAMBA LUV for the compute you donate. No transaction, no gas, nothing moves.\n\n" +
`URI: ${uri}\nVersion: 1\nChain ID: 1\nNonce: ${nonce}\nIssued At: ${issued}`;
}
function step(k, state) { const li = document.querySelector(`#dn-seq [data-k="${k}"]`); if (li) li.dataset.state = state; }
async function routerUrl() { return (await donor.config()).url.replace(/\/$/, ""); }
async function handshake(manual) {
const say = (t) => { $("#dn-login-status").textContent = t; };
try {
$("#dn-seq").hidden = false;
let address;
if (manual) {
address = $("#dn-addr").value.trim();
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) { say("Enter the wallet address (0x + 40 hex characters) first."); return; }
} else {
if (!window.ethereum) { say("No browser wallet found. Use “Sign elsewhere” below."); $("#dn-manual").open = true; return; }
[address] = await window.ethereum.request({ method: "eth_requestAccounts" });
}
step("wallet", "done");
const base = await routerUrl();
const n = await (await fetch(`${base}/auth/nonce?address=${address}`)).json();
if (!n.ok) throw new Error(n.reason);
step("nonce", "done");
const message = siweMessage(address, n.nonce);
let signature;
if (manual) {
$("#dn-msg").value = message;
say("Sign this exact message with your wallet (for example `cast wallet sign`), paste the signature, then press Verify.");
$("#dn-verify").hidden = false;
$("#dn-verify").onclick = () => finish(base, message, $("#dn-sig").value.trim(), say);
return;
}
signature = await window.ethereum.request({ method: "personal_sign", params: [message, address] });
await finish(base, message, signature, say);
} catch (e) {
say(`Sign-in stopped: ${(e && e.message) || e}`);
}
}
async function finish(base, message, signature, say) {
step("sign", "done");
const v = await (await fetch(`${base}/auth/verify`, { method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ message, signature }) })).json();
if (!v.ok) { say(`Not signed in: ${v.reason}`); return; }
step("verify", "done");
const exp = Math.floor(Date.now() / 1000) + v.expires_days * 86400;
try { localStorage.setItem(LOGIN_KEY, JSON.stringify({ address: v.address, token: v.token, exp })); } catch {}
step("open", "done");
say("");
if (donor.running) { donor.stop(); donor.settings({ on: true }); } // rejoin, now paid to this wallet
render();
}
function signOut() {
try { localStorage.removeItem(LOGIN_KEY); } catch {}
document.querySelectorAll("#dn-seq li").forEach((li) => { li.dataset.state = ""; });
$("#dn-seq").hidden = true;
if (donor.running) { donor.stop(); donor.settings({ on: true }); }
render();
}
// ── the share and its confirmation ────────────────────────────────────────────────────────────────────────────────
function wanted() {
return { cpu: $("#dn-cpu-on").checked, pct: +$("#dn-cpu").value, ram: $("#dn-ram-on").checked, jobTokens: +$("#dn-ram").value,
gpu: $("#dn-gpu-on").checked, gpuPct: +$("#dn-gpu").value };
}
function describe(w) {
const threads = Math.max(1, Math.min(4, Math.floor((navigator.hardwareConcurrency || 2) / 2)));
return [
["CPU", w.cpu ? `${w.pct}% of its time on ${threads} of ${navigator.hardwareConcurrency || "?"} cores — after each job it rests ${((100 - w.pct) / w.pct).toFixed(0)}× as long` : "not shared"],
["RAM", w.ram ? `Bonsai stays loaded (about 320 MB) · jobs up to ${w.jobTokens} tokens` : "not shared"],
["GPU", w.gpu ? `up to ${w.gpuPct}% of the graphics card's time (WebGPU, low-power), when this browser has a verified card` : "off"],
["Rewards", login() ? `SHAMBA LUV to ${short(login().address)} · 1 LUV per token your computer writes` : "not signed in — your work counts, but no wallet earns it"],
["Pauses", "while you ask a question, when this tab is hidden, and on battery"],
];
}
function refreshLabels() {
const w = wanted();
$("#dn-cpu-val").textContent = `${w.pct}%`; $("#dn-gpu-val").textContent = `${w.gpuPct}%`;
$("#dn-cpu").disabled = !w.cpu; $("#dn-ram").disabled = !w.ram; $("#dn-gpu").disabled = !w.gpu;
const go = $("#dn-review");
go.disabled = !(w.cpu && w.ram);
go.textContent = donor.ledger.on ? "Review and update" : "Review and start donating";
$("#dn-need").hidden = w.cpu && w.ram;
}
function review() {
const w = wanted(), dlg = $("#dn-confirm");
$("#dn-confirm-list").replaceChildren(...describe(w).map(([k, v]) => {
const li = document.createElement("li"); const b = document.createElement("b"); b.textContent = k + " "; li.append(b, v); return li;
}));
dlg.showModal();
$("#dn-confirm-yes").onclick = async () => {
dlg.close();
const gpuChanged = w.gpu !== donor.ledger.gpu || (w.gpu && w.gpuPct !== donor.ledger.gpuPct);
donor.settings({ pct: w.pct, gpu: w.gpu, gpuPct: w.gpuPct, jobTokens: w.jobTokens });
const say = (t) => { $("#dn-state").textContent = t; };
const mod = await import("./browseml/browseml.js");
let ok;
if (gpuChanged && mod.isReady()) { say("Restarting Bonsai with the new GPU share…"); ok = await reloadEngine((t) => say(t)); }
else ok = await ensureEngine((t) => say(t));
if (!ok) { say("Donating needs Bonsai in this browser: accept the drAIML agreement to start."); return; }
donor.settings({ on: true });
render();
};
$("#dn-confirm-no").onclick = () => dlg.close();
}
function stop() { donor.settings({ on: false }); render(); }
// ── measurement and earnings ──────────────────────────────────────────────────────────────────────────────────────
function row(k, v) { const d = document.createElement("div"); const a = document.createElement("dt"); const b = document.createElement("dd"); a.textContent = k; b.textContent = v; d.append(a, b); return d; }
// why the host credited fewer tokens than the job wrote (router 0.3.0's _credit)
const UNCREDITED = {
"self-served": "not credited, because the question came from this same connection (answering yourself earns nothing)",
"daily ceiling": "partly credited: this wallet reached today's ceiling of 1 trillion LUV",
"cross-check disagreed": "a cross-check, not credited because the answers disagreed",
};
async function render() {
const s = login();
$("#dn-signed").hidden = !s; $("#dn-signin").hidden = !!s;
if (s) $("#dn-who").textContent = s.address;
$("#dn-stop").hidden = !donor.ledger.on;
refreshLabels();
const st = await donor.status(), m = await donor.measure();
const label = { sharing: "🟢 Lending", paused: "⏸️ Paused", waiting: "⏳ Pledged", retrying: "🔄 Reconnecting", stopped: "⛔ Stopped", off: "Off" }[st.state] || st.state;
$("#dn-state").textContent = st.on ? `${label}${st.note ? " · " + st.note : ""}` : "Not donating.";
const g = m.gpu, pc = (x) => (x == null ? "?" : `${Math.round(100 * x)}%`);
// bankML's limiter: limit = the cap on the card's time, busy = its measured busy fraction, share = the rows it computes
const gpu = g ? `${g.card || g.name || "card"} · capped at ${pc(g.limit)} of its time, busy ${pc(g.busy)} · computes ${pc(g.share)} of each layer${g.products_on_card != null ? ` · ${g.products_on_card} products on the card` : ""}`
: (m.gpuWanted ? "asked for, but no verified WebGPU card here · see “Check this browser's graphics card” above" : "off");
$("#dn-measure").replaceChildren(
row("Threads", m.threads ? `${m.threads} of ${m.cores} cores` : "engine not loaded"),
row("Engine memory", m.memoryMB ? `${m.memoryMB} MB${m.deviceMemoryGB ? ` of ~${m.deviceMemoryGB} GB` : ""}` : "—"),
row("GPU", gpu),
row("CPU given", m.lastMs
? `last job ${(m.lastMs / 1000).toFixed(0)} s working, then ${(m.lastMs * (100 - st.pct) / st.pct / 1000).toFixed(0)} s resting = ${st.pct}% per cycle` +
(m.wallMs > 300000 ? ` · ${m.dutyPct.toFixed(1)}% on average since you started` : " · the average settles over a few cycles")
: "no job yet"),
row("Jobs this visit", `${m.jobs} · ${m.tokens} tokens credited · ${(m.engineMs / 1000).toFixed(0)} s of thinking${UNCREDITED[m.lastUncredited] ? ` · last job: ${UNCREDITED[m.lastUncredited]}` : ""}`),
row("Last job speed", m.genTps ? `reads ${m.promptTps.toFixed(1)} · writes ${m.genTps.toFixed(1)} tokens/s` : "—"),
);
// earnings, in SHAMBA LUV only: this browser's own count and the router's account
const local = BigInt(st.luv_wei || "0");
let acct = null; try { acct = await donor.earnings(); } catch {}
const rows = [row("Earned (this browser)", `${format18(local)} LUV`)];
if (acct) {
rows.push(row("Earned (drAIML.dmind ledger)", `${format18(BigInt(acct.luv_wei))} LUV · ${acct.jobs} jobs`),
row("Claimed · paid", `${format18(BigInt(acct.claimed_wei))} · ${format18(BigInt(acct.paid_wei))} LUV`),
row("Available to claim", `${format18(BigInt(acct.available_wei))} LUV`));
}
$("#dn-earn").replaceChildren(...rows);
const pay = $("#dn-payout");
pay.disabled = !(acct && BigInt(acct.available_wei) > 0n);
pay.textContent = s ? `Request payout to ${short(s.address)}` : "Sign in to request a payout";
const list = $("#dn-claims");
list.replaceChildren(...((acct && acct.claims) || []).slice().reverse().map((c) => {
const li = document.createElement("li");
li.textContent = `${new Date(c.t * 1000).toLocaleString()} · ${format18(BigInt(c.luv_wei))} LUV · ${c.status === "paid" ? "paid " : "requested — paid by the drAIML operator in batches"}`;
if (c.tx) { const a = document.createElement("a"); a.href = ETHERSCAN + c.tx; a.target = "_blank"; a.rel = "noopener"; a.textContent = short(c.tx); li.append(a); }
return li;
}));
}
async function payout() {
const s = login(); if (!s) return;
$("#dn-payout").disabled = true;
try {
const r = await donor.claim();
$("#dn-pay-status").textContent = r.ok ? `Requested ${format18(BigInt(r.claim.luv_wei))} LUV to ${short(s.address)}.` : `Not requested: ${r.reason}`;
} catch (e) { $("#dn-pay-status").textContent = `Not requested: ${e.message || e}`; }
render();
}
// ── the drawer ────────────────────────────────────────────────────────────────────────────────────────────────────
export function open() {
const d = $("#donate"); if (!d) return;
const l = donor.ledger;
$("#dn-cpu-on").checked = true; $("#dn-cpu").value = l.pct; $("#dn-ram-on").checked = true; $("#dn-ram").value = String(l.jobTokens);
$("#dn-gpu-on").checked = l.gpu; $("#dn-gpu").value = l.gpuPct;
d.showModal();
render();
clearInterval(timer); timer = setInterval(() => { if (d.open) render(); else clearInterval(timer); }, 5000);
}
export function init() {
$("#donate-open").addEventListener("click", open);
$("#dmind-chip").addEventListener("click", open);
window.addEventListener("draiml:donate", open);
$("#dn-close").onclick = () => $("#donate").close();
$("#dn-go").onclick = () => handshake(false);
$("#dn-manual-go").onclick = () => handshake(true);
$("#dn-signout").onclick = signOut;
["#dn-cpu-on", "#dn-cpu", "#dn-ram-on", "#dn-ram", "#dn-gpu-on", "#dn-gpu"].forEach((s) => $(s).addEventListener("input", refreshLabels));
// with the drAIML WebGPU helper installed, open its check inside the extension (it can open the browser's flag pages)
$("#dn-gpu-check").addEventListener("click", (e) => {
if (document.documentElement.dataset.webgpuHelper) { e.preventDefault(); window.postMessage({ type: "draiml-webgpu-helper:open" }, location.origin); }
});
$("#dn-review").onclick = review;
$("#dn-stop").onclick = stop;
$("#dn-payout").onclick = payout;
}
|