@xyo-network/chain-services 1.11.0 → 1.12.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.
Files changed (30) hide show
  1. package/dist/neutral/AccountBalance/BaseAccountBalanceService.d.ts.map +1 -1
  2. package/dist/neutral/BlockProducer/BaseBlockProducerService.d.ts +17 -3
  3. package/dist/neutral/BlockProducer/BaseBlockProducerService.d.ts.map +1 -1
  4. package/dist/neutral/ChainBlockNumberIteration/model/BlockNumberIteration.d.ts +2 -2
  5. package/dist/neutral/ChainBlockNumberIteration/model/BlockNumberIteration.d.ts.map +1 -1
  6. package/dist/neutral/ChainValidator/XyoValidator.d.ts +20 -7
  7. package/dist/neutral/ChainValidator/XyoValidator.d.ts.map +1 -1
  8. package/dist/neutral/ChainValidator/model/Validator.d.ts +2 -2
  9. package/dist/neutral/ChainValidator/model/Validator.d.ts.map +1 -1
  10. package/dist/neutral/PendingTransactions/BasePendingTransactions.d.ts +4 -4
  11. package/dist/neutral/PendingTransactions/BasePendingTransactions.d.ts.map +1 -1
  12. package/dist/neutral/PendingTransactions/bundledPayloadToHydratedTransaction.d.ts +2 -2
  13. package/dist/neutral/PendingTransactions/bundledPayloadToHydratedTransaction.d.ts.map +1 -1
  14. package/dist/neutral/PendingTransactions/hydratedTransactionToPayloadBundle.d.ts +2 -2
  15. package/dist/neutral/PendingTransactions/hydratedTransactionToPayloadBundle.d.ts.map +1 -1
  16. package/dist/neutral/StakeIntent/XyoStakeIntentService.d.ts +5 -1
  17. package/dist/neutral/StakeIntent/XyoStakeIntentService.d.ts.map +1 -1
  18. package/dist/neutral/index.mjs +344 -225
  19. package/dist/neutral/index.mjs.map +1 -1
  20. package/package.json +37 -37
  21. package/src/AccountBalance/BaseAccountBalanceService.ts +2 -1
  22. package/src/BlockProducer/spec/BaseBlockProducerService.spec.ts +3 -3
  23. package/src/BlockProducer/spec/generateTransactionTransfer.spec.ts +2 -2
  24. package/src/ChainBlockNumberIteration/model/BlockNumberIteration.ts +2 -2
  25. package/src/ChainValidator/XyoValidator.ts +4 -4
  26. package/src/ChainValidator/model/Validator.ts +2 -2
  27. package/src/PendingTransactions/BasePendingTransactions.ts +8 -7
  28. package/src/PendingTransactions/bundledPayloadToHydratedTransaction.ts +2 -2
  29. package/src/PendingTransactions/hydratedTransactionToPayloadBundle.ts +3 -3
  30. package/src/PendingTransactions/spec/BasePendingTransactions.spec.ts +11 -10
@@ -1,39 +1,33 @@
1
1
  var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
- var __decorateClass = (decorators, target, key, kind) => {
5
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
6
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
7
- if (decorator = decorators[i])
8
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
9
- if (kind && result) __defProp(target, key, result);
10
- return result;
11
- };
12
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
3
 
14
4
  // src/AccountBalance/accountBalanceServiceFromArchivist.ts
15
5
  import { exists } from "@xylabs/exists";
16
- import {
17
- asHash,
18
- isHash
19
- } from "@xylabs/hex";
6
+ import { asHash, isHash } from "@xylabs/hex";
20
7
  import { PayloadBuilder } from "@xyo-network/payload-builder";
21
8
  import { LRUCache } from "lru-cache";
22
9
 
23
10
  // src/AccountBalance/BaseAccountBalanceService.ts
24
11
  import { creatable as creatable2 } from "@xylabs/creatable";
25
- import {
26
- AttoXL1
27
- } from "@xyo-network/xl1-protocol";
28
- import {
29
- balanceSummary
30
- } from "@xyo-network/xl1-protocol-sdk";
12
+ import { AttoXL1 } from "@xyo-network/xl1-protocol";
13
+ import { balanceSummary } from "@xyo-network/xl1-protocol-sdk";
31
14
 
32
15
  // src/BaseService.ts
33
16
  import { AbstractCreatable, creatable } from "@xylabs/creatable";
34
17
  import { span, spanAsync } from "@xylabs/telemetry";
35
18
  import { Mutex } from "async-mutex";
19
+ function _ts_decorate(decorators, target, key, desc) {
20
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
23
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
24
+ }
25
+ __name(_ts_decorate, "_ts_decorate");
36
26
  var BaseService = class extends AbstractCreatable {
27
+ static {
28
+ __name(this, "BaseService");
29
+ }
30
+ static singletonInitMutex = new Mutex();
37
31
  static get singletons() {
38
32
  return globalThis["xyoServiceSingletons"] ?? (globalThis["xyoServiceSingletons"] = {});
39
33
  }
@@ -53,21 +47,33 @@ var BaseService = class extends AbstractCreatable {
53
47
  return await spanAsync(name, fn, this.tracer);
54
48
  }
55
49
  };
56
- __publicField(BaseService, "singletonInitMutex", new Mutex());
57
- BaseService = __decorateClass([
50
+ BaseService = _ts_decorate([
58
51
  creatable()
59
52
  ], BaseService);
60
53
  var BaseAccountableService = class extends BaseService {
61
- // Base class for services that have an account
54
+ static {
55
+ __name(this, "BaseAccountableService");
56
+ }
62
57
  };
63
58
  function creatableService() {
64
59
  return (constructor) => {
65
60
  constructor;
66
61
  };
67
62
  }
63
+ __name(creatableService, "creatableService");
68
64
 
69
65
  // src/AccountBalance/BaseAccountBalanceService.ts
66
+ function _ts_decorate2(decorators, target, key, desc) {
67
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
68
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
69
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
70
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
71
+ }
72
+ __name(_ts_decorate2, "_ts_decorate");
70
73
  var BaseAccountBalanceService = class extends BaseService {
74
+ static {
75
+ __name(this, "BaseAccountBalanceService");
76
+ }
71
77
  async balances(head, address) {
72
78
  const summary = await balanceSummary({
73
79
  chainArchivist: this.params.chainArchivist,
@@ -76,17 +82,18 @@ var BaseAccountBalanceService = class extends BaseService {
76
82
  });
77
83
  const result = {};
78
84
  for (const addr of address) {
79
- result[addr] = AttoXL1(summary[addr] ?? 0n);
85
+ const summaryBalance = summary[addr] ?? 0n;
86
+ result[addr] = AttoXL1(summaryBalance < 0n ? 0n : summaryBalance);
80
87
  }
81
88
  return result;
82
89
  }
83
90
  };
84
- BaseAccountBalanceService = __decorateClass([
91
+ BaseAccountBalanceService = _ts_decorate2([
85
92
  creatable2()
86
93
  ], BaseAccountBalanceService);
87
94
 
88
95
  // src/AccountBalance/accountBalanceServiceFromArchivist.ts
89
- var accountBalanceServiceFromArchivist = async (archivist) => {
96
+ var accountBalanceServiceFromArchivist = /* @__PURE__ */ __name(async (archivist) => {
90
97
  const summaryArchivistCache = new LRUCache({
91
98
  max: 1e5,
92
99
  allowStale: true,
@@ -94,13 +101,13 @@ var accountBalanceServiceFromArchivist = async (archivist) => {
94
101
  updateAgeOnGet: true
95
102
  });
96
103
  const summaryRepository = {
97
- get: (hashes) => {
104
+ get: /* @__PURE__ */ __name((hashes) => {
98
105
  const results = hashes.map((hash) => {
99
106
  return summaryArchivistCache.get(hash);
100
107
  }).filter(exists);
101
108
  return results;
102
- },
103
- insert: async (payloads) => {
109
+ }, "get"),
110
+ insert: /* @__PURE__ */ __name(async (payloads) => {
104
111
  const results = (await PayloadBuilder.addStorageMeta(payloads)).map((payload) => {
105
112
  const hash = asHash(payload.hash);
106
113
  if (isHash(hash)) {
@@ -109,35 +116,28 @@ var accountBalanceServiceFromArchivist = async (archivist) => {
109
116
  }
110
117
  }).filter(exists);
111
118
  return results;
112
- },
113
- next: () => {
119
+ }, "insert"),
120
+ next: /* @__PURE__ */ __name(() => {
114
121
  throw new Error("Not implemented");
115
- }
122
+ }, "next")
116
123
  };
117
- const service = await BaseAccountBalanceService.create({ chainArchivist: archivist, summaryRepository });
124
+ const service = await BaseAccountBalanceService.create({
125
+ chainArchivist: archivist,
126
+ summaryRepository
127
+ });
118
128
  return service;
119
- };
129
+ }, "accountBalanceServiceFromArchivist");
120
130
  var accountBalanceServiceFromArchivistV2 = accountBalanceServiceFromArchivist;
121
131
 
122
132
  // src/BlockProducer/BaseBlockProducerService.ts
123
133
  import { assertEx as assertEx2 } from "@xylabs/assert";
124
134
  import { creatable as creatable3 } from "@xylabs/creatable";
125
135
  import { exists as exists2 } from "@xylabs/exists";
126
- import {
127
- hexToBigInt,
128
- toHex
129
- } from "@xylabs/hex";
130
- import {
131
- FixedPercentageBlockRewardDiviner,
132
- FixedPercentageBlockRewardDivinerConfigSchema
133
- } from "@xyo-network/chain-modules";
136
+ import { hexToBigInt, toHex } from "@xylabs/hex";
137
+ import { FixedPercentageBlockRewardDiviner, FixedPercentageBlockRewardDivinerConfigSchema } from "@xyo-network/chain-modules";
134
138
  import { buildNextBlock, createDeclarationIntent } from "@xyo-network/chain-protocol";
135
139
  import { PayloadBuilder as PayloadBuilder3 } from "@xyo-network/payload-builder";
136
- import {
137
- asBlockBoundWitness,
138
- AttoXL1 as AttoXL12,
139
- BlockNumberSchema
140
- } from "@xyo-network/xl1-protocol";
140
+ import { asBlockBoundWitness, AttoXL1 as AttoXL12, BlockNumberSchema } from "@xyo-network/xl1-protocol";
141
141
 
142
142
  // src/BlockProducer/generateTransactionFeeTransfers.ts
143
143
  import { assertEx } from "@xylabs/assert";
@@ -148,7 +148,10 @@ import { transactionRequiredGas } from "@xyo-network/xl1-protocol-sdk";
148
148
  import { HydratedTransactionWrapper } from "@xyo-network/xl1-wrappers";
149
149
  async function generateTransactionFeeTransfers(address, transactions) {
150
150
  const txs = await Promise.all(transactions.map(async (tx) => {
151
- return HydratedTransactionWrapper.parse([await PayloadBuilder2.addStorageMeta(tx[0]), await PayloadBuilder2.addStorageMeta(tx[1])]);
151
+ return HydratedTransactionWrapper.parse([
152
+ await PayloadBuilder2.addStorageMeta(tx[0]),
153
+ await PayloadBuilder2.addStorageMeta(tx[1])
154
+ ]);
152
155
  }));
153
156
  const txBaseFeeCosts = {};
154
157
  for (const tx of txs) {
@@ -178,30 +181,41 @@ async function generateTransactionFeeTransfers(address, transactions) {
178
181
  }
179
182
  return payloads;
180
183
  }
184
+ __name(generateTransactionFeeTransfers, "generateTransactionFeeTransfers");
181
185
 
182
186
  // src/BlockProducer/BaseBlockProducerService.ts
187
+ function _ts_decorate3(decorators, target, key, desc) {
188
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
189
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
190
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
191
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
192
+ }
193
+ __name(_ts_decorate3, "_ts_decorate");
183
194
  var DEFAULT_BLOCK_SIZE = 10;
184
195
  var XYO_PRODUCER_REDECLARATION_DURATION = 1e4;
185
196
  var XYO_PRODUCER_REDECLARATION_WINDOW = 500;
186
- var BaseBlockProducerService = class extends BaseService {
197
+ var BaseBlockProducerService = class _BaseBlockProducerService extends BaseService {
198
+ static {
199
+ __name(this, "BaseBlockProducerService");
200
+ }
187
201
  _blockRewardDiviner;
188
202
  /**
189
- * The default block size for a block
190
- */
203
+ * The default block size for a block
204
+ */
191
205
  static get DefaultBlockSize() {
192
206
  return DEFAULT_BLOCK_SIZE;
193
207
  }
194
208
  /**
195
- * The amount of time for which the producer will redeclare
196
- * their intent to continue producing blocks
197
- */
209
+ * The amount of time for which the producer will redeclare
210
+ * their intent to continue producing blocks
211
+ */
198
212
  static get RedeclarationDuration() {
199
213
  return XYO_PRODUCER_REDECLARATION_DURATION;
200
214
  }
201
215
  /**
202
- * The number of blocks within which the producer will redeclare
203
- * their intent to continue producing blocks
204
- */
216
+ * The number of blocks within which the producer will redeclare
217
+ * their intent to continue producing blocks
218
+ */
205
219
  static get RedeclarationWindow() {
206
220
  return XYO_PRODUCER_REDECLARATION_WINDOW;
207
221
  }
@@ -260,16 +274,22 @@ var BaseBlockProducerService = class extends BaseService {
260
274
  });
261
275
  }
262
276
  const blockHex = assertEx2(toHex(block), () => "Failed to convert block to hex");
263
- const blockId = new PayloadBuilder3({ schema: BlockNumberSchema }).fields({ block: blockHex }).build();
264
- const rewards = await this._blockRewardDiviner.divine([blockId]);
277
+ const blockId = new PayloadBuilder3({
278
+ schema: BlockNumberSchema
279
+ }).fields({
280
+ block: blockHex
281
+ }).build();
282
+ const rewards = await this._blockRewardDiviner.divine([
283
+ blockId
284
+ ]);
265
285
  const [reward] = rewards;
266
286
  return reward;
267
287
  }
268
288
  /**
269
- * Handles the producer redeclaration logic
270
- * @param head The current head block
271
- * @returns chain stake intent for the producer redeclaration, or undefined if no redeclaration is needed
272
- */
289
+ * Handles the producer redeclaration logic
290
+ * @param head The current head block
291
+ * @returns chain stake intent for the producer redeclaration, or undefined if no redeclaration is needed
292
+ */
273
293
  async getProducerRedeclaration(head) {
274
294
  if (this.params.config.producer.disableIntentRedeclaration) return;
275
295
  const ranges = await this.stakeIntentService.getDeclaredCandidateRanges(this.address, "producer");
@@ -278,14 +298,14 @@ var BaseBlockProducerService = class extends BaseService {
278
298
  const [, currentDeclarationEnd] = lastRange;
279
299
  const currentBlock = head.block;
280
300
  const timeToProducerExpiration = currentDeclarationEnd - currentBlock;
281
- if (timeToProducerExpiration > BaseBlockProducerService.RedeclarationWindow) return;
282
- return createDeclarationIntent(this.address, "producer", currentBlock, currentBlock + BaseBlockProducerService.RedeclarationDuration);
301
+ if (timeToProducerExpiration > _BaseBlockProducerService.RedeclarationWindow) return;
302
+ return createDeclarationIntent(this.address, "producer", currentBlock, currentBlock + _BaseBlockProducerService.RedeclarationDuration);
283
303
  }
284
304
  async proposeNextValidBlock(head, validateBalances = false) {
285
305
  return await this.spanAsync("proposeNextValidBlock", async () => {
286
306
  const { block: previousBlock } = assertEx2(asBlockBoundWitness(head), () => "Invalid head block");
287
307
  const nextBlock = previousBlock + 1;
288
- const nextBlockTransactions = await this.pendingTransactionsService.getPendingTransactions(head._hash, BaseBlockProducerService.DefaultBlockSize);
308
+ const nextBlockTransactions = await this.pendingTransactionsService.getPendingTransactions(head._hash, _BaseBlockProducerService.DefaultBlockSize);
289
309
  const blockPayloads = [];
290
310
  const producerRedeclarationPayload = await this.getProducerRedeclaration(head);
291
311
  if (producerRedeclarationPayload) blockPayloads.push(producerRedeclarationPayload);
@@ -299,7 +319,9 @@ var BaseBlockProducerService = class extends BaseService {
299
319
  if (!transfer) return;
300
320
  const totalTransferCost = Object.values(transfer?.transfers).reduce((acc, t) => acc + hexToBigInt(t ?? "00"), 0n);
301
321
  if (validateBalances) {
302
- const balance = (await this.balanceService.balances(head._hash, [transfer.from]))[transfer.from] ?? AttoXL12(0n);
322
+ const balance = (await this.balanceService.balances(head._hash, [
323
+ transfer.from
324
+ ]))[transfer.from] ?? AttoXL12(0n);
303
325
  if (balance >= totalTransferCost) {
304
326
  fundedTransfers.push(transfer);
305
327
  return tx;
@@ -310,9 +332,13 @@ var BaseBlockProducerService = class extends BaseService {
310
332
  }
311
333
  }))).filter(exists2);
312
334
  blockPayloads.push(...fundedTransfers);
313
- const block = await buildNextBlock(head, fundedNextBlockTransactions, blockPayloads, [this.account]);
335
+ const block = await buildNextBlock(head, fundedNextBlockTransactions, blockPayloads, [
336
+ this.account
337
+ ]);
314
338
  this.logger?.info(`buildBlock: ${block[0].block} with ${block[1].length} payloads`);
315
- const errors = await this.validateHydratedBlockState(block, this.chainId, { accountBalance: this.balanceService });
339
+ const errors = await this.validateHydratedBlockState(block, this.chainId, {
340
+ accountBalance: this.balanceService
341
+ });
316
342
  if (errors.length > 0) {
317
343
  this.logger?.warn(`Validation of produced block failed: ${errors.at(0)?.message}`);
318
344
  const rejectedTransactions = block[1];
@@ -323,18 +349,28 @@ var BaseBlockProducerService = class extends BaseService {
323
349
  });
324
350
  }
325
351
  };
326
- BaseBlockProducerService = __decorateClass([
352
+ BaseBlockProducerService = _ts_decorate3([
327
353
  creatable3()
328
354
  ], BaseBlockProducerService);
329
355
 
330
356
  // src/BlockReward/BaseBlockRewardService.ts
331
357
  import { creatable as creatable4 } from "@xylabs/creatable";
358
+ function _ts_decorate4(decorators, target, key, desc) {
359
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
360
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
361
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
362
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
363
+ }
364
+ __name(_ts_decorate4, "_ts_decorate");
332
365
  var BaseBlockRewardService = class extends BaseService {
366
+ static {
367
+ __name(this, "BaseBlockRewardService");
368
+ }
333
369
  getRewardForBlock(_blockNumber) {
334
370
  throw new Error("getRewardForBlock method must be implemented in derived classes");
335
371
  }
336
372
  };
337
- BaseBlockRewardService = __decorateClass([
373
+ BaseBlockRewardService = _ts_decorate4([
338
374
  creatable4()
339
375
  ], BaseBlockRewardService);
340
376
 
@@ -343,7 +379,17 @@ import { assertEx as assertEx3 } from "@xylabs/assert";
343
379
  import { creatable as creatable5 } from "@xylabs/creatable";
344
380
  import { toEthAddress } from "@xylabs/hex";
345
381
  import { XyoChainRewards__factory as XyoChainRewardsFactory } from "@xyo-network/typechain";
382
+ function _ts_decorate5(decorators, target, key, desc) {
383
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
384
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
385
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
386
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
387
+ }
388
+ __name(_ts_decorate5, "_ts_decorate");
346
389
  var EvmBlockRewardService = class extends BaseBlockRewardService {
390
+ static {
391
+ __name(this, "EvmBlockRewardService");
392
+ }
347
393
  _contractAddress;
348
394
  get chainService() {
349
395
  return assertEx3(this.params.chainService, () => "chainService is required");
@@ -368,7 +414,7 @@ var EvmBlockRewardService = class extends BaseBlockRewardService {
368
414
  return await contract.calcBlockReward(blockNumber);
369
415
  }
370
416
  };
371
- EvmBlockRewardService = __decorateClass([
417
+ EvmBlockRewardService = _ts_decorate5([
372
418
  creatable5()
373
419
  ], EvmBlockRewardService);
374
420
 
@@ -377,7 +423,17 @@ import { assertEx as assertEx4 } from "@xylabs/assert";
377
423
  import { creatable as creatable6 } from "@xylabs/creatable";
378
424
  import { toFixedPoint } from "@xylabs/decimal-precision";
379
425
  import { rewardFromBlockNumber } from "@xyo-network/chain-protocol";
426
+ function _ts_decorate6(decorators, target, key, desc) {
427
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
428
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
429
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
430
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
431
+ }
432
+ __name(_ts_decorate6, "_ts_decorate");
380
433
  var MemoryBlockRewardService = class extends BaseBlockRewardService {
434
+ static {
435
+ __name(this, "MemoryBlockRewardService");
436
+ }
381
437
  rewardFromBlockNumber = rewardFromBlockNumber(18);
382
438
  get creatorReward() {
383
439
  return assertEx4(this.params.creatorReward, () => "creatorReward is required");
@@ -409,18 +465,10 @@ var MemoryBlockRewardService = class extends BaseBlockRewardService {
409
465
  };
410
466
  }
411
467
  getRewardForBlock(blockNumber) {
412
- return this.rewardFromBlockNumber(
413
- blockNumber,
414
- this.initialReward,
415
- this.stepSize,
416
- this.stepFactorNumerator,
417
- this.stepFactorDenominator,
418
- this.minRewardPerBlock,
419
- this.creatorReward
420
- );
468
+ return this.rewardFromBlockNumber(blockNumber, this.initialReward, this.stepSize, this.stepFactorNumerator, this.stepFactorDenominator, this.minRewardPerBlock, this.creatorReward);
421
469
  }
422
470
  };
423
- MemoryBlockRewardService = __decorateClass([
471
+ MemoryBlockRewardService = _ts_decorate6([
424
472
  creatable6()
425
473
  ], MemoryBlockRewardService);
426
474
 
@@ -428,13 +476,15 @@ MemoryBlockRewardService = __decorateClass([
428
476
  import { assertEx as assertEx5 } from "@xylabs/assert";
429
477
  import { isDefined, isNull } from "@xylabs/typeof";
430
478
  import { PayloadBuilder as PayloadBuilder4 } from "@xyo-network/payload-builder";
431
- import {
432
- asBlockBoundWitness as asBlockBoundWitness2,
433
- isBlockBoundWitness
434
- } from "@xyo-network/xl1-protocol";
479
+ import { asBlockBoundWitness as asBlockBoundWitness2, isBlockBoundWitness } from "@xyo-network/xl1-protocol";
435
480
  import { LRUCache as LRUCache2 } from "lru-cache";
436
481
  var ChainBlockNumberIterationService = class extends BaseService {
437
- _blocksByBlockNumber = new LRUCache2({ max: 1e4 });
482
+ static {
483
+ __name(this, "ChainBlockNumberIterationService");
484
+ }
485
+ _blocksByBlockNumber = new LRUCache2({
486
+ max: 1e4
487
+ });
438
488
  get chainArchivist() {
439
489
  return assertEx5(this.params.chainArchivist);
440
490
  }
@@ -448,7 +498,9 @@ var ChainBlockNumberIterationService = class extends BaseService {
448
498
  if (cached) return cached;
449
499
  const startingBlock = head;
450
500
  const currentBlockHash = await PayloadBuilder4.hash(startingBlock);
451
- let currentBlock = (await this.chainArchivist.get([currentBlockHash])).at(0);
501
+ let currentBlock = (await this.chainArchivist.get([
502
+ currentBlockHash
503
+ ])).at(0);
452
504
  while (isDefined(currentBlock)) {
453
505
  assertEx5(asBlockBoundWitness2(currentBlock), () => `Expected hash to be a block bound witness [${currentBlock?._hash}]`);
454
506
  if (isBlockBoundWitness(currentBlock)) {
@@ -458,7 +510,9 @@ var ChainBlockNumberIterationService = class extends BaseService {
458
510
  }
459
511
  const { previous } = currentBlock;
460
512
  if (isNull(previous)) break;
461
- currentBlock = (await this.chainArchivist.get([previous])).at(0);
513
+ currentBlock = (await this.chainArchivist.get([
514
+ previous
515
+ ])).at(0);
462
516
  }
463
517
  }
464
518
  throw new Error(`Block not found: ${block}`);
@@ -481,7 +535,9 @@ var ChainBlockNumberIterationService = class extends BaseService {
481
535
  results.push(currentBlock);
482
536
  const { previous } = currentBlock;
483
537
  if (isNull(previous)) break;
484
- const nextBlock = await this.chainArchivist.get([previous]);
538
+ const nextBlock = await this.chainArchivist.get([
539
+ previous
540
+ ]);
485
541
  currentBlock = asBlockBoundWitness2(nextBlock[0]);
486
542
  } else {
487
543
  const hash = PayloadBuilder4.hash(currentBlock);
@@ -493,7 +549,11 @@ var ChainBlockNumberIterationService = class extends BaseService {
493
549
  async updateHead(head) {
494
550
  await Promise.resolve();
495
551
  this.params.head = head;
496
- void this.emit("headUpdated", { blocks: [head] });
552
+ void this.emit("headUpdated", {
553
+ blocks: [
554
+ head
555
+ ]
556
+ });
497
557
  }
498
558
  };
499
559
 
@@ -503,15 +563,15 @@ import { toAddress, toEthAddress as toEthAddress2 } from "@xylabs/hex";
503
563
  import { StakedXyoChain__factory as StakedXyoChainFactory } from "@xyo-network/typechain";
504
564
  import { getAddress } from "ethers/address";
505
565
  var EvmChainService = class extends BaseService {
566
+ static {
567
+ __name(this, "EvmChainService");
568
+ }
506
569
  get chainId() {
507
570
  return assertEx6(this.params.id);
508
571
  }
509
572
  get contract() {
510
573
  if (this.params.contract === void 0) {
511
- this.params.contract = StakedXyoChainFactory.connect(
512
- toEthAddress2(this.chainId),
513
- this.params.runner
514
- );
574
+ this.params.contract = StakedXyoChainFactory.connect(toEthAddress2(this.chainId), this.params.runner);
515
575
  }
516
576
  return assertEx6(this.params.contract);
517
577
  }
@@ -577,6 +637,9 @@ var EvmChainService = class extends BaseService {
577
637
  // src/ChainService/Memory/Memory.ts
578
638
  import { ZERO_ADDRESS } from "@xylabs/hex";
579
639
  var MemoryChainService = class extends BaseService {
640
+ static {
641
+ __name(this, "MemoryChainService");
642
+ }
580
643
  _simulatedStake = 1n;
581
644
  get chainId() {
582
645
  return ZERO_ADDRESS;
@@ -638,7 +701,17 @@ var MemoryChainService = class extends BaseService {
638
701
  // src/ChainValidator/XyoValidator.ts
639
702
  import { assertEx as assertEx7 } from "@xylabs/assert";
640
703
  import { creatable as creatable7 } from "@xylabs/creatable";
704
+ function _ts_decorate7(decorators, target, key, desc) {
705
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
706
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
707
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
708
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
709
+ }
710
+ __name(_ts_decorate7, "_ts_decorate");
641
711
  var XyoValidator = class extends BaseService {
712
+ static {
713
+ __name(this, "XyoValidator");
714
+ }
642
715
  get address() {
643
716
  return this.account.address;
644
717
  }
@@ -666,11 +739,13 @@ var XyoValidator = class extends BaseService {
666
739
  // TODO: Move to validator and inherit this class from validator
667
740
  async validatePendingTransaction(hydratedTransaction) {
668
741
  const [tx] = hydratedTransaction;
669
- if ((await this.chainArchivist.get([tx._hash])).length > 0) return false;
742
+ if ((await this.chainArchivist.get([
743
+ tx._hash
744
+ ])).length > 0) return false;
670
745
  return await Promise.resolve(true);
671
746
  }
672
747
  };
673
- XyoValidator = __decorateClass([
748
+ XyoValidator = _ts_decorate7([
674
749
  creatable7()
675
750
  ], XyoValidator);
676
751
 
@@ -679,7 +754,17 @@ import { assertEx as assertEx8 } from "@xylabs/assert";
679
754
  import { creatable as creatable8 } from "@xylabs/creatable";
680
755
  import { hexToLast4BytesInt, shuffleWithSeed } from "@xyo-network/chain-utils";
681
756
  import { PayloadBuilder as PayloadBuilder5 } from "@xyo-network/payload-builder";
757
+ function _ts_decorate8(decorators, target, key, desc) {
758
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
759
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
760
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
761
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
762
+ }
763
+ __name(_ts_decorate8, "_ts_decorate");
682
764
  var BaseElectionService = class extends BaseService {
765
+ static {
766
+ __name(this, "BaseElectionService");
767
+ }
683
768
  get chainIterator() {
684
769
  return assertEx8(this.params.chainIterator, () => "No chain iterator");
685
770
  }
@@ -704,7 +789,7 @@ var BaseElectionService = class extends BaseService {
704
789
  return creatorArray.slice(0, maxSize);
705
790
  }
706
791
  };
707
- BaseElectionService = __decorateClass([
792
+ BaseElectionService = _ts_decorate8([
708
793
  creatable8()
709
794
  ], BaseElectionService);
710
795
 
@@ -718,63 +803,92 @@ import { forget } from "@xylabs/forget";
718
803
  import { isDefined as isDefined2, isUndefined } from "@xylabs/typeof";
719
804
  import { MemoryArchivist } from "@xyo-network/archivist-memory";
720
805
  import { findMostRecentBlock } from "@xyo-network/chain-protocol";
721
- import {
722
- asBlockBoundWitnessWithHashStorageMeta,
723
- isTransactionBoundWitnessWithStorageMeta
724
- } from "@xyo-network/xl1-protocol";
806
+ import { asBlockBoundWitnessWithHashStorageMeta, isTransactionBoundWitnessWithStorageMeta } from "@xyo-network/xl1-protocol";
725
807
  import { TransactionJsonSchemaValidator, validateTransaction } from "@xyo-network/xl1-validation";
726
808
  import { Mutex as Mutex2 } from "async-mutex";
727
809
 
728
810
  // src/PendingTransactions/bundledPayloadToHydratedTransaction.ts
729
811
  import { PayloadBuilder as PayloadBuilder6 } from "@xyo-network/payload-builder";
730
812
  import { asTransactionBoundWitnessWithStorageMeta } from "@xyo-network/xl1-protocol";
731
- var bundledPayloadToHydratedTransaction = async (payload) => {
813
+ var bundledPayloadToHydratedTransaction = /* @__PURE__ */ __name(async (payload) => {
732
814
  const withStorageMeta = await PayloadBuilder6.addStorageMeta(payload.payloads);
733
815
  const tx = asTransactionBoundWitnessWithStorageMeta(withStorageMeta.find((p) => p._hash === payload.root));
734
816
  if (tx) {
735
- return [tx, withStorageMeta.filter((p) => p._hash !== payload.root)];
817
+ return [
818
+ tx,
819
+ withStorageMeta.filter((p) => p._hash !== payload.root)
820
+ ];
736
821
  }
737
- };
822
+ }, "bundledPayloadToHydratedTransaction");
738
823
 
739
824
  // src/PendingTransactions/hydratedTransactionToPayloadBundle.ts
740
825
  import { PayloadBuilder as PayloadBuilder7 } from "@xyo-network/payload-builder";
741
826
  import { PayloadBundleSchema } from "@xyo-network/payload-model";
742
827
  import { flattenHydratedTransaction } from "@xyo-network/xl1-protocol-sdk";
743
- var hydratedTransactionToPayloadBundle = (transaction) => {
828
+ var hydratedTransactionToPayloadBundle = /* @__PURE__ */ __name((transaction) => {
744
829
  const root = transaction[0]._hash;
745
830
  return bundle(root, transaction);
746
- };
747
- var bundle = (root, transaction) => {
831
+ }, "hydratedTransactionToPayloadBundle");
832
+ var bundle = /* @__PURE__ */ __name((root, transaction) => {
748
833
  const payloads = flattenHydratedTransaction(transaction).flatMap((p) => PayloadBuilder7.omitStorageMeta(p));
749
- return new PayloadBuilder7({ schema: PayloadBundleSchema }).fields({ payloads, root }).build();
750
- };
834
+ return new PayloadBuilder7({
835
+ schema: PayloadBundleSchema
836
+ }).fields({
837
+ payloads,
838
+ root
839
+ }).build();
840
+ }, "bundle");
751
841
 
752
842
  // src/PendingTransactions/BasePendingTransactions.ts
753
- var BasePendingTransactionsService = class extends BaseService {
843
+ function _ts_decorate9(decorators, target, key, desc) {
844
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
845
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
846
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
847
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
848
+ }
849
+ __name(_ts_decorate9, "_ts_decorate");
850
+ var BasePendingTransactionsService = class _BasePendingTransactionsService extends BaseService {
851
+ static {
852
+ __name(this, "BasePendingTransactionsService");
853
+ }
854
+ static MutexPriority = {
855
+ /**
856
+ * Priority for inserting new transactions
857
+ */
858
+ InsertNewTransactions: 5,
859
+ /**
860
+ * Priority for reading pending transactions
861
+ */
862
+ ReadTransactions: 3,
863
+ /**
864
+ * Priority for removing finalized/expired/rejected transactions
865
+ */
866
+ PurgeTransactions: 1
867
+ };
754
868
  /**
755
- * A mutex to ensure that the counting the number of pending transactions is
756
- * not called concurrently
757
- */
869
+ * A mutex to ensure that the counting the number of pending transactions is
870
+ * not called concurrently
871
+ */
758
872
  _countPendingTransactionsMutex = new Mutex2();
759
873
  /**
760
- * A local Archivist optimized for fast retrieval that stores only validated
761
- * pending transactions
762
- */
874
+ * A local Archivist optimized for fast retrieval that stores only validated
875
+ * pending transactions
876
+ */
763
877
  _curatedPendingBundledTransactionsArchivist;
764
878
  /**
765
- * The last count of total pending transactions
766
- */
879
+ * The last count of total pending transactions
880
+ */
767
881
  _pendingTransactionsCount = 0;
768
882
  /**
769
- * A set of transaction hashes that are pending removal from the
770
- * curated pending transactions archivist. This is used to track
771
- * which transactions need to be removed from the archivist.
772
- */
883
+ * A set of transaction hashes that are pending removal from the
884
+ * curated pending transactions archivist. This is used to track
885
+ * which transactions need to be removed from the archivist.
886
+ */
773
887
  _removablePendingTransactionHashes = /* @__PURE__ */ new Set();
774
888
  /**
775
- * A mutex to ensure that the curated pending transactions archivist is
776
- * updated in a thread-safe manner
777
- */
889
+ * A mutex to ensure that the curated pending transactions archivist is
890
+ * updated in a thread-safe manner
891
+ */
778
892
  _updateCuratedPendingTransactionsArchivistMutex = new Mutex2();
779
893
  get chainArchivist() {
780
894
  return assertEx9(this.params.chainArchivist, () => "No completed blocks with data archivist");
@@ -797,7 +911,9 @@ var BasePendingTransactionsService = class extends BaseService {
797
911
  }
798
912
  async createHandler() {
799
913
  await super.createHandler();
800
- this._curatedPendingBundledTransactionsArchivist = await MemoryArchivist.create({ account: "random" });
914
+ this._curatedPendingBundledTransactionsArchivist = await MemoryArchivist.create({
915
+ account: "random"
916
+ });
801
917
  this.pendingBundledTransactionsArchivist.on("inserted", ({ payloads }) => {
802
918
  forget(this.insertNewTransactions(payloads));
803
919
  });
@@ -809,14 +925,11 @@ var BasePendingTransactionsService = class extends BaseService {
809
925
  this.markAnyIncludedTransactionsForRemoval(payloads);
810
926
  forget(this.cleanupWorker());
811
927
  });
812
- const pendingTransactionsCounter = this.meter?.createObservableUpDownCounter(
813
- "xyo_pending_transactions_counter",
814
- {
815
- description: "The current number of pending transactions",
816
- valueType: ValueType.INT,
817
- unit: "1"
818
- }
819
- );
928
+ const pendingTransactionsCounter = this.meter?.createObservableUpDownCounter("xyo_pending_transactions_counter", {
929
+ description: "The current number of pending transactions",
930
+ valueType: ValueType.INT,
931
+ unit: "1"
932
+ });
820
933
  pendingTransactionsCounter?.addCallback((observer) => {
821
934
  observer.observe(this.pendingTransactionsCount);
822
935
  });
@@ -824,7 +937,9 @@ var BasePendingTransactionsService = class extends BaseService {
824
937
  async getPendingTransactions(head, limit) {
825
938
  return await this.spanAsync("getPendingTransactions", async () => {
826
939
  return await this._updateCuratedPendingTransactionsArchivistMutex.runExclusive(async () => {
827
- let [lastHead] = filterAs(await this.chainArchivist.get([head]), asBlockBoundWitnessWithHashStorageMeta);
940
+ let [lastHead] = filterAs(await this.chainArchivist.get([
941
+ head
942
+ ]), asBlockBoundWitnessWithHashStorageMeta);
828
943
  if (isUndefined(lastHead)) return [];
829
944
  await this.pruneCuratedPendingTransactionsArchivist(lastHead._hash);
830
945
  const foundPendingTransactions = [];
@@ -838,9 +953,7 @@ var BasePendingTransactionsService = class extends BaseService {
838
953
  if (pendingBundledTransactions.length === 0) break;
839
954
  cursor = pendingBundledTransactions.at(-1)?._sequence;
840
955
  const undeletedTransactionBundles = pendingBundledTransactions.filter((tx) => !this._removablePendingTransactionHashes.has(tx.root));
841
- const transactions = (await Promise.all(
842
- undeletedTransactionBundles.map((p) => bundledPayloadToHydratedTransaction(p))
843
- )).filter(exists3);
956
+ const transactions = (await Promise.all(undeletedTransactionBundles.map((p) => bundledPayloadToHydratedTransaction(p)))).filter(exists3);
844
957
  const activeTransactions = transactions.filter(isTransactionActive(lastHead.block + 1));
845
958
  foundPendingTransactions.push(...activeTransactions);
846
959
  }
@@ -851,14 +964,14 @@ var BasePendingTransactionsService = class extends BaseService {
851
964
  }
852
965
  }
853
966
  return foundPendingTransactions;
854
- }, BasePendingTransactionsService.MutexPriority.ReadTransactions);
967
+ }, _BasePendingTransactionsService.MutexPriority.ReadTransactions);
855
968
  });
856
969
  }
857
970
  async cleanupWorker() {
858
971
  return await this._updateCuratedPendingTransactionsArchivistMutex.runExclusive(async () => {
859
972
  const lastHead = await findMostRecentBlock(this.chainArchivist);
860
973
  if (isDefined2(lastHead)) await this.pruneCuratedPendingTransactionsArchivist(lastHead._hash);
861
- }, BasePendingTransactionsService.MutexPriority.PurgeTransactions);
974
+ }, _BasePendingTransactionsService.MutexPriority.PurgeTransactions);
862
975
  }
863
976
  async countPendingTransactions() {
864
977
  if (this._countPendingTransactionsMutex.isLocked()) return;
@@ -883,7 +996,9 @@ var BasePendingTransactionsService = class extends BaseService {
883
996
  return await bundledPayloadToHydratedTransaction(tx);
884
997
  }))).filter(exists3);
885
998
  const validTransactions = await filterAsync(hydratedUnprocessedTransactions, async (tx) => {
886
- const errors = await validateTransaction(tx, this.chainId, [TransactionJsonSchemaValidator]);
999
+ const errors = await validateTransaction(tx, this.chainId, [
1000
+ TransactionJsonSchemaValidator
1001
+ ]);
887
1002
  if (errors.length > 0) {
888
1003
  this.logger?.warn("validateTransaction", errors);
889
1004
  }
@@ -893,15 +1008,15 @@ var BasePendingTransactionsService = class extends BaseService {
893
1008
  const bundledTransactions = validTransactions.map((tx) => hydratedTransactionToPayloadBundle(tx));
894
1009
  await this.pendingBundledTransactionsLocalArchivist.insert(bundledTransactions);
895
1010
  }
896
- }, BasePendingTransactionsService.MutexPriority.InsertNewTransactions);
1011
+ }, _BasePendingTransactionsService.MutexPriority.InsertNewTransactions);
897
1012
  });
898
1013
  }
899
1014
  /**
900
- * Marks any included transactions in the provided payloads for removal preventing them
901
- * from being included in the curated pending transactions archivist and from being offered
902
- * during the next retrieval of pending transactions.
903
- * @param payloads An array of payloads that may contain transactions.
904
- */
1015
+ * Marks any included transactions in the provided payloads for removal preventing them
1016
+ * from being included in the curated pending transactions archivist and from being offered
1017
+ * during the next retrieval of pending transactions.
1018
+ * @param payloads An array of payloads that may contain transactions.
1019
+ */
905
1020
  markAnyIncludedTransactionsForRemoval(payloads) {
906
1021
  const hashes = payloads.filter(isTransactionBoundWitnessWithStorageMeta).map((p) => p._hash);
907
1022
  for (const hash of hashes) {
@@ -912,7 +1027,9 @@ var BasePendingTransactionsService = class extends BaseService {
912
1027
  return await this.spanAsync("pruneCuratedPendingTransactionsArchivist", async () => {
913
1028
  const foundPendingTransactionsToDeleteHashes = [];
914
1029
  let cursor;
915
- let [lastHead] = filterAs(await this.chainArchivist.get([head]), asBlockBoundWitnessWithHashStorageMeta);
1030
+ let [lastHead] = filterAs(await this.chainArchivist.get([
1031
+ head
1032
+ ]), asBlockBoundWitnessWithHashStorageMeta);
916
1033
  while (isDefined2(lastHead)) {
917
1034
  const pendingBundledTransactions = await this.pendingBundledTransactionsLocalArchivist.next({
918
1035
  limit: 100,
@@ -924,13 +1041,9 @@ var BasePendingTransactionsService = class extends BaseService {
924
1041
  }
925
1042
  cursor = pendingBundledTransactions.at(-1)?._sequence;
926
1043
  const deletedTransactionBundles = pendingBundledTransactions.filter((tx) => this._removablePendingTransactionHashes.has(tx.root));
927
- foundPendingTransactionsToDeleteHashes.push(
928
- ...deletedTransactionBundles.map((tx) => tx._hash).filter(exists3)
929
- );
1044
+ foundPendingTransactionsToDeleteHashes.push(...deletedTransactionBundles.map((tx) => tx._hash).filter(exists3));
930
1045
  const undeletedTransactionBundles = pendingBundledTransactions.filter((tx) => !this._removablePendingTransactionHashes.has(tx.root));
931
- const transactions = (await Promise.all(
932
- undeletedTransactionBundles.map((p) => bundledPayloadToHydratedTransaction(p))
933
- )).filter(exists3);
1046
+ const transactions = (await Promise.all(undeletedTransactionBundles.map((p) => bundledPayloadToHydratedTransaction(p)))).filter(exists3);
934
1047
  const expiredTransactions = transactions.filter(isTransactionExpired(lastHead.block + 1));
935
1048
  const expiredBundleHashes = expiredTransactions.map((expiredHydratedTx) => (
936
1049
  // Find the corresponding payload bundle hash for the expired transaction
@@ -951,25 +1064,11 @@ var BasePendingTransactionsService = class extends BaseService {
951
1064
  });
952
1065
  }
953
1066
  };
954
- __publicField(BasePendingTransactionsService, "MutexPriority", {
955
- /**
956
- * Priority for inserting new transactions
957
- */
958
- InsertNewTransactions: 5,
959
- /**
960
- * Priority for reading pending transactions
961
- */
962
- ReadTransactions: 3,
963
- /**
964
- * Priority for removing finalized/expired/rejected transactions
965
- */
966
- PurgeTransactions: 1
967
- });
968
- BasePendingTransactionsService = __decorateClass([
1067
+ BasePendingTransactionsService = _ts_decorate9([
969
1068
  creatable9()
970
1069
  ], BasePendingTransactionsService);
971
- var isTransactionExpired = (block) => ([txBw]) => txBw.exp < block;
972
- var isTransactionActive = (block) => ([txBw]) => txBw.nbf <= block && txBw.exp >= block;
1070
+ var isTransactionExpired = /* @__PURE__ */ __name((block) => ([txBw]) => txBw.exp < block, "isTransactionExpired");
1071
+ var isTransactionActive = /* @__PURE__ */ __name((block) => ([txBw]) => txBw.nbf <= block && txBw.exp >= block, "isTransactionActive");
973
1072
 
974
1073
  // src/StakeIntent/lib/getBlockSignedStakeDeclarations.ts
975
1074
  import { filterAs as filterAs2 } from "@xylabs/array";
@@ -978,7 +1077,7 @@ import { asOptionalBoundWitness } from "@xyo-network/boundwitness-model";
978
1077
  import { payloadSchemasContains } from "@xyo-network/boundwitness-validator";
979
1078
  import { BoundWitnessWrapper } from "@xyo-network/boundwitness-wrapper";
980
1079
  import { asChainStakeIntent, ChainStakeIntentSchema } from "@xyo-network/xl1-protocol";
981
- var getBlockSignedStakeDeclarations = async (block, archivist, intent) => {
1080
+ var getBlockSignedStakeDeclarations = /* @__PURE__ */ __name(async (block, archivist, intent) => {
982
1081
  const blockData = await archivist.get(block.payload_hashes);
983
1082
  const bwsFromBlock = filterAs2(blockData, asOptionalBoundWitness);
984
1083
  const bwsFromBlockWithDeclarations = bwsFromBlock.filter((bw) => payloadSchemasContains(bw, ChainStakeIntentSchema));
@@ -989,48 +1088,41 @@ var getBlockSignedStakeDeclarations = async (block, archivist, intent) => {
989
1088
  const stakeIntents = filterAs2(payloads, asChainStakeIntent).filter((p) => p.intent === intent).filter((p) => bw.addresses.includes(p.from));
990
1089
  return stakeIntents;
991
1090
  }))).flat();
992
- };
993
- var filterToValidSignedBoundWitnesses = async (bws) => {
1091
+ }, "getBlockSignedStakeDeclarations");
1092
+ var filterToValidSignedBoundWitnesses = /* @__PURE__ */ __name(async (bws) => {
994
1093
  const validBwIndexes = await Promise.all(bws.map((bw) => BoundWitnessWrapper.parse(bw).getValid()));
995
1094
  return bws.filter((_, index) => validBwIndexes[index]);
996
- };
997
- var mapBoundWitnessToStakeIntentHashes = (bw) => {
1095
+ }, "filterToValidSignedBoundWitnesses");
1096
+ var mapBoundWitnessToStakeIntentHashes = /* @__PURE__ */ __name((bw) => {
998
1097
  return bw.payload_schemas.map((schema, index) => schema === ChainStakeIntentSchema ? bw.payload_hashes[index] : void 0);
999
- };
1098
+ }, "mapBoundWitnessToStakeIntentHashes");
1000
1099
 
1001
1100
  // src/StakeIntent/XyoStakeIntentService.ts
1002
1101
  import { filterAs as filterAs3 } from "@xylabs/array";
1003
1102
  import { assertEx as assertEx10 } from "@xylabs/assert";
1004
1103
  import { creatable as creatable10 } from "@xylabs/creatable";
1005
- import {
1006
- asAddress
1007
- } from "@xylabs/hex";
1104
+ import { asAddress } from "@xylabs/hex";
1008
1105
  import { isUndefined as isUndefined2 } from "@xylabs/typeof";
1009
- import {
1010
- analyzeChain,
1011
- ChainStakeIntentAnalyzer,
1012
- isChainSummaryStakeIntent
1013
- } from "@xyo-network/chain-analyze";
1014
- import {
1015
- DEFAULT_FIND_FIRST_MATCHING_NEXT_OPTIONS,
1016
- findFirstMatching,
1017
- IntervalMap
1018
- } from "@xyo-network/chain-utils";
1106
+ import { analyzeChain, ChainStakeIntentAnalyzer, isChainSummaryStakeIntent } from "@xyo-network/chain-analyze";
1107
+ import { DEFAULT_FIND_FIRST_MATCHING_NEXT_OPTIONS, findFirstMatching, IntervalMap } from "@xyo-network/chain-utils";
1019
1108
  import { PayloadBuilder as PayloadBuilder8 } from "@xyo-network/payload-builder";
1020
- import {
1021
- asBlockBoundWitness as asBlockBoundWitness3,
1022
- asBlockBoundWitnessWithStorageMeta,
1023
- asChainIndexingServiceStateWithStorageMeta,
1024
- asChainStakeIntent as asChainStakeIntent2,
1025
- ChainIndexingServiceStateSchema,
1026
- isChainIndexingServiceState
1027
- } from "@xyo-network/xl1-protocol";
1109
+ import { asBlockBoundWitness as asBlockBoundWitness3, asBlockBoundWitnessWithStorageMeta, asChainIndexingServiceStateWithStorageMeta, asChainStakeIntent as asChainStakeIntent2, ChainIndexingServiceStateSchema, isChainIndexingServiceState } from "@xyo-network/xl1-protocol";
1028
1110
  import { Mutex as Mutex3 } from "async-mutex";
1029
1111
  import { LRUCache as LRUCache3 } from "lru-cache";
1112
+ function _ts_decorate10(decorators, target, key, desc) {
1113
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1114
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1115
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1116
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1117
+ }
1118
+ __name(_ts_decorate10, "_ts_decorate");
1030
1119
  var ACTIVE_STAKE_TTL = 1e3 * 60 * 60 * 2;
1031
1120
  var NO_ACTIVE_STAKE_TTL = 1e3 * 2;
1032
1121
  var STAKE_CACHE_MAX_ENTRIES = 1e4;
1033
1122
  var XyoStakeIntentService = class extends BaseService {
1123
+ static {
1124
+ __name(this, "XyoStakeIntentService");
1125
+ }
1034
1126
  // TODO: Use hash instead of block number to handle chain reorgs
1035
1127
  _lastIndexedBlockHash = void 0;
1036
1128
  // TODO: Interval tree per declaration (bank, validator, etc.)
@@ -1041,7 +1133,9 @@ var XyoStakeIntentService = class extends BaseService {
1041
1133
  // in performance for small sets, and (most importantly) easily
1042
1134
  // persisted so we can recover state on restart.
1043
1135
  _producers = new IntervalMap();
1044
- _stakeCache = new LRUCache3({ max: STAKE_CACHE_MAX_ENTRIES });
1136
+ _stakeCache = new LRUCache3({
1137
+ max: STAKE_CACHE_MAX_ENTRIES
1138
+ });
1045
1139
  _updateMutex = new Mutex3();
1046
1140
  get chainArchivist() {
1047
1141
  return assertEx10(this.params.chainArchivist, () => "chainArchivist not set");
@@ -1074,7 +1168,9 @@ var XyoStakeIntentService = class extends BaseService {
1074
1168
  return await this.spanAsync("getDeclaredCandidatesForBlock", async () => {
1075
1169
  assertEx10(intent === "producer", () => `Error: Support not yet added for intent ${intent}`);
1076
1170
  const results = this._producers.findAllContaining(block);
1077
- const candidates = [...results];
1171
+ const candidates = [
1172
+ ...results
1173
+ ];
1078
1174
  const requiredMinimumStake = this.getRequiredMinimumStakeForIntent(intent);
1079
1175
  const validCandidates = await this.filterToValidStake(candidates, this.chainStakeViewer, requiredMinimumStake);
1080
1176
  return validCandidates;
@@ -1096,41 +1192,62 @@ var XyoStakeIntentService = class extends BaseService {
1096
1192
  await this.updateIndex(true);
1097
1193
  }
1098
1194
  async filterToValidStake(candidates, chainStakeViewer, requiredMinimumStake) {
1099
- const candidatesWithStake = await Promise.all(
1100
- candidates.map(async (candidate) => {
1101
- const stake = this._stakeCache.get(candidate);
1102
- if (stake === void 0) {
1103
- const activeStake = await chainStakeViewer.activeByAddressStaked(`${candidate}`);
1104
- if (activeStake > 0n) {
1105
- this._stakeCache.set(candidate, activeStake, { ttl: ACTIVE_STAKE_TTL });
1106
- } else {
1107
- this._stakeCache.set(candidate, activeStake, { ttl: NO_ACTIVE_STAKE_TTL });
1108
- }
1109
- return { candidate, stake: activeStake };
1195
+ const candidatesWithStake = await Promise.all(candidates.map(async (candidate) => {
1196
+ const stake = this._stakeCache.get(candidate);
1197
+ if (stake === void 0) {
1198
+ const activeStake = await chainStakeViewer.activeByAddressStaked(`${candidate}`);
1199
+ if (activeStake > 0n) {
1200
+ this._stakeCache.set(candidate, activeStake, {
1201
+ ttl: ACTIVE_STAKE_TTL
1202
+ });
1110
1203
  } else {
1111
- return { candidate, stake };
1204
+ this._stakeCache.set(candidate, activeStake, {
1205
+ ttl: NO_ACTIVE_STAKE_TTL
1206
+ });
1112
1207
  }
1113
- })
1114
- );
1208
+ return {
1209
+ candidate,
1210
+ stake: activeStake
1211
+ };
1212
+ } else {
1213
+ return {
1214
+ candidate,
1215
+ stake
1216
+ };
1217
+ }
1218
+ }));
1115
1219
  return candidatesWithStake.filter(({ stake }) => stake >= requiredMinimumStake).map(({ candidate }) => candidate);
1116
1220
  }
1117
1221
  async persistState(current) {
1118
1222
  const state = this._producers.serialize();
1119
- const payload = new PayloadBuilder8({ schema: ChainIndexingServiceStateSchema }).fields({ endBlockHash: current, state }).build();
1120
- await this.stakeIntentStateArchivist.insert([payload]);
1223
+ const payload = new PayloadBuilder8({
1224
+ schema: ChainIndexingServiceStateSchema
1225
+ }).fields({
1226
+ endBlockHash: current,
1227
+ state
1228
+ }).build();
1229
+ await this.stakeIntentStateArchivist.insert([
1230
+ payload
1231
+ ]);
1121
1232
  }
1122
1233
  async recoverState(current) {
1123
- const currentBlock = assertEx10(asBlockBoundWitness3((await this.chainArchivist.get([current]))?.[0]), () => `Block ${current} not found`);
1234
+ const currentBlock = assertEx10(asBlockBoundWitness3((await this.chainArchivist.get([
1235
+ current
1236
+ ]))?.[0]), () => `Block ${current} not found`);
1124
1237
  const currentBlockNum = currentBlock.block;
1125
- const opts = { ...DEFAULT_FIND_FIRST_MATCHING_NEXT_OPTIONS };
1238
+ const opts = {
1239
+ ...DEFAULT_FIND_FIRST_MATCHING_NEXT_OPTIONS
1240
+ };
1126
1241
  while (true) {
1127
- const predicate = (p) => {
1242
+ const predicate = /* @__PURE__ */ __name((p) => {
1128
1243
  const state2 = asChainIndexingServiceStateWithStorageMeta(p);
1129
1244
  return state2 ? true : false;
1130
- };
1245
+ }, "predicate");
1131
1246
  const state = await findFirstMatching(this.stakeIntentStateArchivist, predicate, opts);
1132
1247
  if (isChainIndexingServiceState(state)) {
1133
- const indexed = (await this.chainArchivist.get([state.endBlockHash]))?.[0];
1248
+ const indexed = (await this.chainArchivist.get([
1249
+ state.endBlockHash
1250
+ ]))?.[0];
1134
1251
  const indexedBlock = asBlockBoundWitnessWithStorageMeta(indexed);
1135
1252
  if (indexedBlock) {
1136
1253
  const indexedBlockNum = indexedBlock.block;
@@ -1156,7 +1273,9 @@ var XyoStakeIntentService = class extends BaseService {
1156
1273
  const currentHead = await this.chainIterator.head();
1157
1274
  if (isUndefined2(currentHead)) return;
1158
1275
  const currentHeadHash = await PayloadBuilder8.hash(currentHead);
1159
- const result = await analyzeChain(this.chainArchivist, [new ChainStakeIntentAnalyzer("producer")], currentHeadHash, this._lastIndexedBlockHash);
1276
+ const result = await analyzeChain(this.chainArchivist, [
1277
+ new ChainStakeIntentAnalyzer("producer")
1278
+ ], currentHeadHash, this._lastIndexedBlockHash);
1160
1279
  const signedDeclarations = filterAs3(result.find(isChainSummaryStakeIntent)?.intents ?? [], asChainStakeIntent2);
1161
1280
  if (currentHead.block === void 0) return;
1162
1281
  const currentHeadBlockNum = currentHead.block;
@@ -1175,7 +1294,7 @@ var XyoStakeIntentService = class extends BaseService {
1175
1294
  });
1176
1295
  }
1177
1296
  };
1178
- XyoStakeIntentService = __decorateClass([
1297
+ XyoStakeIntentService = _ts_decorate10([
1179
1298
  creatable10()
1180
1299
  ], XyoStakeIntentService);
1181
1300
  export {