File size: 13,131 Bytes
c181f01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// SPDX-License-Identifier: MIT
// drAIML · donate compute to drAIML.dmind. With the visitor's say-so (a toggle, 10% by default), this tab lends a
// share of its CPU, RAM and GPU to a distributed.mind host: the host hands it thinking jobs (chat completions), the
// browseML engine already loaded for Bonsai runs them exactly as sent, and its bankML receipt goes back with the
// answer. The share is a duty cycle — after a job that held the engine t ms the tab rests t·(100−p)/p ms — and the
// visitor always comes first: a question of theirs, a hidden tab or a battery not charging pauses the lending.
//
// The wire protocol is dmind's, as browseML's share module speaks it (github.com/browseML/browseML, MIT):
//   POST /sharedcpu/join · /update (heartbeat) · /pull (long-poll) · /result · /decline · /leave.
// Reward: SHAMBA LUV, 1 wei per generated token (dmind's paymint), measured to 18 decimals (SCIEN·TIFIC), and
// priced in BANKON units: PAI (1 PAI = 1 USDC), SATPAY (1 satoshi), BTC, and GLDB (gld.basket's troy-ounce unit).
// BANKON tokens are not deployed: here they are units of account only.

const STORE = "draiml-dmind";
const SCALE = 10n ** 18n;
export const LUV = { token: "0x2711111111683B8708cb9a48cBf36a51315F8254", pair: "0x57D2085Aa859a145cB107845AD03c0eAAFBD8a31", tokenIs0: true };
const USDC_WETH = "0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc";   // token0 USDC (6), token1 WETH (18)
const RPC = "https://ethereum-rpc.publicnode.com";
const LLAMA = "https://coins.llama.fi/prices/current/coingecko:bitcoin,coingecko:pax-gold";
const GLDB_OZ = "0.000241833";          // troy ounces per GLDB at gld.basket's genesis reading
const WEI_PER_TOKEN = 1n;
const MODEL_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3";   // browseml/browseML/*.FORK.json               // dmind paymint: 1 wei of LUV per generated token

// ── 18-decimal arithmetic (SCIEN·TIFIC) ──────────────────────────────────────────────────────────────────────────
export const format18 = (x) => { const neg = x < 0n; if (neg) x = -x; return `${neg ? "-" : ""}${x / SCALE}.${(x % SCALE).toString().padStart(18, "0")}`; };
export function parse18(s) {
  const m = /^(\d+)(?:\.(\d{1,18}))?/.exec(String(s).trim());
  return m ? BigInt(m[1]) * SCALE + BigInt(((m[2] || "") + "0".repeat(18)).slice(0, 18)) : 0n;
}
/** a small 18-decimal amount in scientific notation as well, since 18 places round it to zero */
const sci = (x18) => (x18 === 0n ? "0" : (Number(x18) / 1e18).toExponential(3));

// ── the ledger, kept in this browser ─────────────────────────────────────────────────────────────────────────────
function readLedger() {
  try { const l = JSON.parse(localStorage.getItem(STORE) || "{}"); return { tokens: BigInt(l.tokens || 0), jobs: l.jobs || 0, engineMs: l.engineMs || 0, wallet: l.wallet || "", pct: l.pct || 10, on: !!l.on }; }
  catch { return { tokens: 0n, jobs: 0, engineMs: 0, wallet: "", pct: 10, on: false }; }
}
function writeLedger(l) { try { localStorage.setItem(STORE, JSON.stringify({ ...l, tokens: l.tokens.toString() })); } catch {} }

// ── prices ───────────────────────────────────────────────────────────────────────────────────────────────────────
async function rpc(method, params) {
  const r = await fetch(RPC, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) });
  const j = await r.json(); if (!j.result) throw new Error((j.error && j.error.message) || "no result"); return j.result;
}
async function reserves(pair, block) {
  const out = await rpc("eth_call", [{ to: pair, data: "0x0902f1ac" }, block]);   // getReserves()
  return [BigInt("0x" + out.slice(2, 66)), BigInt("0x" + out.slice(66, 130))];
}
let priceCache = null;
/** USD per LUV (18 decimals) from the Uniswap reserves at one block, as luv.oracle prices it; BTC and gold from
 *  DeFiLlama. Cached for 5 minutes. */
export async function prices() {
  if (priceCache && Date.now() - priceCache.at < 300000) return priceCache;
  const block = await rpc("eth_blockNumber", []);
  const [[l0, l1], [u0, u1]] = await Promise.all([reserves(LUV.pair, block), reserves(USDC_WETH, block)]);
  const [luv, weth] = LUV.tokenIs0 ? [l0, l1] : [l1, l0];
  const usdPerEth18 = u0 * 10n ** 12n * SCALE / u1;
  const luvUsd18 = weth * usdPerEth18 / luv;
  let btcUsd18 = 0n, xauUsd18 = 0n;
  try {
    const c = (await (await fetch(LLAMA)).json()).coins || {};
    btcUsd18 = parse18(String(c["coingecko:bitcoin"]?.price ?? 0));
    xauUsd18 = parse18(String(c["coingecko:pax-gold"]?.price ?? 0));
  } catch {}
  priceCache = { at: Date.now(), block: BigInt(block).toString(), luvUsd18, btcUsd18, xauUsd18 };
  return priceCache;
}

/** What the LUV earned is worth, every amount an 18-decimal integer. */
export function valuation(luvWei, p) {
  const usd = luvWei * p.luvUsd18 / SCALE;                         // PAI (= USDC), 18 decimals
  const btc = p.btcUsd18 ? usd * SCALE / p.btcUsd18 : 0n;
  const sat = btc * 100000000n;                                      // SATPAY (1 satoshi), 18 decimals
  const gldbUsd18 = p.xauUsd18 * parse18(GLDB_OZ) / SCALE;
  const gldb = gldbUsd18 ? usd * SCALE / gldbUsd18 : 0n;
  return { PAI: usd, BTC: btc, SATPAY: sat, GLDB: gldb };
}

// ── the sharing loop ─────────────────────────────────────────────────────────────────────────────────────────────
async function sha256hex(t) {
  return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(t)))].map((b) => b.toString(16).padStart(2, "0")).join("");
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export const restMs = (engineMs, pct) => Math.round(engineMs * (100 - pct) / pct);

export class Donor {
  constructor(engine, isVisitorBusy) {
    this.engine = engine;             // () => Promise<browseml module>, loaded (the Agreement was accepted)
    this.busy = isVisitorBusy;        // () => boolean: the visitor's own question is running
    this.ledger = readLedger();
    this.host = null; this.session = ""; this.running = false; this.state = "off"; this.note = ""; this.wake = null;
  }
  async config() {
    if (this.host) return this.host;
    try { this.host = await (await fetch(new URL("./dmind-host.json", import.meta.url), { cache: "no-cache" })).json(); }
    catch { this.host = { label: "drAIML.dmind", url: "" }; }
    return this.host;
  }
  async call(path, body, keepalive = false) {
    const h = this.host, token = h.token_key ? (localStorage.getItem(h.token_key) || "") : "";
    const r = await fetch(h.url.replace(/\/$/, "") + path, { method: "POST", credentials: "omit", keepalive,
      headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify(body) });
    if (r.status === 401 || r.status === 403) throw Object.assign(new Error("the host asks you to sign in to share"), { final: true });
    return r.json();
  }
  settings({ on, pct, wallet }) {
    if (pct) this.ledger.pct = Math.max(5, Math.min(50, Math.round(pct / 5) * 5));
    if (wallet !== undefined) this.ledger.wallet = /^0x[0-9a-fA-F]{40}$/.test(wallet) ? wallet : "";
    this.ledger.on = !!on; writeLedger(this.ledger);
    if (on && !this.running) this.start(); else if (!on && this.running) this.stop();
    if (this.session) this.call("/sharedcpu/update", { session: this.session, share_pct: this.ledger.pct }).catch(() => {});
    if (this.wake) this.wake();
  }
  pauseReason() {
    if (document.hidden) return "this tab is hidden";
    if (this.busy()) return "your own question comes first";
    if (this.battery && !this.battery.charging) return "on battery — sharing waits for the charger";
    return "";
  }
  async rest(ms) { await Promise.race([sleep(ms), new Promise((r) => { this.wake = r; })]); this.wake = null; }
  async start() {
    this.running = true;
    try { this.battery = navigator.getBattery ? await navigator.getBattery() : null; } catch { this.battery = null; }
    const h = await this.config();
    if (!h.url) { this.state = "waiting"; this.note = `${h.label} is not open yet: your pledge of ${this.ledger.pct}% is saved and sharing starts when it opens.`; this.running = false; return; }
    const b = await this.engine();
    let backoff = 0;
    while (this.running) {
      try {
        const why = this.pauseReason();
        if (why) { this.state = "paused"; this.note = why; if (this.session) await this.call("/sharedcpu/update", { session: this.session, paused: true }).catch(() => {}); await this.rest(5000); continue; }
        if (!this.session) {
          const j = await this.call("/sharedcpu/join", { model: b.MODEL.name, model_sha256: MODEL_SHA256, threads: 1,
            share_pct: this.ledger.pct, max_job_tokens: 256, engine: "browseml/draiml", contributor: "browser",
            ...(this.ledger.wallet ? { wallet: this.ledger.wallet } : {}) });
          if (!j.ok) throw Object.assign(new Error(`the host refused: ${j.reason || "no reason given"}`), { final: !!j.barred });
          this.session = String(j.session);
        }
        this.state = "sharing"; this.note = `lending ${this.ledger.pct}% to ${h.label}`;
        const got = await this.call("/sharedcpu/pull", { session: this.session });
        if (got.barred || got.final) throw Object.assign(new Error(got.reason || "stopped by the host"), { final: true });
        if (!got.ok) { if (/session/.test(String(got.reason))) this.session = ""; await this.rest(got.retry_after_s ? got.retry_after_s * 1000 : 5000); continue; }
        const job = got.job; if (!job) continue;
        if (this.busy()) { await this.call("/sharedcpu/decline", { session: this.session, job: job.job, reason: "the visitor is asking" }).catch(() => {}); continue; }
        let cancelled = false;
        const beat = setInterval(() => { this.call("/sharedcpu/update", { session: this.session }).then((u) => { if (u.cancelled === job.job) cancelled = true; }).catch(() => {}); }, 30000);
        const t0 = performance.now(); let text = "", res;
        try { res = await b.chat({ messages: job.messages, max_tokens: job.max_tokens, temperature: job.temperature }, (p) => { text += p; }); }
        finally { clearInterval(beat); }
        const ms = performance.now() - t0;
        if (cancelled) continue;
        const rc = res && res.bankml_receipt;
        if (!rc || (await sha256hex(text)) !== rc.response_sha256) { await this.call("/sharedcpu/fail", { session: this.session, job: job.job, reason: "receipt did not match" }).catch(() => {}); continue; }
        const r = await this.call("/sharedcpu/result", { session: this.session, job: job.job, text, receipt: rc, usage: res.usage, timings: res.timings });
        if (r.ok) {
          const n = BigInt((res.usage && res.usage.completion_tokens) || 0);
          this.ledger.tokens += n * WEI_PER_TOKEN; this.ledger.jobs++; this.ledger.engineMs += Math.round(ms); writeLedger(this.ledger);
        }
        backoff = 0;
        await this.rest(restMs(ms, this.ledger.pct));
      } catch (e) {
        if (e.final) { this.state = "stopped"; this.note = e.message; break; }
        backoff = Math.min(300000, backoff ? backoff * 2 : 5000);
        this.state = "retrying"; this.note = `${e.message || e} · again in ${backoff / 1000} s`;
        await this.rest(backoff);
      }
    }
    this.running = false;
  }
  stop() {
    this.running = false; this.state = "off"; this.note = "";
    if (this.session) { this.call("/sharedcpu/leave", { session: this.session }, true).catch(() => {}); this.session = ""; }
    if (this.wake) this.wake();
  }
  async status() {
    const h = await this.config(), l = this.ledger;
    const luvWei = l.tokens;   // 1 wei per token
    let worth = null, block = null;
    try { const p = await prices(); const v = valuation(luvWei, p); block = p.block;
      worth = Object.fromEntries(Object.entries(v).map(([k, x]) => [k, { exact: format18(x), sci: sci(x) }]));
      worth.LUV_USD = { exact: format18(p.luvUsd18), sci: sci(p.luvUsd18) };
    } catch (e) { worth = { error: String(e.message || e) }; }
    return { on: l.on, pct: l.pct, wallet: l.wallet, host: h.label, open: !!h.url, state: this.state, note: this.note,
             jobs: l.jobs, tokens: l.tokens.toString(), engine_s: Math.round(l.engineMs / 1000),
             luv: format18(luvWei), luv_wei: luvWei.toString(), worth, block };
  }
}