banking_model.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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?.ssb) return services.ssb;
  146. if (services?.cooler?.open) return services.cooler.open();
  147. if (global.ssb) return global.ssb;
  148. try {
  149. const srv = require("../server/SSB_server.js");
  150. if (srv?.ssb) return srv.ssb;
  151. if (srv?.server) return srv.server;
  152. if (srv?.default) return srv.default;
  153. } catch (_) {}
  154. return null;
  155. }
  156. async function getWalletFromSSB(userId) {
  157. const ssb = await openSsb();
  158. if (!ssb) return null;
  159. const msgs = await new Promise((resolve, reject) =>
  160. pull(
  161. ssb.createLogStream({ limit: getLogLimit() }),
  162. pull.collect((err, arr) => err ? reject(err) : resolve(arr))
  163. )
  164. );
  165. for (let i = msgs.length - 1; i >= 0; i--) {
  166. const v = msgs[i].value || {};
  167. const c = v.content || {};
  168. if (v.author === userId && c && c.type === "wallet" && c.coin === "ECO" && typeof c.address === "string") {
  169. return c.address;
  170. }
  171. }
  172. return null;
  173. }
  174. async function scanAllWalletsSSB() {
  175. const ssb = await openSsb();
  176. if (!ssb) return {};
  177. const latest = {};
  178. const msgs = await new Promise((resolve, reject) =>
  179. pull(
  180. ssb.createLogStream({ limit: getLogLimit() }),
  181. pull.collect((err, arr) => err ? reject(err) : resolve(arr))
  182. )
  183. );
  184. for (let i = msgs.length - 1; i >= 0; i--) {
  185. const v = msgs[i].value || {};
  186. const c = v.content || {};
  187. if (c && c.type === "wallet" && c.coin === "ECO" && typeof c.address === "string") {
  188. if (!latest[v.author]) latest[v.author] = c.address;
  189. }
  190. }
  191. return latest;
  192. }
  193. async function publishSelfAddress(address) {
  194. const ssb = await openSsb();
  195. if (!ssb) return false;
  196. const msg = { type: "wallet", coin: "ECO", address, updatedAt: new Date().toISOString() };
  197. await new Promise((resolve, reject) => ssb.publish(msg, (err, val) => err ? reject(err) : resolve(val)));
  198. return true;
  199. }
  200. async function listUsers() {
  201. const addrLocal = readAddrMap();
  202. const ids = Object.keys(addrLocal);
  203. if (ids.length > 0) return ids.map(id => ({ id }));
  204. return [{ id: config.keys.id }];
  205. }
  206. async function getUserAddress(userId) {
  207. const v = readAddrMap()[userId];
  208. const local = typeof v === "string" ? v : (v && v.address) || null;
  209. if (local) return local;
  210. const ssbAddr = await getWalletFromSSB(userId);
  211. return ssbAddr;
  212. }
  213. async function setUserAddress(userId, address, publishIfSelf) {
  214. const m = readAddrMap();
  215. m[userId] = address;
  216. writeAddrMap(m);
  217. if (publishIfSelf && userId === config.keys.id) await publishSelfAddress(address);
  218. return true;
  219. }
  220. async function addAddress({ userId, address }) {
  221. if (!userId || !address || !isValidEcoinAddress(address)) return { status: "invalid" };
  222. const m = readAddrMap();
  223. const prev = m[userId];
  224. if (prev && (prev === address || (prev.address && prev.address === address))) return { status: "exists" };
  225. m[userId] = address;
  226. writeAddrMap(m);
  227. if (userId === config.keys.id) await publishSelfAddress(address);
  228. return { status: prev ? "updated" : "added" };
  229. }
  230. async function removeAddress({ userId }) {
  231. if (!userId) return { status: "invalid" };
  232. const m = readAddrMap();
  233. if (!m[userId]) return { status: "not_found" };
  234. delete m[userId];
  235. writeAddrMap(m);
  236. return { status: "deleted" };
  237. }
  238. async function listAddressesMerged() {
  239. const local = readAddrMap();
  240. const ssbAll = await scanAllWalletsSSB();
  241. const keys = new Set([...Object.keys(local), ...Object.keys(ssbAll)]);
  242. const out = [];
  243. for (const id of keys) {
  244. if (local[id]) out.push({ id, address: typeof local[id] === "string" ? local[id] : local[id].address, source: "local" });
  245. else if (ssbAll[id]) out.push({ id, address: ssbAll[id], source: "ssb" });
  246. }
  247. return out;
  248. }
  249. function idsEqual(a, b) {
  250. if (!a || !b) return false;
  251. const A = String(a).trim();
  252. const B = String(b).trim();
  253. if (A === B) return true;
  254. const strip = s => s.replace(/^@/, "").replace(/\.ed25519$/, "");
  255. return strip(A) === strip(B);
  256. }
  257. function inferType(c = {}) {
  258. if (c.vote) return "vote";
  259. if (c.votes) return "votes";
  260. if (c.address && c.coin === "ECO" && c.type === "wallet") return "bankWallet";
  261. if (typeof c.amount !== "undefined" && c.epochId && c.allocationId) return "bankClaim";
  262. if (typeof c.item_type !== "undefined" && typeof c.status !== "undefined") return "market";
  263. if (typeof c.goal !== "undefined" && typeof c.progress !== "undefined") return "project";
  264. if (typeof c.members !== "undefined" && typeof c.isAnonymous !== "undefined") return "tribe";
  265. if (typeof c.date !== "undefined" && typeof c.location !== "undefined") return "event";
  266. if (typeof c.priority !== "undefined" && typeof c.status !== "undefined" && c.title) return "task";
  267. if (typeof c.confirmations !== "undefined" && typeof c.severity !== "undefined") return "report";
  268. if (typeof c.job_type !== "undefined" && typeof c.status !== "undefined") return "job";
  269. if (typeof c.url !== "undefined" && typeof c.mimeType !== "undefined" && c.type === "audio") return "audio";
  270. if (typeof c.url !== "undefined" && typeof c.mimeType !== "undefined" && c.type === "video") return "video";
  271. if (typeof c.url !== "undefined" && c.title && c.key) return "document";
  272. if (typeof c.text !== "undefined" && typeof c.refeeds !== "undefined") return "feed";
  273. if (typeof c.text !== "undefined" && typeof c.contentWarning !== "undefined") return "post";
  274. if (typeof c.contact !== "undefined") return "contact";
  275. if (typeof c.about !== "undefined") return "about";
  276. if (typeof c.concept !== "undefined" && typeof c.amount !== "undefined" && c.status) return "transfer";
  277. return "";
  278. }
  279. function normalizeType(a) {
  280. const t = a.type || a.content?.type || inferType(a.content) || "";
  281. return String(t).toLowerCase();
  282. }
  283. function priorityBump(p) {
  284. const s = String(p || "").toUpperCase();
  285. if (s === "HIGH") return 3;
  286. if (s === "MEDIUM") return 1;
  287. return 0;
  288. }
  289. function severityBump(s) {
  290. const x = String(s || "").toUpperCase();
  291. if (x === "CRITICAL") return 6;
  292. if (x === "HIGH") return 4;
  293. if (x === "MEDIUM") return 2;
  294. return 0;
  295. }
  296. function scoreMarket(c) {
  297. const st = String(c.status || "").toUpperCase();
  298. let s = 5;
  299. if (st === "SOLD") s += 8;
  300. else if (st === "ACTIVE") s += 3;
  301. const bids = Array.isArray(c.auctions_poll) ? c.auctions_poll.length : 0;
  302. s += Math.min(10, bids);
  303. return s;
  304. }
  305. function scoreProject(c) {
  306. const st = String(c.status || "ACTIVE").toUpperCase();
  307. const prog = Number(c.progress || 0);
  308. let s = 8 + Math.min(10, prog / 10);
  309. if (st === "FUNDED") s += 10;
  310. return s;
  311. }
  312. function calculateOpinionScore(content) {
  313. const cats = content?.opinions || {};
  314. let s = 0;
  315. for (const k in cats) {
  316. if (!Object.prototype.hasOwnProperty.call(cats, k)) continue;
  317. if (k === "interesting" || k === "inspiring") s += 5;
  318. else if (k === "boring" || k === "spam" || k === "propaganda") s -= 3;
  319. else s += 1;
  320. }
  321. return s;
  322. }
  323. async function listAllActions() {
  324. if (services?.feed?.listAll) {
  325. const arr = await services.feed.listAll();
  326. FEED_SRC = "services.feed.listAll";
  327. return normalizeFeedArray(arr);
  328. }
  329. if (services?.activity?.list) {
  330. const arr = await services.activity.list();
  331. FEED_SRC = "services.activity.list";
  332. return normalizeFeedArray(arr);
  333. }
  334. if (typeof global.listFeed === "function") {
  335. const arr = await global.listFeed("all");
  336. FEED_SRC = "global.listFeed('all')";
  337. return normalizeFeedArray(arr);
  338. }
  339. const ssb = await openSsb();
  340. if (!ssb || !ssb.createLogStream) {
  341. FEED_SRC = "none";
  342. return [];
  343. }
  344. const msgs = await new Promise((resolve, reject) =>
  345. pull(
  346. ssb.createLogStream({ limit: getLogLimit() }),
  347. pull.collect((err, arr) => err ? reject(err) : resolve(arr))
  348. )
  349. );
  350. FEED_SRC = "ssb.createLogStream";
  351. return msgs.map(m => {
  352. const v = m.value || {};
  353. const c = v.content || {};
  354. return {
  355. id: v.key || m.key,
  356. author: v.author,
  357. type: (c.type || "").toLowerCase(),
  358. value: v,
  359. content: c
  360. };
  361. });
  362. }
  363. function normalizeFeedArray(arr) {
  364. if (!Array.isArray(arr)) return [];
  365. return arr.map(x => {
  366. const value = x.value || {};
  367. const content = x.content || value.content || {};
  368. const author = x.author || value.author || content.author || null;
  369. const type = (content.type || "").toLowerCase();
  370. return { id: x.id || value.key || x.key, author, type, value, content };
  371. });
  372. }
  373. async function publishKarmaScore(userId, karmaScore) {
  374. const ssb = await openSsb();
  375. if (!ssb) return false;
  376. const timestamp = new Date().toISOString();
  377. const content = {
  378. type: "karmaScore",
  379. karmaScore,
  380. userId: userId,
  381. timestamp: timestamp,
  382. };
  383. return new Promise((resolve, reject) => {
  384. ssb.publish(content, (err, msg) => {
  385. if (err) reject(err);
  386. else resolve(msg);
  387. });
  388. });
  389. }
  390. async function fetchUserActions(userId) {
  391. const me = resolveUserId(userId);
  392. const actions = await listAllActions();
  393. const authored = actions.filter(a =>
  394. (a.author && a.author === me) || (a.value?.author && a.value.author === me)
  395. );
  396. if (authored.length) return authored;
  397. return actions.filter(a => {
  398. const c = a.content || {};
  399. const fields = [c.author, c.organizer, c.seller, c.about, c.contact];
  400. return fields.some(f => f && f === me);
  401. });
  402. }
  403. function scoreFromActions(actions) {
  404. let score = 0;
  405. for (const action of actions) {
  406. const t = normalizeType(action);
  407. const c = action.content || {};
  408. if (t === "post") score += 10;
  409. else if (t === "comment") score += 5;
  410. else if (t === "like") score += 2;
  411. else if (t === "image") score += 8;
  412. else if (t === "video") score += 12;
  413. else if (t === "audio") score += 8;
  414. else if (t === "document") score += 6;
  415. else if (t === "bookmark") score += 2;
  416. else if (t === "feed") score += 6;
  417. else if (t === "forum") score += c.root ? 5 : 10;
  418. else if (t === "vote") score += 3 + calculateOpinionScore(c);
  419. else if (t === "votes") score += Math.min(10, Number(c.totalVotes || 0));
  420. else if (t === "market") score += scoreMarket(c);
  421. else if (t === "project") score += scoreProject(c);
  422. else if (t === "tribe") score += 6 + Math.min(10, Array.isArray(c.members) ? c.members.length * 0.5 : 0);
  423. else if (t === "event") score += 4 + Math.min(10, Array.isArray(c.attendees) ? c.attendees.length : 0);
  424. else if (t === "task") score += 3 + priorityBump(c.priority);
  425. else if (t === "report") score += 4 + (Array.isArray(c.confirmations) ? c.confirmations.length : 0) + severityBump(c.severity);
  426. else if (t === "curriculum") score += 5;
  427. else if (t === "aiexchange") score += Array.isArray(c.ctx) ? Math.min(10, c.ctx.length) : 0;
  428. else if (t === "job") score += 4 + (Array.isArray(c.subscribers) ? c.subscribers.length : 0);
  429. else if (t === "bankclaim") score += Math.min(20, Math.log(1 + Math.max(0, Number(c.amount) || 0)) * 5);
  430. else if (t === "bankwallet") score += 2;
  431. else if (t === "transfer") score += 1;
  432. else if (t === "about") score += 1;
  433. else if (t === "contact") score += 1;
  434. else if (t === "pub") score += 1;
  435. }
  436. return Math.max(0, Math.round(score));
  437. }
  438. async function getUserEngagementScore(userId) {
  439. const actions = await fetchUserActions(userId);
  440. const karmaScore = scoreFromActions(actions);
  441. const previousKarmaScore = await getLastKarmaScore(userId);
  442. const lastPublishedTimestamp = await getLastPublishedTimestamp(userId);
  443. const currentTimestamp = Date.now();
  444. const timeDifference = currentTimestamp - new Date(lastPublishedTimestamp).getTime();
  445. const shouldPublish = karmaScore !== previousKarmaScore && timeDifference >= 24 * 60 * 60 * 1000;
  446. const canPublish = Boolean(services?.ssb || global.ssb);
  447. if (shouldPublish && canPublish) {
  448. await publishKarmaScore(userId, karmaScore);
  449. }
  450. return karmaScore;
  451. }
  452. async function getLastKarmaScore(userId) {
  453. const ssb = await openSsb();
  454. if (!ssb) return 0;
  455. const matchOne = (arr) => {
  456. if (!arr || !arr.length) return 0;
  457. const v = arr[0].value || arr[0];
  458. const c = v.content || {};
  459. return Number(c.karmaScore) || 0;
  460. };
  461. return new Promise((resolve) => {
  462. const source = ssb.messagesByType
  463. ? ssb.messagesByType({ type: "karmaScore", reverse: true })
  464. : ssb.createLogStream && ssb.createLogStream({ reverse: true });
  465. if (!source) return resolve(0);
  466. pull(
  467. source,
  468. pull.filter((msg) => {
  469. const v = msg.value || msg;
  470. const c = v.content || {};
  471. return c && c.type === "karmaScore" && c.userId === userId;
  472. }),
  473. pull.take(1),
  474. pull.collect((err, arr) => {
  475. if (err) return resolve(0);
  476. resolve(matchOne(arr));
  477. })
  478. );
  479. });
  480. }
  481. async function getLastPublishedTimestamp(userId) {
  482. const ssb = await openSsb();
  483. if (!ssb) return new Date(0).toISOString();
  484. const fallback = new Date(0).toISOString();
  485. return new Promise((resolve) => {
  486. const source = ssb.messagesByType
  487. ? ssb.messagesByType({ type: "karmaScore", reverse: true })
  488. : ssb.createLogStream && ssb.createLogStream({ reverse: true });
  489. if (!source) return resolve(fallback);
  490. pull(
  491. source,
  492. pull.filter((msg) => {
  493. const v = msg.value || msg;
  494. const c = v.content || {};
  495. return c && c.type === "karmaScore" && c.userId === userId;
  496. }),
  497. pull.take(1),
  498. pull.collect((err, arr) => {
  499. if (err || !arr || !arr.length) return resolve(fallback);
  500. const v = arr[0].value || arr[0];
  501. const c = v.content || {};
  502. resolve(c.timestamp || fallback);
  503. })
  504. );
  505. });
  506. }
  507. function computePoolVars(pubBal, rules) {
  508. const alphaCap = (rules.alpha || DEFAULT_RULES.alpha) * pubBal;
  509. const available = Math.max(0, pubBal - (rules.reserveMin || DEFAULT_RULES.reserveMin));
  510. const rawMin = Math.min(available, (rules.capPerEpoch || DEFAULT_RULES.capPerEpoch), alphaCap);
  511. const pool = clamp(rawMin, 0, Number.MAX_SAFE_INTEGER);
  512. return { pubBal, alphaCap, available, rawMin, pool };
  513. }
  514. async function computeEpoch({ epochId, userId, rules = DEFAULT_RULES }) {
  515. const pubBal = await safeGetBalance("pub");
  516. const pv = computePoolVars(pubBal, rules);
  517. const engagementScore = await getUserEngagementScore(userId);
  518. const userWeight = 1 + engagementScore / 100;
  519. const weights = [{ user: userId, w: userWeight }];
  520. const W = weights.reduce((acc, x) => acc + x.w, 0) || 1;
  521. const capUser = (rules.caps && rules.caps.cap_user_epoch) || DEFAULT_RULES.caps.cap_user_epoch;
  522. const allocations = weights.map(({ user, w }) => {
  523. const amount = Math.min(pv.pool * w / W, capUser);
  524. return {
  525. id: `alloc:${epochId}:${user}`,
  526. epoch: epochId,
  527. user,
  528. weight: Number(w.toFixed(6)),
  529. amount: Number(amount.toFixed(6))
  530. };
  531. });
  532. const snapshot = JSON.stringify({ epochId, pool: pv.pool, weights, allocations, rules }, null, 2);
  533. const hash = crypto.createHash("sha256").update(snapshot).digest("hex");
  534. return { epoch: { id: epochId, pool: Number(pv.pool.toFixed(6)), weightsSum: Number(W.toFixed(6)), rules, hash }, allocations };
  535. }
  536. async function executeEpoch({ epochId, rules = DEFAULT_RULES }) {
  537. const { epoch, allocations } = await computeEpoch({ epochId, userId: config.keys.id, rules });
  538. await epochsRepo.save(epoch);
  539. for (const a of allocations) {
  540. if (a.amount <= 0) continue;
  541. await transfersRepo.create({
  542. id: a.id,
  543. from: "PUB",
  544. to: a.user,
  545. amount: a.amount,
  546. concept: `UBI ${epochId}`,
  547. status: "UNCONFIRMED",
  548. createdAt: new Date().toISOString(),
  549. deadline: new Date(Date.now() + DEFAULT_RULES.graceDays * 86400000).toISOString(),
  550. tags: ["UBI", `epoch:${epochId}`],
  551. opinions: {}
  552. });
  553. }
  554. return { epoch, allocations };
  555. }
  556. async function publishBankClaim({ amount, epochId, allocationId, txid }) {
  557. const ssbClient = await openSsb();
  558. const content = { type: "bankClaim", amount, epochId, allocationId, txid, timestamp: Date.now() };
  559. return new Promise((resolve, reject) => ssbClient.publish(content, (err, res) => err ? reject(err) : resolve(res)));
  560. }
  561. async function claimAllocation({ transferId, claimerId, pubWalletUrl, pubWalletUser, pubWalletPass }) {
  562. const allocation = await transfersRepo.findById(transferId);
  563. if (!allocation || allocation.status !== "UNCONFIRMED") throw new Error("Invalid allocation or already confirmed.");
  564. if (allocation.to !== claimerId) throw new Error("This allocation is not for you.");
  565. const txid = await rpcCall("sendtoaddress", [pubWalletUrl, allocation.amount, "UBI claim", pubWalletUser, pubWalletPass]);
  566. return { txid };
  567. }
  568. async function updateAllocationStatus(allocationId, status, txid) {
  569. const all = await transfersRepo.listAll();
  570. const idx = all.findIndex(t => t.id === allocationId);
  571. if (idx >= 0) {
  572. all[idx].status = status;
  573. all[idx].txid = txid;
  574. await transfersRepo.create(all[idx]);
  575. }
  576. }
  577. async function listBanking(filter = "overview", userId) {
  578. const uid = resolveUserId(userId);
  579. const epochId = epochIdNow();
  580. const pubBalance = await safeGetBalance("pub");
  581. const userBalance = await safeGetBalance("user");
  582. const epochs = await epochsRepo.list();
  583. const all = await transfersRepo.listByTag("UBI");
  584. const allocations = all.map(t => ({
  585. id: t.id, concept: t.concept, from: t.from, to: t.to, amount: t.amount, status: t.status,
  586. createdAt: t.createdAt || t.deadline || new Date().toISOString(), txid: t.txid
  587. }));
  588. let computed = null;
  589. try { computed = await computeEpoch({ epochId, userId: uid, rules: DEFAULT_RULES }); } catch {}
  590. const pv = computePoolVars(pubBalance, DEFAULT_RULES);
  591. const actions = await fetchUserActions(uid);
  592. const engagementScore = scoreFromActions(actions);
  593. const poolForEpoch = computed?.epoch?.pool || pv.pool || 0;
  594. const futureUBI = Number(((engagementScore / 100) * poolForEpoch).toFixed(6));
  595. const addresses = await listAddressesMerged();
  596. const summary = {
  597. userBalance,
  598. pubBalance,
  599. epochId,
  600. pool: poolForEpoch,
  601. weightsSum: computed?.epoch?.weightsSum || 0,
  602. userEngagementScore: engagementScore,
  603. futureUBI
  604. };
  605. return { summary, allocations, epochs, rules: DEFAULT_RULES, addresses };
  606. }
  607. async function getAllocationById(id) {
  608. const t = await transfersRepo.findById(id);
  609. if (!t) return null;
  610. 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 };
  611. }
  612. async function getEpochById(id) {
  613. const existing = await epochsRepo.get(id);
  614. if (existing) return existing;
  615. const all = await transfersRepo.listAll();
  616. const filtered = all.filter(t => (t.tags || []).includes(`epoch:${id}`));
  617. const pool = filtered.reduce((s, t) => s + Number(t.amount || 0), 0);
  618. return { id, pool, weightsSum: 0, rules: DEFAULT_RULES, hash: "-" };
  619. }
  620. async function listEpochAllocations(id) {
  621. const all = await transfersRepo.listAll();
  622. return all.filter(t => (t.tags || []).includes(`epoch:${id}`)).map(t => ({
  623. 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
  624. }));
  625. }
  626. async function calculateEcoinValue() {
  627. let isSynced = false;
  628. let circulatingSupply = 0;
  629. try {
  630. circulatingSupply = await getCirculatingSupply();
  631. isSynced = circulatingSupply > 0;
  632. } catch (error) {
  633. circulatingSupply = 0;
  634. isSynced = false;
  635. }
  636. const totalSupply = 25500000;
  637. const ecoValuePerHour = await calculateEcoValuePerHour(circulatingSupply);
  638. const ecoInHours = calculateEcoinHours(circulatingSupply, ecoValuePerHour);
  639. const inflationFactor = await calculateInflationFactor(circulatingSupply, totalSupply);
  640. return {
  641. ecoValue: ecoValuePerHour,
  642. ecoInHours: Number(ecoInHours.toFixed(2)),
  643. totalSupply: totalSupply,
  644. inflationFactor: inflationFactor ? Number(inflationFactor.toFixed(2)) : 0,
  645. currentSupply: circulatingSupply,
  646. isSynced: isSynced
  647. };
  648. }
  649. async function calculateEcoValuePerHour(circulatingSupply) {
  650. const issuanceRate = await getIssuanceRate();
  651. const inflation = await calculateInflationFactor(circulatingSupply, 25500000);
  652. const ecoValuePerHour = (circulatingSupply / 100000) * (1 + inflation / 100);
  653. return ecoValuePerHour;
  654. }
  655. function calculateEcoinHours(circulatingSupply, ecoValuePerHour) {
  656. const ecoInHours = circulatingSupply / ecoValuePerHour;
  657. return ecoInHours;
  658. }
  659. async function calculateInflationFactor(circulatingSupply, totalSupply) {
  660. const issuanceRate = await getIssuanceRate();
  661. if (circulatingSupply > 0) {
  662. const inflationRate = (issuanceRate / circulatingSupply) * 100;
  663. return inflationRate;
  664. }
  665. return 0;
  666. }
  667. async function getIssuanceRate() {
  668. try {
  669. const result = await rpcCall("getmininginfo", []);
  670. const blockValue = result?.blockvalue || 0;
  671. const blocks = result?.blocks || 0;
  672. return (blockValue / 1e8) * blocks;
  673. } catch (error) {
  674. return 0.02;
  675. }
  676. }
  677. async function getCirculatingSupply() {
  678. try {
  679. const result = await rpcCall("getinfo", []);
  680. return result?.moneysupply || 0;
  681. } catch (error) {
  682. return 0;
  683. }
  684. }
  685. async function getBankingData(userId) {
  686. const ecoValue = await calculateEcoinValue();
  687. const karmaScore = await getUserEngagementScore(userId);
  688. return {
  689. ecoValue,
  690. karmaScore,
  691. };
  692. }
  693. return {
  694. DEFAULT_RULES,
  695. computeEpoch,
  696. executeEpoch,
  697. getUserEngagementScore,
  698. publishBankClaim,
  699. claimAllocation,
  700. listBanking,
  701. getAllocationById,
  702. getEpochById,
  703. listEpochAllocations,
  704. addAddress,
  705. removeAddress,
  706. ensureSelfAddressPublished,
  707. getUserAddress,
  708. setUserAddress,
  709. listAddressesMerged,
  710. calculateEcoinValue,
  711. getBankingData
  712. };
  713. };