@render-foundation/utils 0.0.58 → 0.0.60

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,709 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var _Deferred_promise, _Deferred_resolve, _Deferred_reject;
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.Deferred = exports.pgClient = exports.BURN_TABLE = exports.JOB_TABLE = exports.JOB_ID_TABLE = exports.SOL_TRANSFER_INFO_TABLE = exports.SOL_TRANSFER_TABLE = exports.ENTITY_TABLE = exports.MANUAL_BURN_TABLE = exports.EPOCH_TABLE = exports.SOL_TX_TABLE = void 0;
25
+ const pg_1 = require("pg");
26
+ const kysely_1 = require("kysely");
27
+ const logger_1 = require("../../logger");
28
+ const transferTypToChan = (t) => {
29
+ if (t == 'open_compute_rewards') {
30
+ return 'open_compute';
31
+ }
32
+ if (t == 'node_operator_rewards') {
33
+ return 'node_operator';
34
+ }
35
+ return 'upgrade';
36
+ };
37
+ const transferFromDB = (o) => {
38
+ return {
39
+ id: o.id,
40
+ solKey: o.sol_key,
41
+ solTx: o.sol_tx,
42
+ sqTx: o.sq_tx,
43
+ createdAt: o.created_at,
44
+ payedAt: o.payed_at,
45
+ amountDue: BigInt(o.amount_due),
46
+ amountPayed: o.amount_payed ? BigInt(o.amount_payed) : undefined,
47
+ operatorRewards: o.transfer_type == 'node_operator_rewards'
48
+ ? {
49
+ epochId: o.epoch_id,
50
+ startTime: o.start_time,
51
+ endTime: o.end_time,
52
+ }
53
+ : undefined,
54
+ computeClientRewards: o.transfer_type == 'open_compute_rewards'
55
+ ? {
56
+ epochId: o.epoch_id,
57
+ deviceId: o.device_id,
58
+ }
59
+ : undefined,
60
+ upgradeRewards: o.transfer_type == 'upgrade_rewards' && !!o.epoch_id
61
+ ? {
62
+ epochId: o.epoch_id,
63
+ epochStartTime: o.epoch_start_time,
64
+ points: BigInt(o.points),
65
+ }
66
+ : undefined,
67
+ };
68
+ };
69
+ exports.SOL_TX_TABLE = 'sol_tx';
70
+ exports.EPOCH_TABLE = 'epoch';
71
+ exports.MANUAL_BURN_TABLE = 'manual_burn';
72
+ exports.ENTITY_TABLE = 'entity';
73
+ exports.SOL_TRANSFER_TABLE = 'sol_transfer';
74
+ exports.SOL_TRANSFER_INFO_TABLE = 'sol_transfer_info';
75
+ exports.JOB_ID_TABLE = 'job_id';
76
+ exports.JOB_TABLE = 'job';
77
+ exports.BURN_TABLE = 'burn';
78
+ const pgClient = (config) => {
79
+ var _a, _b;
80
+ const dialect = new kysely_1.PostgresDialect({
81
+ pool: new pg_1.Pool(Object.assign(Object.assign({}, config), { port: (_a = config.port) !== null && _a !== void 0 ? _a : 5432, max: (_b = config.max) !== null && _b !== void 0 ? _b : 10 })),
82
+ });
83
+ // Database interface is passed to Kysely's constructor, and from now on, Kysely
84
+ // knows your database structure.
85
+ // Dialect is passed to Kysely's constructor, and from now on, Kysely knows how
86
+ // to communicate with your database.
87
+ const db = new kysely_1.Kysely({
88
+ dialect,
89
+ });
90
+ const getOrInsertEntity = (db, p, log = logger_1.consoleLogger) => __awaiter(void 0, void 0, void 0, function* () {
91
+ const res = (yield db
92
+ .selectFrom(exports.ENTITY_TABLE)
93
+ .select('id')
94
+ .where('sol_key', '=', p.solKey)
95
+ .executeTakeFirst());
96
+ if (res) {
97
+ log.debug(`already found entity ${res.id}`);
98
+ return res.id;
99
+ }
100
+ const { id } = (yield db
101
+ .insertInto(exports.ENTITY_TABLE)
102
+ .values({
103
+ sol_key: p.solKey,
104
+ })
105
+ .onConflict((oc) => oc.column('sol_key').doNothing())
106
+ .returning((eb) => ['id as id'])
107
+ .executeTakeFirst());
108
+ log.debug(`inserted entity ${id}`);
109
+ return id;
110
+ });
111
+ const getOrInsertTx = (db, p, log = logger_1.consoleLogger) => __awaiter(void 0, void 0, void 0, function* () {
112
+ const res = yield db
113
+ .selectFrom(exports.SOL_TX_TABLE)
114
+ .select('id')
115
+ .where('sig', '=', p.sig)
116
+ .executeTakeFirst();
117
+ if (res) {
118
+ log.debug(`already found tx ${res.id}`);
119
+ return res.id;
120
+ }
121
+ const { id } = (yield db
122
+ .insertInto(exports.SOL_TX_TABLE)
123
+ .values({
124
+ sig: p.sig,
125
+ executed_at: p.executedAt,
126
+ })
127
+ .onConflict((oc) => oc.column('sig').doNothing())
128
+ .returning((eb) => ['id as id'])
129
+ .executeTakeFirst());
130
+ log.debug(`inserted tx ${id}`);
131
+ return id;
132
+ });
133
+ const getOrInsertEpoch = (db, p, log = logger_1.consoleLogger) => __awaiter(void 0, void 0, void 0, function* () {
134
+ const res = yield db
135
+ .selectFrom(exports.EPOCH_TABLE)
136
+ .select('id')
137
+ .where('ui', '=', String(p.uiEpochId))
138
+ .where('channel', '=', p.channel)
139
+ .executeTakeFirst();
140
+ if (res) {
141
+ log.debug(`already found epoch ${res.id}`);
142
+ return res.id;
143
+ }
144
+ const { id } = (yield db
145
+ .insertInto(exports.EPOCH_TABLE)
146
+ .values({
147
+ ui: p.uiEpochId,
148
+ channel: p.channel,
149
+ start_time: p.startTime,
150
+ end_time: p.endTime,
151
+ total_rndr: p.totalRndr,
152
+ })
153
+ .onConflict((oc) => oc.columns(['ui', 'channel']).doNothing())
154
+ .returning((eb) => ['id as id'])
155
+ .executeTakeFirst());
156
+ log.debug(`inserted epoch ${id}`);
157
+ return id;
158
+ });
159
+ const createTransfers = (db, transfers, log = logger_1.consoleLogger, totalRndr = BigInt(0)) => __awaiter(void 0, void 0, void 0, function* () {
160
+ const epochIds = [];
161
+ for (const t of transfers) {
162
+ let solTxId;
163
+ if (t.solTx) {
164
+ solTxId = yield getOrInsertTx(db, {
165
+ sig: t.solTx,
166
+ executedAt: t.payedAt,
167
+ }, log);
168
+ }
169
+ const entityId = yield getOrInsertEntity(db, { solKey: t.solKey }, log);
170
+ const { id: transferId } = (yield db
171
+ .insertInto(exports.SOL_TRANSFER_TABLE)
172
+ .values({
173
+ sol_tx_id: solTxId,
174
+ entity_id: entityId,
175
+ channel: transferTypToChan((() => {
176
+ if (t.operatorRewards) {
177
+ return 'node_operator_rewards';
178
+ }
179
+ else if (t.upgradeRewards) {
180
+ return 'upgrade_rewards';
181
+ }
182
+ else if (t.computeClientRewards) {
183
+ return 'open_compute_rewards';
184
+ }
185
+ throw new Error('wtf');
186
+ })()),
187
+ created_at: t.createdAt,
188
+ amount_due: BigInt(t.amountDue),
189
+ amount_payed: t.amountPayed ? BigInt(t.amountPayed) : 0,
190
+ })
191
+ .returning((eb) => ['id as id'])
192
+ .executeTakeFirst());
193
+ log.info(`inserted transfer ${JSON.stringify(t, (key, value) => typeof value === 'bigint' ? value.toString() : value)}`);
194
+ let epochId;
195
+ let deviceId;
196
+ let points;
197
+ let startTime;
198
+ let endTime;
199
+ let channel;
200
+ if (t.operatorRewards) {
201
+ log.info(`inserting operator rewards ${transferId}`);
202
+ epochId = t.operatorRewards.epochId;
203
+ startTime = t.operatorRewards.startTime;
204
+ endTime = t.operatorRewards.endTime;
205
+ channel = 'node_operator';
206
+ }
207
+ else if (t.computeClientRewards) {
208
+ log.info(`inserting compute client rewards ${transferId}`);
209
+ epochId = t.computeClientRewards.epochId;
210
+ deviceId = t.computeClientRewards.deviceId;
211
+ channel = 'open_compute';
212
+ }
213
+ else if (t.upgradeRewards) {
214
+ log.info(`inserting upgrade rewards ${transferId}`);
215
+ channel = 'upgrade';
216
+ epochId = t.upgradeRewards.epochId;
217
+ points = t.upgradeRewards.points;
218
+ }
219
+ const epochIdDb = yield getOrInsertEpoch(db, {
220
+ channel,
221
+ startTime,
222
+ endTime,
223
+ uiEpochId: epochId,
224
+ totalRndr,
225
+ }, log);
226
+ yield db
227
+ .insertInto(exports.SOL_TRANSFER_INFO_TABLE)
228
+ .values({
229
+ transfer_id: transferId,
230
+ device_id: deviceId,
231
+ points,
232
+ epoch_id: BigInt(epochIdDb),
233
+ })
234
+ .executeTakeFirst();
235
+ epochIds.push({ epochDbId: epochIdDb });
236
+ }
237
+ return epochIds;
238
+ });
239
+ return {
240
+ db,
241
+ saveNodeOperatorEpoch(epochId, transfers, jobIds, totalRndr, log = logger_1.consoleLogger) {
242
+ return __awaiter(this, void 0, void 0, function* () {
243
+ yield db
244
+ .transaction()
245
+ .setIsolationLevel('repeatable read')
246
+ .execute((trx) => __awaiter(this, void 0, void 0, function* () {
247
+ const epochDbIds = yield createTransfers(trx, transfers, log, totalRndr);
248
+ log.info(`inserted transfers`);
249
+ for (const id of jobIds) {
250
+ yield trx
251
+ .insertInto(exports.JOB_ID_TABLE)
252
+ .values({
253
+ id: BigInt(id),
254
+ epoch_id: epochDbIds[0].epochDbId,
255
+ })
256
+ .executeTakeFirstOrThrow();
257
+ }
258
+ log.debug(`saved epoch`);
259
+ /*const now = new Date(Date.now())
260
+ const res = await trx
261
+ .updateTable(EPOCH_TABLE)
262
+ .set({
263
+ saved_at: now,
264
+ total_rndr: totalRndr,
265
+ })
266
+ .where('channel')
267
+ .where('ui', '=', epochId.toString())
268
+ .where('', '=')
269
+ .executeTakeFirstOrThrow()*/
270
+ }));
271
+ return;
272
+ });
273
+ },
274
+ getLatestNodeOperatorEpoch(log = logger_1.consoleLogger) {
275
+ var _a;
276
+ return __awaiter(this, void 0, void 0, function* () {
277
+ const now = new Date(Date.now());
278
+ try {
279
+ const res = yield db
280
+ .selectFrom(exports.EPOCH_TABLE)
281
+ .selectAll()
282
+ .where('channel', '=', 'node_operator')
283
+ .where('end_time', '<=', now)
284
+ .where('saved_at', 'is', null)
285
+ .orderBy('end_time asc')
286
+ .limit(1)
287
+ .executeTakeFirstOrThrow();
288
+ return {
289
+ epochId: BigInt(res.ui),
290
+ startedAt: res.start_time,
291
+ endedAt: res.end_time,
292
+ savedAt: (_a = res.saved_at) !== null && _a !== void 0 ? _a : undefined,
293
+ };
294
+ }
295
+ catch (e) {
296
+ if (e instanceof kysely_1.NoResultError) {
297
+ log.info(`no node operator epoch found`);
298
+ return undefined;
299
+ }
300
+ throw e;
301
+ }
302
+ });
303
+ },
304
+ getOutstanding(f, log = logger_1.consoleLogger) {
305
+ var _a;
306
+ return __awaiter(this, void 0, void 0, function* () {
307
+ const { typ, nullKey, due } = f;
308
+ //select sol_key, sum(amount_due)-sum(amount_payed) from transfer group by sol_key;
309
+ let q = db
310
+ .selectFrom(exports.SOL_TRANSFER_TABLE)
311
+ .innerJoin(exports.ENTITY_TABLE, 'sol_transfer.entity_id', 'entity.id')
312
+ .select(({ fn, val, ref }) => [
313
+ 'entity.sol_key',
314
+ (0, kysely_1.sql) `${fn.sum('sol_transfer.amount_due')} -
315
+ ${fn.sum('sol_transfer.amount_payed')}`.as('due'),
316
+ ])
317
+ .where('sol_transfer.channel', '=', transferTypToChan(typ))
318
+ .groupBy(['entity.sol_key']);
319
+ if (!nullKey) {
320
+ q = q.where('entity.sol_key', 'is not', null);
321
+ }
322
+ if (due) {
323
+ q = q.having(({ fn, ref }) => (0, kysely_1.sql) `${fn.sum('sol_transfer.amount_due')} -
324
+ ${fn.sum('sol_transfer.amount_payed')}
325
+ >
326
+ 0`);
327
+ }
328
+ const res = yield q.execute();
329
+ log.info(`outstanding query ${q.compile().sql} params ${JSON.stringify(f)} ${res.length} rows`);
330
+ const out = {};
331
+ for (const r of res) {
332
+ out[(_a = r.sol_key) !== null && _a !== void 0 ? _a : ''] = BigInt(r.due);
333
+ }
334
+ return out;
335
+ });
336
+ },
337
+ fetchTransfers(f, log = logger_1.consoleLogger) {
338
+ return __awaiter(this, void 0, void 0, function* () {
339
+ let base = db
340
+ .selectFrom(exports.SOL_TRANSFER_TABLE)
341
+ .selectAll(exports.SOL_TRANSFER_TABLE)
342
+ .innerJoin(exports.SOL_TRANSFER_INFO_TABLE, 'sol_transfer_info.transfer_id', 'sol_transfer.id')
343
+ .select(['sol_transfer_info.device_id', 'sol_transfer_info.points'])
344
+ .innerJoin(exports.ENTITY_TABLE, 'entity.id', 'sol_transfer.entity_id')
345
+ .select(['entity.sol_key'])
346
+ .where('sol_transfer.channel', '=', transferTypToChan(f.typ));
347
+ if (f.solKey) {
348
+ base = base.where('entity.sol_key', '=', f.solKey);
349
+ }
350
+ if (f.payed != undefined) {
351
+ base = base
352
+ .leftJoin(exports.SOL_TX_TABLE, 'sol_tx.id', 'sol_transfer.sol_tx_id')
353
+ .select(['sol_tx.sig', 'sol_tx.executed_at'])
354
+ .where('sol_transfer.sol_tx_id', f.payed ? 'is not' : 'is', null);
355
+ }
356
+ if (f.createdBefore != undefined) {
357
+ base = base.where('sol_transfer.created_at', '<=', f.createdBefore);
358
+ }
359
+ if (f.epochId) {
360
+ base = base
361
+ .innerJoin(exports.EPOCH_TABLE, 'epoch.id', 'sol_transfer_info.epoch_id')
362
+ .select(['epoch.ui'])
363
+ .where('epoch.ui', '=', String(f.epochId));
364
+ }
365
+ if (f.sort) {
366
+ base = base.orderBy('entity.sol_key asc');
367
+ }
368
+ const res = yield base.execute();
369
+ log.info(`fetched ${base.compile().sql} params ${JSON.stringify(f)} ${res.length} transfers`);
370
+ return res.map((r) => transferFromDB(r));
371
+ });
372
+ },
373
+ payoutTransfers(idToAmt, payedAt, solTx, log = logger_1.consoleLogger) {
374
+ return __awaiter(this, void 0, void 0, function* () {
375
+ yield db
376
+ .transaction()
377
+ .setIsolationLevel('repeatable read')
378
+ .execute((tx) => __awaiter(this, void 0, void 0, function* () {
379
+ const alreadyUpdatedIds = (yield tx
380
+ .selectFrom(exports.SOL_TRANSFER_TABLE)
381
+ .innerJoin(exports.SOL_TX_TABLE, 'sol_transfer.sol_tx_id', 'sol_tx.id')
382
+ .select(['sol_transfer.id'])
383
+ .where('sol_transfer.id', 'in', Object.keys(idToAmt))
384
+ .where('sol_tx.sig', 'is not', null)
385
+ .execute()).map(({ id }) => id);
386
+ for (const [id, amt] of Object.entries(idToAmt)) {
387
+ if (alreadyUpdatedIds.includes(id)) {
388
+ log.info(`transfer ${id} already marked payed out. skipping`);
389
+ continue;
390
+ }
391
+ const solTxId = yield getOrInsertTx(tx, { sig: solTx, executedAt: payedAt }, log);
392
+ const res = yield tx
393
+ .updateTable(exports.SOL_TRANSFER_TABLE)
394
+ .set({
395
+ sol_tx_id: solTxId,
396
+ amount_payed: amt,
397
+ })
398
+ .where('id', '=', id.toString())
399
+ .executeTakeFirstOrThrow();
400
+ log.info(`marked ${res.numUpdatedRows} transfer payed out`);
401
+ }
402
+ }));
403
+ });
404
+ },
405
+ payoutTransfer(id, payedAt, solTx, amtPayed, log = logger_1.consoleLogger) {
406
+ return __awaiter(this, void 0, void 0, function* () {
407
+ yield db
408
+ .transaction()
409
+ .setIsolationLevel('repeatable read')
410
+ .execute((tx) => __awaiter(this, void 0, void 0, function* () {
411
+ const solTxId = yield getOrInsertTx(tx, { sig: solTx, executedAt: payedAt }, log);
412
+ const res = yield tx
413
+ .updateTable(exports.SOL_TRANSFER_TABLE)
414
+ .set({
415
+ sol_tx_id: solTxId,
416
+ amount_payed: amtPayed,
417
+ })
418
+ .where('id', '=', id.toString())
419
+ .executeTakeFirst();
420
+ log.info(`marked ${res.numUpdatedRows} transfer payed out`);
421
+ }));
422
+ });
423
+ },
424
+ createTransfers(transfers, log = logger_1.consoleLogger) {
425
+ return __awaiter(this, void 0, void 0, function* () {
426
+ yield db
427
+ .transaction()
428
+ .setIsolationLevel('repeatable read')
429
+ .execute((trx) => __awaiter(this, void 0, void 0, function* () {
430
+ yield createTransfers(trx, transfers, log);
431
+ }));
432
+ });
433
+ },
434
+ fetchInfoForEpoch(epochId, log = logger_1.consoleLogger) {
435
+ var _a;
436
+ return __awaiter(this, void 0, void 0, function* () {
437
+ const q = db
438
+ .selectFrom(exports.JOB_ID_TABLE)
439
+ .innerJoin(exports.EPOCH_TABLE, 'epoch.id', 'job_id.epoch_id')
440
+ .leftJoin(exports.MANUAL_BURN_TABLE, 'manual_burn.epoch_id', 'epoch.id')
441
+ .where('epoch.ui', '=', String(epochId))
442
+ .where('epoch.channel', '=', 'node_operator')
443
+ .select([
444
+ 'job_id.id',
445
+ 'epoch.total_rndr',
446
+ 'epoch.start_time',
447
+ 'epoch.end_time',
448
+ 'manual_burn.burned',
449
+ 'manual_burn.tx_sig',
450
+ ])
451
+ .orderBy('job_id.id asc');
452
+ log.debug(`fetch epoch info q ${q.compile().sql} epochId ${epochId}`);
453
+ const res = yield q.execute();
454
+ if (res.length == 0) {
455
+ throw new Error(`epoch ${epochId} not found`);
456
+ }
457
+ return {
458
+ jobIds: res.map((r) => Number(r.id)),
459
+ totalRndr: BigInt(res[0].total_rndr),
460
+ startTime: res[0].start_time,
461
+ endTime: res[0].end_time,
462
+ burned: BigInt((_a = res[0].burned) !== null && _a !== void 0 ? _a : 0),
463
+ burnTx: res[0].tx_sig,
464
+ };
465
+ });
466
+ },
467
+ updateComputeClientSolKey(deviceId, solKey, log = logger_1.consoleLogger) {
468
+ return __awaiter(this, void 0, void 0, function* () {
469
+ const q = db
470
+ .updateTable(`${exports.ENTITY_TABLE} as e`)
471
+ .set({
472
+ sol_key: solKey,
473
+ })
474
+ .from(`${exports.SOL_TRANSFER_TABLE} as t`)
475
+ .innerJoin(exports.SOL_TRANSFER_INFO_TABLE, 'sol_transfer_info.transfer_id', 't.id')
476
+ //.whereRef('t.id', '=', 'o.transfer_id')
477
+ .where('e.sol_key', 'is', null)
478
+ .where('sol_transfer_info.device_id', '=', deviceId);
479
+ const sql = yield q.compile();
480
+ log.info(`sql ${sql.sql} params ${sql.parameters}`);
481
+ const res = yield q.executeTakeFirstOrThrow();
482
+ log.info(`updated ${res.numUpdatedRows} device-id sol_keys`);
483
+ });
484
+ },
485
+ markJobsBurnt(trx, p, log = logger_1.consoleLogger) {
486
+ return __awaiter(this, void 0, void 0, function* () {
487
+ const solTxId = yield getOrInsertTx(trx, { sig: p.solTx, executedAt: p.executedAt }, log);
488
+ const { id } = yield trx
489
+ .insertInto(exports.BURN_TABLE)
490
+ .values({
491
+ sol_tx_id: solTxId,
492
+ priced_at: p.pricedAt,
493
+ usdc_spent: p.usdcSpent,
494
+ quote_amt: p.quoteAmt,
495
+ burned: p.burned,
496
+ })
497
+ //.onConflict((oc) => oc.column('sol_tx').doNothing())
498
+ .returning((eb) => ['id as id'])
499
+ .executeTakeFirstOrThrow();
500
+ const jobIdsStr = p.jobsIds.map(String);
501
+ const res = yield trx
502
+ .updateTable(exports.JOB_TABLE)
503
+ .where('id', 'in', jobIdsStr)
504
+ .set('burn_id', id)
505
+ .executeTakeFirstOrThrow();
506
+ log.debug(`set burn_id on ${res.numUpdatedRows} jobs`);
507
+ return;
508
+ });
509
+ },
510
+ produceBurnedJobs(jobs, log = logger_1.consoleLogger) {
511
+ return __awaiter(this, void 0, void 0, function* () {
512
+ yield db.transaction().execute((trx) => __awaiter(this, void 0, void 0, function* () {
513
+ var _a;
514
+ let num = BigInt(0);
515
+ for (const { amount, completedAt, jobId } of jobs) {
516
+ const res = yield trx
517
+ .insertInto(exports.JOB_TABLE)
518
+ .values({
519
+ id: jobId,
520
+ render_amt: amount,
521
+ completed_at: completedAt,
522
+ inserted_at: new Date(Date.now()),
523
+ })
524
+ .onConflict((oc) => oc.column('id').doNothing())
525
+ .executeTakeFirstOrThrow();
526
+ num += (_a = res.numInsertedOrUpdatedRows) !== null && _a !== void 0 ? _a : BigInt(0);
527
+ }
528
+ log.debug(`inserted ${num} of ${jobs.length} burn jobs`);
529
+ }));
530
+ });
531
+ },
532
+ markJobsBurned(p, log = logger_1.consoleLogger) {
533
+ return __awaiter(this, void 0, void 0, function* () {
534
+ let { markedAt, solTx } = p;
535
+ let res = yield db
536
+ .updateTable(exports.BURN_TABLE)
537
+ .set({ marked_burned_at: markedAt })
538
+ .from(exports.SOL_TX_TABLE)
539
+ .whereRef('burn.sol_tx_id', '=', 'sol_tx.id')
540
+ .where('sol_tx.sig', '=', solTx)
541
+ .executeTakeFirstOrThrow();
542
+ log.debug(`set ${res.numUpdatedRows} ${solTx} -> marked_burned_at ${markedAt.toISOString()}`);
543
+ });
544
+ },
545
+ consumeAndLockBurnJobs(limit, lowerRndrThreshold, upperRndrThreshold, log = logger_1.consoleLogger) {
546
+ return __awaiter(this, void 0, void 0, function* () {
547
+ const trx = yield begin(db);
548
+ const q = trx.trx
549
+ .selectFrom(trx.trx
550
+ .selectFrom(exports.JOB_TABLE)
551
+ .select(({ fn, val, ref }) => [
552
+ 'id',
553
+ fn
554
+ .sum('render_amt')
555
+ .over((ob) => ob.orderBy(`completed_at`, `asc`))
556
+ .as('total'),
557
+ ])
558
+ .where('burn_id', 'is', null)
559
+ .as('t'))
560
+ .select('id')
561
+ .where('total', '>', lowerRndrThreshold)
562
+ .where('total', '<', upperRndrThreshold);
563
+ log.debug(`outstanding jobs q: ${q.compile().sql} ${JSON.stringify({
564
+ limit,
565
+ lowerRndrThreshold,
566
+ upperRndrThreshold,
567
+ })}`);
568
+ const idRs = yield q.execute();
569
+ const ids = idRs.map((x) => x.id);
570
+ log.debug(`${ids.length} candidate jobs for burn. locking up to ${limit} jobs`);
571
+ if (ids.length == 0) {
572
+ return { trx, jobs: [] };
573
+ }
574
+ const rows = yield trx.trx
575
+ .selectFrom(exports.JOB_TABLE)
576
+ .selectAll()
577
+ .where('id', 'in', ids)
578
+ .limit(limit)
579
+ .forUpdate()
580
+ .skipLocked()
581
+ .execute();
582
+ log.debug(`locked ${rows.length} jobs`);
583
+ const jobs = [];
584
+ for (const r of rows) {
585
+ jobs.push({
586
+ id: Number(r.id),
587
+ completedAt: r.completed_at,
588
+ rndrUsed: BigInt(r.render_amt),
589
+ });
590
+ }
591
+ return { trx, jobs };
592
+ });
593
+ },
594
+ incrBuyBurnMetrics(log = logger_1.consoleLogger) {
595
+ var _a;
596
+ return __awaiter(this, void 0, void 0, function* () {
597
+ const res = yield db
598
+ .selectFrom(exports.JOB_TABLE)
599
+ .select('completed_at')
600
+ .orderBy('completed_at asc')
601
+ .where('burn_id', 'is', null)
602
+ .execute();
603
+ if (res.length == 0) {
604
+ return { outstandingJobs: 0 };
605
+ }
606
+ return {
607
+ outstandingJobs: res.length,
608
+ oldestJobFinishedAt: (_a = res[0].completed_at) !== null && _a !== void 0 ? _a : undefined,
609
+ };
610
+ });
611
+ },
612
+ deleteAll() {
613
+ return __awaiter(this, void 0, void 0, function* () {
614
+ if (config.database.includes('render')) {
615
+ throw new Error('cannot nuke from deployed database. call from tests only');
616
+ }
617
+ yield Promise.all([
618
+ db
619
+ .deleteFrom(exports.SOL_TX_TABLE)
620
+ .where('id', 'is not', null)
621
+ .executeTakeFirst(),
622
+ db
623
+ .deleteFrom(exports.SOL_TRANSFER_TABLE)
624
+ .where('id', 'is not', null)
625
+ .executeTakeFirst(),
626
+ db
627
+ .deleteFrom(exports.SOL_TRANSFER_INFO_TABLE)
628
+ .where('transfer_id', 'is not', null)
629
+ .executeTakeFirst(),
630
+ db
631
+ .deleteFrom(exports.EPOCH_TABLE)
632
+ .where('id', 'is not', null)
633
+ .executeTakeFirst(),
634
+ db
635
+ .deleteFrom(exports.ENTITY_TABLE)
636
+ .where('id', 'is not', null)
637
+ .executeTakeFirst(),
638
+ db
639
+ .deleteFrom(exports.MANUAL_BURN_TABLE)
640
+ .where('epoch_id', 'is not', null)
641
+ .executeTakeFirst(),
642
+ db
643
+ .deleteFrom(exports.JOB_ID_TABLE)
644
+ .where('id', 'is not', null)
645
+ .executeTakeFirst(),
646
+ db.deleteFrom(exports.JOB_TABLE).where('id', 'is not', null).executeTakeFirst(),
647
+ db
648
+ .deleteFrom(exports.BURN_TABLE)
649
+ .where('id', 'is not', null)
650
+ .executeTakeFirst(),
651
+ ]);
652
+ });
653
+ },
654
+ };
655
+ };
656
+ exports.pgClient = pgClient;
657
+ function begin(db) {
658
+ return __awaiter(this, void 0, void 0, function* () {
659
+ const connection = new Deferred();
660
+ const result = new Deferred();
661
+ // Do NOT await this line.
662
+ db.transaction()
663
+ .setIsolationLevel('repeatable read')
664
+ .execute((trx) => {
665
+ connection.resolve(trx);
666
+ return result.promise;
667
+ })
668
+ .catch((err) => {
669
+ // Don't do anything here. Just swallow the exception.
670
+ });
671
+ const trx = yield connection.promise;
672
+ return {
673
+ trx,
674
+ commit() {
675
+ result.resolve(null);
676
+ },
677
+ rollback() {
678
+ result.reject(new Error('rollback'));
679
+ },
680
+ };
681
+ });
682
+ }
683
+ class Deferred {
684
+ constructor() {
685
+ _Deferred_promise.set(this, void 0);
686
+ _Deferred_resolve.set(this, void 0);
687
+ _Deferred_reject.set(this, void 0);
688
+ this.resolve = (value) => {
689
+ if (__classPrivateFieldGet(this, _Deferred_resolve, "f")) {
690
+ __classPrivateFieldGet(this, _Deferred_resolve, "f").call(this, value);
691
+ }
692
+ };
693
+ this.reject = (reason) => {
694
+ if (__classPrivateFieldGet(this, _Deferred_reject, "f")) {
695
+ __classPrivateFieldGet(this, _Deferred_reject, "f").call(this, reason);
696
+ }
697
+ };
698
+ __classPrivateFieldSet(this, _Deferred_promise, new Promise((resolve, reject) => {
699
+ __classPrivateFieldSet(this, _Deferred_reject, reject, "f");
700
+ __classPrivateFieldSet(this, _Deferred_resolve, resolve, "f");
701
+ }), "f");
702
+ }
703
+ get promise() {
704
+ return __classPrivateFieldGet(this, _Deferred_promise, "f");
705
+ }
706
+ }
707
+ exports.Deferred = Deferred;
708
+ _Deferred_promise = new WeakMap(), _Deferred_resolve = new WeakMap(), _Deferred_reject = new WeakMap();
709
+ //# sourceMappingURL=v2.js.map