banking_model.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. const crypto = require("crypto");
  2. const fs = require("fs");
  3. const path = require("path");
  4. const pull = require("../server/node_modules/pull-stream");
  5. const { getConfig } = require("../configs/config-manager.js");
  6. const { config } = require("../server/SSB_server.js");
  7. const clamp = (x, lo, hi) => Math.max(lo, Math.min(hi, x));
  8. const DEFAULT_RULES = {
  9. epochKind: "WEEKLY",
  10. alpha: 0.2,
  11. reserveMin: 500,
  12. capPerEpoch: 2000,
  13. caps: { M_max: 3, T_max: 1.5, P_max: 2, cap_user_epoch: 50, w_min: 0.2, w_max: 6 },
  14. coeffs: { a1: 0.6, a2: 0.4, a3: 0.3, a4: 0.5, b1: 0.5, b2: 1.0 },
  15. graceDays: 14
  16. };
  17. const STORAGE_DIR = path.join(__dirname, "..", "configs");
  18. const EPOCHS_PATH = path.join(STORAGE_DIR, "banking-epochs.json");
  19. const TRANSFERS_PATH = path.join(STORAGE_DIR, "banking-allocations.json");
  20. const ADDR_PATH = path.join(STORAGE_DIR, "wallet-addresses.json");
  21. function ensureStoreFiles() {
  22. if (!fs.existsSync(STORAGE_DIR)) fs.mkdirSync(STORAGE_DIR, { recursive: true });
  23. if (!fs.existsSync(EPOCHS_PATH)) fs.writeFileSync(EPOCHS_PATH, "[]");
  24. if (!fs.existsSync(TRANSFERS_PATH)) fs.writeFileSync(TRANSFERS_PATH, "[]");
  25. if (!fs.existsSync(ADDR_PATH)) fs.writeFileSync(ADDR_PATH, "{}");
  26. }
  27. function epochIdNow() {
  28. const d = new Date();
  29. const tmp = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
  30. const dayNum = tmp.getUTCDay() || 7;
  31. tmp.setUTCDate(tmp.getUTCDate() + 4 - dayNum);
  32. const yearStart = new Date(Date.UTC(tmp.getUTCFullYear(), 0, 1));
  33. const weekNo = Math.ceil((((tmp - yearStart) / 86400000) + 1) / 7);
  34. const yyyy = tmp.getUTCFullYear();
  35. return `${yyyy}-${String(weekNo).padStart(2, "0")}`;
  36. }
  37. async function ensureSelfAddressPublished() {
  38. const me = config.keys.id;
  39. const local = readAddrMap();
  40. const current = typeof local[me] === "string" ? local[me] : (local[me] && local[me].address) || null;
  41. if (current && isValidEcoinAddress(current)) return { status: "present", address: current };
  42. const cfg = getWalletCfg("user") || {};
  43. if (!cfg.url) return { status: "skipped" };
  44. try {
  45. const addr = await rpcCall("getaddress", []);
  46. if (addr && isValidEcoinAddress(addr)) {
  47. await setUserAddress(me, addr, true);
  48. return { status: "published", address: addr };
  49. }
  50. } catch (_) {
  51. return { status: "error" };
  52. }
  53. return { status: "noop" };
  54. }
  55. function readJson(p, d) {
  56. try { return JSON.parse(fs.readFileSync(p, "utf8")); } catch { return d; }
  57. }
  58. function writeJson(p, v) {
  59. fs.writeFileSync(p, JSON.stringify(v, null, 2));
  60. }
  61. async function rpcCall(method, params, kind = "user") {
  62. const cfg = getWalletCfg(kind);
  63. if (!cfg?.url) {
  64. return null;
  65. }
  66. const headers = {
  67. "Content-Type": "application/json",
  68. };
  69. if (cfg.user || cfg.pass) {
  70. headers.authorization = "Basic " + Buffer.from(`${cfg.user}:${cfg.pass}`).toString("base64");
  71. }
  72. try {
  73. const res = await fetch(cfg.url, {
  74. method: "POST",
  75. headers: headers,
  76. body: JSON.stringify({
  77. jsonrpc: "1.0",
  78. id: "oasis",
  79. method: method,
  80. params: params,
  81. }),
  82. });
  83. if (!res.ok) {
  84. return null;
  85. }
  86. const data = await res.json();
  87. if (data.error) {
  88. return null;
  89. }
  90. return data.result;
  91. } catch (err) {
  92. return null;
  93. }
  94. }
  95. async function safeGetBalance(kind = "user") {
  96. try {
  97. const r = await rpcCall("getbalance", [], kind);
  98. return Number(r) || 0;
  99. } catch {
  100. return 0;
  101. }
  102. }
  103. function readAddrMap() {
  104. ensureStoreFiles();
  105. const raw = readJson(ADDR_PATH, {});
  106. return raw && typeof raw === "object" ? raw : {};
  107. }
  108. function writeAddrMap(m) {
  109. ensureStoreFiles();
  110. writeJson(ADDR_PATH, m || {});
  111. }
  112. function getLogLimit() {
  113. return getConfig().ssbLogStream?.limit || 1000;
  114. }
  115. function isValidEcoinAddress(addr) {
  116. return typeof addr === "string" && /^[A-Za-z0-9]{20,64}$/.test(addr);
  117. }
  118. function getWalletCfg(kind) {
  119. const cfg = getConfig() || {};
  120. if (kind === "pub") {
  121. return cfg.walletPub || cfg.pubWallet || (cfg.pub && cfg.pub.wallet) || null;
  122. }
  123. return cfg.wallet || null;
  124. }
  125. function resolveUserId(maybeId) {
  126. const s = String(maybeId || "").trim();
  127. if (s) return s;
  128. return config?.keys?.id || "";
  129. }
  130. let FEED_SRC = "none";
  131. module.exports = ({ services } = {}) => {
  132. const transfersRepo = {
  133. listAll: async () => { ensureStoreFiles(); return readJson(TRANSFERS_PATH, []); },
  134. listByTag: async (tag) => { ensureStoreFiles(); return readJson(TRANSFERS_PATH, []).filter(t => (t.tags || []).includes(tag)); },
  135. findById: async (id) => { ensureStoreFiles(); return readJson(TRANSFERS_PATH, []).find(t => t.id === id) || null; },
  136. create: async (t) => { ensureStoreFiles(); const all = readJson(TRANSFERS_PATH, []); all.push(t); writeJson(TRANSFERS_PATH, all); },
  137. markClosed: async (id, txid) => { ensureStoreFiles(); const all = readJson(TRANSFERS_PATH, []); const i = all.findIndex(x => x.id === id); if (i >= 0) { all[i].status = "CLOSED"; all[i].txid = txid; writeJson(TRANSFERS_PATH, all); } }
  138. };
  139. const epochsRepo = {
  140. list: async () => { ensureStoreFiles(); return readJson(EPOCHS_PATH, []); },
  141. save: async (epoch) => { ensureStoreFiles(); const all = readJson(EPOCHS_PATH, []); const i = all.findIndex(e => e.id === epoch.id); if (i >= 0) all[i] = epoch; else all.push(epoch); writeJson(EPOCHS_PATH, all); },
  142. get: async (id) => { ensureStoreFiles(); return readJson(EPOCHS_PATH, []).find(e => e.id === id) || null; }
  143. };
  144. async function openSsb() {
  145. if (services?.cooler?.open) return services.cooler.open();
  146. if (global.ssb) return global.ssb;
  147. try {
  148. const srv = require("../server/SSB_server.js");
  149. if (srv?.ssb) return srv.ssb;
  150. if (srv?.server) return srv.server;
  151. if (srv?.default) return srv.default;
  152. } catch (_) {}
  153. return null;
  154. }
  155. async function getWalletFromSSB(userId) {
  156. const ssb = await openSsb();
  157. if (!ssb) return null;
  158. const msgs = await new Promise((resolve, reject) =>
  159. pull(
  160. ssb.createLogStream({ limit: getLogLimit() }),
  161. pull.collect((err, arr) => err ? reject(err) : resolve(arr))
  162. )
  163. );
  164. for (let i = msgs.length - 1; i >= 0; i--) {
  165. const v = msgs[i].value || {};
  166. const c = v.content || {};
  167. if (v.author === userId && c && c.type === "wallet" && c.coin === "ECO" && typeof c.address === "string") {
  168. return c.address;
  169. }
  170. }
  171. return null;
  172. }
  173. async function scanAllWalletsSSB() {
  174. const ssb = await openSsb();
  175. if (!ssb) return {};
  176. const latest = {};
  177. const msgs = await new Promise((resolve, reject) =>
  178. pull(
  179. ssb.createLogStream({ limit: getLogLimit() }),
  180. pull.collect((err, arr) => err ? reject(err) : resolve(arr))
  181. )
  182. );
  183. for (let i = msgs.length - 1; i >= 0; i--) {
  184. const v = msgs[i].value || {};
  185. const c = v.content || {};
  186. if (c && c.type === "wallet" && c.coin === "ECO" && typeof c.address === "string") {
  187. if (!latest[v.author]) latest[v.author] = c.address;
  188. }
  189. }
  190. return latest;
  191. }
  192. async function publishSelfAddress(address) {
  193. const ssb = await openSsb();
  194. if (!ssb) return false;
  195. const msg = { type: "wallet", coin: "ECO", address, updatedAt: new Date().toISOString() };
  196. await new Promise((resolve, reject) => ssb.publish(msg, (err, val) => err ? reject(err) : resolve(val)));
  197. return true;
  198. }
  199. async function listUsers() {
  200. const addrLocal = readAddrMap();
  201. const ids = Object.keys(addrLocal);
  202. if (ids.length > 0) return ids.map(id => ({ id }));
  203. return [{ id: config.keys.id }];
  204. }
  205. async function getUserAddress(userId) {
  206. const v = readAddrMap()[userId];
  207. const local = typeof v === "string" ? v : (v && v.address) || null;
  208. if (local) return local;
  209. const ssbAddr = await getWalletFromSSB(userId);
  210. return ssbAddr;
  211. }
  212. async function setUserAddress(userId, address, publishIfSelf) {
  213. const m = readAddrMap();
  214. m[userId] = address;
  215. writeAddrMap(m);
  216. if (publishIfSelf && userId === config.keys.id) await publishSelfAddress(address);
  217. return true;
  218. }
  219. async function addAddress({ userId, address }) {
  220. if (!userId || !address || !isValidEcoinAddress(address)) return { status: "invalid" };
  221. const m = readAddrMap();
  222. const prev = m[userId];
  223. if (prev && (prev === address || (prev.address && prev.address === address))) return { status: "exists" };
  224. m[userId] = address;
  225. writeAddrMap(m);
  226. if (userId === config.keys.id) await publishSelfAddress(address);
  227. return { status: prev ? "updated" : "added" };
  228. }
  229. async function removeAddress({ userId }) {
  230. if (!userId) return { status: "invalid" };
  231. const m = readAddrMap();
  232. if (!m[userId]) return { status: "not_found" };
  233. delete m[userId];
  234. writeAddrMap(m);
  235. return { status: "deleted" };
  236. }
  237. async function listAddressesMerged() {
  238. const local = readAddrMap();
  239. const ssbAll = await scanAllWalletsSSB();
  240. const keys = new Set([...Object.keys(local), ...Object.keys(ssbAll)]);
  241. const out = [];
  242. for (const id of keys) {
  243. if (local[id]) out.push({ id, address: typeof local[id] === "string" ? local[id] : local[id].address, source: "local" });
  244. else if (ssbAll[id]) out.push({ id, address: ssbAll[id], source: "ssb" });
  245. }
  246. return out;
  247. }
  248. function idsEqual(a, b) {
  249. if (!a || !b) return false;
  250. const A = String(a).trim();
  251. const B = String(b).trim();
  252. if (A === B) return true;
  253. const strip = s => s.replace(/^@/, "").replace(/\.ed25519$/, "");
  254. return strip(A) === strip(B);
  255. }
  256. function inferType(c = {}) {
  257. if (c.vote) return "vote";
  258. if (c.votes) return "votes";
  259. if (c.address && c.coin === "ECO" && c.type === "wallet") return "bankWallet";
  260. if (typeof c.amount !== "undefined" && c.epochId && c.allocationId) return "bankClaim";
  261. if (typeof c.item_type !== "undefined" && typeof c.status !== "undefined") return "market";
  262. if (typeof c.goal !== "undefined" && typeof c.progress !== "undefined") return "project";
  263. if (typeof c.members !== "undefined" && typeof c.isAnonymous !== "undefined") return "tribe";
  264. if (typeof c.date !== "undefined" && typeof c.location !== "undefined") return "event";
  265. if (typeof c.priority !== "undefined" && typeof c.status !== "undefined" && c.title) return "task";
  266. if (typeof c.confirmations !== "undefined" && typeof c.severity !== "undefined") return "report";
  267. if (typeof c.job_type !== "undefined" && typeof c.status !== "undefined") return "job";
  268. if (typeof c.url !== "undefined" && typeof c.mimeType !== "undefined" && c.type === "audio") return "audio";
  269. if (typeof c.url !== "undefined" && typeof c.mimeType !== "undefined" && c.type === "video") return "video";
  270. if (typeof c.url !== "undefined" && c.title && c.key) return "document";
  271. if (typeof c.text !== "undefined" && typeof c.refeeds !== "undefined") return "feed";
  272. if (typeof c.text !== "undefined" && typeof c.contentWarning !== "undefined") return "post";
  273. if (typeof c.contact !== "undefined") return "contact";
  274. if (typeof c.about !== "undefined") return "about";
  275. if (typeof c.concept !== "undefined" && typeof c.amount !== "undefined" && c.status) return "transfer";
  276. return "";
  277. }
  278. function normalizeType(a) {
  279. const t = a.type || a.content?.type || inferType(a.content) || "";
  280. return String(t).toLowerCase();
  281. }
  282. function priorityBump(p) {
  283. const s = String(p || "").toUpperCase();
  284. if (s === "HIGH") return 3;
  285. if (s === "MEDIUM") return 1;
  286. return 0;
  287. }
  288. function severityBump(s) {
  289. const x = String(s || "").toUpperCase();
  290. if (x === "CRITICAL") return 6;
  291. if (x === "HIGH") return 4;
  292. if (x === "MEDIUM") return 2;
  293. return 0;
  294. }
  295. function scoreMarket(c) {
  296. const st = String(c.status || "").toUpperCase();
  297. let s = 5;
  298. if (st === "SOLD") s += 8;
  299. else if (st === "ACTIVE") s += 3;
  300. const bids = Array.isArray(c.auctions_poll) ? c.auctions_poll.length : 0;
  301. s += Math.min(10, bids);
  302. return s;
  303. }
  304. function scoreProject(c) {
  305. const st = String(c.status || "ACTIVE").toUpperCase();
  306. const prog = Number(c.progress || 0);
  307. let s = 8 + Math.min(10, prog / 10);
  308. if (st === "FUNDED") s += 10;
  309. return s;
  310. }
  311. function calculateOpinionScore(content) {
  312. const cats = content?.opinions || {};
  313. let s = 0;
  314. for (const k in cats) {
  315. if (!Object.prototype.hasOwnProperty.call(cats, k)) continue;
  316. if (k === "interesting" || k === "inspiring") s += 5;
  317. else if (k === "boring" || k === "spam" || k === "propaganda") s -= 3;
  318. else s += 1;
  319. }
  320. return s;
  321. }
  322. async function listAllActions() {
  323. if (services?.feed?.listAll) {
  324. const arr = await services.feed.listAll();
  325. FEED_SRC = "services.feed.listAll";
  326. return normalizeFeedArray(arr);
  327. }
  328. if (services?.activity?.list) {
  329. const arr = await services.activity.list();
  330. FEED_SRC = "services.activity.list";
  331. return normalizeFeedArray(arr);
  332. }
  333. if (typeof global.listFeed === "function") {
  334. const arr = await global.listFeed("all");
  335. FEED_SRC = "global.listFeed('all')";
  336. return normalizeFeedArray(arr);
  337. }
  338. const ssb = await openSsb();
  339. if (!ssb || !ssb.createLogStream) {
  340. FEED_SRC = "none";
  341. return [];
  342. }
  343. const msgs = await new Promise((resolve, reject) =>
  344. pull(
  345. ssb.createLogStream({ limit: getLogLimit() }),
  346. pull.collect((err, arr) => err ? reject(err) : resolve(arr))
  347. )
  348. );
  349. FEED_SRC = "ssb.createLogStream";
  350. return msgs.map(m => {
  351. const v = m.value || {};
  352. const c = v.content || {};
  353. return {
  354. id: v.key || m.key,
  355. author: v.author,
  356. type: (c.type || "").toLowerCase(),
  357. value: v,
  358. content: c
  359. };
  360. });
  361. }
  362. function normalizeFeedArray(arr) {
  363. if (!Array.isArray(arr)) return [];
  364. return arr.map(x => {
  365. const value = x.value || {};
  366. const content = x.content || value.content || {};
  367. const author = x.author || value.author || content.author || null;
  368. const type = (content.type || "").toLowerCase();
  369. return { id: x.id || value.key || x.key, author, type, value, content };
  370. });
  371. }
  372. async function publishKarmaScore(userId, karmaScore) {
  373. const ssb = await openSsb();
  374. if (!ssb || !ssb.publish) return false;
  375. const timestamp = new Date().toISOString();
  376. const content = { type: "karmaScore", karmaScore, userId, timestamp };
  377. return new Promise((resolve, reject) => {
  378. ssb.publish(content, (err, msg) => err ? reject(err) : resolve(msg));
  379. });
  380. }
  381. async function fetchUserActions(userId) {
  382. const me = resolveUserId(userId);
  383. const actions = await listAllActions();
  384. const authored = actions.filter(a =>
  385. (a.author && a.author === me) || (a.value?.author && a.value.author === me)
  386. );
  387. if (authored.length) return authored;
  388. return actions.filter(a => {
  389. const c = a.content || {};
  390. const fields = [c.author, c.organizer, c.seller, c.about, c.contact];
  391. return fields.some(f => f && f === me);
  392. });
  393. }
  394. function scoreFromActions(actions) {
  395. let score = 0;
  396. for (const action of actions) {
  397. const t = normalizeType(action);
  398. const c = action.content || {};
  399. if (t === "post") score += 10;
  400. else if (t === "comment") score += 5;
  401. else if (t === "like") score += 2;
  402. else if (t === "image") score += 8;
  403. else if (t === "video") score += 12;
  404. else if (t === "audio") score += 8;
  405. else if (t === "document") score += 6;
  406. else if (t === "bookmark") score += 2;
  407. else if (t === "feed") score += 6;
  408. else if (t === "forum") score += c.root ? 5 : 10;
  409. else if (t === "vote") score += 3 + calculateOpinionScore(c);
  410. else if (t === "votes") score += Math.min(10, Number(c.totalVotes || 0));
  411. else if (t === "market") score += scoreMarket(c);
  412. else if (t === "project") score += scoreProject(c);
  413. else if (t === "tribe") score += 6 + Math.min(10, Array.isArray(c.members) ? c.members.length * 0.5 : 0);
  414. else if (t === "event") score += 4 + Math.min(10, Array.isArray(c.attendees) ? c.attendees.length : 0);
  415. else if (t === "task") score += 3 + priorityBump(c.priority);
  416. else if (t === "report") score += 4 + (Array.isArray(c.confirmations) ? c.confirmations.length : 0) + severityBump(c.severity);
  417. else if (t === "curriculum") score += 5;
  418. else if (t === "aiexchange") score += Array.isArray(c.ctx) ? Math.min(10, c.ctx.length) : 0;
  419. else if (t === "job") score += 4 + (Array.isArray(c.subscribers) ? c.subscribers.length : 0);
  420. else if (t === "bankclaim") score += Math.min(20, Math.log(1 + Math.max(0, Number(c.amount) || 0)) * 5);
  421. else if (t === "bankwallet") score += 2;
  422. else if (t === "transfer") score += 1;
  423. else if (t === "about") score += 1;
  424. else if (t === "contact") score += 1;
  425. else if (t === "pub") score += 1;
  426. }
  427. return Math.max(0, Math.round(score));
  428. }
  429. async function getUserEngagementScore(userId) {
  430. const ssb = await openSsb();
  431. const uid = resolveUserId(userId);
  432. const actions = await fetchUserActions(uid);
  433. const karmaScore = scoreFromActions(actions);
  434. const prev = await getLastKarmaScore(uid);
  435. const lastPublishedTimestamp = await getLastPublishedTimestamp(uid);
  436. const isSelf = idsEqual(uid, ssb.id);
  437. const hasSSB = !!(ssb && ssb.publish);
  438. const changed = (prev === null) || (karmaScore !== prev);
  439. const nowMs = Date.now();
  440. const lastMs = lastPublishedTimestamp ? new Date(lastPublishedTimestamp).getTime() : 0;
  441. const cooldownOk = (nowMs - lastMs) >= 24 * 60 * 60 * 1000;
  442. if (isSelf && hasSSB && changed && cooldownOk) {
  443. await publishKarmaScore(uid, karmaScore);
  444. }
  445. return karmaScore;
  446. }
  447. async function getLastKarmaScore(userId) {
  448. const ssb = await openSsb();
  449. if (!ssb) return null;
  450. return new Promise((resolve) => {
  451. const source = ssb.messagesByType
  452. ? ssb.messagesByType({ type: "karmaScore", reverse: true })
  453. : ssb.createLogStream && ssb.createLogStream({ reverse: true });
  454. if (!source) return resolve(null);
  455. pull(
  456. source,
  457. pull.filter(msg => {
  458. const v = msg.value || msg;
  459. const c = v.content || {};
  460. return c && c.type === "karmaScore" && c.userId === userId;
  461. }),
  462. pull.take(1),
  463. pull.collect((err, arr) => {
  464. if (err || !arr || !arr.length) return resolve(null);
  465. const v = arr[0].value || arr[0];
  466. const c = v.content || {};
  467. resolve(Number(c.karmaScore) || 0);
  468. })
  469. );
  470. });
  471. }
  472. async function getLastPublishedTimestamp(userId) {
  473. const ssb = await openSsb();
  474. if (!ssb) return new Date(0).toISOString();
  475. const fallback = new Date(0).toISOString();
  476. return new Promise((resolve) => {
  477. const source = ssb.messagesByType
  478. ? ssb.messagesByType({ type: "karmaScore", reverse: true })
  479. : ssb.createLogStream && ssb.createLogStream({ reverse: true });
  480. if (!source) return resolve(fallback);
  481. pull(
  482. source,
  483. pull.filter(msg => {
  484. const v = msg.value || msg;
  485. const c = v.content || {};
  486. return c && c.type === "karmaScore" && c.userId === userId;
  487. }),
  488. pull.take(1),
  489. pull.collect((err, arr) => {
  490. if (err || !arr || !arr.length) return resolve(fallback);
  491. const v = arr[0].value || arr[0];
  492. const c = v.content || {};
  493. resolve(c.timestamp || fallback);
  494. })
  495. );
  496. });
  497. }
  498. function computePoolVars(pubBal, rules) {
  499. const alphaCap = (rules.alpha || DEFAULT_RULES.alpha) * pubBal;
  500. const available = Math.max(0, pubBal - (rules.reserveMin || DEFAULT_RULES.reserveMin));
  501. const rawMin = Math.min(available, (rules.capPerEpoch || DEFAULT_RULES.capPerEpoch), alphaCap);
  502. const pool = clamp(rawMin, 0, Number.MAX_SAFE_INTEGER);
  503. return { pubBal, alphaCap, available, rawMin, pool };
  504. }
  505. async function computeEpoch({ epochId, userId, rules = DEFAULT_RULES }) {
  506. const pubBal = await safeGetBalance("pub");
  507. const pv = computePoolVars(pubBal, rules);
  508. const engagementScore = await getUserEngagementScore(userId);
  509. const userWeight = 1 + engagementScore / 100;
  510. const weights = [{ user: userId, w: userWeight }];
  511. const W = weights.reduce((acc, x) => acc + x.w, 0) || 1;
  512. const capUser = (rules.caps && rules.caps.cap_user_epoch) || DEFAULT_RULES.caps.cap_user_epoch;
  513. const allocations = weights.map(({ user, w }) => {
  514. const amount = Math.min(pv.pool * w / W, capUser);
  515. return {
  516. id: `alloc:${epochId}:${user}`,
  517. epoch: epochId,
  518. user,
  519. weight: Number(w.toFixed(6)),
  520. amount: Number(amount.toFixed(6))
  521. };
  522. });
  523. const snapshot = JSON.stringify({ epochId, pool: pv.pool, weights, allocations, rules }, null, 2);
  524. const hash = crypto.createHash("sha256").update(snapshot).digest("hex");
  525. return { epoch: { id: epochId, pool: Number(pv.pool.toFixed(6)), weightsSum: Number(W.toFixed(6)), rules, hash }, allocations };
  526. }
  527. async function executeEpoch({ epochId, rules = DEFAULT_RULES }) {
  528. const { epoch, allocations } = await computeEpoch({ epochId, userId: config.keys.id, rules });
  529. await epochsRepo.save(epoch);
  530. for (const a of allocations) {
  531. if (a.amount <= 0) continue;
  532. await transfersRepo.create({
  533. id: a.id,
  534. from: "PUB",
  535. to: a.user,
  536. amount: a.amount,
  537. concept: `UBI ${epochId}`,
  538. status: "UNCONFIRMED",
  539. createdAt: new Date().toISOString(),
  540. deadline: new Date(Date.now() + DEFAULT_RULES.graceDays * 86400000).toISOString(),
  541. tags: ["UBI", `epoch:${epochId}`],
  542. opinions: {}
  543. });
  544. }
  545. return { epoch, allocations };
  546. }
  547. async function publishBankClaim({ amount, epochId, allocationId, txid }) {
  548. const ssbClient = await openSsb();
  549. const content = { type: "bankClaim", amount, epochId, allocationId, txid, timestamp: Date.now() };
  550. return new Promise((resolve, reject) => ssbClient.publish(content, (err, res) => err ? reject(err) : resolve(res)));
  551. }
  552. async function claimAllocation({ transferId, claimerId, pubWalletUrl, pubWalletUser, pubWalletPass }) {
  553. const allocation = await transfersRepo.findById(transferId);
  554. if (!allocation || allocation.status !== "UNCONFIRMED") throw new Error("Invalid allocation or already confirmed.");
  555. if (allocation.to !== claimerId) throw new Error("This allocation is not for you.");
  556. const txid = await rpcCall("sendtoaddress", [pubWalletUrl, allocation.amount, "UBI claim", pubWalletUser, pubWalletPass]);
  557. return { txid };
  558. }
  559. async function updateAllocationStatus(allocationId, status, txid) {
  560. const all = await transfersRepo.listAll();
  561. const idx = all.findIndex(t => t.id === allocationId);
  562. if (idx >= 0) {
  563. all[idx].status = status;
  564. all[idx].txid = txid;
  565. await transfersRepo.create(all[idx]);
  566. }
  567. }
  568. async function listBanking(filter = "overview", userId) {
  569. const uid = resolveUserId(userId);
  570. const epochId = epochIdNow();
  571. const pubBalance = await safeGetBalance("pub");
  572. const userBalance = await safeGetBalance("user");
  573. const epochs = await epochsRepo.list();
  574. const all = await transfersRepo.listByTag("UBI");
  575. const allocations = all.map(t => ({
  576. id: t.id, concept: t.concept, from: t.from, to: t.to, amount: t.amount, status: t.status,
  577. createdAt: t.createdAt || t.deadline || new Date().toISOString(), txid: t.txid
  578. }));
  579. let computed = null;
  580. try { computed = await computeEpoch({ epochId, userId: uid, rules: DEFAULT_RULES }); } catch {}
  581. const pv = computePoolVars(pubBalance, DEFAULT_RULES);
  582. const actions = await fetchUserActions(uid);
  583. const engagementScore = scoreFromActions(actions);
  584. const poolForEpoch = computed?.epoch?.pool || pv.pool || 0;
  585. const futureUBI = Number(((engagementScore / 100) * poolForEpoch).toFixed(6));
  586. const addresses = await listAddressesMerged();
  587. const summary = {
  588. userBalance,
  589. pubBalance,
  590. epochId,
  591. pool: poolForEpoch,
  592. weightsSum: computed?.epoch?.weightsSum || 0,
  593. userEngagementScore: engagementScore,
  594. futureUBI
  595. };
  596. return { summary, allocations, epochs, rules: DEFAULT_RULES, addresses };
  597. }
  598. async function getAllocationById(id) {
  599. const t = await transfersRepo.findById(id);
  600. if (!t) return null;
  601. return { id: t.id, concept: t.concept, from: t.from, to: t.to, amount: t.amount, status: t.status, createdAt: t.createdAt || new Date().toISOString(), txid: t.txid };
  602. }
  603. async function getEpochById(id) {
  604. const existing = await epochsRepo.get(id);
  605. if (existing) return existing;
  606. const all = await transfersRepo.listAll();
  607. const filtered = all.filter(t => (t.tags || []).includes(`epoch:${id}`));
  608. const pool = filtered.reduce((s, t) => s + Number(t.amount || 0), 0);
  609. return { id, pool, weightsSum: 0, rules: DEFAULT_RULES, hash: "-" };
  610. }
  611. async function listEpochAllocations(id) {
  612. const all = await transfersRepo.listAll();
  613. return all.filter(t => (t.tags || []).includes(`epoch:${id}`)).map(t => ({
  614. id: t.id, concept: t.concept, from: t.from, to: t.to, amount: t.amount, status: t.status, createdAt: t.createdAt || new Date().toISOString(), txid: t.txid
  615. }));
  616. }
  617. async function calculateEcoinValue() {
  618. let isSynced = false;
  619. let circulatingSupply = 0;
  620. try {
  621. circulatingSupply = await getCirculatingSupply();
  622. isSynced = circulatingSupply > 0;
  623. } catch (error) {
  624. circulatingSupply = 0;
  625. isSynced = false;
  626. }
  627. const totalSupply = 25500000;
  628. const ecoValuePerHour = await calculateEcoValuePerHour(circulatingSupply);
  629. const ecoInHours = calculateEcoinHours(circulatingSupply, ecoValuePerHour);
  630. const inflationFactor = await calculateInflationFactor(circulatingSupply, totalSupply);
  631. return {
  632. ecoValue: ecoValuePerHour,
  633. ecoInHours: Number(ecoInHours.toFixed(2)),
  634. totalSupply: totalSupply,
  635. inflationFactor: inflationFactor ? Number(inflationFactor.toFixed(2)) : 0,
  636. currentSupply: circulatingSupply,
  637. isSynced: isSynced
  638. };
  639. }
  640. async function calculateEcoValuePerHour(circulatingSupply) {
  641. const issuanceRate = await getIssuanceRate();
  642. const inflation = await calculateInflationFactor(circulatingSupply, 25500000);
  643. const ecoValuePerHour = (circulatingSupply / 100000) * (1 + inflation / 100);
  644. return ecoValuePerHour;
  645. }
  646. function calculateEcoinHours(circulatingSupply, ecoValuePerHour) {
  647. const ecoInHours = circulatingSupply / ecoValuePerHour;
  648. return ecoInHours;
  649. }
  650. async function calculateInflationFactor(circulatingSupply, totalSupply) {
  651. const issuanceRate = await getIssuanceRate();
  652. if (circulatingSupply > 0) {
  653. const inflationRate = (issuanceRate / circulatingSupply) * 100;
  654. return inflationRate;
  655. }
  656. return 0;
  657. }
  658. async function getIssuanceRate() {
  659. try {
  660. const result = await rpcCall("getmininginfo", []);
  661. const blockValue = result?.blockvalue || 0;
  662. const blocks = result?.blocks || 0;
  663. return (blockValue / 1e8) * blocks;
  664. } catch (error) {
  665. return 0.02;
  666. }
  667. }
  668. async function getCirculatingSupply() {
  669. try {
  670. const result = await rpcCall("getinfo", []);
  671. return result?.moneysupply || 0;
  672. } catch (error) {
  673. return 0;
  674. }
  675. }
  676. async function getBankingData(userId) {
  677. const ecoValue = await calculateEcoinValue();
  678. const karmaScore = await getUserEngagementScore(userId);
  679. return {
  680. ecoValue,
  681. karmaScore,
  682. };
  683. }
  684. return {
  685. DEFAULT_RULES,
  686. computeEpoch,
  687. executeEpoch,
  688. getUserEngagementScore,
  689. publishBankClaim,
  690. claimAllocation,
  691. listBanking,
  692. getAllocationById,
  693. getEpochById,
  694. listEpochAllocations,
  695. addAddress,
  696. removeAddress,
  697. ensureSelfAddressPublished,
  698. getUserAddress,
  699. setUserAddress,
  700. listAddressesMerged,
  701. calculateEcoinValue,
  702. getBankingData
  703. };
  704. };