@xyo-network/xl1-protocol-sdk 1.16.13 → 1.16.15

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.
@@ -111,10 +111,10 @@ var tryHydrateBlock = /* @__PURE__ */ __name(async (archivist, hash, maxDepth =
111
111
  // src/block/primitives/blockFromBlockNumber.ts
112
112
  import { asHash } from "@xylabs/sdk-js";
113
113
  import { toSafeJsonString } from "@xylabs/sdk-js";
114
- import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta2, StepSizes } from "@xyo-network/xl1-protocol";
114
+ import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta3, StepSizes as StepSizes5 } from "@xyo-network/xl1-protocol";
115
115
 
116
116
  // src/model/ChainContext/ChainContext.ts
117
- import { isDefined as isDefined2, isUndefined } from "@xylabs/sdk-js";
117
+ import { isDefined as isDefined5, isUndefined } from "@xylabs/sdk-js";
118
118
 
119
119
  // src/driver/cache/LruCacheMap.ts
120
120
  import { LRUCache } from "lru-cache";
@@ -202,168 +202,97 @@ var MemoryMap = class {
202
202
  }
203
203
  };
204
204
 
205
- // src/model/ChainContext/ChainContext.ts
206
- function contextCache(context, name, create) {
207
- if (!context.caches) {
208
- context.caches = {};
209
- }
210
- if (isUndefined(context.caches[name])) {
211
- context.caches[name] = create?.() ?? new MemoryMap();
205
+ // src/primitives/readPayloadMapFromStore.ts
206
+ import { isDefined as isDefined2 } from "@xylabs/sdk-js";
207
+ function readPayloadMapFromStore(store) {
208
+ if (isReadArchivist(store)) {
209
+ return {
210
+ get: /* @__PURE__ */ __name(async (hash) => {
211
+ return (await store.get([
212
+ hash
213
+ ]))[0];
214
+ }, "get"),
215
+ getMany: /* @__PURE__ */ __name(async (hashes) => {
216
+ return await store.get(hashes);
217
+ }, "getMany"),
218
+ has: /* @__PURE__ */ __name(async (hash) => {
219
+ return isDefined2((await store.get([
220
+ hash
221
+ ]))[0]);
222
+ }, "has")
223
+ };
212
224
  }
213
- return context.caches[name];
225
+ return store;
214
226
  }
215
- __name(contextCache, "contextCache");
216
- async function withContextCacheResponse(context, name, key, func, options) {
217
- const cache = contextCache(context, name, () => new LruCacheMap({
218
- max: options?.max ?? 1e4
219
- }));
220
- const cacheResult = await cache.get(key);
221
- if (isDefined2(cacheResult)) {
222
- return cacheResult;
223
- }
224
- const result = await func();
225
- await cache.set(key, result);
226
- return result;
227
+ __name(readPayloadMapFromStore, "readPayloadMapFromStore");
228
+
229
+ // src/primitives/step/completedStepRewardAddress.ts
230
+ import { toAddress } from "@xylabs/sdk-js";
231
+ import { StepSizes } from "@xyo-network/xl1-protocol";
232
+ import { keccak256 } from "ethers";
233
+ function completedStepRewardAddress({ block, step }) {
234
+ const resolvedStepSize = step < StepSizes.length ? StepSizes[step] : step;
235
+ const addressKey = new TextEncoder().encode(`${block}|${resolvedStepSize}`);
236
+ return toAddress(keccak256(addressKey).slice(-40), {
237
+ prefix: false
238
+ });
227
239
  }
228
- __name(withContextCacheResponse, "withContextCacheResponse");
240
+ __name(completedStepRewardAddress, "completedStepRewardAddress");
229
241
 
230
- // src/block/primitives/blockFromBlockNumber.ts
231
- async function blockFromBlockNumber(context, blockNumber) {
232
- const cacheKey = `${blockNumber}`;
233
- return await withContextCacheResponse(context, "blockFromBlockNumber", cacheKey, async () => {
234
- const [headHash] = await context.head();
235
- const result = await context.store.chainMap.get(headHash);
236
- let currentBlock = asBlockBoundWitnessWithStorageMeta2(result, () => `Head block not found for hash: ${headHash}`, {
237
- required: true
238
- });
239
- if (currentBlock.block < blockNumber) {
240
- throw new Error(`Block number ${blockNumber} is greater than head ${currentBlock.block}.`);
241
- }
242
- while (currentBlock.block > blockNumber) {
243
- let jumpHash = currentBlock.previous;
244
- let jumpBlockNumber = currentBlock.block - 1;
245
- for (const [step, stepSize2] of StepSizes.entries()) {
246
- const possibleJumpBlockNumber = currentBlock.block - currentBlock.block % stepSize2 - 1;
247
- if (possibleJumpBlockNumber >= blockNumber && possibleJumpBlockNumber <= jumpBlockNumber) {
248
- jumpBlockNumber = possibleJumpBlockNumber;
249
- jumpHash = asHash(currentBlock.step_hashes.at(step), () => `Step hash not found for step ${step} in block ${currentBlock.block}`);
250
- }
251
- }
252
- const newBlock = await context.store.chainMap.get(asHash(jumpHash, () => `Jump hash not found for block number [${blockNumber}]: ${jumpBlockNumber} ${toSafeJsonString(currentBlock, 10)}`));
253
- currentBlock = asBlockBoundWitnessWithStorageMeta2(newBlock, () => `Block not found for hash: ${jumpHash}`, {
254
- required: true
255
- });
256
- if (currentBlock.block === blockNumber) {
257
- break;
258
- }
259
- if (currentBlock.block < blockNumber) {
260
- throw new Error(`Block number ${blockNumber} is not a valid step block number for block ${headHash}.`);
261
- }
262
- }
263
- return currentBlock;
242
+ // src/primitives/step/derivedReceiveAddress.ts
243
+ import { toAddress as toAddress2 } from "@xylabs/sdk-js";
244
+ import { isDefined as isDefined3 } from "@xylabs/sdk-js";
245
+ import { keccak256 as keccak2562 } from "ethers";
246
+ function derivedReceiveAddress(address, scope) {
247
+ const addressKey = new TextEncoder().encode(isDefined3(scope) ? `${scope}|${address}` : address);
248
+ return toAddress2(keccak2562(addressKey).slice(-40), {
249
+ prefix: false
264
250
  });
265
251
  }
266
- __name(blockFromBlockNumber, "blockFromBlockNumber");
252
+ __name(derivedReceiveAddress, "derivedReceiveAddress");
267
253
 
268
- // src/block/primitives/frames/calculateFramesFromRange.ts
269
- import { asXL1BlockNumber, stepSize } from "@xyo-network/xl1-protocol";
270
- function calculateFramesFromRange(range, step) {
271
- const size = stepSize(step);
272
- let start = Math.trunc(range[0] / size) * size;
273
- const fitted = [];
274
- const remaining = [];
275
- if (start !== range[0]) {
276
- start += size;
277
- remaining.push([
278
- range[0],
279
- asXL1BlockNumber(Math.min(start - 1, range[1]), true)
280
- ]);
281
- }
282
- for (let i = start; i <= range[1]; i += size) {
283
- if (i + size - 1 <= range[1]) {
284
- fitted.push([
285
- asXL1BlockNumber(i, {
286
- name: "calculateFramesFromRange A"
287
- }),
288
- asXL1BlockNumber(Math.min(i + size - 1, range[1]), {
289
- name: "calculateFramesFromRange B"
290
- })
291
- ]);
292
- } else {
293
- remaining.push([
294
- asXL1BlockNumber(i, {
295
- name: "calculateFramesFromRange C"
296
- }),
297
- range[1]
298
- ]);
299
- }
300
- }
301
- return [
302
- fitted,
303
- remaining
304
- ];
254
+ // src/primitives/step/stepBlockRange.ts
255
+ import { asXL1BlockRange, StepSizes as StepSizes2 } from "@xyo-network/xl1-protocol";
256
+ function stepBlockRange({ block, step }) {
257
+ const stepSize2 = StepSizes2[step];
258
+ const start = block - stepSize2;
259
+ return asXL1BlockRange([
260
+ start,
261
+ start + stepSize2 - 1
262
+ ], {
263
+ name: "stepBlockRange"
264
+ });
305
265
  }
306
- __name(calculateFramesFromRange, "calculateFramesFromRange");
266
+ __name(stepBlockRange, "stepBlockRange");
307
267
 
308
- // src/block/primitives/frames/deepCalculateFramesFromRange.ts
309
- import { StepSizes as StepSizes2 } from "@xyo-network/xl1-protocol";
310
- function deepCalculateFramesFromRange(range, startingStep = StepSizes2.length - 1) {
311
- const fitted = [];
312
- let remaining = [
313
- range
314
- ];
315
- for (let step = startingStep; step >= 0; step--) {
316
- const newRemaining = [];
317
- for (const range2 of remaining) {
318
- const [newFittedFrames, newRemainingFrames] = calculateFramesFromRange(range2, step);
319
- fitted.push(...newFittedFrames);
320
- newRemaining.push(...newRemainingFrames);
321
- }
322
- remaining = newRemaining;
323
- }
324
- for (const range2 of remaining) {
325
- for (let i = range2[0]; i <= range2[1]; i++) {
326
- fitted.push([
327
- i,
328
- i
329
- ]);
268
+ // src/primitives/step/stepTransferIndex.ts
269
+ import { assertEx as assertEx4 } from "@xylabs/sdk-js";
270
+ import { StepSizes as StepSizes3 } from "@xyo-network/xl1-protocol";
271
+ function stepTransferIndex(block, step) {
272
+ let rewardTransferCount = 0;
273
+ let rewardTransferIndex = -1;
274
+ for (let i = 3; i < StepSizes3.length; i++) {
275
+ const stepSize2 = StepSizes3[i];
276
+ if (block % stepSize2 === 0) {
277
+ if (stepSize2 === StepSizes3[step]) {
278
+ rewardTransferIndex = rewardTransferCount;
279
+ }
280
+ rewardTransferCount++;
330
281
  }
331
282
  }
332
- return fitted.toSorted((a, b) => a[0] - b[0]);
333
- }
334
- __name(deepCalculateFramesFromRange, "deepCalculateFramesFromRange");
335
-
336
- // src/block/primitives/hashFromBlockNumber.ts
337
- async function hashFromBlockNumber(context, blockNumber) {
338
- return (await blockFromBlockNumber(context, blockNumber))._hash;
339
- }
340
- __name(hashFromBlockNumber, "hashFromBlockNumber");
341
-
342
- // src/block/primitives/model.ts
343
- function isReadArchivist(value) {
344
- return value.get !== void 0 && value.next !== void 0;
345
- }
346
- __name(isReadArchivist, "isReadArchivist");
347
- function isWriteArchivist(value) {
348
- return value.insert !== void 0;
349
- }
350
- __name(isWriteArchivist, "isWriteArchivist");
351
- function isReadWriteArchivist(value) {
352
- return isReadArchivist(value) && isWriteArchivist(value);
353
- }
354
- __name(isReadWriteArchivist, "isReadWriteArchivist");
355
-
356
- // src/block/primitives/toStepIdentityString.ts
357
- function toStepIdentityString({ block, step }) {
358
- return `${block}|${step}`;
283
+ assertEx4(rewardTransferIndex >= 0, () => `Could not find step size for step ${step} at block ${block}`);
284
+ return [
285
+ rewardTransferIndex,
286
+ rewardTransferCount
287
+ ];
359
288
  }
360
- __name(toStepIdentityString, "toStepIdentityString");
289
+ __name(stepTransferIndex, "stepTransferIndex");
361
290
 
362
- // src/block/primitives/transfers/transfersStepSummaryFromRange.ts
363
- import { assertEx as assertEx4 } from "@xylabs/sdk-js";
291
+ // src/primitives/summary/balances/balancesStepSummaryFromRange.ts
292
+ import { assertEx as assertEx5 } from "@xylabs/sdk-js";
364
293
  import { PayloadBuilder } from "@xyo-network/payload-builder";
365
294
  import { isAnyPayload } from "@xyo-network/payload-model";
366
- import { StepSizes as StepSizes3 } from "@xyo-network/xl1-protocol";
295
+ import { StepSizes as StepSizes4 } from "@xyo-network/xl1-protocol";
367
296
 
368
297
  // src/payloads/AddressPairPayload.ts
369
298
  import { AsObjectFactory } from "@xylabs/sdk-js";
@@ -374,7 +303,7 @@ var asAddressPairPayload = AsObjectFactory.create(isAddressPairPayload);
374
303
  var asOptionalAddressPairPayload = AsObjectFactory.createOptional(isAddressPairPayload);
375
304
 
376
305
  // src/payloads/netBalancesForPayloads.ts
377
- import { hexToBigInt, toAddress } from "@xylabs/sdk-js";
306
+ import { hexToBigInt, toAddress as toAddress3 } from "@xylabs/sdk-js";
378
307
  import { span } from "@xylabs/telemetry";
379
308
  import { isTransfer } from "@xyo-network/xl1-protocol";
380
309
  var netBalancesForPayloads = /* @__PURE__ */ __name((payloads) => {
@@ -384,8 +313,8 @@ var netBalancesForPayloads = /* @__PURE__ */ __name((payloads) => {
384
313
  if (isTransfer(payload)) {
385
314
  const { from } = payload;
386
315
  for (let [address, amount] of Object.entries(payload.transfers)) {
387
- balances[toAddress(address)] = (balances[toAddress(address)] ?? 0n) + hexToBigInt(amount);
388
- balances[toAddress(from)] = (balances[toAddress(from)] ?? 0n) - hexToBigInt(amount);
316
+ balances[toAddress3(address)] = (balances[toAddress3(address)] ?? 0n) + hexToBigInt(amount);
317
+ balances[toAddress3(from)] = (balances[toAddress3(from)] ?? 0n) - hexToBigInt(amount);
389
318
  }
390
319
  }
391
320
  }
@@ -477,27 +406,313 @@ var toPositiveBigInt = /* @__PURE__ */ __name((value) => {
477
406
  positive: value.positive
478
407
  };
479
408
  }
480
- if (typeof value === "bigint") {
481
- return {
482
- positive: toHex(value)
483
- };
409
+ if (typeof value === "bigint") {
410
+ return {
411
+ positive: toHex(value)
412
+ };
413
+ }
414
+ throw new Error("Invalid value for positive big int");
415
+ }, "toPositiveBigInt");
416
+
417
+ // src/primitives/summary/balances/balancesStepSummaryFromRange.ts
418
+ async function balancesStepSummaryFromRange(context, range) {
419
+ const frameHeadHash = await hashFromBlockNumber(context, range[1]);
420
+ const frameSize = range[1] - range[0] + 1;
421
+ const [headHash] = await context.head();
422
+ let result = void 0;
423
+ if (frameSize === 1) {
424
+ const hash = await hashFromBlockNumber(context, range[0]);
425
+ const [, payloads] = await hydrateBlock(context.store, hash);
426
+ const balances = {};
427
+ for (const [address, balance] of Object.entries(netBalancesForPayloads(payloads))) {
428
+ balances[address] = toSignedBigInt(balance);
429
+ }
430
+ result = {
431
+ schema: BalancesStepSummarySchema,
432
+ hash: headHash,
433
+ stepSize: -1,
434
+ balances
435
+ };
436
+ } else {
437
+ const step = StepSizes4.indexOf(frameSize);
438
+ assertEx5(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes4.join(", ")}`);
439
+ const summaryResult = await context.summaryMap.get(`${frameHeadHash}|${frameSize}`);
440
+ if (isAnyPayload(summaryResult)) {
441
+ result = summaryResult;
442
+ } else {
443
+ await context.stepSemaphores[step].acquire();
444
+ try {
445
+ const subRanges = deepCalculateFramesFromRange(range, step - 1);
446
+ const promises = subRanges.map((subRange) => balancesStepSummaryFromRange(context, subRange));
447
+ const subResults = await Promise.all(promises);
448
+ const bigIntBalances = {};
449
+ for (const subResult of subResults) {
450
+ for (const [address, balance] of Object.entries(subResult.balances)) {
451
+ bigIntBalances[address] = (bigIntBalances[address] ?? 0n) + parseSignedBigInt(balance);
452
+ }
453
+ }
454
+ const balances = {};
455
+ for (const [address, balance] of Object.entries(bigIntBalances)) {
456
+ balances[address] = toSignedBigInt(balance);
457
+ }
458
+ result = {
459
+ schema: BalancesStepSummarySchema,
460
+ hash: frameHeadHash,
461
+ stepSize: frameSize,
462
+ balances
463
+ };
464
+ await context.summaryMap.set(`${frameHeadHash}|${frameSize}`, result);
465
+ } finally {
466
+ context.stepSemaphores[step].release();
467
+ }
468
+ }
469
+ }
470
+ const finalResult = await PayloadBuilder.addStorageMeta(result);
471
+ return finalResult;
472
+ }
473
+ __name(balancesStepSummaryFromRange, "balancesStepSummaryFromRange");
474
+
475
+ // src/primitives/summary/balances/balancesSummary.ts
476
+ import { asAddress, isDefined as isDefined4 } from "@xylabs/sdk-js";
477
+ import { spanRootAsync } from "@xylabs/telemetry";
478
+ import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta2, asXL1BlockNumber, asXL1BlockRange as asXL1BlockRange2 } from "@xyo-network/xl1-protocol";
479
+ async function balancesSummary(context) {
480
+ return await spanRootAsync("balanceSummary", async () => {
481
+ const [headHash] = await context.head();
482
+ const headResult = await context.store.chainMap.get(headHash);
483
+ const headBoundWitness = asBlockBoundWitnessWithStorageMeta2(headResult, () => `Head block not found for hash: ${headHash}`, {
484
+ required: true
485
+ });
486
+ const rangeStart = asXL1BlockNumber(isDefined4(context.windowSize) ? Math.max(headBoundWitness.block - context.windowSize + 1, 0) : 0);
487
+ const ranges = deepCalculateFramesFromRange(asXL1BlockRange2([
488
+ rangeStart,
489
+ headBoundWitness.block
490
+ ], {
491
+ name: "balancesSummary"
492
+ }));
493
+ const summaries = await Promise.all(ranges.map((range) => balancesStepSummaryFromRange(context, range)));
494
+ const balances = {};
495
+ for (let summary of summaries) {
496
+ for (const [address, balance] of Object.entries(summary.balances)) {
497
+ const validAddress = asAddress(address, () => `Invalid address: ${address}`);
498
+ balances[validAddress] = (balances[validAddress] ?? 0n) + parseSignedBigInt(balance);
499
+ }
500
+ }
501
+ return balances;
502
+ });
503
+ }
504
+ __name(balancesSummary, "balancesSummary");
505
+
506
+ // src/primitives/timeBudget.ts
507
+ async function timeBudget(name, logger, func, budget) {
508
+ const start = Date.now();
509
+ const result = await func();
510
+ const duration = Date.now() - start;
511
+ if (budget > 0 && duration > budget) {
512
+ logger?.warn(`Function [${name}] execution exceeded budget: ${duration}ms > ${budget}ms`);
513
+ }
514
+ return result;
515
+ }
516
+ __name(timeBudget, "timeBudget");
517
+
518
+ // src/primitives/transaction/elevatedPayloads.ts
519
+ import { isAllowedBlockPayload } from "@xyo-network/xl1-protocol";
520
+ var ELEVATE_OPCODE = "elevate";
521
+ function elevatedPayloads([tx, payloads]) {
522
+ const opCodes = (tx.script ?? []).filter((operation) => operation.startsWith(`${ELEVATE_OPCODE}|`));
523
+ const elevatedPayloads2 = [];
524
+ for (const opCode of opCodes) {
525
+ const [code, hash] = opCode.split("|");
526
+ if (code === ELEVATE_OPCODE) {
527
+ const elevatedPayload = payloads.find((payload) => payload._hash === hash);
528
+ if (isAllowedBlockPayload(elevatedPayload)) {
529
+ elevatedPayloads2.push(elevatedPayload);
530
+ }
531
+ }
532
+ }
533
+ if (opCodes.length === elevatedPayloads2.length) {
534
+ return elevatedPayloads2;
535
+ }
536
+ throw new Error("Not all elevated payloads could be found in the transaction payloads");
537
+ }
538
+ __name(elevatedPayloads, "elevatedPayloads");
539
+
540
+ // src/model/ChainContext/ChainContext.ts
541
+ function contextCache(context, name, create) {
542
+ if (!context.caches) {
543
+ context.caches = {};
544
+ }
545
+ if (isUndefined(context.caches[name])) {
546
+ context.caches[name] = create?.() ?? new MemoryMap();
547
+ }
548
+ return context.caches[name];
549
+ }
550
+ __name(contextCache, "contextCache");
551
+ async function withContextCacheResponse(context, name, key, func, { max = 1e4, timeBudgetMs = 0 } = {}) {
552
+ const cache = contextCache(context, name, () => new LruCacheMap({
553
+ max
554
+ }));
555
+ const cacheResult = await cache.get(key);
556
+ if (isDefined5(cacheResult)) {
557
+ return cacheResult;
558
+ }
559
+ const result = timeBudgetMs > 0 ? await timeBudget(name, context.logger, func, timeBudgetMs) : await func();
560
+ await cache.set(key, result);
561
+ return result;
562
+ }
563
+ __name(withContextCacheResponse, "withContextCacheResponse");
564
+
565
+ // src/block/primitives/blockFromBlockNumber.ts
566
+ async function blockFromBlockNumber(context, blockNumber) {
567
+ const cacheKey = `${blockNumber}`;
568
+ return await withContextCacheResponse(context, "blockFromBlockNumber", cacheKey, async () => {
569
+ const [headHash] = await context.head();
570
+ const result = await context.store.chainMap.get(headHash);
571
+ let currentBlock = asBlockBoundWitnessWithStorageMeta3(result, () => `Head block not found for hash: ${headHash}`, {
572
+ required: true
573
+ });
574
+ if (currentBlock.block < blockNumber) {
575
+ throw new Error(`Block number ${blockNumber} is greater than head ${currentBlock.block}.`);
576
+ }
577
+ while (currentBlock.block > blockNumber) {
578
+ let jumpHash = currentBlock.previous;
579
+ let jumpBlockNumber = currentBlock.block - 1;
580
+ for (const [step, stepSize2] of StepSizes5.entries()) {
581
+ const possibleJumpBlockNumber = currentBlock.block - currentBlock.block % stepSize2 - 1;
582
+ if (possibleJumpBlockNumber >= blockNumber && possibleJumpBlockNumber <= jumpBlockNumber) {
583
+ jumpBlockNumber = possibleJumpBlockNumber;
584
+ jumpHash = asHash(currentBlock.step_hashes.at(step), () => `Step hash not found for step ${step} in block ${currentBlock.block}`);
585
+ }
586
+ }
587
+ const newBlock = await context.store.chainMap.get(asHash(jumpHash, () => `Jump hash not found for block number [${blockNumber}]: ${jumpBlockNumber} ${toSafeJsonString(currentBlock, 10)}`));
588
+ currentBlock = asBlockBoundWitnessWithStorageMeta3(newBlock, () => `Block not found for hash: ${jumpHash}`, {
589
+ required: true
590
+ });
591
+ if (currentBlock.block === blockNumber) {
592
+ break;
593
+ }
594
+ if (currentBlock.block < blockNumber) {
595
+ throw new Error(`Block number ${blockNumber} is not a valid step block number for block ${headHash}.`);
596
+ }
597
+ }
598
+ return currentBlock;
599
+ });
600
+ }
601
+ __name(blockFromBlockNumber, "blockFromBlockNumber");
602
+
603
+ // src/block/primitives/frames/calculateFramesFromRange.ts
604
+ import { asXL1BlockNumber as asXL1BlockNumber2, stepSize } from "@xyo-network/xl1-protocol";
605
+ function calculateFramesFromRange(range, step) {
606
+ const size = stepSize(step);
607
+ let start = Math.trunc(range[0] / size) * size;
608
+ const fitted = [];
609
+ const remaining = [];
610
+ if (start !== range[0]) {
611
+ start += size;
612
+ remaining.push([
613
+ range[0],
614
+ asXL1BlockNumber2(Math.min(start - 1, range[1]), true)
615
+ ]);
616
+ }
617
+ for (let i = start; i <= range[1]; i += size) {
618
+ if (i + size - 1 <= range[1]) {
619
+ fitted.push([
620
+ asXL1BlockNumber2(i, {
621
+ name: "calculateFramesFromRange A"
622
+ }),
623
+ asXL1BlockNumber2(Math.min(i + size - 1, range[1]), {
624
+ name: "calculateFramesFromRange B"
625
+ })
626
+ ]);
627
+ } else {
628
+ remaining.push([
629
+ asXL1BlockNumber2(i, {
630
+ name: "calculateFramesFromRange C"
631
+ }),
632
+ range[1]
633
+ ]);
634
+ }
635
+ }
636
+ return [
637
+ fitted,
638
+ remaining
639
+ ];
640
+ }
641
+ __name(calculateFramesFromRange, "calculateFramesFromRange");
642
+
643
+ // src/block/primitives/frames/deepCalculateFramesFromRange.ts
644
+ import { StepSizes as StepSizes6 } from "@xyo-network/xl1-protocol";
645
+ function deepCalculateFramesFromRange(range, startingStep = StepSizes6.length - 1) {
646
+ const fitted = [];
647
+ let remaining = [
648
+ range
649
+ ];
650
+ for (let step = startingStep; step >= 0; step--) {
651
+ const newRemaining = [];
652
+ for (const range2 of remaining) {
653
+ const [newFittedFrames, newRemainingFrames] = calculateFramesFromRange(range2, step);
654
+ fitted.push(...newFittedFrames);
655
+ newRemaining.push(...newRemainingFrames);
656
+ }
657
+ remaining = newRemaining;
658
+ }
659
+ for (const range2 of remaining) {
660
+ for (let i = range2[0]; i <= range2[1]; i++) {
661
+ fitted.push([
662
+ i,
663
+ i
664
+ ]);
665
+ }
484
666
  }
485
- throw new Error("Invalid value for positive big int");
486
- }, "toPositiveBigInt");
667
+ return fitted.toSorted((a, b) => a[0] - b[0]);
668
+ }
669
+ __name(deepCalculateFramesFromRange, "deepCalculateFramesFromRange");
670
+
671
+ // src/block/primitives/hashFromBlockNumber.ts
672
+ async function hashFromBlockNumber(context, blockNumber) {
673
+ return (await blockFromBlockNumber(context, blockNumber))._hash;
674
+ }
675
+ __name(hashFromBlockNumber, "hashFromBlockNumber");
676
+
677
+ // src/block/primitives/model.ts
678
+ function isReadArchivist(value) {
679
+ return value.get !== void 0 && value.next !== void 0;
680
+ }
681
+ __name(isReadArchivist, "isReadArchivist");
682
+ function isWriteArchivist(value) {
683
+ return value.insert !== void 0;
684
+ }
685
+ __name(isWriteArchivist, "isWriteArchivist");
686
+ function isReadWriteArchivist(value) {
687
+ return isReadArchivist(value) && isWriteArchivist(value);
688
+ }
689
+ __name(isReadWriteArchivist, "isReadWriteArchivist");
690
+
691
+ // src/block/primitives/toStepIdentityString.ts
692
+ function toStepIdentityString({ block, step }) {
693
+ return `${block}|${step}`;
694
+ }
695
+ __name(toStepIdentityString, "toStepIdentityString");
696
+
697
+ // src/block/primitives/transfers/transfersStepSummaryFromRange.ts
698
+ import { assertEx as assertEx6 } from "@xylabs/sdk-js";
699
+ import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
700
+ import { isAnyPayload as isAnyPayload2 } from "@xyo-network/payload-model";
701
+ import { StepSizes as StepSizes7 } from "@xyo-network/xl1-protocol";
487
702
 
488
703
  // src/block/primitives/transfers/transfersSummary.ts
489
- import { asAddress, isDefined as isDefined3 } from "@xylabs/sdk-js";
490
- import { spanRootAsync } from "@xylabs/telemetry";
491
- import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta3, asXL1BlockNumber as asXL1BlockNumber2, asXL1BlockRange } from "@xyo-network/xl1-protocol";
704
+ import { asAddress as asAddress2, isDefined as isDefined6 } from "@xylabs/sdk-js";
705
+ import { spanRootAsync as spanRootAsync2 } from "@xylabs/telemetry";
706
+ import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta4, asXL1BlockNumber as asXL1BlockNumber3, asXL1BlockRange as asXL1BlockRange3 } from "@xyo-network/xl1-protocol";
492
707
  async function transfersSummary(transferContext) {
493
- return await spanRootAsync("transferSummary", async () => {
708
+ return await spanRootAsync2("transferSummary", async () => {
494
709
  const [headHash] = await transferContext.head();
495
710
  const headResult = await transferContext.store.chainMap.get(headHash);
496
- const headBoundWitness = asBlockBoundWitnessWithStorageMeta3(headResult, () => `Head block not found for hash: ${transferContext.head}`, {
711
+ const headBoundWitness = asBlockBoundWitnessWithStorageMeta4(headResult, () => `Head block not found for hash: ${transferContext.head}`, {
497
712
  required: true
498
713
  });
499
- const rangeStart = asXL1BlockNumber2(isDefined3(transferContext.windowSize) ? Math.max(headBoundWitness.block - transferContext.windowSize + 1, 0) : 0);
500
- const ranges = deepCalculateFramesFromRange(asXL1BlockRange([
714
+ const rangeStart = asXL1BlockNumber3(isDefined6(transferContext.windowSize) ? Math.max(headBoundWitness.block - transferContext.windowSize + 1, 0) : 0);
715
+ const ranges = deepCalculateFramesFromRange(asXL1BlockRange3([
501
716
  rangeStart,
502
717
  headBoundWitness.block
503
718
  ], {
@@ -507,10 +722,10 @@ async function transfersSummary(transferContext) {
507
722
  const transfers = {};
508
723
  for (let summary of summaries) {
509
724
  for (const [from, toMap] of Object.entries(summary.transfers)) {
510
- const validFrom = asAddress(from, () => `Invalid address: ${from}`);
725
+ const validFrom = asAddress2(from, () => `Invalid address: ${from}`);
511
726
  transfers[validFrom] = transfers[validFrom] ?? {};
512
727
  for (const [to, transfer] of Object.entries(toMap)) {
513
- const validTo = asAddress(to, () => `Invalid address: ${to}`);
728
+ const validTo = asAddress2(to, () => `Invalid address: ${to}`);
514
729
  transfers[validFrom][validTo] = (transfers[validFrom][validTo] ?? 0n) + parseSignedBigInt(transfer);
515
730
  }
516
731
  }
@@ -547,11 +762,11 @@ async function transfersStepSummaryFromRange(context, range) {
547
762
  transfers
548
763
  };
549
764
  } else {
550
- const step = StepSizes3.indexOf(frameSize);
551
- assertEx4(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes3.join(", ")}`);
765
+ const step = StepSizes7.indexOf(frameSize);
766
+ assertEx6(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes7.join(", ")}`);
552
767
  const key = transfersSummaryKey(frameHeadHash, frameSize);
553
768
  const summaryResult = await context.summaryMap.get(key);
554
- if (isAnyPayload(summaryResult)) {
769
+ if (isAnyPayload2(summaryResult)) {
555
770
  result = summaryResult;
556
771
  } else {
557
772
  await context.stepSemaphores[step].acquire();
@@ -587,7 +802,7 @@ async function transfersStepSummaryFromRange(context, range) {
587
802
  }
588
803
  }
589
804
  }
590
- const finalResult = await PayloadBuilder.addStorageMeta(result);
805
+ const finalResult = await PayloadBuilder2.addStorageMeta(result);
591
806
  return finalResult;
592
807
  }
593
808
  __name(transfersStepSummaryFromRange, "transfersStepSummaryFromRange");
@@ -838,13 +1053,13 @@ var MempoolConfigZod = z8.object({
838
1053
  });
839
1054
 
840
1055
  // src/config/Producer.ts
841
- import { AddressZod, asAddress as asAddress2 } from "@xylabs/sdk-js";
1056
+ import { AddressZod, asAddress as asAddress3 } from "@xylabs/sdk-js";
842
1057
  import { globalRegistry as globalRegistry8 } from "zod";
843
1058
  import * as z9 from "zod";
844
1059
  var ProducerConfigZod = z9.object({
845
1060
  allowlist: z9.preprocess((val) => {
846
1061
  if (typeof val === "string") {
847
- return val.split(",").map((s) => asAddress2(s.trim()));
1062
+ return val.split(",").map((s) => asAddress3(s.trim()));
848
1063
  }
849
1064
  return val;
850
1065
  }, z9.array(AddressZod).optional().register(globalRegistry8, {
@@ -924,12 +1139,12 @@ var RewardRedemptionApiConfigZod = z10.object({
924
1139
  });
925
1140
 
926
1141
  // src/config/storage/driver/Mongo.ts
927
- import { isDefined as isDefined4, isUndefined as isUndefined2 } from "@xylabs/sdk-js";
1142
+ import { isDefined as isDefined7, isUndefined as isUndefined2 } from "@xylabs/sdk-js";
928
1143
  import { globalRegistry as globalRegistry10 } from "zod";
929
1144
  import * as z11 from "zod";
930
1145
  var hasMongoConfig = /* @__PURE__ */ __name((config) => {
931
1146
  if (isUndefined2(config)) return false;
932
- return isDefined4(config.connectionString) && isDefined4(config.database) && isDefined4(config.domain) && isDefined4(config.password) && isDefined4(config.username);
1147
+ return isDefined7(config.connectionString) && isDefined7(config.database) && isDefined7(config.domain) && isDefined7(config.password) && isDefined7(config.username);
933
1148
  }, "hasMongoConfig");
934
1149
  var MongoConfigZod = z11.object({
935
1150
  // TODO: Create from other arguments
@@ -989,13 +1204,13 @@ var TelemetryConfigZod = z13.object({
989
1204
  }).describe("Telemetry configuration options");
990
1205
 
991
1206
  // src/config/Validation.ts
992
- import { AddressZod as AddressZod2, asAddress as asAddress3 } from "@xylabs/sdk-js";
1207
+ import { AddressZod as AddressZod2, asAddress as asAddress4 } from "@xylabs/sdk-js";
993
1208
  import { globalRegistry as globalRegistry13 } from "zod";
994
1209
  import * as z14 from "zod";
995
1210
  var ValidationConfigZod = z14.object({
996
1211
  allowedRewardRedeemers: z14.preprocess((val) => {
997
1212
  if (typeof val === "string") {
998
- return val.split(",").map((s) => asAddress3(s.trim()));
1213
+ return val.split(",").map((s) => asAddress4(s.trim()));
999
1214
  }
1000
1215
  return val;
1001
1216
  }, z14.array(AddressZod2).optional().register(globalRegistry13, {
@@ -1005,7 +1220,7 @@ var ValidationConfigZod = z14.object({
1005
1220
  })),
1006
1221
  allowedRewardEscrowAccountSigners: z14.preprocess((val) => {
1007
1222
  if (typeof val === "string") {
1008
- return val.split(",").map((s) => asAddress3(s.trim()));
1223
+ return val.split(",").map((s) => asAddress4(s.trim()));
1009
1224
  }
1010
1225
  return val;
1011
1226
  }, z14.array(AddressZod2).optional().register(globalRegistry13, {
@@ -1128,11 +1343,11 @@ var isEIP712SignaturePayload = isPayloadOfZodType2(EIP712SignaturePayloadFieldsZ
1128
1343
  var asEIP712SignaturePayload = AsObjectFactory5.create(isEIP712SignaturePayload);
1129
1344
 
1130
1345
  // src/eip-712/sign.ts
1131
- import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
1346
+ import { PayloadBuilder as PayloadBuilder3 } from "@xyo-network/payload-builder";
1132
1347
  var signEIP712Message = /* @__PURE__ */ __name(async (signer, data) => {
1133
1348
  const { domain, types, values } = data;
1134
1349
  const signature = await signer.signTypedData(domain, types, values);
1135
- const hash = await PayloadBuilder2.hash(data);
1350
+ const hash = await PayloadBuilder3.hash(data);
1136
1351
  const address = await signer.getAddress();
1137
1352
  return {
1138
1353
  address,
@@ -1144,13 +1359,13 @@ var signEIP712Message = /* @__PURE__ */ __name(async (signer, data) => {
1144
1359
 
1145
1360
  // src/eip-712/verify.ts
1146
1361
  import { asHash as asHash2, isUndefined as isUndefined3 } from "@xylabs/sdk-js";
1147
- import { PayloadBuilder as PayloadBuilder3 } from "@xyo-network/payload-builder";
1362
+ import { PayloadBuilder as PayloadBuilder4 } from "@xyo-network/payload-builder";
1148
1363
  import { verifyTypedData } from "ethers/hash";
1149
1364
  var verifyEIP712Message = /* @__PURE__ */ __name(async (data, sig) => {
1150
1365
  const { address, signature, hash } = sig;
1151
1366
  const { schema, ...fields } = data;
1152
1367
  const signedHash = asHash2(hash);
1153
- if (isUndefined3(signedHash) || signedHash !== await PayloadBuilder3.hash(data)) return false;
1368
+ if (isUndefined3(signedHash) || signedHash !== await PayloadBuilder4.hash(data)) return false;
1154
1369
  const recoveredAddress = verifyTypedData(fields.domain, fields.types, fields.values, signature);
1155
1370
  return recoveredAddress.toLowerCase() === address.toLowerCase();
1156
1371
  }, "verifyEIP712Message");
@@ -1167,219 +1382,6 @@ var RewardMultipliers = {
1167
1382
  ]
1168
1383
  };
1169
1384
 
1170
- // src/primitives/readPayloadMapFromStore.ts
1171
- import { isDefined as isDefined5 } from "@xylabs/sdk-js";
1172
- function readPayloadMapFromStore(store) {
1173
- if (isReadArchivist(store)) {
1174
- return {
1175
- get: /* @__PURE__ */ __name(async (hash) => {
1176
- return (await store.get([
1177
- hash
1178
- ]))[0];
1179
- }, "get"),
1180
- getMany: /* @__PURE__ */ __name(async (hashes) => {
1181
- return await store.get(hashes);
1182
- }, "getMany"),
1183
- has: /* @__PURE__ */ __name(async (hash) => {
1184
- return isDefined5((await store.get([
1185
- hash
1186
- ]))[0]);
1187
- }, "has")
1188
- };
1189
- }
1190
- return store;
1191
- }
1192
- __name(readPayloadMapFromStore, "readPayloadMapFromStore");
1193
-
1194
- // src/primitives/step/completedStepRewardAddress.ts
1195
- import { toAddress as toAddress2 } from "@xylabs/sdk-js";
1196
- import { StepSizes as StepSizes4 } from "@xyo-network/xl1-protocol";
1197
- import { keccak256 } from "ethers";
1198
- function completedStepRewardAddress({ block, step }) {
1199
- const resolvedStepSize = step < StepSizes4.length ? StepSizes4[step] : step;
1200
- const addressKey = new TextEncoder().encode(`${block}|${resolvedStepSize}`);
1201
- return toAddress2(keccak256(addressKey).slice(-40), {
1202
- prefix: false
1203
- });
1204
- }
1205
- __name(completedStepRewardAddress, "completedStepRewardAddress");
1206
-
1207
- // src/primitives/step/derivedReceiveAddress.ts
1208
- import { toAddress as toAddress3 } from "@xylabs/sdk-js";
1209
- import { isDefined as isDefined6 } from "@xylabs/sdk-js";
1210
- import { keccak256 as keccak2562 } from "ethers";
1211
- function derivedReceiveAddress(address, scope) {
1212
- const addressKey = new TextEncoder().encode(isDefined6(scope) ? `${scope}|${address}` : address);
1213
- return toAddress3(keccak2562(addressKey).slice(-40), {
1214
- prefix: false
1215
- });
1216
- }
1217
- __name(derivedReceiveAddress, "derivedReceiveAddress");
1218
-
1219
- // src/primitives/step/stepBlockRange.ts
1220
- import { asXL1BlockRange as asXL1BlockRange2, StepSizes as StepSizes5 } from "@xyo-network/xl1-protocol";
1221
- function stepBlockRange({ block, step }) {
1222
- const stepSize2 = StepSizes5[step];
1223
- const start = block - stepSize2;
1224
- return asXL1BlockRange2([
1225
- start,
1226
- start + stepSize2 - 1
1227
- ], {
1228
- name: "stepBlockRange"
1229
- });
1230
- }
1231
- __name(stepBlockRange, "stepBlockRange");
1232
-
1233
- // src/primitives/step/stepTransferIndex.ts
1234
- import { assertEx as assertEx5 } from "@xylabs/sdk-js";
1235
- import { StepSizes as StepSizes6 } from "@xyo-network/xl1-protocol";
1236
- function stepTransferIndex(block, step) {
1237
- let rewardTransferCount = 0;
1238
- let rewardTransferIndex = -1;
1239
- for (let i = 3; i < StepSizes6.length; i++) {
1240
- const stepSize2 = StepSizes6[i];
1241
- if (block % stepSize2 === 0) {
1242
- if (stepSize2 === StepSizes6[step]) {
1243
- rewardTransferIndex = rewardTransferCount;
1244
- }
1245
- rewardTransferCount++;
1246
- }
1247
- }
1248
- assertEx5(rewardTransferIndex >= 0, () => `Could not find step size for step ${step} at block ${block}`);
1249
- return [
1250
- rewardTransferIndex,
1251
- rewardTransferCount
1252
- ];
1253
- }
1254
- __name(stepTransferIndex, "stepTransferIndex");
1255
-
1256
- // src/primitives/summary/balances/balancesStepSummaryFromRange.ts
1257
- import { assertEx as assertEx6 } from "@xylabs/sdk-js";
1258
- import { PayloadBuilder as PayloadBuilder4 } from "@xyo-network/payload-builder";
1259
- import { isAnyPayload as isAnyPayload2 } from "@xyo-network/payload-model";
1260
- import { StepSizes as StepSizes7 } from "@xyo-network/xl1-protocol";
1261
- async function balancesStepSummaryFromRange(context, range) {
1262
- const frameHeadHash = await hashFromBlockNumber(context, range[1]);
1263
- const frameSize = range[1] - range[0] + 1;
1264
- const [headHash] = await context.head();
1265
- let result = void 0;
1266
- if (frameSize === 1) {
1267
- const hash = await hashFromBlockNumber(context, range[0]);
1268
- const [, payloads] = await hydrateBlock(context.store, hash);
1269
- const balances = {};
1270
- for (const [address, balance] of Object.entries(netBalancesForPayloads(payloads))) {
1271
- balances[address] = toSignedBigInt(balance);
1272
- }
1273
- result = {
1274
- schema: BalancesStepSummarySchema,
1275
- hash: headHash,
1276
- stepSize: -1,
1277
- balances
1278
- };
1279
- } else {
1280
- const step = StepSizes7.indexOf(frameSize);
1281
- assertEx6(step !== -1, () => `Invalid step size: ${frameSize}. Must be one of ${StepSizes7.join(", ")}`);
1282
- const summaryResult = await context.summaryMap.get(`${frameHeadHash}|${frameSize}`);
1283
- if (isAnyPayload2(summaryResult)) {
1284
- result = summaryResult;
1285
- } else {
1286
- await context.stepSemaphores[step].acquire();
1287
- try {
1288
- const subRanges = deepCalculateFramesFromRange(range, step - 1);
1289
- const promises = subRanges.map((subRange) => balancesStepSummaryFromRange(context, subRange));
1290
- const subResults = await Promise.all(promises);
1291
- const bigIntBalances = {};
1292
- for (const subResult of subResults) {
1293
- for (const [address, balance] of Object.entries(subResult.balances)) {
1294
- bigIntBalances[address] = (bigIntBalances[address] ?? 0n) + parseSignedBigInt(balance);
1295
- }
1296
- }
1297
- const balances = {};
1298
- for (const [address, balance] of Object.entries(bigIntBalances)) {
1299
- balances[address] = toSignedBigInt(balance);
1300
- }
1301
- result = {
1302
- schema: BalancesStepSummarySchema,
1303
- hash: frameHeadHash,
1304
- stepSize: frameSize,
1305
- balances
1306
- };
1307
- await context.summaryMap.set(`${frameHeadHash}|${frameSize}`, result);
1308
- } finally {
1309
- context.stepSemaphores[step].release();
1310
- }
1311
- }
1312
- }
1313
- const finalResult = await PayloadBuilder4.addStorageMeta(result);
1314
- return finalResult;
1315
- }
1316
- __name(balancesStepSummaryFromRange, "balancesStepSummaryFromRange");
1317
-
1318
- // src/primitives/summary/balances/balancesSummary.ts
1319
- import { asAddress as asAddress4, isDefined as isDefined7 } from "@xylabs/sdk-js";
1320
- import { spanRootAsync as spanRootAsync2 } from "@xylabs/telemetry";
1321
- import { asBlockBoundWitnessWithStorageMeta as asBlockBoundWitnessWithStorageMeta4, asXL1BlockNumber as asXL1BlockNumber3, asXL1BlockRange as asXL1BlockRange3 } from "@xyo-network/xl1-protocol";
1322
- async function balancesSummary(context) {
1323
- return await spanRootAsync2("balanceSummary", async () => {
1324
- const [headHash] = await context.head();
1325
- const headResult = await context.store.chainMap.get(headHash);
1326
- const headBoundWitness = asBlockBoundWitnessWithStorageMeta4(headResult, () => `Head block not found for hash: ${headHash}`, {
1327
- required: true
1328
- });
1329
- const rangeStart = asXL1BlockNumber3(isDefined7(context.windowSize) ? Math.max(headBoundWitness.block - context.windowSize + 1, 0) : 0);
1330
- const ranges = deepCalculateFramesFromRange(asXL1BlockRange3([
1331
- rangeStart,
1332
- headBoundWitness.block
1333
- ], {
1334
- name: "balancesSummary"
1335
- }));
1336
- const summaries = await Promise.all(ranges.map((range) => balancesStepSummaryFromRange(context, range)));
1337
- const balances = {};
1338
- for (let summary of summaries) {
1339
- for (const [address, balance] of Object.entries(summary.balances)) {
1340
- const validAddress = asAddress4(address, () => `Invalid address: ${address}`);
1341
- balances[validAddress] = (balances[validAddress] ?? 0n) + parseSignedBigInt(balance);
1342
- }
1343
- }
1344
- return balances;
1345
- });
1346
- }
1347
- __name(balancesSummary, "balancesSummary");
1348
-
1349
- // src/primitives/timeBudget.ts
1350
- async function timeBudget(name, logger, func, budget) {
1351
- const start = Date.now();
1352
- const result = await func();
1353
- const duration = Date.now() - start;
1354
- if (duration > budget) {
1355
- logger?.warn(`Function [${name}] execution exceeded budget: ${duration}ms > ${budget}ms`);
1356
- }
1357
- return result;
1358
- }
1359
- __name(timeBudget, "timeBudget");
1360
-
1361
- // src/primitives/transaction/elevatedPayloads.ts
1362
- import { isAllowedBlockPayload } from "@xyo-network/xl1-protocol";
1363
- var ELEVATE_OPCODE = "elevate";
1364
- function elevatedPayloads([tx, payloads]) {
1365
- const opCodes = (tx.script ?? []).filter((operation) => operation.startsWith(`${ELEVATE_OPCODE}|`));
1366
- const elevatedPayloads2 = [];
1367
- for (const opCode of opCodes) {
1368
- const [code, hash] = opCode.split("|");
1369
- if (code === ELEVATE_OPCODE) {
1370
- const elevatedPayload = payloads.find((payload) => payload._hash === hash);
1371
- if (isAllowedBlockPayload(elevatedPayload)) {
1372
- elevatedPayloads2.push(elevatedPayload);
1373
- }
1374
- }
1375
- }
1376
- if (opCodes.length === elevatedPayloads2.length) {
1377
- return elevatedPayloads2;
1378
- }
1379
- throw new Error("Not all elevated payloads could be found in the transaction payloads");
1380
- }
1381
- __name(elevatedPayloads, "elevatedPayloads");
1382
-
1383
1385
  // src/services/StakeIntentService/ChainIndexingServiceStateSchema.ts
1384
1386
  import { AsObjectFactory as AsObjectFactory6 } from "@xylabs/sdk-js";
1385
1387
  import { isPayloadOfSchemaType as isPayloadOfSchemaType4, isStorageMeta as isStorageMeta3 } from "@xyo-network/payload-model";