@render-foundation/utils 0.0.233 → 0.0.234-beta.1

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.
@@ -35,7 +35,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
35
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
36
  };
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.pgClient = exports.batchFinishedAtMedian = exports.DISPERSED_SETTLEMENT_TABLE = exports.GRANT_BURN_TABLE = exports.GRANT_BURN_ID_TABLE = exports.USER_GRANT_SPEND_TABLE = exports.CURRENT_USER_GRANT_SPEND_TABLE = exports.POLYGON_UPGRADE_TABLE = exports.ENTITY_EPOCH_INFO_TABLE = exports.BURN_CORRECTION_TABLE = exports.NETWORK_REVENUE_TABLE = exports.BRIDGE_TRANSFER_TABLE = exports.BURN_TABLE = exports.JOB_TABLE = exports.JOB_ID_TABLE = exports.LIABILITY_ADJUSTMENT_BATCH_TABLE = exports.LIABILITY_ADJUSTMENT_TABLE = exports.LIABILITY_TABLE = exports.SOL_TRANSFER_TABLE = exports.ENTITY_TABLE = exports.MANUAL_BURN_TABLE = exports.EPOCH_TABLE = exports.SOL_TX_TABLE = void 0;
38
+ exports.pgClient = exports.batchFinishedAtMedian = exports.DISPERSED_SETTLEMENT_TABLE = exports.GRANT_BURN_TABLE = exports.GRANT_BURN_ID_TABLE = exports.USER_GRANT_SPEND_TABLE = exports.CURRENT_USER_GRANT_SPEND_TABLE = exports.POLYGON_UPGRADE_TABLE = exports.ENTITY_EPOCH_INFO_TABLE = exports.TX_BURN_ADJUSTMENT_TABLE = exports.JOB_BURN_ADJUSTMENT_TABLE = exports.NETWORK_REVENUE_TABLE = exports.BRIDGE_TRANSFER_TABLE = exports.BURN_TABLE = exports.JOB_TABLE = exports.JOB_ID_TABLE = exports.LIABILITY_ADJUSTMENT_BATCH_TABLE = exports.LIABILITY_ADJUSTMENT_TABLE = exports.LIABILITY_TABLE = exports.SOL_TRANSFER_TABLE = exports.ENTITY_TABLE = exports.MANUAL_BURN_TABLE = exports.EPOCH_TABLE = exports.SOL_TX_TABLE = void 0;
39
39
  const kysely_1 = require("kysely");
40
40
  const logger_1 = require("../../logger");
41
41
  const pg_1 = require("pg");
@@ -54,7 +54,8 @@ exports.JOB_TABLE = 'job';
54
54
  exports.BURN_TABLE = 'burn';
55
55
  exports.BRIDGE_TRANSFER_TABLE = 'bridge_transfer';
56
56
  exports.NETWORK_REVENUE_TABLE = 'network_revenue';
57
- exports.BURN_CORRECTION_TABLE = 'burn_correction';
57
+ exports.JOB_BURN_ADJUSTMENT_TABLE = 'job_burn_adjustment';
58
+ exports.TX_BURN_ADJUSTMENT_TABLE = 'tx_burn_adjustment';
58
59
  exports.ENTITY_EPOCH_INFO_TABLE = 'entity_epoch_info';
59
60
  exports.POLYGON_UPGRADE_TABLE = 'polygon_upgrade';
60
61
  exports.CURRENT_USER_GRANT_SPEND_TABLE = 'current_user_grant_spend';
@@ -1124,7 +1125,7 @@ const pgClient = (config) => {
1124
1125
  let buyBurnId;
1125
1126
  let grantBurnId;
1126
1127
  if (p.buyBurn) {
1127
- const { burned, usdcSpent, eurToUsdc, renderToUsdc, quoteAmt, tags, downCorrectionId, escrowCorrectionId, toBurn, fromEscrowUsdc, } = p.buyBurn;
1128
+ const { burned, usdcSpent, eurToUsdc, renderToUsdc, quoteAmt, tags, jobBurnAdjustmentId, txBurnAdjustmentId, toBurn, fromEscrowUsdc, } = p.buyBurn;
1128
1129
  let pricedAt = p.buyBurn.pricedAt;
1129
1130
  if (!pricedAt) {
1130
1131
  const jobs = yield fetchJobs1(trx.trx, { ids: p.jobs.map((j) => String(j.id)) }, log);
@@ -1143,8 +1144,8 @@ const pgClient = (config) => {
1143
1144
  quote_amt: quoteAmt,
1144
1145
  burned: burned,
1145
1146
  tags: tags.join(','),
1146
- down_correction_id: downCorrectionId,
1147
- escrow_correction_id: escrowCorrectionId,
1147
+ job_burn_adjustment_id: jobBurnAdjustmentId,
1148
+ tx_burn_adjustment_id: txBurnAdjustmentId,
1148
1149
  to_burn: toBurn,
1149
1150
  from_escrow_usdc: fromEscrowUsdc !== null && fromEscrowUsdc !== void 0 ? fromEscrowUsdc : 0,
1150
1151
  };
@@ -1711,7 +1712,7 @@ const pgClient = (config) => {
1711
1712
  });
1712
1713
  },
1713
1714
  insertDispersedOutbox(p, log = logger_1.consoleLogger) {
1714
- var _a, _b;
1715
+ var _a, _b, _c;
1715
1716
  return __awaiter(this, void 0, void 0, function* () {
1716
1717
  const res = yield db
1717
1718
  .insertInto(exports.DISPERSED_SETTLEMENT_TABLE)
@@ -1724,6 +1725,7 @@ const pgClient = (config) => {
1724
1725
  executed_at: p.executedAt,
1725
1726
  eur_render: (_a = p.eurRender) !== null && _a !== void 0 ? _a : null,
1726
1727
  last_valid_block_height: (_b = p.lastValidBlockHeight) !== null && _b !== void 0 ? _b : null,
1728
+ usdc_spent: (_c = p.usdcSpent) !== null && _c !== void 0 ? _c : null,
1727
1729
  })
1728
1730
  .onConflict((oc) => oc.column('tx_signature').doNothing())
1729
1731
  .executeTakeFirst();
@@ -1749,7 +1751,7 @@ const pgClient = (config) => {
1749
1751
  .execute();
1750
1752
  log.debug(`dispersed outbox: ${rows.length} unsettled`);
1751
1753
  return rows.map((r) => {
1752
- var _a;
1754
+ var _a, _b;
1753
1755
  return ({
1754
1756
  txSignature: r.tx_signature,
1755
1757
  claimUuid: r.claim_uuid,
@@ -1758,6 +1760,7 @@ const pgClient = (config) => {
1758
1760
  burnedAmount: r.burned_amount,
1759
1761
  executedAt: r.executed_at,
1760
1762
  eurRender: (_a = r.eur_render) !== null && _a !== void 0 ? _a : undefined,
1763
+ usdcSpent: (_b = r.usdc_spent) !== null && _b !== void 0 ? _b : undefined,
1761
1764
  // int8 comes back as a string from pg; block heights are well within JS safe-integer range.
1762
1765
  lastValidBlockHeight: r.last_valid_block_height != null
1763
1766
  ? Number(r.last_valid_block_height)
@@ -1777,6 +1780,79 @@ const pgClient = (config) => {
1777
1780
  log.debug(`dispersed outbox void tx ${txSignature}: ${res.numDeletedRows} row(s)`);
1778
1781
  });
1779
1782
  },
1783
+ fetchDispersedSettlements(f, _log = logger_1.consoleLogger) {
1784
+ var _a;
1785
+ return __awaiter(this, void 0, void 0, function* () {
1786
+ let q = db
1787
+ .selectFrom(exports.DISPERSED_SETTLEMENT_TABLE)
1788
+ // Settled burns only — pending (un-landed) outbox rows aren't real, completed burns.
1789
+ .where('settled_at', 'is not', null);
1790
+ if (f.settledAfter)
1791
+ q = q.where('settled_at', '>=', f.settledAfter);
1792
+ if (f.settledBefore)
1793
+ q = q.where('settled_at', '<', f.settledBefore);
1794
+ const rows = yield q
1795
+ .select([
1796
+ 'tx_signature',
1797
+ 'claim_uuid',
1798
+ 'obligation_uuids',
1799
+ 'settled_amount',
1800
+ 'burned_amount',
1801
+ 'usdc_spent',
1802
+ 'eur_render',
1803
+ 'executed_at',
1804
+ 'settled_at',
1805
+ ])
1806
+ .orderBy('settled_at', 'desc')
1807
+ .limit((_a = f.limit) !== null && _a !== void 0 ? _a : 500)
1808
+ .execute();
1809
+ return rows.map((r) => {
1810
+ var _a, _b;
1811
+ return ({
1812
+ txSignature: r.tx_signature,
1813
+ claimUuid: r.claim_uuid,
1814
+ obligationUuids: r.obligation_uuids,
1815
+ settledAmount: r.settled_amount,
1816
+ burnedAmount: r.burned_amount,
1817
+ usdcSpent: (_a = r.usdc_spent) !== null && _a !== void 0 ? _a : null,
1818
+ eurRender: (_b = r.eur_render) !== null && _b !== void 0 ? _b : null,
1819
+ executedAt: r.executed_at,
1820
+ settledAt: r.settled_at,
1821
+ });
1822
+ });
1823
+ });
1824
+ },
1825
+ fetchDispersedMonthlyStats(f, _log = logger_1.consoleLogger) {
1826
+ return __awaiter(this, void 0, void 0, function* () {
1827
+ let q = db
1828
+ .selectFrom(exports.DISPERSED_SETTLEMENT_TABLE)
1829
+ .where('settled_at', 'is not', null);
1830
+ if (f.settledAfter)
1831
+ q = q.where('settled_at', '>=', f.settledAfter);
1832
+ if (f.settledBefore)
1833
+ q = q.where('settled_at', '<', f.settledBefore);
1834
+ const rows = yield q
1835
+ .select([
1836
+ // Bucket by UTC calendar month of settlement.
1837
+ (0, kysely_1.sql) `date_trunc('month', settled_at at time zone 'UTC')`.as('month'),
1838
+ (0, kysely_1.sql) `coalesce(sum(settled_amount), 0)::text`.as('settled_eur'),
1839
+ // usdc_spent is NULL for pre-migration-39 burns; sum() skips NULLs so they simply don't count.
1840
+ (0, kysely_1.sql) `coalesce(sum(usdc_spent), 0)::text`.as('usdc_spent'),
1841
+ (0, kysely_1.sql) `coalesce(sum(burned_amount), 0)::text`.as('render_burned'),
1842
+ (0, kysely_1.sql) `count(*)::text`.as('burn_count'),
1843
+ ])
1844
+ .groupBy('month')
1845
+ .orderBy('month', 'asc')
1846
+ .execute();
1847
+ return rows.map((r) => ({
1848
+ month: r.month,
1849
+ settledEur: r.settled_eur,
1850
+ usdcSpent: r.usdc_spent,
1851
+ renderBurned: r.render_burned,
1852
+ burnCount: Number(r.burn_count),
1853
+ }));
1854
+ });
1855
+ },
1780
1856
  fetchJobs(db, f, log = logger_1.consoleLogger) {
1781
1857
  return __awaiter(this, void 0, void 0, function* () {
1782
1858
  return yield fetchJobs1(db.trx, f, log);
@@ -1846,79 +1922,90 @@ const pgClient = (config) => {
1846
1922
  }));
1847
1923
  });
1848
1924
  },
1849
- createBurnCorrection(trx, p, log = logger_1.consoleLogger) {
1925
+ createTxBurnAdjustment(trx, p, log = logger_1.consoleLogger) {
1850
1926
  return __awaiter(this, void 0, void 0, function* () {
1851
- // Anchor + unit invariants are also DB CHECKs; validate here for a clearer error.
1852
- if ((p.jobId == null) === (p.solTxId == null))
1853
- throw new Error('burn_correction needs exactly one anchor (jobId XOR solTxId)');
1854
- if (p.kind === 'down_adjust' && p.amountRender == null)
1855
- throw new Error('down_adjust needs amountRender');
1856
- if (p.kind === 'escrow_credit' && p.amountUsdc == null)
1857
- throw new Error('escrow_credit needs amountUsdc');
1858
- // Idempotent per (anchor, kind) — a re-run for the same bad job/tx is a no-op.
1927
+ // Idempotent per sol_tx_id (unique) a re-run for the same bad tx is a no-op.
1859
1928
  const row = yield trx.trx
1860
- .insertInto(exports.BURN_CORRECTION_TABLE)
1929
+ .insertInto(exports.TX_BURN_ADJUSTMENT_TABLE)
1861
1930
  .values({
1862
- kind: p.kind,
1863
- job_id: p.jobId,
1864
1931
  sol_tx_id: p.solTxId,
1865
- amount_render: p.amountRender,
1866
- amount_usdc: p.amountUsdc,
1932
+ surplus_usdc: p.surplusUsdc,
1867
1933
  description: p.description,
1868
1934
  })
1869
- .onConflict((oc) => oc.doNothing())
1935
+ .onConflict((oc) => oc.column('sol_tx_id').doNothing())
1870
1936
  .returning('id')
1871
1937
  .executeTakeFirst();
1872
1938
  if (!row) {
1873
- log.info(`burn_correction ${p.kind} for ${p.jobId != null ? `job ${p.jobId}` : `sol_tx ${p.solTxId}`} already exists — skipped`);
1939
+ log.info(`tx_burn_adjustment for sol_tx ${p.solTxId} already exists — skipped`);
1874
1940
  return undefined;
1875
1941
  }
1876
- log.info(`created burn_correction ${row.id} (${p.kind}, ${p.jobId != null ? `job ${p.jobId}` : `sol_tx ${p.solTxId}`}): ${p.kind === 'down_adjust' ? `${p.amountRender} RENDER` : `${p.amountUsdc} USDC`}`);
1942
+ log.info(`created tx_burn_adjustment ${row.id}: ${p.surplusUsdc} USDC over-spent (sol_tx ${p.solTxId})`);
1877
1943
  return Number(row.id);
1878
1944
  });
1879
1945
  },
1880
- getBurnCorrections(trx, ps, log = logger_1.consoleLogger) {
1946
+ getJobBurnAdjustments(trx, ps, log = logger_1.consoleLogger) {
1881
1947
  return __awaiter(this, void 0, void 0, function* () {
1882
1948
  if (!ps.toFill)
1883
1949
  return [];
1884
- // fill column depends on kind: down_adjust consumes (to_burn - burned); escrow_credit consumes
1885
- // from_escrow_usdc. Each links via its own burn FK so one burn can carry one of each.
1886
- const linkCol = ps.kind === 'down_adjust' ? 'down_correction_id' : 'escrow_correction_id';
1887
1950
  const q = trx.trx
1888
- .selectFrom(exports.BURN_CORRECTION_TABLE)
1889
- .selectAll(exports.BURN_CORRECTION_TABLE)
1890
- .leftJoin(exports.BURN_TABLE, `${exports.BURN_TABLE}.${linkCol}`, `${exports.BURN_CORRECTION_TABLE}.id`)
1951
+ .selectFrom(exports.JOB_BURN_ADJUSTMENT_TABLE)
1952
+ .selectAll(exports.JOB_BURN_ADJUSTMENT_TABLE)
1953
+ .innerJoin(exports.JOB_TABLE, `${exports.JOB_TABLE}.id`, `${exports.JOB_BURN_ADJUSTMENT_TABLE}.job_id`)
1954
+ .select([`${exports.JOB_TABLE}.completed_at`, `${exports.JOB_TABLE}.render_amt`])
1955
+ .leftJoin(exports.BURN_TABLE, `${exports.BURN_TABLE}.job_burn_adjustment_id`, `${exports.JOB_BURN_ADJUSTMENT_TABLE}.id`)
1891
1956
  .select(({ fn, lit }) => [
1892
1957
  fn.sum(fn.coalesce(`${exports.BURN_TABLE}.to_burn`, lit(0))).as('tot_to_burn'),
1893
1958
  fn.sum(fn.coalesce(`${exports.BURN_TABLE}.burned`, lit(0))).as('tot_burned'),
1959
+ ])
1960
+ .groupBy([
1961
+ `${exports.JOB_BURN_ADJUSTMENT_TABLE}.id`,
1962
+ `${exports.JOB_TABLE}.completed_at`,
1963
+ `${exports.JOB_TABLE}.render_amt`,
1964
+ ]);
1965
+ log.info(`getJobBurnAdjustments ${q.compile().sql}`);
1966
+ const res = yield q.execute();
1967
+ return res
1968
+ .map((r) => ({
1969
+ id: Number(r.id),
1970
+ createdAt: r.created_at,
1971
+ jobId: Number(r.job_id),
1972
+ downAdjRndrUsed: Number(r.down_adj_rndr_used),
1973
+ downAdjToBurn: Number(r.down_adj_to_burn),
1974
+ adjusted: Number(r.tot_to_burn) - Number(r.tot_burned),
1975
+ job: {
1976
+ id: Number(r.job_id),
1977
+ completedAt: r.completed_at,
1978
+ rndrUsed: BigInt(r.render_amt),
1979
+ },
1980
+ }))
1981
+ .filter((a) => a.adjusted < a.downAdjToBurn);
1982
+ });
1983
+ },
1984
+ getTxBurnAdjustments(trx, ps, log = logger_1.consoleLogger) {
1985
+ return __awaiter(this, void 0, void 0, function* () {
1986
+ if (!ps.toFill)
1987
+ return [];
1988
+ const q = trx.trx
1989
+ .selectFrom(exports.TX_BURN_ADJUSTMENT_TABLE)
1990
+ .selectAll(exports.TX_BURN_ADJUSTMENT_TABLE)
1991
+ .leftJoin(exports.BURN_TABLE, `${exports.BURN_TABLE}.tx_burn_adjustment_id`, `${exports.TX_BURN_ADJUSTMENT_TABLE}.id`)
1992
+ .select(({ fn, lit }) => [
1894
1993
  fn
1895
1994
  .sum(fn.coalesce(`${exports.BURN_TABLE}.from_escrow_usdc`, lit(0)))
1896
1995
  .as('tot_from_escrow'),
1897
1996
  ])
1898
- .where(`${exports.BURN_CORRECTION_TABLE}.kind`, '=', ps.kind)
1899
- .groupBy(`${exports.BURN_CORRECTION_TABLE}.id`)
1900
- .orderBy(`${exports.BURN_CORRECTION_TABLE}.created_at`, 'asc');
1901
- log.info(`getBurnCorrections(${ps.kind}) ${q.compile().sql}`);
1997
+ .groupBy(`${exports.TX_BURN_ADJUSTMENT_TABLE}.id`);
1998
+ log.info(`getTxBurnAdjustments ${q.compile().sql}`);
1902
1999
  const res = yield q.execute();
1903
2000
  return res
1904
2001
  .map((r) => ({
1905
2002
  id: Number(r.id),
1906
2003
  createdAt: r.created_at,
1907
- jobId: r.job_id != null ? Number(r.job_id) : undefined,
1908
- solTxId: r.sol_tx_id != null ? Number(r.sol_tx_id) : undefined,
1909
- kind: r.kind,
1910
- amountRender: r.amount_render != null ? Number(r.amount_render) : undefined,
1911
- amountUsdc: r.amount_usdc != null ? Number(r.amount_usdc) : undefined,
1912
- consumed: ps.kind === 'down_adjust'
1913
- ? Number(r.tot_to_burn) - Number(r.tot_burned)
1914
- : Number(r.tot_from_escrow),
2004
+ solTxId: Number(r.sol_tx_id),
2005
+ surplusUsdc: Number(r.surplus_usdc),
2006
+ consumed: Number(r.tot_from_escrow),
1915
2007
  }))
1916
- .filter((c) => {
1917
- var _a, _b;
1918
- return c.kind === 'down_adjust'
1919
- ? c.consumed < ((_a = c.amountRender) !== null && _a !== void 0 ? _a : 0)
1920
- : c.consumed < ((_b = c.amountUsdc) !== null && _b !== void 0 ? _b : 0);
1921
- });
2008
+ .filter((a) => a.consumed < a.surplusUsdc);
1922
2009
  });
1923
2010
  },
1924
2011
  insertPolygonUpgrade(db, p, log = logger_1.consoleLogger) {