@render-foundation/utils 0.0.240 → 0.0.242

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.calculateBurnAmounts = exports.batchFinishedAtMedian = void 0;
15
+ const spl_utils_1 = require("@render-foundation/spl-utils");
16
+ const logger_1 = require("../logger");
17
+ // Utility function copied from cron-server
18
+ const batchFinishedAtMedian = (jobs) => {
19
+ const pricedAt = jobs.length % 2 == 0
20
+ ? new Date(Math.trunc((Date.parse(jobs[jobs.length / 2].finishedAt) +
21
+ Date.parse(jobs[jobs.length / 2 - 1].finishedAt)) /
22
+ 2))
23
+ : new Date(Date.parse(jobs[Math.floor(jobs.length / 2)].finishedAt));
24
+ return pricedAt;
25
+ };
26
+ exports.batchFinishedAtMedian = batchFinishedAtMedian;
27
+ /**
28
+ * Pure function that calculates burn amounts without side effects
29
+ * This is the core logic extracted from consumeIncrBuyAndBurnRenderPG
30
+ */
31
+ const calculateBurnAmounts = (input, opts = {
32
+ perpetual: true,
33
+ }, log = logger_1.consoleLogger) => {
34
+ const { jobs, userGrantSpends, burnAdjustments, params, decimals, priceAtDate, eurToUSDC, } = input;
35
+ // Apply grant/buy split logic to jobs
36
+ const processedJobs = jobs.map((j) => {
37
+ const { buyRenderAmt, grantRenderAmt } = j, rest = __rest(j, ["buyRenderAmt", "grantRenderAmt"]);
38
+ return rest;
39
+ }); // Deep copy to avoid mutations
40
+ for (const j of processedJobs) {
41
+ const userGrantSpend = userGrantSpends[j.userId];
42
+ if (userGrantSpend) {
43
+ if (opts.perpetual ||
44
+ userGrantSpend.userGrantSpend.perpetual ||
45
+ j.rndrUsed <= userGrantSpend.currAllot) {
46
+ j.grantRenderAmt = Number(j.rndrUsed);
47
+ log.debug(`job ${j.id} grant split: ${j.rndrUsed}`);
48
+ userGrantSpend.currAllot -= BigInt(j.rndrUsed);
49
+ }
50
+ else if (userGrantSpend.currAllot <= BigInt(0)) {
51
+ log.debug(`job ${j.id} buy split: ${j.rndrUsed}`);
52
+ j.buyRenderAmt = Number(j.rndrUsed);
53
+ }
54
+ else {
55
+ log.debug(`job ${j.id} buy + grant split: ${j.rndrUsed} grant: ${Number(userGrantSpend.currAllot)} buy: ${Number(j.rndrUsed) - Number(userGrantSpend.currAllot)}`);
56
+ j.grantRenderAmt = Number(userGrantSpend.currAllot);
57
+ j.buyRenderAmt = Number(j.rndrUsed) - Number(userGrantSpend.currAllot);
58
+ userGrantSpend.currAllot = BigInt(0);
59
+ }
60
+ }
61
+ else {
62
+ log.debug(`job ${j.id} no grant split: ${j.rndrUsed}`);
63
+ j.buyRenderAmt = Number(j.rndrUsed);
64
+ }
65
+ }
66
+ const totalRenderUsed = processedJobs.reduce((tot, job) => tot + Number(job.rndrUsed.toString()), 0);
67
+ log.debug(`jobs buy + grant split: ${JSON.stringify(processedJobs)}`);
68
+ // Check minimum threshold
69
+ if (totalRenderUsed < (0, spl_utils_1.toBN)(params.minTotalRndrThreshold, decimals).toNumber()) {
70
+ throw new Error(`totalRenderUsed ${totalRenderUsed / Math.pow(10, decimals)} < total threshold ${params.minTotalRndrThreshold}`);
71
+ }
72
+ const totalRenderBuyAndBurn = processedJobs.reduce((tot, job) => { var _a; return tot + Number((_a = job.buyRenderAmt) !== null && _a !== void 0 ? _a : 0); }, 0);
73
+ const totalRender = processedJobs.reduce((tot, job) => tot + Number(job.rndrUsed.toString()), 0);
74
+ log.debug(`Burn calculation inputs:`);
75
+ log.debug(` totalRenderUsed: ${totalRenderUsed}`);
76
+ log.debug(` totalRenderBuyAndBurn: ${totalRenderBuyAndBurn}`);
77
+ log.debug(` totalRender: ${totalRender}`);
78
+ log.debug(` priceAtDate: ${priceAtDate}`);
79
+ log.debug(` eurToUSDC: ${eurToUSDC}`);
80
+ const pricedAt = (0, exports.batchFinishedAtMedian)(processedJobs.map((job) => ({
81
+ finishedAt: job.completedAt.toISOString(),
82
+ jobId: job.id,
83
+ rndrUsed: Number(job.rndrUsed.toString()),
84
+ })));
85
+ // Core burn calculation logic
86
+ const toBurn = Math.trunc((totalRender / priceAtDate / 4) * 0.95 * eurToUSDC);
87
+ let renderToBuyAndBurn = Math.trunc((totalRenderBuyAndBurn / totalRender) * toBurn);
88
+ const origRenderToBuyAndBurn = renderToBuyAndBurn;
89
+ log.debug(`Core burn calculation:`);
90
+ log.debug(` toBurn: ${toBurn}`);
91
+ log.debug(` renderToBuyAndBurn: ${renderToBuyAndBurn}`);
92
+ log.debug(` origRenderToBuyAndBurn: ${origRenderToBuyAndBurn}`);
93
+ let burnAdjustmentId = undefined;
94
+ // Apply burn adjustments
95
+ if (burnAdjustments.length > 0) {
96
+ const adjustment = burnAdjustments[0];
97
+ burnAdjustmentId = adjustment.id;
98
+ const adjLeft = adjustment.downAdjToBurn - adjustment.adjusted;
99
+ const minBurnRndrThreshold = (0, spl_utils_1.toBN)(params.minBurnRndrThreshold, decimals).toNumber();
100
+ const available = renderToBuyAndBurn - minBurnRndrThreshold;
101
+ if (adjLeft > available) {
102
+ renderToBuyAndBurn = minBurnRndrThreshold;
103
+ }
104
+ else {
105
+ renderToBuyAndBurn -= adjLeft;
106
+ }
107
+ }
108
+ // Validate burn thresholds
109
+ const toBuyAndBurnUI = renderToBuyAndBurn / Math.pow(10, decimals);
110
+ if (renderToBuyAndBurn != 0) {
111
+ if (toBuyAndBurnUI > params.maxBurnRndrThreshold) {
112
+ throw new Error(`buy and burn RENDER ${toBuyAndBurnUI} too high`);
113
+ }
114
+ if (toBuyAndBurnUI < params.minBurnRndrThreshold) {
115
+ throw new Error(`buy and burn RENDER ${toBuyAndBurnUI} too low < ${params.minBurnRndrThreshold}`);
116
+ }
117
+ }
118
+ const renderToBurnFromEmissions = toBurn - origRenderToBuyAndBurn;
119
+ const totalToBurn = renderToBuyAndBurn + renderToBurnFromEmissions;
120
+ log.debug(`Final burn calculation results:`);
121
+ log.debug(` renderToBuyAndBurn: ${renderToBuyAndBurn}`);
122
+ log.debug(` renderToBurnFromEmissions: ${renderToBurnFromEmissions}`);
123
+ log.debug(` totalToBurn: ${totalToBurn}`);
124
+ log.debug(` toBurn: ${toBurn}`);
125
+ return {
126
+ totalRenderUsed,
127
+ totalRenderBuyAndBurn,
128
+ totalRender,
129
+ renderToBuyAndBurn,
130
+ renderToBurnFromEmissions,
131
+ totalToBurn,
132
+ toBurn,
133
+ origRenderToBuyAndBurn,
134
+ burnAdjustmentId,
135
+ pricedAt,
136
+ processedJobs,
137
+ };
138
+ };
139
+ exports.calculateBurnAmounts = calculateBurnAmounts;
140
+ //# sourceMappingURL=burnCalculations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"burnCalculations.js","sourceRoot":"","sources":["../../../src/burn/burnCalculations.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,4DAAmD;AACnD,sCAAuD;AAWvD,2CAA2C;AACpC,MAAM,qBAAqB,GAAG,CACnC,IAA+D,EACzD,EAAE;IACR,MAAM,QAAQ,GACZ,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC;QAClB,CAAC,CAAC,IAAI,IAAI,CACN,IAAI,CAAC,KAAK,CACR,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,UAAU,CAAC;YAC3C,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC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B;KACF;IAED,2BAA2B;IAC3B,MAAM,cAAc,GAAG,kBAAkB,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAA;IAElE,IAAI,kBAAkB,IAAI,CAAC,EAAE;QAC3B,IAAI,cAAc,GAAG,MAAM,CAAC,oBAAoB,EAAE;YAChD,MAAM,IAAI,KAAK,CAAC,uBAAuB,cAAc,WAAW,CAAC,CAAA;SAClE;QACD,IAAI,cAAc,GAAG,MAAM,CAAC,oBAAoB,EAAE;YAChD,MAAM,IAAI,KAAK,CACb,uBAAuB,cAAc,cAAc,MAAM,CAAC,oBAAoB,EAAE,CACjF,CAAA;SACF;KACF;IAED,MAAM,yBAAyB,GAAG,MAAM,GAAG,sBAAsB,CAAA;IACjE,MAAM,WAAW,GAAG,kBAAkB,GAAG,yBAAyB,CAAA;IAElE,GAAG,CAAC,KAAK,CAAC,iCAAiC,CAAC,CAAA;IAC5C,GAAG,CAAC,KAAK,CAAC,yBAAyB,kBAAkB,EAAE,CAAC,CAAA;IACxD,GAAG,CAAC,KAAK,CAAC,gCAAgC,yBAAyB,EAAE,CAAC,CAAA;IACtE,GAAG,CAAC,KAAK,CAAC,kBAAkB,WAAW,EAAE,CAAC,CAAA;IAC1C,GAAG,CAAC,KAAK,CAAC,aAAa,MAAM,EAAE,CAAC,CAAA;IAEhC,OAAO;QACL,eAAe;QACf,qBAAqB;QACrB,WAAW;QACX,kBAAkB;QAClB,yBAAyB;QACzB,WAAW;QACX,MAAM;QACN,sBAAsB;QACtB,gBAAgB;QAChB,QAAQ;QACR,aAAa;KACd,CAAA;AACH,CAAC,CAAA;AAxKY,QAAA,oBAAoB,wBAwKhC"}
@@ -241,20 +241,29 @@ const pgClient = (config) => {
241
241
  .execute();
242
242
  if (!grants.length)
243
243
  return out;
244
- // Anything already booked against a pool grant, in EITHER direction:
245
- // - negative delta = spend drawn from the grant (this mechanism)
244
+ // EVERY grant-ledger row retires pool capacity, in either direction:
245
+ // - negative delta = an emissions burn. ALL of them count, not just ones stamped with an
246
+ // otoy_grant_id. Historical grants are now backfilled to cover the Sep/Oct-2025 burns, so those
247
+ // burns must net against them; counting only stamped rows would re-issue ~1.06M credits of
248
+ // already-spent grant.
246
249
  // - positive delta = the grant was CREDITED into current_user_grant_spend (the one-off canary
247
- // route). That balance is already handed to the caller separately, so leaving it in the pool too
248
- // would hand out the same grant twice.
249
- // Hence abs(): both directions retire pool capacity.
250
+ // route). That balance reaches the split separately, so leaving it in the pool double-issues it.
251
+ // Hence abs() over the whole ledger.
252
+ // NOT abs() over the whole ledger — that would charge the Sep/Oct-2025 CSV *credits* as if they
253
+ // were spend, double-penalising those users (464e8e33: 376,749 burned + 79,304 credited = 456,053).
254
+ // A positive only retires capacity when it is tied to a pool grant (the canary route, where the
255
+ // grant was moved into current_user_grant_spend and reaches the split from there).
250
256
  const spent = yield db
251
257
  .selectFrom(exports.USER_GRANT_SPEND_TABLE)
252
258
  .select((eb) => [
253
259
  'user_id',
254
- eb.fn.sum((0, kysely_1.sql) `abs(render_spent_delta)`).as('net'),
260
+ eb.fn
261
+ .sum((0, kysely_1.sql) `case when render_spent_delta < 0 then -render_spent_delta
262
+ when otoy_grant_id is not null then render_spent_delta
263
+ else 0 end`)
264
+ .as('net'),
255
265
  ])
256
266
  .where('user_id', 'in', p.userIds)
257
- .where('otoy_grant_id', 'is not', null)
258
267
  .groupBy('user_id')
259
268
  .execute();
260
269
  // jobs already settled by a burn correction — their grant is spoken for (double-spend guard)