@xyo-network/xl1-cli 1.16.19 → 1.16.21

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 (2) hide show
  1. package/dist/cli-min.mjs +2123 -1807
  2. package/package.json +10 -10
package/dist/cli-min.mjs CHANGED
@@ -7,6 +7,8 @@ import require$$0$e from 'tty';
7
7
  import require$$0$a, { format as format$4, inspect } from 'util';
8
8
  import require$$0$c, { createHmac, pbkdf2Sync, randomBytes as randomBytes$3, createHash, subtle } from 'crypto';
9
9
  import { trace, context, SpanStatusCode, propagation, ROOT_CONTEXT, ValueType, metrics as metrics$3 } from '@opentelemetry/api';
10
+ import * as nc from 'node:crypto';
11
+ import { randomFillSync, randomUUID } from 'node:crypto';
10
12
  import require$$0$9, { Readable } from 'stream';
11
13
  import require$$2$5 from 'http';
12
14
  import require$$1$3 from 'https';
@@ -15,14 +17,15 @@ import require$$0$b, { statSync, readdirSync, readFileSync, writeFile } from 'fs
15
17
  import http2 from 'http2';
16
18
  import require$$4$4, { strictEqual, notStrictEqual } from 'assert';
17
19
  import zlib, { gunzipSync } from 'zlib';
18
- import * as nc from 'node:crypto';
19
- import { randomFillSync, randomUUID } from 'node:crypto';
20
20
  import { open } from 'lmdb';
21
21
  import require$$0$k from 'fs/promises';
22
22
  import { ConsoleSpanExporter, BatchSpanProcessor, AlwaysOnSampler, BasicTracerProvider } from '@opentelemetry/sdk-trace-base';
23
23
  import process$1 from 'node:process';
24
24
  import os from 'node:os';
25
25
  import tty from 'node:tty';
26
+ import require$$0$h from 'net';
27
+ import require$$2$6 from 'tls';
28
+ import require$$0$f from 'buffer';
26
29
  import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
27
30
  import { CompositePropagator, W3CTraceContextPropagator, W3CBaggagePropagator } from '@opentelemetry/core';
28
31
  import { PrometheusExporter } from '@opentelemetry/exporter-prometheus';
@@ -35,10 +38,8 @@ import { MeterProvider } from '@opentelemetry/sdk-metrics';
35
38
  import { ATTR_SERVICE_VERSION, ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
36
39
  import { createRequire } from 'node:module';
37
40
  import require$$2$7, { readdirSync as readdirSync$1, readFileSync as readFileSync$1 } from 'node:fs';
38
- import require$$0$f from 'buffer';
39
41
  import require$$1$4 from 'string_decoder';
40
42
  import require$$4$5 from 'node:zlib';
41
- import require$$0$h from 'net';
42
43
  import require$$1$6 from 'node:events';
43
44
  import require$$7$2 from 'node:path';
44
45
  import require$$2$8 from 'node:http';
@@ -49,7 +50,6 @@ import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
49
50
  import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
50
51
  import require$$0$i from 'timers';
51
52
  import require$$0$j from 'dns';
52
- import require$$2$6 from 'tls';
53
53
  import require$$1$8 from 'child_process';
54
54
  import require$$0$l from 'timers/promises';
55
55
  import require$$1$9 from 'module';
@@ -20724,46 +20724,46 @@ function createInstance(defaultConfig) {
20724
20724
  }
20725
20725
 
20726
20726
  // Create the default instance to be exported
20727
- const axios$1 = createInstance(defaults$3);
20727
+ const axios = createInstance(defaults$3);
20728
20728
 
20729
20729
  // Expose Axios class to allow class inheritance
20730
- axios$1.Axios = Axios$1;
20730
+ axios.Axios = Axios$1;
20731
20731
 
20732
20732
  // Expose Cancel & CancelToken
20733
- axios$1.CanceledError = CanceledError$1;
20734
- axios$1.CancelToken = CancelToken$1;
20735
- axios$1.isCancel = isCancel$1;
20736
- axios$1.VERSION = VERSION$1;
20737
- axios$1.toFormData = toFormData$1;
20733
+ axios.CanceledError = CanceledError$1;
20734
+ axios.CancelToken = CancelToken$1;
20735
+ axios.isCancel = isCancel$1;
20736
+ axios.VERSION = VERSION$1;
20737
+ axios.toFormData = toFormData$1;
20738
20738
 
20739
20739
  // Expose AxiosError class
20740
- axios$1.AxiosError = AxiosError$1;
20740
+ axios.AxiosError = AxiosError$1;
20741
20741
 
20742
20742
  // alias for CanceledError for backward compatibility
20743
- axios$1.Cancel = axios$1.CanceledError;
20743
+ axios.Cancel = axios.CanceledError;
20744
20744
 
20745
20745
  // Expose all/spread
20746
- axios$1.all = function all(promises) {
20746
+ axios.all = function all(promises) {
20747
20747
  return Promise.all(promises);
20748
20748
  };
20749
20749
 
20750
- axios$1.spread = spread$1;
20750
+ axios.spread = spread$1;
20751
20751
 
20752
20752
  // Expose isAxiosError
20753
- axios$1.isAxiosError = isAxiosError$1;
20753
+ axios.isAxiosError = isAxiosError$1;
20754
20754
 
20755
20755
  // Expose mergeConfig
20756
- axios$1.mergeConfig = mergeConfig$1;
20756
+ axios.mergeConfig = mergeConfig$1;
20757
20757
 
20758
- axios$1.AxiosHeaders = AxiosHeaders$1;
20758
+ axios.AxiosHeaders = AxiosHeaders$1;
20759
20759
 
20760
- axios$1.formToJSON = thing => formDataToJSON(utils$b.isHTMLForm(thing) ? new FormData(thing) : thing);
20760
+ axios.formToJSON = thing => formDataToJSON(utils$b.isHTMLForm(thing) ? new FormData(thing) : thing);
20761
20761
 
20762
- axios$1.getAdapter = adapters$1.getAdapter;
20762
+ axios.getAdapter = adapters$1.getAdapter;
20763
20763
 
20764
- axios$1.HttpStatusCode = HttpStatusCode$1;
20764
+ axios.HttpStatusCode = HttpStatusCode$1;
20765
20765
 
20766
- axios$1.default = axios$1;
20766
+ axios.default = axios;
20767
20767
 
20768
20768
  // This module is intended to unwrap Axios default export as named.
20769
20769
  // Keep top-level export same with static properties
@@ -20785,7 +20785,7 @@ const {
20785
20785
  formToJSON,
20786
20786
  getAdapter,
20787
20787
  mergeConfig
20788
- } = axios$1;
20788
+ } = axios;
20789
20789
 
20790
20790
  // src/index.ts
20791
20791
  var exists$1 = (x) => {
@@ -38125,23 +38125,7 @@ function axiosJsonConfig({
38125
38125
  ...config
38126
38126
  };
38127
38127
  }
38128
- function deprecated(from, to, logger = console) {
38129
- logger.warn(`${from} is deprecated. Please use ${to} instead.`);
38130
- }
38131
- var AxiosJson = class _AxiosJson extends Axios {
38132
- constructor(config) {
38133
- deprecated("AxiosJson", "axiosJsonConfig");
38134
- super(_AxiosJson.axiosConfig(config));
38135
- }
38136
- static axiosConfig(config = {}) {
38137
- return axiosJsonConfig(config);
38138
- }
38139
- static create(config) {
38140
- return new Axios(this.axiosConfig(config));
38141
- }
38142
- };
38143
38128
  var axiosJson = new Axios(axiosJsonConfig());
38144
- var axios = axiosJson;
38145
38129
 
38146
38130
  // src/Base.ts
38147
38131
  var DEFAULT_HISTORY_INTERVAL = 1e3 * 5;
@@ -72776,7 +72760,7 @@ var DnsRecordType = {
72776
72760
  var DnsReturnCode = {
72777
72761
  NoError: 0};
72778
72762
  var googleDnsOverHttps = async (name, type = DnsRecordType.A) => {
72779
- return (await axios.get(`https://dns.google/resolve?name=${name}&type=${type}`)).data;
72763
+ return (await axiosJson.get(`https://dns.google/resolve?name=${name}&type=${type}`)).data;
72780
72764
  };
72781
72765
 
72782
72766
  // src/domainResolve.ts
@@ -75799,7 +75783,7 @@ var ResolveHelper = class _ResolveHelper extends ResolveHelperStatic {
75799
75783
  ...up ? await upResolver.resolve("*", upLocalOptions) : []
75800
75784
  ].filter(duplicateModules);
75801
75785
  if (modules.length > 0) {
75802
- log?.log("modules [count]", modules.length);
75786
+ log?.debug("modules [count]", modules.length);
75803
75787
  log?.debug("modules", toSafeJsonString(modules, 4));
75804
75788
  }
75805
75789
  if (maxDepth === 0) {
@@ -77573,7 +77557,7 @@ var AbstractArchivist = class _AbstractArchivist extends AbstractModuleInstance
77573
77557
  get storeParentReads() {
77574
77558
  return !!this.config?.storeParentReads;
77575
77559
  }
77576
- /** deprecated use next or snapshot instead */
77560
+ /** @deprecated use next or snapshot instead */
77577
77561
  async all() {
77578
77562
  this._noOverride("all");
77579
77563
  this.isSupportedQuery(ArchivistAllQuerySchema, "all");
@@ -82341,6 +82325,218 @@ var SimpleAccountBalanceViewer = class {
82341
82325
  ].toSorted((a, b) => b - a).slice(0, max);
82342
82326
  }
82343
82327
  };
82328
+ function _ts_decorate$4(decorators, target, key, desc) {
82329
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
82330
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
82331
+ 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;
82332
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
82333
+ }
82334
+ __name$k(_ts_decorate$4, "_ts_decorate");
82335
+ var SimpleChainStakeEventsViewer = class extends AbstractCreatable {
82336
+ static {
82337
+ __name$k(this, "SimpleChainStakeEventsViewer");
82338
+ }
82339
+ get positions() {
82340
+ return this.params.positions;
82341
+ }
82342
+ positionCount(range) {
82343
+ return this.positionsFromRange(range).length;
82344
+ }
82345
+ stakeEvents(range, { name } = {}) {
82346
+ const positions = this.positionsFromRange(range);
82347
+ const events = this.eventsFromPositions(positions);
82348
+ if (isDefined(name)) {
82349
+ return events.filter((event) => event.name === name);
82350
+ }
82351
+ return events;
82352
+ }
82353
+ async startHandler() {
82354
+ await super.startHandler();
82355
+ }
82356
+ eventsFromPositions(positions) {
82357
+ const events = positions.map((position) => {
82358
+ const events2 = [
82359
+ {
82360
+ name: "StakeAdded",
82361
+ time: position.addBlock,
82362
+ args: {
82363
+ staker: position.staker,
82364
+ staked: position.staked,
82365
+ amount: position.amount,
82366
+ id: position.id
82367
+ }
82368
+ }
82369
+ ];
82370
+ if (position.removeBlock !== 0) {
82371
+ events2.push({
82372
+ name: "StakeRemoved",
82373
+ time: position.removeBlock,
82374
+ args: {
82375
+ staker: position.staker,
82376
+ staked: position.staked,
82377
+ amount: position.amount,
82378
+ id: position.id
82379
+ }
82380
+ });
82381
+ }
82382
+ if (position.withdrawBlock !== 0) {
82383
+ events2.push({
82384
+ name: "StakeWithdrawn",
82385
+ time: position.withdrawBlock,
82386
+ args: {
82387
+ staker: position.staker,
82388
+ staked: position.staked,
82389
+ amount: position.amount,
82390
+ id: position.id
82391
+ }
82392
+ });
82393
+ }
82394
+ return events2;
82395
+ });
82396
+ return events.flat();
82397
+ }
82398
+ positionsFromRange(range) {
82399
+ const startBlock = range[0];
82400
+ const endBlock = range[1] === "latest" ? Number.MAX_SAFE_INTEGER : range[1];
82401
+ const filteredPositions = this.positions.filter((position) => {
82402
+ return position.addBlock <= endBlock && (position.removeBlock === 0 || position.removeBlock >= startBlock);
82403
+ });
82404
+ return filteredPositions;
82405
+ }
82406
+ };
82407
+ SimpleChainStakeEventsViewer = _ts_decorate$4([
82408
+ creatable()
82409
+ ], SimpleChainStakeEventsViewer);
82410
+
82411
+ // src/simple/chainStake/SimpleChainStakeViewer.ts
82412
+ function _ts_decorate2$4(decorators, target, key, desc) {
82413
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
82414
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
82415
+ 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;
82416
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
82417
+ }
82418
+ __name$k(_ts_decorate2$4, "_ts_decorate");
82419
+ var SimpleChainStakeViewer = class extends AbstractCreatable {
82420
+ static {
82421
+ __name$k(this, "SimpleChainStakeViewer");
82422
+ }
82423
+ _chainId;
82424
+ _chainStakeEventsViewer;
82425
+ get chainId() {
82426
+ return assertEx(this._chainId, () => "Chain ID not set");
82427
+ }
82428
+ get chainMap() {
82429
+ return this.params.chainMap;
82430
+ }
82431
+ get minWithdrawalBlocks() {
82432
+ return this.params.minWithdrawalBlocks ?? 10;
82433
+ }
82434
+ get rewardsContract() {
82435
+ return toAddress("0x000000000000000000000000000000");
82436
+ }
82437
+ get stakeEvents() {
82438
+ return assertEx(this._chainStakeEventsViewer, () => "Stake events viewer not set");
82439
+ }
82440
+ get stakingTokenAddress() {
82441
+ return toAddress("0x000000000000000000000000000011");
82442
+ }
82443
+ get positions() {
82444
+ return this.params.positions;
82445
+ }
82446
+ active() {
82447
+ let active = 0n;
82448
+ for (const position of this.positions) {
82449
+ if (position.removeBlock === 0) {
82450
+ active += position.amount;
82451
+ }
82452
+ }
82453
+ return active;
82454
+ }
82455
+ activeByAddressStaked(staked) {
82456
+ let active = 0n;
82457
+ for (const position of this.positions) {
82458
+ if (position.removeBlock === 0 && asAddress(position.staked) === asAddress(staked)) {
82459
+ active += position.amount;
82460
+ }
82461
+ }
82462
+ return active;
82463
+ }
82464
+ activeByStaker(staker) {
82465
+ let active = 0n;
82466
+ for (const position of this.positions) {
82467
+ if (position.removeBlock === 0 && asAddress(position.staker) === asAddress(staker)) {
82468
+ active += position.amount;
82469
+ }
82470
+ }
82471
+ return active;
82472
+ }
82473
+ pending() {
82474
+ let pending = 0n;
82475
+ for (const position of this.positions) {
82476
+ if (position.removeBlock !== 0 && position.withdrawBlock === 0) {
82477
+ pending += position.amount;
82478
+ }
82479
+ }
82480
+ return pending;
82481
+ }
82482
+ pendingByStaker(staker) {
82483
+ let pending = 0n;
82484
+ for (const position of this.positions) {
82485
+ if (position.removeBlock !== 0 && position.withdrawBlock === 0 && asAddress(position.staker) === asAddress(staker)) {
82486
+ pending += position.amount;
82487
+ }
82488
+ }
82489
+ return pending;
82490
+ }
82491
+ stakeById(id) {
82492
+ return assertEx(this.positions[id], () => new Error(`Stake with id ${id} not found`));
82493
+ }
82494
+ stakeByStaker(staker, slot) {
82495
+ return this.positions.filter((s) => asAddress(s.staker) === asAddress(staker))[slot];
82496
+ }
82497
+ stakesByStaked(staked, range = [
82498
+ 0,
82499
+ void 0
82500
+ ]) {
82501
+ const endBlock = range[1] ?? Number.MAX_SAFE_INTEGER;
82502
+ return this.positions.filter((s) => asAddress(s.staked) === asAddress(staked) && s.addBlock <= endBlock && s.removeBlock <= endBlock);
82503
+ }
82504
+ stakesByStaker(staker, range = [
82505
+ 0,
82506
+ void 0
82507
+ ]) {
82508
+ const endBlock = range[1] ?? Number.MAX_SAFE_INTEGER;
82509
+ return this.positions.filter((s) => asAddress(s.staker) === asAddress(staker) && s.addBlock <= endBlock && s.removeBlock <= endBlock);
82510
+ }
82511
+ withdrawn() {
82512
+ let withdrawn = 0n;
82513
+ for (const position of this.positions) {
82514
+ if (position.withdrawBlock !== 0) {
82515
+ withdrawn += position.amount;
82516
+ }
82517
+ }
82518
+ return withdrawn;
82519
+ }
82520
+ withdrawnByStaker(staker) {
82521
+ let withdrawn = 0n;
82522
+ for (const position of this.positions) {
82523
+ if (position.withdrawBlock !== 0 && asAddress(position.staker) === asAddress(staker)) {
82524
+ withdrawn += position.amount;
82525
+ }
82526
+ }
82527
+ return withdrawn;
82528
+ }
82529
+ async startHandler() {
82530
+ await super.startHandler();
82531
+ this._chainId = this.params.chainId ?? (await Account.random()).address;
82532
+ this._chainStakeEventsViewer = await SimpleChainStakeEventsViewer.create({
82533
+ positions: this.positions
82534
+ });
82535
+ }
82536
+ };
82537
+ SimpleChainStakeViewer = _ts_decorate2$4([
82538
+ creatable()
82539
+ ], SimpleChainStakeViewer);
82344
82540
 
82345
82541
  // src/simple/client/SimpleXyoClient.ts
82346
82542
  (class {
@@ -82806,7 +83002,7 @@ var StatusNetworks = {
82806
83002
  }
82807
83003
  async makeRequest(url3) {
82808
83004
  try {
82809
- const response = await axios$1.get(url3);
83005
+ const response = await axios.get(url3);
82810
83006
  if (isNetworkStatus(response.data)) {
82811
83007
  return response.data;
82812
83008
  } else {
@@ -84359,7 +84555,7 @@ async function allStakersForRange(chain, externalRange, staked) {
84359
84555
  __name$j(allStakersForRange, "allStakersForRange");
84360
84556
  async function allStakersForStep(context, stepContext, staked) {
84361
84557
  const xl1BlockRange = stepBlockRange(stepContext);
84362
- return await allStakersForRange(context.events, await externalBlockRangeFromXL1BlockRange(context, xl1BlockRange), staked);
84558
+ return await allStakersForRange(context.stake.stakeEvents, await externalBlockRangeFromXL1BlockRange(context, xl1BlockRange), staked);
84363
84559
  }
84364
84560
  __name$j(allStakersForStep, "allStakersForStep");
84365
84561
  async function weightedStakeForRangeByAddress(chainEvents, range, staked, staker) {
@@ -84390,7 +84586,7 @@ async function weightedStakeForRangeByPosition(context, externalRange, positionI
84390
84586
  return await withContextCacheResponse(context, "weightedStakeForRangeByPosition", cacheKey, async () => {
84391
84587
  let weightedStakeSum = 0n;
84392
84588
  if (isDefined(positionId)) {
84393
- const mergedEvents = (await mergedAddRemoveStakeEventsByPosition(context.events, [
84589
+ const mergedEvents = (await mergedAddRemoveStakeEventsByPosition(context.stake.stakeEvents, [
84394
84590
  0,
84395
84591
  externalRange[1]
84396
84592
  ], positionId)).toSorted((a, b) => a.time - b.time);
@@ -84417,7 +84613,7 @@ async function weightedStakeForRangeByPosition(context, externalRange, positionI
84417
84613
  weightedStakeSum += currentStake * BigInt(externalRange[1] - currentTime);
84418
84614
  }
84419
84615
  } else {
84420
- const positionCount = await context.events.positionCount(externalRange);
84616
+ const positionCount = await context.stake.stakeEvents.positionCount(externalRange);
84421
84617
  for (let pos = 0; pos < positionCount; pos++) {
84422
84618
  weightedStakeSum += await weightedStakeForRangeByPosition(context, externalRange, pos);
84423
84619
  }
@@ -117577,116 +117773,6 @@ BaseTimeSyncService = _ts_decorate14([
117577
117773
  creatable()
117578
117774
  ], BaseTimeSyncService);
117579
117775
 
117580
- var __defProp$i = Object.defineProperty;
117581
- var __name$a = (target, value) => __defProp$i(target, "name", { value, configurable: true });
117582
- var initContextManager = /* @__PURE__ */ __name$a(() => {
117583
- const contextManager = new AsyncLocalStorageContextManager();
117584
- context.setGlobalContextManager(contextManager.enable());
117585
- }, "initContextManager");
117586
- var initPropagation = /* @__PURE__ */ __name$a(() => {
117587
- propagation.setGlobalPropagator(new CompositePropagator({
117588
- propagators: [
117589
- new W3CTraceContextPropagator(),
117590
- new W3CBaggagePropagator()
117591
- ]
117592
- }));
117593
- }, "initPropagation");
117594
- var initResource = /* @__PURE__ */ __name$a((attributes) => {
117595
- const detectedResource = detectResources({
117596
- detectors: [
117597
- // hostDetector,
117598
- // osDetector,
117599
- // processDetector,
117600
- serviceInstanceIdDetector
117601
- ]
117602
- });
117603
- const staticResource = resourceFromAttributes({
117604
- [ATTR_SERVICE_NAME]: attributes.serviceName,
117605
- [ATTR_SERVICE_VERSION]: attributes.serviceName
117606
- });
117607
- const resource = detectedResource.merge(staticResource);
117608
- return resource;
117609
- }, "initResource");
117610
- var initHostMetrics = /* @__PURE__ */ __name$a((meterProvider) => {
117611
- const hostMetrics = new HostMetrics({
117612
- meterProvider,
117613
- name: "host-metrics"
117614
- });
117615
- hostMetrics.start();
117616
- }, "initHostMetrics");
117617
- var initNodeMetrics = /* @__PURE__ */ __name$a((meterProvider) => {
117618
- const instrumentation = new RuntimeNodeInstrumentation({
117619
- monitoringPrecision: 5e3
117620
- });
117621
- instrumentation.setMeterProvider(meterProvider);
117622
- instrumentation.enable();
117623
- }, "initNodeMetrics");
117624
- var initMetricsExporter = /* @__PURE__ */ __name$a((metricsConfig) => {
117625
- const { port, endpoint } = metricsConfig;
117626
- const exporter = new PrometheusExporter({
117627
- port,
117628
- endpoint
117629
- }, (err) => {
117630
- if (err) console.error("Error initializing Prometheus exporter", err);
117631
- });
117632
- return exporter;
117633
- }, "initMetricsExporter");
117634
- var initMeterProvider = /* @__PURE__ */ __name$a((resource, readers) => {
117635
- const meterProvider = new MeterProvider({
117636
- readers,
117637
- resource,
117638
- views: [
117639
- {
117640
- aggregation: void 0,
117641
- instrumentName: "*",
117642
- instrumentType: void 0,
117643
- meterName: "*"
117644
- }
117645
- ]
117646
- });
117647
- metrics$3.setGlobalMeterProvider(meterProvider);
117648
- return meterProvider;
117649
- }, "initMeterProvider");
117650
- var initTraceProvider = /* @__PURE__ */ __name$a((otlpEndpoint, resource) => {
117651
- const spanProcessors = [];
117652
- if (isDefined(otlpEndpoint)) {
117653
- const isHttp = otlpEndpoint.includes("/v1/traces") || otlpEndpoint.includes(":4318") || otlpEndpoint.startsWith("http");
117654
- const exporter = isHttp ? new OTLPTraceExporter({
117655
- url: otlpEndpoint
117656
- }) : new OTLPTraceExporter$1({
117657
- url: otlpEndpoint
117658
- });
117659
- const batchSpanProcessorConfig = {};
117660
- const spanProcessor = new BatchSpanProcessor(exporter, batchSpanProcessorConfig);
117661
- spanProcessors.push(spanProcessor);
117662
- }
117663
- const config = {
117664
- resource,
117665
- sampler: new AlwaysOnSampler(),
117666
- spanProcessors
117667
- };
117668
- const traceProvider = new BasicTracerProvider(config);
117669
- trace.setGlobalTracerProvider(traceProvider);
117670
- return traceProvider;
117671
- }, "initTraceProvider");
117672
- var initTelemetry = /* @__PURE__ */ __name$a((params) => {
117673
- const { attributes, metricsConfig, otlpEndpoint } = params;
117674
- initContextManager();
117675
- initPropagation();
117676
- const resource = initResource(attributes);
117677
- const exporter = initMetricsExporter(metricsConfig);
117678
- const meterProvider = initMeterProvider(resource, [
117679
- exporter
117680
- ]);
117681
- initHostMetrics(meterProvider);
117682
- initNodeMetrics(meterProvider);
117683
- const traceProvider = initTraceProvider(otlpEndpoint, resource);
117684
- return {
117685
- meterProvider,
117686
- traceProvider
117687
- };
117688
- }, "initTelemetry");
117689
-
117690
117776
  // src/AbstractNode.ts
117691
117777
  var AbstractNode = class _AbstractNode extends AbstractModuleInstance {
117692
117778
  static configSchemas = [...super.configSchemas, NodeConfigSchema];
@@ -118622,9 +118708,9 @@ factory.create(requiredAttachableBridgeInstanceFunctions, [
118622
118708
  // src/Config.ts
118623
118709
  var BridgeConfigSchema = "network.xyo.bridge.config";
118624
118710
 
118625
- var __defProp$h = Object.defineProperty;
118711
+ var __defProp$i = Object.defineProperty;
118626
118712
  var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
118627
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
118713
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
118628
118714
  var __decorateClass$7 = (decorators, target, key, kind) => {
118629
118715
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target;
118630
118716
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
@@ -119538,11 +119624,11 @@ var AbstractModuleProxy = class extends AbstractModuleInstance {
119538
119624
  }
119539
119625
  };
119540
119626
 
119541
- var __defProp$g = Object.defineProperty;
119627
+ var __defProp$h = Object.defineProperty;
119542
119628
  var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor;
119543
119629
  var __getProtoOf$4 = Object.getPrototypeOf;
119544
119630
  var __reflectGet$4 = Reflect.get;
119545
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
119631
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
119546
119632
  var __decorateClass$6 = (decorators, target, key, kind) => {
119547
119633
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target;
119548
119634
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
@@ -119832,7 +119918,7 @@ var HttpBridge = class extends AbstractBridge {
119832
119918
  return [];
119833
119919
  }
119834
119920
  };
119835
- __publicField$6(HttpBridge, "axios", new AxiosJson());
119921
+ __publicField$6(HttpBridge, "axios", new Axios(axiosJsonConfig()));
119836
119922
  __publicField$6(HttpBridge, "configSchemas", [...__superGet$4(HttpBridge, HttpBridge, "configSchemas"), HttpBridgeConfigSchema]);
119837
119923
  __publicField$6(HttpBridge, "defaultConfigSchema", HttpBridgeConfigSchema);
119838
119924
  __publicField$6(HttpBridge, "defaultFailureRetryTime", 1e3 * 60);
@@ -119843,9 +119929,1627 @@ HttpBridge = __decorateClass$6([
119843
119929
  creatableModule()
119844
119930
  ], HttpBridge);
119845
119931
 
119932
+ var __defProp$g = Object.defineProperty;
119933
+ var __name$a = (target, value) => __defProp$g(target, "name", { value, configurable: true });
119934
+
119935
+ // src/BaseEthProvider.ts
119936
+ (class {
119937
+ static {
119938
+ __name$a(this, "BaseEthProvider");
119939
+ }
119940
+ eth_accounts() {
119941
+ throw new Error("Method not implemented.");
119942
+ }
119943
+ eth_blockNumber() {
119944
+ throw new Error("Method not implemented.");
119945
+ }
119946
+ eth_call(_transaction, _blockNumber) {
119947
+ throw new Error("Method not implemented.");
119948
+ }
119949
+ eth_clearSubscriptions(_keepSyncing) {
119950
+ throw new Error("Method not implemented.");
119951
+ }
119952
+ eth_coinbase() {
119953
+ throw new Error("Method not implemented.");
119954
+ }
119955
+ eth_compileLLL(_code) {
119956
+ throw new Error("Method not implemented.");
119957
+ }
119958
+ eth_compileSerpent(_code) {
119959
+ throw new Error("Method not implemented.");
119960
+ }
119961
+ eth_compileSolidity(_code) {
119962
+ throw new Error("Method not implemented.");
119963
+ }
119964
+ eth_estimateGas(_transaction, _blockNumber) {
119965
+ throw new Error("Method not implemented.");
119966
+ }
119967
+ eth_feeHistory(_blockCount, _newestBlock, _rewardPercentiles) {
119968
+ throw new Error("Method not implemented.");
119969
+ }
119970
+ eth_gasPrice() {
119971
+ throw new Error("Method not implemented.");
119972
+ }
119973
+ eth_getBalance(_address, _blockNumber) {
119974
+ throw new Error("Method not implemented.");
119975
+ }
119976
+ eth_getBlockByHash(_blockHash, _hydrated) {
119977
+ throw new Error("Method not implemented.");
119978
+ }
119979
+ eth_getBlockByNumber(_blockNumber, _hydrated) {
119980
+ throw new Error("Method not implemented.");
119981
+ }
119982
+ eth_getBlockTransactionCountByHash(_blockHash) {
119983
+ throw new Error("Method not implemented.");
119984
+ }
119985
+ eth_getBlockTransactionCountByNumber(_blockNumber) {
119986
+ throw new Error("Method not implemented.");
119987
+ }
119988
+ eth_getCode(_address, _blockNumber) {
119989
+ throw new Error("Method not implemented.");
119990
+ }
119991
+ eth_getCompilers() {
119992
+ throw new Error("Method not implemented.");
119993
+ }
119994
+ eth_getFilterChanges(_filterIdentifier) {
119995
+ throw new Error("Method not implemented.");
119996
+ }
119997
+ eth_getFilterLogs(_filterIdentifier) {
119998
+ throw new Error("Method not implemented.");
119999
+ }
120000
+ eth_getLogs(_filter) {
120001
+ throw new Error("Method not implemented.");
120002
+ }
120003
+ eth_getStorageAt(_address, _storageSlot, _blockNumber) {
120004
+ throw new Error("Method not implemented.");
120005
+ }
120006
+ eth_getTransactionByBlockHashAndIndex(_blockHash, _transactionIndex) {
120007
+ throw new Error("Method not implemented.");
120008
+ }
120009
+ eth_getTransactionByBlockNumberAndIndex(_blockNumber, _transactionIndex) {
120010
+ throw new Error("Method not implemented.");
120011
+ }
120012
+ eth_getTransactionByHash(_transactionHash) {
120013
+ throw new Error("Method not implemented.");
120014
+ }
120015
+ eth_getTransactionCount(_address, _blockNumber) {
120016
+ throw new Error("Method not implemented.");
120017
+ }
120018
+ eth_getTransactionReceipt(_transactionHash) {
120019
+ throw new Error("Method not implemented.");
120020
+ }
120021
+ eth_getUncleByBlockHashAndIndex(_blockHash, _uncleIndex) {
120022
+ throw new Error("Method not implemented.");
120023
+ }
120024
+ eth_getUncleByBlockNumberAndIndex(_blockNumber, _uncleIndex) {
120025
+ throw new Error("Method not implemented.");
120026
+ }
120027
+ eth_getUncleCountByBlockHash(_blockHash) {
120028
+ throw new Error("Method not implemented.");
120029
+ }
120030
+ eth_getUncleCountByBlockNumber(_blockNumber) {
120031
+ throw new Error("Method not implemented.");
120032
+ }
120033
+ eth_getWork() {
120034
+ throw new Error("Method not implemented.");
120035
+ }
120036
+ eth_hashrate() {
120037
+ throw new Error("Method not implemented.");
120038
+ }
120039
+ eth_maxPriorityFeePerGas() {
120040
+ throw new Error("Method not implemented.");
120041
+ }
120042
+ eth_mining() {
120043
+ throw new Error("Method not implemented.");
120044
+ }
120045
+ eth_newBlockFilter() {
120046
+ throw new Error("Method not implemented.");
120047
+ }
120048
+ eth_newFilter(_filter) {
120049
+ throw new Error("Method not implemented.");
120050
+ }
120051
+ eth_newPendingTransactionFilter() {
120052
+ throw new Error("Method not implemented.");
120053
+ }
120054
+ eth_protocolVersion() {
120055
+ throw new Error("Method not implemented.");
120056
+ }
120057
+ eth_sendRawTransaction(_transaction) {
120058
+ throw new Error("Method not implemented.");
120059
+ }
120060
+ eth_sendTransaction(_transaction) {
120061
+ throw new Error("Method not implemented.");
120062
+ }
120063
+ eth_sign(_address, _message) {
120064
+ throw new Error("Method not implemented.");
120065
+ }
120066
+ eth_signTransaction(_transaction) {
120067
+ throw new Error("Method not implemented.");
120068
+ }
120069
+ eth_submitHashrate(_hashRate, _id) {
120070
+ throw new Error("Method not implemented.");
120071
+ }
120072
+ eth_submitWork(_nonce, _hash, _digest) {
120073
+ throw new Error("Method not implemented.");
120074
+ }
120075
+ eth_subscribe(..._params) {
120076
+ throw new Error("Method not implemented.");
120077
+ }
120078
+ eth_syncing() {
120079
+ throw new Error("Method not implemented.");
120080
+ }
120081
+ eth_uninstallFilter(_filterIdentifier) {
120082
+ throw new Error("Method not implemented.");
120083
+ }
120084
+ eth_unsubscribe(_subscriptionId) {
120085
+ throw new Error("Method not implemented.");
120086
+ }
120087
+ });
120088
+ var createChainContract = /* @__PURE__ */ __name$a(async (signer, stakingTokenAddress, genesisBlockHash, rewardsContractAddress, minWithdrawalBlocks, gas = {}) => {
120089
+ try {
120090
+ const xyoChainFactory = new StakedXyoChain__factory(signer);
120091
+ const contractTransactionResponse = await (await xyoChainFactory.deploy(ETH_ZERO_ADDRESS, 0n, hexToBigInt(genesisBlockHash), toEthAddress(rewardsContractAddress), minWithdrawalBlocks, toEthAddress(stakingTokenAddress), gas)).waitForDeployment();
120092
+ const xyoChainContractAddress = await contractTransactionResponse.getAddress();
120093
+ return assertEx(asAddress(xyoChainContractAddress), () => "Invalid staking contract address");
120094
+ } catch (ex) {
120095
+ console.log(ex);
120096
+ throw ex;
120097
+ }
120098
+ }, "createChainContract");
120099
+ var gasConfig = /* @__PURE__ */ __name$a(() => {
120100
+ return {
120101
+ gasLimit: 2e6,
120102
+ gasPrice: parseUnits$1("100", "gwei")
120103
+ };
120104
+ }, "gasConfig");
120105
+ var createChainRewardsContract = /* @__PURE__ */ __name$a(async (signer, genesisReward = 0n, gas = gasConfig()) => {
120106
+ try {
120107
+ const xyoChainRewardsFactory = new XyoChainRewards__factory(signer);
120108
+ const xyoChainRewardsFactoryResponse = await (await xyoChainRewardsFactory.deploy(toFixedPoint(1000n), 1000000n, 95n, 100n, toFixedPoint(30n), genesisReward, 18n, gas)).waitForDeployment();
120109
+ const xyoChainRewardsAddress = await xyoChainRewardsFactoryResponse.getAddress();
120110
+ return assertEx(asAddress(xyoChainRewardsAddress), () => "Invalid rewards contract address");
120111
+ } catch (ex) {
120112
+ console.log(ex);
120113
+ throw ex;
120114
+ }
120115
+ }, "createChainRewardsContract");
120116
+ var nextContractAddressForAddress = /* @__PURE__ */ __name$a(async (address, provider) => {
120117
+ const deployerAddress = toEthAddress(address);
120118
+ const nonce = await provider.getTransactionCount(deployerAddress);
120119
+ const contractAddress = getCreateAddress({
120120
+ from: deployerAddress,
120121
+ nonce
120122
+ });
120123
+ return assertEx(asAddress(contractAddress), () => "Unable to convert contract address to address");
120124
+ }, "nextContractAddressForAddress");
120125
+ var nextContractAddress = /* @__PURE__ */ __name$a(async (signer) => {
120126
+ const provider = assertEx(signer.provider, () => "Unable to obtain provider from signer");
120127
+ const address = assertEx(asAddress(await signer.getAddress()), () => "Unable to obtain address from signer");
120128
+ return await nextContractAddressForAddress(address, provider);
120129
+ }, "nextContractAddress");
120130
+
120131
+ // src/createChain.ts
120132
+ async function createChain(signer, stakingTokenAddress, initialBlockProducer, rewardsContractAddress, genesisBlockRewardAmount, genesisBlockRewardAddress, minWithdrawalBlocks, gas) {
120133
+ const ethStakingTokenAddress = toEthAddress(stakingTokenAddress);
120134
+ const rewardContractAddressResolved = rewardsContractAddress ?? await createChainRewardsContract(signer, genesisBlockRewardAmount, gas);
120135
+ const contractAddress = await nextContractAddress(signer);
120136
+ const genesisBlock = await createGenesisBlock(initialBlockProducer, contractAddress, genesisBlockRewardAmount, genesisBlockRewardAddress);
120137
+ const chainId = toAddress(await createChainContract(signer, ethStakingTokenAddress, await PayloadBuilder.hash(genesisBlock[0]), rewardContractAddressResolved, minWithdrawalBlocks, gas));
120138
+ return [
120139
+ chainId,
120140
+ genesisBlock,
120141
+ rewardContractAddressResolved
120142
+ ];
120143
+ }
120144
+ __name$a(createChain, "createChain");
120145
+ function _ts_decorate(decorators, target, key, desc) {
120146
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
120147
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
120148
+ 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;
120149
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
120150
+ }
120151
+ __name$a(_ts_decorate, "_ts_decorate");
120152
+ var ethStakeToStake = /* @__PURE__ */ __name$a((ethStake) => {
120153
+ const stake = {
120154
+ id: Number(ethStake.id),
120155
+ staked: toAddress(ethStake.staked),
120156
+ staker: toAddress(ethStake.staker),
120157
+ amount: asAttoXL1(ethStake.amount),
120158
+ addBlock: Number(ethStake.addBlock),
120159
+ removeBlock: Number(ethStake.removeBlock),
120160
+ withdrawBlock: Number(ethStake.withdrawBlock)
120161
+ };
120162
+ return stake;
120163
+ }, "ethStakeToStake");
120164
+ var EthereumChainStakeViewer = class extends AbstractCreatable {
120165
+ static {
120166
+ __name$a(this, "EthereumChainStakeViewer");
120167
+ }
120168
+ _callMutex = new Mutex$1();
120169
+ _chainId;
120170
+ _deploymentBlock = 0;
120171
+ _stakeCache = /* @__PURE__ */ new Map();
120172
+ get chainId() {
120173
+ return assertEx(this._chainId, () => "Chain ID not set");
120174
+ }
120175
+ get contract() {
120176
+ return assertEx(this.params.contract, () => new Error("Contract not defined"));
120177
+ }
120178
+ get minWithdrawalBlocks() {
120179
+ return 0;
120180
+ }
120181
+ get rewardsContract() {
120182
+ return toAddress("0x000000000000000000000000000000");
120183
+ }
120184
+ get stakeEvents() {
120185
+ return this.params.stakeEventsViewer;
120186
+ }
120187
+ get stakingTokenAddress() {
120188
+ return toAddress("0x000000000000000000000000000011");
120189
+ }
120190
+ async active() {
120191
+ return await this._callMutex.runExclusive(async () => {
120192
+ return await this.contract.active();
120193
+ });
120194
+ }
120195
+ async activeByAddressStaked(address) {
120196
+ return await this._callMutex.runExclusive(async () => {
120197
+ return await this.contract.activeByAddressStaked(toEthAddress(address));
120198
+ });
120199
+ }
120200
+ async activeByStaker(address) {
120201
+ return await this._callMutex.runExclusive(async () => {
120202
+ return await this.contract.activeByStaker(toEthAddress(address));
120203
+ });
120204
+ }
120205
+ async pending() {
120206
+ return await this._callMutex.runExclusive(async () => {
120207
+ return await this.contract.pending();
120208
+ });
120209
+ }
120210
+ async pendingByStaker(staker) {
120211
+ return await this._callMutex.runExclusive(async () => {
120212
+ return await this.contract.pendingByStaker(toEthAddress(staker));
120213
+ });
120214
+ }
120215
+ async stakeById(id) {
120216
+ return await this._callMutex.runExclusive(async () => {
120217
+ const startTime = Date.now();
120218
+ const cachedStake = this._stakeCache.get(id);
120219
+ if (cachedStake) {
120220
+ return cachedStake;
120221
+ }
120222
+ const ethResult = await this.contract.getStakeById(id);
120223
+ const stake = ethStakeToStake(ethResult);
120224
+ this._stakeCache.set(stake.id, stake);
120225
+ this.logger?.log(`EthereumChainStake: stakeById(${id}) took ${Date.now() - startTime}ms`);
120226
+ return stake;
120227
+ });
120228
+ }
120229
+ async stakeByStaker(staker, slot) {
120230
+ return await this._callMutex.runExclusive(async () => {
120231
+ const ethResult = await this.contract.getStake(toEthAddress(staker), slot);
120232
+ const stake = ethStakeToStake(ethResult);
120233
+ this._stakeCache.set(stake.id, stake);
120234
+ return stake;
120235
+ });
120236
+ }
120237
+ async stakesByStaked(staked, range = [
120238
+ 0,
120239
+ void 0
120240
+ ]) {
120241
+ const events = await this.stakeEvents.stakeEvents([
120242
+ Math.max(range[0], this._deploymentBlock),
120243
+ range.at(1) ?? "latest"
120244
+ ], {
120245
+ name: "StakeAdded",
120246
+ args: {
120247
+ staked
120248
+ }
120249
+ });
120250
+ const result = [];
120251
+ for (const event of events) {
120252
+ if (toAddress(event.args.staked) === toAddress(staked)) {
120253
+ result.push(await this.stakeById(event.args.id));
120254
+ }
120255
+ }
120256
+ return result;
120257
+ }
120258
+ async stakesByStaker(staker, range = [
120259
+ 0,
120260
+ void 0
120261
+ ]) {
120262
+ const events = await this.stakeEvents.stakeEvents([
120263
+ Math.max(range[0], this._deploymentBlock),
120264
+ range.at(1) ?? "latest"
120265
+ ], {
120266
+ name: "StakeAdded",
120267
+ args: {
120268
+ staker
120269
+ }
120270
+ });
120271
+ const result = [];
120272
+ for (const event of events) {
120273
+ if (toAddress(event.args.staker) === toAddress(staker)) {
120274
+ result.push(await this.stakeById(event.args.id));
120275
+ }
120276
+ }
120277
+ return result;
120278
+ }
120279
+ async withdrawn() {
120280
+ return await this._callMutex.runExclusive(async () => {
120281
+ return await this.contract.withdrawn();
120282
+ });
120283
+ }
120284
+ async withdrawnByStaker(staker) {
120285
+ return await this._callMutex.runExclusive(async () => {
120286
+ return await this.contract.withdrawnByStaker(toEthAddress(staker));
120287
+ });
120288
+ }
120289
+ async startHandler() {
120290
+ this._chainId = toAddress(await this.contract.chainId());
120291
+ await this.contract.on(this.contract.getEvent("StakeAdded"), (staked, staker, id, amount, event) => {
120292
+ this._stakeCache.set(Number(id), {
120293
+ id: Number(id),
120294
+ staked: toAddress(staked),
120295
+ staker: toAddress(staker),
120296
+ amount: asAttoXL1(amount),
120297
+ addBlock: event.blockNumber,
120298
+ removeBlock: 0,
120299
+ withdrawBlock: 0
120300
+ });
120301
+ });
120302
+ await this.contract.on(this.contract.getEvent("StakeRemoved"), (staked, staker, id, amount, event) => {
120303
+ const stake = assertEx(this._stakeCache.get(Number(id)));
120304
+ this._stakeCache.set(Number(id), {
120305
+ ...stake,
120306
+ removeBlock: event.blockNumber
120307
+ });
120308
+ });
120309
+ await this.contract.on(this.contract.getEvent("StakeWithdrawn"), (staked, staker, id, amount, event) => {
120310
+ const stake = assertEx(this._stakeCache.get(Number(id)));
120311
+ this._stakeCache.set(Number(id), {
120312
+ ...stake,
120313
+ withdrawBlock: event.blockNumber
120314
+ });
120315
+ });
120316
+ const allStakeEvents = (await Promise.all([
120317
+ this.stakeEvents.stakeEvents([
120318
+ this._deploymentBlock,
120319
+ "latest"
120320
+ ], {
120321
+ name: "StakeAdded"
120322
+ }),
120323
+ this.stakeEvents.stakeEvents([
120324
+ this._deploymentBlock,
120325
+ "latest"
120326
+ ], {
120327
+ name: "StakeRemoved"
120328
+ }),
120329
+ this.stakeEvents.stakeEvents([
120330
+ this._deploymentBlock,
120331
+ "latest"
120332
+ ], {
120333
+ name: "StakeWithdrawn"
120334
+ })
120335
+ ])).flat().toSorted((a, b) => a.time - b.time);
120336
+ for (const event of allStakeEvents) {
120337
+ switch (event.name) {
120338
+ case "StakeAdded": {
120339
+ this._stakeCache.set(event.args.id, {
120340
+ id: event.args.id,
120341
+ staked: event.args.staked,
120342
+ staker: event.args.staker,
120343
+ amount: event.args.amount,
120344
+ addBlock: event.time,
120345
+ removeBlock: 0,
120346
+ withdrawBlock: 0
120347
+ });
120348
+ break;
120349
+ }
120350
+ case "StakeRemoved": {
120351
+ const stake = assertEx(this._stakeCache.get(event.args.id));
120352
+ this._stakeCache.set(event.args.id, {
120353
+ ...stake,
120354
+ removeBlock: event.time
120355
+ });
120356
+ break;
120357
+ }
120358
+ case "StakeWithdrawn": {
120359
+ const stake = assertEx(this._stakeCache.get(event.args.id));
120360
+ this._stakeCache.set(event.args.id, {
120361
+ ...stake,
120362
+ withdrawBlock: event.time
120363
+ });
120364
+ break;
120365
+ }
120366
+ }
120367
+ }
120368
+ for (const event of allStakeEvents) {
120369
+ await this.stakeById(event.args.id);
120370
+ }
120371
+ }
120372
+ };
120373
+ EthereumChainStakeViewer = _ts_decorate([
120374
+ creatable()
120375
+ ], EthereumChainStakeViewer);
120376
+ function _ts_decorate2(decorators, target, key, desc) {
120377
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
120378
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
120379
+ 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;
120380
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
120381
+ }
120382
+ __name$a(_ts_decorate2, "_ts_decorate");
120383
+ var isStakeLogEventName = /* @__PURE__ */ __name$a((name) => {
120384
+ return isString$1(name) && [
120385
+ "StakeAdded",
120386
+ "StakeRemoved",
120387
+ "StakeWithdrawn"
120388
+ ].includes(name);
120389
+ }, "isStakeLogEventName");
120390
+ var EthereumChainStakeEvents = class extends AbstractCreatable {
120391
+ static {
120392
+ __name$a(this, "EthereumChainStakeEvents");
120393
+ }
120394
+ eventCache = /* @__PURE__ */ new Map();
120395
+ get contract() {
120396
+ return assertEx(this.params.contract, () => new Error("Contract not defined"));
120397
+ }
120398
+ get deploymentBlock() {
120399
+ return this.params.deploymentBlock ?? 0;
120400
+ }
120401
+ async positionCount(range) {
120402
+ const events = await this.stakeEvents(range);
120403
+ const positionIds = events.map((e) => e.args.id);
120404
+ return Math.max(-1, ...positionIds) + 1;
120405
+ }
120406
+ stakeEvents(range = [
120407
+ 0,
120408
+ "latest"
120409
+ ], filter) {
120410
+ const allEvents = [
120411
+ ...this.eventCache.values()
120412
+ ];
120413
+ const result = allEvents.filter((e) => {
120414
+ if (range[1] !== "latest" && e.time > range[1]) {
120415
+ return false;
120416
+ }
120417
+ if (e.time < range[0]) {
120418
+ return false;
120419
+ }
120420
+ if (isDefined(filter?.name) && e.name !== filter.name) {
120421
+ return false;
120422
+ }
120423
+ if (isDefined(filter?.args?.id) && e.args.id !== filter.args.id) {
120424
+ return false;
120425
+ }
120426
+ if (isDefined(filter?.args?.staked) && e.args.staked !== filter.args.staked) {
120427
+ return false;
120428
+ }
120429
+ if (isDefined(filter?.args?.staker) && e.args.staker !== filter.args.staker) {
120430
+ return false;
120431
+ }
120432
+ return true;
120433
+ });
120434
+ return result;
120435
+ }
120436
+ onEventHandler(staked, staker, id, amount, { eventName, blockNumber }) {
120437
+ if (blockNumber === void 0) {
120438
+ this.logger?.warn(`Received ${eventName} event with ${blockNumber} blockNumber, ignoring...`);
120439
+ return;
120440
+ }
120441
+ if (!isStakeLogEventName(eventName)) {
120442
+ this.logger?.warn(`Received event with unsupported name '${eventName}'`);
120443
+ return;
120444
+ }
120445
+ this.logger?.log(`Processing ${eventName} event for stake ID ${id} at block ${blockNumber}`);
120446
+ const cacheKey = `${Number(id)}|${eventName}|${staker}`;
120447
+ const existingStakeEvent = this.eventCache.get(cacheKey);
120448
+ const stakeEvent = {
120449
+ name: eventName,
120450
+ args: {
120451
+ id: Number(id),
120452
+ staked: toAddress(staked),
120453
+ staker: toAddress(staker),
120454
+ amount: asAttoXL1(amount)
120455
+ },
120456
+ time: blockNumber
120457
+ };
120458
+ if (isDefined(existingStakeEvent)) {
120459
+ this.logger?.warn(`Received ${eventName} event for stake ID ${id} that is already cached, updating cache...`);
120460
+ this.logger?.warn("1");
120461
+ this.logger?.warn("Previous event", existingStakeEvent);
120462
+ this.logger?.warn("2");
120463
+ this.logger?.warn("New event", stakeEvent);
120464
+ this.logger?.warn("3");
120465
+ }
120466
+ this.eventCache.set(cacheKey, stakeEvent);
120467
+ return stakeEvent;
120468
+ }
120469
+ async startHandler() {
120470
+ try {
120471
+ const currentEthBlock = assertEx(await this.contract.runner?.provider?.getBlockNumber(), () => new Error("Failed to egt currentEthBlock"));
120472
+ await this.contract.on(this.contract.getEvent("StakeAdded"), (staked, staker, id, amount, event) => {
120473
+ this.onEventHandler(staked, staker, id, amount, event);
120474
+ });
120475
+ await this.contract.on(this.contract.getEvent("StakeRemoved"), (staked, staker, id, amount, event) => {
120476
+ this.onEventHandler(staked, staker, id, amount, event);
120477
+ });
120478
+ await this.contract.on(this.contract.getEvent("StakeWithdrawn"), (staked, staker, id, amount, event) => {
120479
+ this.onEventHandler(staked, staker, id, amount, event);
120480
+ });
120481
+ const allStakeEvents = (await Promise.all([
120482
+ this.stakeEventsNative([
120483
+ this.deploymentBlock,
120484
+ currentEthBlock
120485
+ ], {
120486
+ name: "StakeAdded"
120487
+ }),
120488
+ this.stakeEventsNative([
120489
+ this.deploymentBlock,
120490
+ currentEthBlock
120491
+ ], {
120492
+ name: "StakeRemoved"
120493
+ }),
120494
+ this.stakeEventsNative([
120495
+ this.deploymentBlock,
120496
+ currentEthBlock
120497
+ ], {
120498
+ name: "StakeWithdrawn"
120499
+ })
120500
+ ])).flat().toSorted((a, b) => a.time - b.time);
120501
+ console.warn(`Caching ${allStakeEvents.length} stake events from chain starting at block ${this.deploymentBlock}`);
120502
+ for (const event of allStakeEvents) {
120503
+ this.eventCache.set(`${Number(event.args.id)}|${event.name}|${event.args.staker}`, event);
120504
+ }
120505
+ } catch (error) {
120506
+ this.logger?.error("EthereumChainStakeEvents failed to start:", error);
120507
+ throw error;
120508
+ }
120509
+ }
120510
+ async stakeEventsNative(range = [
120511
+ 0,
120512
+ "latest"
120513
+ ], filter) {
120514
+ const name = filter?.name;
120515
+ if (isDefined(name)) {
120516
+ const stakedFilter = filter?.args?.staked;
120517
+ const stakerFilter = filter?.args?.staker;
120518
+ const stakedFilterEth = isDefined(stakedFilter) ? toEthAddress(stakedFilter) : void 0;
120519
+ const stakerFilterEth = isDefined(stakerFilter) ? toEthAddress(stakerFilter) : void 0;
120520
+ let ethEvents = [];
120521
+ const ethFilter = this.contract.filters[name](stakedFilterEth, stakerFilterEth);
120522
+ ethEvents = await this.contract.queryFilter(ethFilter, range[0], range[1]);
120523
+ return ethEvents.map((e) => {
120524
+ assertEx(e.eventName === name, () => `Event name mismatch expected '${name}' but got '${e.eventName}'`);
120525
+ return this.onEventHandler(e.args.staked, e.args.by, e.args.id, e.args.amount, e);
120526
+ }).filter(exists$1);
120527
+ } else {
120528
+ throw new Error("Only filtered stake events (by name) are supported");
120529
+ }
120530
+ }
120531
+ };
120532
+ EthereumChainStakeEvents = _ts_decorate2([
120533
+ creatable()
120534
+ ], EthereumChainStakeEvents);
120535
+
119846
120536
  var __defProp$f = Object.defineProperty;
119847
120537
  var __name$9 = (target, value) => __defProp$f(target, "name", { value, configurable: true });
119848
- var initArchivistSync = /* @__PURE__ */ __name$9(async (name, inArchivist, outArchivist, frequency = 1e3, max = 1e3, traceProvider) => {
120538
+ var NodeXyoViewer = class extends AbstractCreatable {
120539
+ static {
120540
+ __name$9(this, "NodeXyoViewer");
120541
+ }
120542
+ // TODO: Make configurable with defaults
120543
+ _tracer;
120544
+ addressBalanceDivinerPath = "XYOChain:Chain:AddressBalanceDiviner";
120545
+ finalizedArchivistPath = "XYOChain:Chain:Finalized";
120546
+ headValidationDivinerPath = "XYOChain:Chain:HeadValidationDiviner";
120547
+ transferBalanceDivinerPath = "XYOChain:Chain:AddressTransferDiviner";
120548
+ _addressBalanceDiviner;
120549
+ _chainId;
120550
+ _finalizedArchivist;
120551
+ _rewardMultipliers;
120552
+ _signedHydratedBlockCache;
120553
+ _signedHydratedTransactionCache;
120554
+ _transferBalanceDiviner;
120555
+ get context() {
120556
+ return assertEx(this.params.context, () => "NodeXyoViewer requires a context");
120557
+ }
120558
+ get initRewardsCache() {
120559
+ return this.params.initRewardsCache ?? true;
120560
+ }
120561
+ get node() {
120562
+ return this.params.node;
120563
+ }
120564
+ get rewardMultipliers() {
120565
+ this._rewardMultipliers = this._rewardMultipliers ?? this.params.rewardMultipliers ?? {};
120566
+ return this._rewardMultipliers;
120567
+ }
120568
+ get stake() {
120569
+ return this.context.stake;
120570
+ }
120571
+ get transfersSummaryContext() {
120572
+ return this.params.transfersSummaryContext ?? {
120573
+ ...this.context
120574
+ };
120575
+ }
120576
+ async accountBalance(address) {
120577
+ return await spanRootAsync("accountBalance", async () => {
120578
+ const diviner = await this.getAddressBalanceDiviner();
120579
+ const query = new PayloadBuilder({
120580
+ schema: AddressSchema
120581
+ }).fields({
120582
+ address
120583
+ }).build();
120584
+ const result = await diviner.divine([
120585
+ query
120586
+ ]);
120587
+ const chainSummary = assertEx(result.find(isChainSummaryBalances), () => "Failed to divine chain summary balances");
120588
+ const balances = chainSummary.balances;
120589
+ const signedBalance = balances[address] === void 0 ? 0n : parseSignedBigInt(balances[address]);
120590
+ return asAttoXL1(signedBalance > 0n ? signedBalance : 0n);
120591
+ }, this.tracer);
120592
+ }
120593
+ async accountBalanceHistory(address, rangeOrHash) {
120594
+ return await spanRootAsync("accountHistory", async () => {
120595
+ const range = asRange(rangeOrHash);
120596
+ const startingRange = asXL1BlockRange(range ?? [
120597
+ 0,
120598
+ await this.currentBlockNumber()
120599
+ ], {
120600
+ name: "accountBalanceHistory"
120601
+ });
120602
+ const blockNumbers = await this.distillTransferHistory(address, startingRange);
120603
+ const blocks = (await Promise.all(blockNumbers.map(async (bn) => await this.blockByNumber(bn)))).filter(exists$1);
120604
+ const result = [];
120605
+ for (const block of blocks) {
120606
+ const transferIndexes = block[0].payload_schemas.map((schema, index) => schema === TransferSchema ? index : void 0).filter(exists$1);
120607
+ const transfers = transferIndexes.map((index) => {
120608
+ const hash = block[0].payload_hashes[index];
120609
+ return assertEx(block[1].find((p) => p._hash === hash), () => `Could not find Transfer with hash ${hash} in block ${block[0]._hash}`);
120610
+ }).filter(exists$1).filter((t) => t.from === address || isDefined(t.transfers[address]));
120611
+ if (transfers.length === 0) {
120612
+ continue;
120613
+ }
120614
+ const pairs = transfers.map((transfer) => {
120615
+ return [
120616
+ block[0],
120617
+ transfer
120618
+ ];
120619
+ });
120620
+ result.push(...pairs.map(([block2, transfer]) => [
120621
+ block2,
120622
+ null,
120623
+ transfer
120624
+ ]));
120625
+ }
120626
+ return result;
120627
+ }, this.tracer);
120628
+ }
120629
+ async blockByHash(hash) {
120630
+ return await spanRootAsync("blockByHash", async () => {
120631
+ const cache = await this.getHydratedBlockCache();
120632
+ return await cache.get(hash);
120633
+ }, this.tracer);
120634
+ }
120635
+ async blockByNumber(blockNumber) {
120636
+ return await spanRootAsync("blockByNumber", async () => {
120637
+ return await hydratedBlockByNumber(this.context, blockNumber);
120638
+ }, this.tracer);
120639
+ }
120640
+ async blocksByHash(hash, limit = 10) {
120641
+ return await spanRootAsync("blocksByHash", async () => {
120642
+ assertEx(limit > 0, () => "limit must be greater than 0");
120643
+ assertEx(limit <= 100, () => "limit must be less than 100");
120644
+ const blocks = [];
120645
+ let current = await this.blockByHash(hash);
120646
+ while (current && blocks.length < limit) {
120647
+ blocks.push(current);
120648
+ const previousHash = current[0].previous;
120649
+ if (previousHash === null) break;
120650
+ current = await this.blockByHash(previousHash);
120651
+ }
120652
+ return blocks;
120653
+ }, this.tracer);
120654
+ }
120655
+ async chainId() {
120656
+ return await spanRootAsync("chainId", async () => {
120657
+ if (this._chainId !== void 0) return this._chainId;
120658
+ const block = await this.currentBlock();
120659
+ this._chainId = block[0].chain;
120660
+ return this._chainId;
120661
+ }, this.tracer);
120662
+ }
120663
+ async chainIdAtBlock(blockNumber) {
120664
+ return await spanRootAsync("chainIdAtBlock", async () => {
120665
+ if (this._chainId !== void 0) return this._chainId;
120666
+ const block = await this.blockByNumber(blockNumber);
120667
+ this._chainId = block?.[0].chain;
120668
+ return this._chainId;
120669
+ }, this.tracer);
120670
+ }
120671
+ async currentBlock() {
120672
+ return await spanRootAsync("currentBlock", async () => {
120673
+ const currentHead = assertEx(await this.getCurrentHead(), () => "Could not find most recent block");
120674
+ const cache = await this.getHydratedBlockCache();
120675
+ const block = await cache.get(currentHead._hash);
120676
+ if (!block) {
120677
+ console.log(`Could not find current block with hash ${currentHead._hash}`);
120678
+ }
120679
+ return assertEx(block, () => "Could not find current block");
120680
+ }, this.tracer);
120681
+ }
120682
+ async currentBlockHash() {
120683
+ return await spanRootAsync("currentBlockHash", async () => {
120684
+ const currentHead = assertEx(await this.getCurrentHead(), () => "Could not find most recent block");
120685
+ return currentHead._hash;
120686
+ }, this.tracer);
120687
+ }
120688
+ async currentBlockNumber() {
120689
+ return await spanRootAsync("currentBlockNumber", async () => {
120690
+ const currentHead = assertEx(await this.getCurrentHead(), () => "Could not find most recent block");
120691
+ return asXL1BlockNumber(currentHead.block, {
120692
+ name: "currentBlockNumber"
120693
+ });
120694
+ }, this.tracer);
120695
+ }
120696
+ forkHistory() {
120697
+ throw new Error("Method not implemented.");
120698
+ }
120699
+ networkStakeStepRewardAddressHistory(_address) {
120700
+ throw new Error("Method not implemented.");
120701
+ }
120702
+ networkStakeStepRewardAddressReward(_context, _address) {
120703
+ throw new Error("Method not implemented.");
120704
+ }
120705
+ networkStakeStepRewardAddressShare(_context, _address) {
120706
+ throw new Error("Method not implemented.");
120707
+ }
120708
+ networkStakeStepRewardClaimedByAddress(_address) {
120709
+ throw new Error("Method not implemented.");
120710
+ }
120711
+ async networkStakeStepRewardForPosition(position, range) {
120712
+ return await timeBudget("networkStakeStepRewardForPosition", this.logger, async () => {
120713
+ const externalRange = await externalBlockRangeFromXL1BlockRange(this.context, range);
120714
+ const positionCount = await this.context.stake.stakeEvents.positionCount(externalRange);
120715
+ if (positionCount === 0) {
120716
+ return [
120717
+ 0n,
120718
+ 0n
120719
+ ];
120720
+ }
120721
+ const steps = blockRangeSteps(range, [
120722
+ 3,
120723
+ 4,
120724
+ 5,
120725
+ 6,
120726
+ 7
120727
+ ]);
120728
+ const rewards = await Promise.all(steps.map((step) => this.networkStakeStepRewardForStepForPosition(step, position)));
120729
+ const positionReward = rewards.reduce((a, b) => a + b[0], 0n);
120730
+ const totalReward = rewards.reduce((a, b) => a + b[1], 0n);
120731
+ return [
120732
+ positionReward,
120733
+ totalReward
120734
+ ];
120735
+ }, 100);
120736
+ }
120737
+ async networkStakeStepRewardForStep(stepContext) {
120738
+ return await stepRewardTotal(this.context, stepContext, this.rewardMultipliers);
120739
+ }
120740
+ async networkStakeStepRewardForStepForPosition(stepIdentity, position) {
120741
+ const stepIdentityString = toStepIdentityString(stepIdentity);
120742
+ const cacheKey = `${stepIdentityString}|${position}`;
120743
+ return await withContextCacheResponse(this.context, "NodeXyoViewer-networkStakeStepRewardForStepForPosition", cacheKey, async () => {
120744
+ const range = await externalBlockRangeFromStep(this.context, stepIdentity);
120745
+ const stake = await this.stakeById(position);
120746
+ const numerator = stake.staked === XYO_NETWORK_STAKING_ADDRESS ? await weightedStakeForRangeByPosition(this.context, range, position) : 0n;
120747
+ const denominator = await this.stepWeightedDenominator(stepIdentity);
120748
+ const totalReward = await this.networkStakeStepRewardForStep(stepIdentity);
120749
+ const positionReward = denominator > 0n ? totalReward * numerator / denominator : 0n;
120750
+ const result = [
120751
+ positionReward,
120752
+ totalReward
120753
+ ];
120754
+ return result;
120755
+ });
120756
+ }
120757
+ async networkStakeStepRewardPoolRewards(step) {
120758
+ const stakes = await this.context.stake.stakesByStaked(XYO_NETWORK_STAKING_ADDRESS);
120759
+ const rewards = [];
120760
+ for (const stake of stakes) {
120761
+ rewards.push([
120762
+ stake.staker,
120763
+ await this.networkStakeStepRewardForStepForPosition(step, stake.id)
120764
+ ]);
120765
+ }
120766
+ const result = {};
120767
+ for (const [staker, reward] of rewards) {
120768
+ result[staker] = (result[staker] ?? 0n) + reward[0];
120769
+ }
120770
+ const filtered = Object.fromEntries(Object.entries(result).filter(([_, v]) => v > 0n));
120771
+ return filtered;
120772
+ }
120773
+ networkStakeStepRewardPoolShares(_context) {
120774
+ throw new Error("Method not implemented.");
120775
+ }
120776
+ async networkStakeStepRewardPositionWeight(stepContext, position) {
120777
+ return await networkStakeStepRewardPositionWeight(this.context, stepContext, position);
120778
+ }
120779
+ networkStakeStepRewardPotentialPositionLoss(_context, _position) {
120780
+ throw new Error("Method not implemented.");
120781
+ }
120782
+ networkStakeStepRewardRandomizer(_context) {
120783
+ throw new Error("Method not implemented.");
120784
+ }
120785
+ async networkStakeStepRewardStakerCount(stepContext) {
120786
+ return Object.keys(await allStakersForStep(this.context, stepContext, XYO_NETWORK_STAKING_ADDRESS)).length;
120787
+ }
120788
+ networkStakeStepRewardUnclaimedByAddress(_address) {
120789
+ throw new Error("Method not implemented.");
120790
+ }
120791
+ networkStakeStepRewardWeightForAddress(_context, _address) {
120792
+ throw new Error("Method not implemented.");
120793
+ }
120794
+ async networkStakeStepRewardsForPosition(position, range) {
120795
+ const steps = blockRangeSteps(range, [
120796
+ 3,
120797
+ 4,
120798
+ 5,
120799
+ 6,
120800
+ 7,
120801
+ 8
120802
+ ]);
120803
+ const rewards = await Promise.all(steps.map(async (step) => {
120804
+ return [
120805
+ toStepIdentityString(step),
120806
+ await this.networkStakeStepRewardForStepForPosition(step, position)
120807
+ ];
120808
+ }));
120809
+ const result = {};
120810
+ for (const [step, reward] of rewards) {
120811
+ result[step] = reward;
120812
+ }
120813
+ const filtered = Object.fromEntries(Object.entries(result).filter(([_, v]) => v[0] > 0n));
120814
+ return filtered;
120815
+ }
120816
+ async networkStakeStepRewardsForRange(range) {
120817
+ return await timeBudget("networkStakeStepRewardsForRange", this.logger, async () => {
120818
+ const steps = blockRangeSteps(range, [
120819
+ 3,
120820
+ 4,
120821
+ 5,
120822
+ 6,
120823
+ 7,
120824
+ 8
120825
+ ]);
120826
+ const rewards = await Promise.all(steps.map(async (step) => {
120827
+ return await this.networkStakeStepRewardForStep(step);
120828
+ }));
120829
+ return rewards.reduce((a, b) => a + b, 0n);
120830
+ }, 100);
120831
+ }
120832
+ async networkStakeStepRewardsForStepLevel(stepLevel, range) {
120833
+ const steps = blockRangeSteps(range, [
120834
+ stepLevel
120835
+ ]);
120836
+ const rewards = await Promise.all(steps.map(async (step) => {
120837
+ return await this.networkStakeStepRewardForStep(step);
120838
+ }));
120839
+ return rewards.reduce((a, b) => a + b, 0n);
120840
+ }
120841
+ async stakeById(id) {
120842
+ return await this.stake.stakeById(id);
120843
+ }
120844
+ async stakeByStaker(staker, slot) {
120845
+ return await this.stake.stakeByStaker(staker, slot);
120846
+ }
120847
+ async stakedByStaker(staker) {
120848
+ const result = /* @__PURE__ */ new Set();
120849
+ let slot = 0;
120850
+ while (true) {
120851
+ try {
120852
+ const ethStake = await this.stake.stakeByStaker(staker, slot);
120853
+ result.add(toAddress(ethStake.staked));
120854
+ slot++;
120855
+ } catch {
120856
+ break;
120857
+ }
120858
+ }
120859
+ return [
120860
+ ...result
120861
+ ];
120862
+ }
120863
+ async stakesByStaked(staked) {
120864
+ return await this.stake.stakesByStaked(staked);
120865
+ }
120866
+ async stakesByStaker(staker) {
120867
+ return await this.stake.stakesByStaker(staker);
120868
+ }
120869
+ async transactionByBlockHashAndIndex(blockHash, transactionIndex = 0) {
120870
+ return await spanRootAsync("transactionByBlockHashAndIndex", async () => {
120871
+ assertEx(transactionIndex >= 0, () => "transactionIndex must be greater than or equal to 0");
120872
+ try {
120873
+ const block = await this.blockByHash(blockHash);
120874
+ if (!block) return null;
120875
+ const blockBoundWitnessIndexes = block[0].payload_schemas.map((schema, index) => schema === BoundWitnessSchema ? index : void 0).filter(exists$1);
120876
+ const blockBoundWitnessHashes = new Set(blockBoundWitnessIndexes.map((index) => block[0].payload_hashes[index]));
120877
+ const blockBoundWitnesses = block[1].filter((payload) => blockBoundWitnessHashes.has(payload._hash) || blockBoundWitnessHashes.has(payload._dataHash));
120878
+ const blockTransactionBoundWitnesses = blockBoundWitnesses.filter(isTransactionBoundWitnessWithStorageMeta);
120879
+ const transaction = blockTransactionBoundWitnesses.at(transactionIndex);
120880
+ if (!transaction) return null;
120881
+ return await this.transactionByHash(transaction._hash);
120882
+ } catch {
120883
+ return null;
120884
+ }
120885
+ }, this.tracer);
120886
+ }
120887
+ async transactionByBlockNumberAndIndex(blockNumber, transactionIndex = 0) {
120888
+ return await spanRootAsync("transactionByBlockNumberAndIndex", async () => {
120889
+ try {
120890
+ const block = await this.blockByNumber(blockNumber);
120891
+ if (!block) return null;
120892
+ return await this.transactionByBlockHashAndIndex(block[0]._hash, transactionIndex);
120893
+ } catch {
120894
+ return null;
120895
+ }
120896
+ }, this.tracer);
120897
+ }
120898
+ async transactionByHash(transactionHash) {
120899
+ return await spanRootAsync("transactionByHash", async () => {
120900
+ try {
120901
+ const cache = await this.getHydratedTransactionCache();
120902
+ const hydratedTransaction = await cache.get(transactionHash);
120903
+ return hydratedTransaction ?? null;
120904
+ } catch {
120905
+ return null;
120906
+ }
120907
+ }, this.tracer);
120908
+ }
120909
+ async transferBalance(address) {
120910
+ return await spanRootAsync("transferBalance", async () => {
120911
+ const diviner = await this.getTransferBalanceDiviner();
120912
+ const query = new PayloadBuilder({
120913
+ schema: AddressSchema
120914
+ }).fields({
120915
+ address
120916
+ }).build();
120917
+ const result = await diviner.divine([
120918
+ query
120919
+ ]);
120920
+ const chainSummary = result.find(isChainSummaryTransfers);
120921
+ const transfers = chainSummary?.transfers ?? {};
120922
+ let transferBalance = 0n;
120923
+ for (const [from, transfer] of Object.entries(transfers)) {
120924
+ if (from === address) {
120925
+ for (const [, amount] of Object.entries(transfer)) {
120926
+ transferBalance += parseSignedBigInt(amount);
120927
+ }
120928
+ }
120929
+ }
120930
+ return asAttoXL1(transferBalance > 0n ? transferBalance : 0n);
120931
+ }, this.tracer);
120932
+ }
120933
+ transferBalanceHistory(_address) {
120934
+ throw new Error("Method not implemented.");
120935
+ }
120936
+ async transferPairBalance(pair) {
120937
+ return await spanRootAsync("transferPairBalance", async () => {
120938
+ const diviner = await this.getTransferBalanceDiviner();
120939
+ const query = new PayloadBuilder({
120940
+ schema: AddressPairSchema
120941
+ }).fields({
120942
+ addresses: [
120943
+ pair[0],
120944
+ pair[1]
120945
+ ]
120946
+ }).build();
120947
+ const result = await diviner.divine([
120948
+ query
120949
+ ]);
120950
+ const chainSummary = assertEx(result.find(isChainSummaryTransfers), () => "Failed to divine chain summary transfers");
120951
+ const transfers = chainSummary.transfers;
120952
+ const balance = transfers[pair[0]]?.[pair[1]];
120953
+ return isDefined(balance) ? asAttoXL1(parseSignedBigInt(balance) * -1n) : asAttoXL1(0n);
120954
+ }, this.tracer);
120955
+ }
120956
+ transferPairBalanceHistory(_pair) {
120957
+ throw new Error("Method not implemented.");
120958
+ }
120959
+ getAddressBalanceDiviner = /* @__PURE__ */ __name$9(async () => {
120960
+ if (this._addressBalanceDiviner) return this._addressBalanceDiviner;
120961
+ const resolved = await this.getDiviner(this.addressBalanceDivinerPath);
120962
+ this._addressBalanceDiviner = resolved;
120963
+ return assertEx(this._addressBalanceDiviner, () => `Could not resolve ${this.addressBalanceDivinerPath} to a diviner instance`);
120964
+ }, "getAddressBalanceDiviner");
120965
+ getArchivist = /* @__PURE__ */ __name$9(async (identifier) => {
120966
+ const archivist = await this.node.resolve(identifier);
120967
+ return assertEx(asAttachableArchivistInstance(archivist), () => `Could not resolve ${identifier} to an archivist instance`);
120968
+ }, "getArchivist");
120969
+ async getCurrentHead() {
120970
+ const chainArchivist = await this.getFinalizedArchivist();
120971
+ return await findMostRecentBlock(chainArchivist);
120972
+ }
120973
+ getDiviner = /* @__PURE__ */ __name$9(async (identifier) => {
120974
+ const diviner = await this.node.resolve(identifier);
120975
+ return assertEx(asDivinerInstance(diviner), () => `Could not resolve ${identifier} to a diviner instance`);
120976
+ }, "getDiviner");
120977
+ getFinalizedArchivist = /* @__PURE__ */ __name$9(async () => {
120978
+ if (this._finalizedArchivist) return this._finalizedArchivist;
120979
+ const resolved = await this.getArchivist(this.finalizedArchivistPath);
120980
+ this._finalizedArchivist = resolved;
120981
+ return assertEx(this._finalizedArchivist, () => `Could not resolve finalized archivist at ${this.finalizedArchivistPath}`);
120982
+ }, "getFinalizedArchivist");
120983
+ getFinalizedPayloadMap = /* @__PURE__ */ __name$9(async () => {
120984
+ const archivist = this.getFinalizedArchivist();
120985
+ return readPayloadMapFromStore(await archivist);
120986
+ }, "getFinalizedPayloadMap");
120987
+ async getHydratedBlockCache() {
120988
+ if (this._signedHydratedBlockCache) return this._signedHydratedBlockCache;
120989
+ const chainMap = await this.getFinalizedPayloadMap();
120990
+ this._signedHydratedBlockCache = new HydratedCache(chainMap, hydrateBlock, 200);
120991
+ return this._signedHydratedBlockCache;
120992
+ }
120993
+ async getHydratedTransactionCache() {
120994
+ if (this._signedHydratedTransactionCache) return this._signedHydratedTransactionCache;
120995
+ const chainMap = await this.getFinalizedPayloadMap();
120996
+ this._signedHydratedTransactionCache = new HydratedCache(chainMap, tryHydrateTransaction, 200);
120997
+ return this._signedHydratedTransactionCache;
120998
+ }
120999
+ getTransferBalanceDiviner = /* @__PURE__ */ __name$9(async () => {
121000
+ if (this._transferBalanceDiviner) return this._transferBalanceDiviner;
121001
+ const resolved = await this.getDiviner(this.transferBalanceDivinerPath);
121002
+ this._transferBalanceDiviner = resolved;
121003
+ return assertEx(this._transferBalanceDiviner, () => `Could not resolve ${this.transferBalanceDivinerPath} to a diviner instance`);
121004
+ }, "getTransferBalanceDiviner");
121005
+ async startHandler() {
121006
+ try {
121007
+ const currentBlockNumber = await this.currentBlockNumber();
121008
+ await this.transferBalance(XYO_ZERO_ADDRESS);
121009
+ await this.accountBalance(XYO_ZERO_ADDRESS);
121010
+ if (this.initRewardsCache) {
121011
+ const externalRange = await externalBlockRangeFromXL1BlockRange(this.context, asXL1BlockRange([
121012
+ 0,
121013
+ currentBlockNumber
121014
+ ], {
121015
+ name: "startHandler"
121016
+ }));
121017
+ const positionCount = await this.context.stake.stakeEvents.positionCount(externalRange);
121018
+ this.logger?.log(`NodeXyoViewer: Precomputing networkStakeStepRewardForPosition up to position ${positionCount - 1}`);
121019
+ for (let position = 0; position < positionCount; position++) {
121020
+ await this.networkStakeStepRewardForPosition(position, asXL1BlockRange([
121021
+ 0,
121022
+ currentBlockNumber
121023
+ ], {
121024
+ name: "startHandler"
121025
+ }));
121026
+ }
121027
+ this.logger?.log(`NodeXyoViewer: Precomputed networkStakeStepRewardForPosition up to position ${positionCount - 1}`);
121028
+ }
121029
+ } catch (ex) {
121030
+ this.logger?.error(`NodeXyoViewer: Error during startHandler initialization: ${ex.message}`);
121031
+ this.logger?.error(ex.stack ?? "<No Stack>");
121032
+ throw ex;
121033
+ }
121034
+ }
121035
+ async stepWeightedDenominator(stepIdentity) {
121036
+ const cacheKey = toStepIdentityString(stepIdentity);
121037
+ return await withContextCacheResponse(this.context, "NodeXyoViewer-networkStakeStepRewardForStepForPosition-denominator", cacheKey, async () => {
121038
+ const range = await externalBlockRangeFromStep(this.context, stepIdentity);
121039
+ return await weightedStakeForRangeByPosition(this.context, range);
121040
+ });
121041
+ }
121042
+ async distillTransferHistory(address, range, max = 50) {
121043
+ if (range[1] - range[0] <= StepSizes[0] || max <= 1) {
121044
+ return Array.from({
121045
+ length: range[1] - range[0] + 1
121046
+ }, (_, i) => range[1] - i).slice(0, max).map((n) => asXL1BlockNumber(n, {
121047
+ name: "distillTransferHistory"
121048
+ }));
121049
+ }
121050
+ const frames = deepCalculateFramesFromRange(asXL1BlockRange(range, {
121051
+ name: "distillTransferHistory"
121052
+ }));
121053
+ const transferSummaryPairs = await Promise.all(frames.map(async (frame) => {
121054
+ return [
121055
+ frame,
121056
+ await transfersStepSummaryFromRange(this.transfersSummaryContext, frame)
121057
+ ];
121058
+ }));
121059
+ const filteredTransferSummaryPairs = transferSummaryPairs.filter(([_, summary]) => Object.keys(summary.transfers).includes(address));
121060
+ const sortedTransferSummaryPairs = filteredTransferSummaryPairs.toSorted((a, b) => {
121061
+ return b[0][1] - a[0][1];
121062
+ });
121063
+ const resultBlockNumbers = /* @__PURE__ */ new Set();
121064
+ for (const [frame] of sortedTransferSummaryPairs) {
121065
+ if (frame[1] - frame[0] + 1 > StepSizes[0]) {
121066
+ const values = await this.distillTransferHistory(address, asXL1BlockRange([
121067
+ frame[0],
121068
+ frame[1] - 1
121069
+ ], {
121070
+ name: "distillTransferHistory"
121071
+ }), max - resultBlockNumbers.size);
121072
+ for (const value of values) {
121073
+ resultBlockNumbers.add(value);
121074
+ }
121075
+ resultBlockNumbers.add(frame[1]);
121076
+ } else {
121077
+ for (let i = frame[0]; i <= frame[1]; i++) {
121078
+ resultBlockNumbers.add(i);
121079
+ }
121080
+ }
121081
+ if (resultBlockNumbers.size >= max) {
121082
+ break;
121083
+ }
121084
+ }
121085
+ return [
121086
+ ...resultBlockNumbers
121087
+ ].toSorted((a, b) => b - a).slice(0, max);
121088
+ }
121089
+ };
121090
+
121091
+ var __defProp$e = Object.defineProperty;
121092
+ var __name$8 = (target, value) => __defProp$e(target, "name", { value, configurable: true });
121093
+ var initContextManager = /* @__PURE__ */ __name$8(() => {
121094
+ const contextManager = new AsyncLocalStorageContextManager();
121095
+ context.setGlobalContextManager(contextManager.enable());
121096
+ }, "initContextManager");
121097
+ var initPropagation = /* @__PURE__ */ __name$8(() => {
121098
+ propagation.setGlobalPropagator(new CompositePropagator({
121099
+ propagators: [
121100
+ new W3CTraceContextPropagator(),
121101
+ new W3CBaggagePropagator()
121102
+ ]
121103
+ }));
121104
+ }, "initPropagation");
121105
+ var initResource = /* @__PURE__ */ __name$8((attributes) => {
121106
+ const detectedResource = detectResources({
121107
+ detectors: [
121108
+ // hostDetector,
121109
+ // osDetector,
121110
+ // processDetector,
121111
+ serviceInstanceIdDetector
121112
+ ]
121113
+ });
121114
+ const staticResource = resourceFromAttributes({
121115
+ [ATTR_SERVICE_NAME]: attributes.serviceName,
121116
+ [ATTR_SERVICE_VERSION]: attributes.serviceName
121117
+ });
121118
+ const resource = detectedResource.merge(staticResource);
121119
+ return resource;
121120
+ }, "initResource");
121121
+ var initHostMetrics = /* @__PURE__ */ __name$8((meterProvider) => {
121122
+ const hostMetrics = new HostMetrics({
121123
+ meterProvider,
121124
+ name: "host-metrics"
121125
+ });
121126
+ hostMetrics.start();
121127
+ }, "initHostMetrics");
121128
+ var initNodeMetrics = /* @__PURE__ */ __name$8((meterProvider) => {
121129
+ const instrumentation = new RuntimeNodeInstrumentation({
121130
+ monitoringPrecision: 5e3
121131
+ });
121132
+ instrumentation.setMeterProvider(meterProvider);
121133
+ instrumentation.enable();
121134
+ }, "initNodeMetrics");
121135
+ var initMetricsExporter = /* @__PURE__ */ __name$8((metricsConfig) => {
121136
+ const { port, endpoint } = metricsConfig;
121137
+ const exporter = new PrometheusExporter({
121138
+ port,
121139
+ endpoint
121140
+ }, (err) => {
121141
+ if (err) console.error("Error initializing Prometheus exporter", err);
121142
+ });
121143
+ return exporter;
121144
+ }, "initMetricsExporter");
121145
+ var initMeterProvider = /* @__PURE__ */ __name$8((resource, readers) => {
121146
+ const meterProvider = new MeterProvider({
121147
+ readers,
121148
+ resource,
121149
+ views: [
121150
+ {
121151
+ aggregation: void 0,
121152
+ instrumentName: "*",
121153
+ instrumentType: void 0,
121154
+ meterName: "*"
121155
+ }
121156
+ ]
121157
+ });
121158
+ metrics$3.setGlobalMeterProvider(meterProvider);
121159
+ return meterProvider;
121160
+ }, "initMeterProvider");
121161
+ var initTraceProvider = /* @__PURE__ */ __name$8((otlpEndpoint, resource) => {
121162
+ const spanProcessors = [];
121163
+ if (isDefined(otlpEndpoint)) {
121164
+ const isHttp = otlpEndpoint.includes("/v1/traces") || otlpEndpoint.includes(":4318") || otlpEndpoint.startsWith("http");
121165
+ const exporter = isHttp ? new OTLPTraceExporter({
121166
+ url: otlpEndpoint
121167
+ }) : new OTLPTraceExporter$1({
121168
+ url: otlpEndpoint
121169
+ });
121170
+ const batchSpanProcessorConfig = {};
121171
+ const spanProcessor = new BatchSpanProcessor(exporter, batchSpanProcessorConfig);
121172
+ spanProcessors.push(spanProcessor);
121173
+ }
121174
+ const config = {
121175
+ resource,
121176
+ sampler: new AlwaysOnSampler(),
121177
+ spanProcessors
121178
+ };
121179
+ const traceProvider = new BasicTracerProvider(config);
121180
+ trace.setGlobalTracerProvider(traceProvider);
121181
+ return traceProvider;
121182
+ }, "initTraceProvider");
121183
+ var initTelemetry = /* @__PURE__ */ __name$8((params) => {
121184
+ const { attributes, metricsConfig, otlpEndpoint } = params;
121185
+ initContextManager();
121186
+ initPropagation();
121187
+ const resource = initResource(attributes);
121188
+ const exporter = initMetricsExporter(metricsConfig);
121189
+ const meterProvider = initMeterProvider(resource, [
121190
+ exporter
121191
+ ]);
121192
+ initHostMetrics(meterProvider);
121193
+ initNodeMetrics(meterProvider);
121194
+ const traceProvider = initTraceProvider(otlpEndpoint, resource);
121195
+ return {
121196
+ meterProvider,
121197
+ traceProvider
121198
+ };
121199
+ }, "initTelemetry");
121200
+
121201
+ var __defProp$d = Object.defineProperty;
121202
+ var __name$7 = (target, value) => __defProp$d(target, "name", { value, configurable: true });
121203
+ async function networkStakeStepRewardEarnedForPosition(context, stepIdentity, position, rewardMultipliers = {}) {
121204
+ const cacheKey = `${stepIdentity.block}|${stepIdentity.step}|${position.id}`;
121205
+ return await withContextCacheResponse(context, "networkStakeStepRewardEarnedForPosition", cacheKey, async () => {
121206
+ const range = await externalBlockRangeFromStep(context, stepIdentity);
121207
+ const numerator = position.staked === XYO_NETWORK_STAKING_ADDRESS ? await weightedStakeForRangeByPosition(context, range, position.id) : 0n;
121208
+ const denominator = await weightedStakeForRangeByPosition(context, range);
121209
+ const totalReward = await stepRewardTotal(context, stepIdentity, rewardMultipliers);
121210
+ const positionReward = denominator > 0n ? totalReward * numerator / denominator : 0n;
121211
+ const result = [
121212
+ positionReward,
121213
+ totalReward
121214
+ ];
121215
+ return result;
121216
+ });
121217
+ }
121218
+ __name$7(networkStakeStepRewardEarnedForPosition, "networkStakeStepRewardEarnedForPosition");
121219
+
121220
+ // src/primitives/networkStakeStepRewardEarned.ts
121221
+ async function networkStakeStepRewardEarned(context, stepIdentity, rewardMultipliers = {}) {
121222
+ const cacheKey = `${stepIdentity.block}|${stepIdentity.step}`;
121223
+ return await withContextCacheResponse(context, "networkStakeStepRewardEarned", cacheKey, async () => {
121224
+ const positions = await context.stake.stakesByStaked(XYO_NETWORK_STAKING_ADDRESS);
121225
+ const results = await Promise.all(positions.map((pos) => {
121226
+ return networkStakeStepRewardEarnedForPosition(context, stepIdentity, pos, rewardMultipliers);
121227
+ }));
121228
+ const numerator = results.reduce((acc, [positionReward]) => acc + positionReward, 0n);
121229
+ const result = results.length > 0 ? [
121230
+ numerator,
121231
+ results[0][1]
121232
+ ] : [
121233
+ 0n,
121234
+ 0n
121235
+ ];
121236
+ return result;
121237
+ });
121238
+ }
121239
+ __name$7(networkStakeStepRewardEarned, "networkStakeStepRewardEarned");
121240
+ async function networkStakeStepRewardEarnedForStaker(context, stepIdentity, staker, rewardMultipliers = {}) {
121241
+ const stepId = toStepIdentityString(stepIdentity);
121242
+ return await withContextCacheResponse(context, "networkStakeStepRewardEarnedForStaker", `${stepId}-${staker}`, async () => {
121243
+ const positions = (await context.stake.stakesByStaker(staker)).filter((pos) => pos.staked === XYO_NETWORK_STAKING_ADDRESS);
121244
+ const results = await Promise.all(positions.map((pos) => {
121245
+ return networkStakeStepRewardEarnedForPosition(context, stepIdentity, pos, rewardMultipliers);
121246
+ }));
121247
+ const numerator = results.reduce((acc, [positionReward]) => acc + positionReward, 0n);
121248
+ const result = results.length > 0 ? [
121249
+ numerator,
121250
+ results[0][1]
121251
+ ] : [
121252
+ 0n,
121253
+ 0n
121254
+ ];
121255
+ return result;
121256
+ });
121257
+ }
121258
+ __name$7(networkStakeStepRewardEarnedForStaker, "networkStakeStepRewardEarnedForStaker");
121259
+ var SimpleStepRewardsByPositionViewer = class extends AbstractCreatable {
121260
+ static {
121261
+ __name$7(this, "SimpleStepRewardsByPositionViewer");
121262
+ }
121263
+ get context() {
121264
+ return this.params.context;
121265
+ }
121266
+ get rewardMultipliers() {
121267
+ return this.params.rewardMultipliers ?? {};
121268
+ }
121269
+ async bonus({ range, positions } = {}) {
121270
+ const total = await this.total({
121271
+ range,
121272
+ positions
121273
+ });
121274
+ const earned = await this.earned({
121275
+ range,
121276
+ positions
121277
+ });
121278
+ const result = {};
121279
+ for (const pos of Object.keys(total).map(Number)) {
121280
+ result[pos] = asAttoXL1(total[pos] - (earned[pos] ?? 0n));
121281
+ }
121282
+ return result;
121283
+ }
121284
+ claimed(_options) {
121285
+ throw new Error("Method not implemented.");
121286
+ }
121287
+ async earned({ range, positions } = {}) {
121288
+ return await this.calculateRewards({
121289
+ range,
121290
+ positions
121291
+ });
121292
+ }
121293
+ async total({ range, positions } = {}) {
121294
+ return await this.calculateRewards({
121295
+ range,
121296
+ positions
121297
+ }, this.rewardMultipliers);
121298
+ }
121299
+ unclaimed(_options = {}) {
121300
+ throw new Error("Method not implemented.");
121301
+ }
121302
+ async calculateRewards({ range, positions } = {}, rewardMultipliers) {
121303
+ const result = {};
121304
+ const steps = blockRangeSteps(asXL1BlockRange(range ?? [
121305
+ 0,
121306
+ (await this.context.head())[1]
121307
+ ], {
121308
+ name: "NodeStepRewardsByPositionViewer"
121309
+ }), [
121310
+ 3,
121311
+ 4,
121312
+ 5,
121313
+ 6,
121314
+ 7
121315
+ ]);
121316
+ for (const step of steps) {
121317
+ if (isArray$1(positions)) {
121318
+ for (const positionId of positions) {
121319
+ const position = await this.context.stake.stakeById(positionId);
121320
+ result[positionId] = asAttoXL1((result[positionId] ?? 0n) + (await networkStakeStepRewardEarnedForPosition(this.context, step, position, rewardMultipliers))[0]);
121321
+ }
121322
+ }
121323
+ }
121324
+ return result;
121325
+ }
121326
+ };
121327
+ var SimpleStepRewardsByStakerViewer = class extends AbstractCreatable {
121328
+ static {
121329
+ __name$7(this, "SimpleStepRewardsByStakerViewer");
121330
+ }
121331
+ get context() {
121332
+ return this.params.context;
121333
+ }
121334
+ get rewardMultipliers() {
121335
+ return this.params.rewardMultipliers ?? {};
121336
+ }
121337
+ get stakedChainContext() {
121338
+ return this.params.context;
121339
+ }
121340
+ async bonus({ range, stakers } = {}) {
121341
+ const total = await this.total({
121342
+ range,
121343
+ stakers
121344
+ });
121345
+ const earned = await this.earned({
121346
+ range,
121347
+ stakers
121348
+ });
121349
+ const result = {};
121350
+ for (const staker of Object.keys(total)) {
121351
+ result[staker] = asAttoXL1(total[staker] - (earned[staker] ?? 0n));
121352
+ }
121353
+ return result;
121354
+ }
121355
+ claimed(_options) {
121356
+ throw new Error("Method not implemented.");
121357
+ }
121358
+ async earned(options = {}) {
121359
+ return await this.calculateRewards(options);
121360
+ }
121361
+ async total(options = {}) {
121362
+ return await this.calculateRewards(options, this.rewardMultipliers);
121363
+ }
121364
+ unclaimed(_options = {}) {
121365
+ throw new Error("Method not implemented.");
121366
+ }
121367
+ async calculateRewards({ range, stakers } = {}, rewardMultipliers) {
121368
+ const result = {};
121369
+ const steps = blockRangeSteps(asXL1BlockRange(range ?? [
121370
+ 0,
121371
+ (await this.context.head())[1]
121372
+ ], {
121373
+ name: "NodeStepRewardsByStakerViewer"
121374
+ }), [
121375
+ 3,
121376
+ 4,
121377
+ 5,
121378
+ 6,
121379
+ 7
121380
+ ]);
121381
+ for (const step of steps) {
121382
+ if (isArray$1(stakers)) {
121383
+ for (const staker of stakers) {
121384
+ result[staker] = asAttoXL1((result[staker] ?? 0n) + (await networkStakeStepRewardEarnedForStaker(this.context, step, staker, rewardMultipliers))[0]);
121385
+ }
121386
+ }
121387
+ }
121388
+ return result;
121389
+ }
121390
+ };
121391
+ var SimpleStepRewardsByStepViewer = class extends AbstractCreatable {
121392
+ static {
121393
+ __name$7(this, "SimpleStepRewardsByStepViewer");
121394
+ }
121395
+ get context() {
121396
+ return this.params.context;
121397
+ }
121398
+ get rewardMultipliers() {
121399
+ return this.params.rewardMultipliers ?? {};
121400
+ }
121401
+ async bonus({ range, steps } = {}) {
121402
+ const total = await this.total({
121403
+ range,
121404
+ steps
121405
+ });
121406
+ const earned = await this.earned({
121407
+ range,
121408
+ steps
121409
+ });
121410
+ const result = {};
121411
+ for (const stepString of Object.keys(total)) {
121412
+ result[stepString] = asAttoXL1(total[stepString] - (earned[stepString] ?? 0n));
121413
+ }
121414
+ return result;
121415
+ }
121416
+ claimed(_options) {
121417
+ throw new Error("Method not implemented.");
121418
+ }
121419
+ async earned({ range, steps } = {}) {
121420
+ const result = {};
121421
+ const resolvedSteps = steps ?? blockRangeSteps(asXL1BlockRange(range ?? [
121422
+ 0,
121423
+ (await this.context.head())[1]
121424
+ ], {
121425
+ name: "NodeStepRewardsByStepViewer"
121426
+ }), [
121427
+ 3,
121428
+ 4,
121429
+ 5,
121430
+ 6,
121431
+ 7
121432
+ ]);
121433
+ for (const step of resolvedSteps) {
121434
+ const stepIdentityString = toStepIdentityString(step);
121435
+ result[stepIdentityString] = asAttoXL1((result[stepIdentityString] ?? 0n) + (await networkStakeStepRewardEarned(this.context, step))[0]);
121436
+ }
121437
+ return result;
121438
+ }
121439
+ async total({ range, steps } = {}) {
121440
+ const result = {};
121441
+ const resolvedSteps = steps ?? blockRangeSteps(asXL1BlockRange(range ?? [
121442
+ 0,
121443
+ (await this.context.head())[1]
121444
+ ], {
121445
+ name: "NodeStepRewardsByStepViewer"
121446
+ }), [
121447
+ 3,
121448
+ 4,
121449
+ 5,
121450
+ 6,
121451
+ 7
121452
+ ]);
121453
+ for (const step of resolvedSteps) {
121454
+ const stepIdentityString = toStepIdentityString(step);
121455
+ result[stepIdentityString] = asAttoXL1((result[stepIdentityString] ?? 0n) + (await networkStakeStepRewardEarned(this.context, step, this.rewardMultipliers))[0]);
121456
+ }
121457
+ return result;
121458
+ }
121459
+ unclaimed(_options = {}) {
121460
+ throw new Error("Method not implemented.");
121461
+ }
121462
+ };
121463
+ var SimpleStepRewardsViewer = class extends AbstractCreatable {
121464
+ static {
121465
+ __name$7(this, "SimpleStepRewardsViewer");
121466
+ }
121467
+ _position;
121468
+ _staker;
121469
+ _step;
121470
+ get position() {
121471
+ return assertEx(this._position, () => "Position viewer not initialized");
121472
+ }
121473
+ get staker() {
121474
+ return assertEx(this._staker, () => "Position viewer not initialized");
121475
+ }
121476
+ get step() {
121477
+ return assertEx(this._step, () => "Step viewer not initialized");
121478
+ }
121479
+ get total() {
121480
+ throw new Error("Method not implemented.");
121481
+ }
121482
+ get context() {
121483
+ return this.params.context;
121484
+ }
121485
+ get rewardMultipliers() {
121486
+ return this.params.rewardMultipliers;
121487
+ }
121488
+ async createHandler() {
121489
+ await super.createHandler();
121490
+ this._position = await SimpleStepRewardsByPositionViewer.create({
121491
+ context: this.context,
121492
+ rewardMultipliers: this.rewardMultipliers
121493
+ });
121494
+ this._staker = await SimpleStepRewardsByStakerViewer.create({
121495
+ context: this.context,
121496
+ rewardMultipliers: this.rewardMultipliers
121497
+ });
121498
+ this._step = await SimpleStepRewardsByStepViewer.create({
121499
+ context: this.context,
121500
+ rewardMultipliers: this.rewardMultipliers
121501
+ });
121502
+ }
121503
+ async startHandler() {
121504
+ await super.startHandler();
121505
+ await assertEx(this._position, () => "Position viewer not created").start();
121506
+ await assertEx(this._staker, () => "Staker viewer not created").start();
121507
+ await assertEx(this._step, () => "Step viewer not created").start();
121508
+ }
121509
+ };
121510
+ var SimpleNetworkStakeViewer = class extends AbstractCreatable {
121511
+ static {
121512
+ __name$7(this, "SimpleNetworkStakeViewer");
121513
+ }
121514
+ _stepRewardsViewer;
121515
+ get context() {
121516
+ return this.params.context;
121517
+ }
121518
+ get rewardMultipliers() {
121519
+ return this.params.rewardMultipliers;
121520
+ }
121521
+ get stepRewards() {
121522
+ return assertEx(this._stepRewardsViewer, () => "Step rewards viewer not initialized");
121523
+ }
121524
+ async active(blockNumber) {
121525
+ const resolvedBlockNumber = blockNumber ?? (await this.context.head())[1];
121526
+ return [
121527
+ await this.context.stake.active(resolvedBlockNumber),
121528
+ resolvedBlockNumber
121529
+ ];
121530
+ }
121531
+ async createHandler() {
121532
+ await super.createHandler();
121533
+ this._stepRewardsViewer = await SimpleStepRewardsViewer.create({
121534
+ context: this.context,
121535
+ rewardMultipliers: this.rewardMultipliers
121536
+ });
121537
+ }
121538
+ async startHandler() {
121539
+ await super.startHandler();
121540
+ const stepRewardsByPositionViewer = await SimpleStepRewardsByPositionViewer.create({
121541
+ context: this.context,
121542
+ rewardMultipliers: this.rewardMultipliers
121543
+ });
121544
+ console.log("Initializing NodeStepRewardsByPositionViewer...");
121545
+ await stepRewardsByPositionViewer.start();
121546
+ console.log("Initialized NodeStepRewardsByPositionViewer.");
121547
+ }
121548
+ };
121549
+
121550
+ var __defProp$c = Object.defineProperty;
121551
+ var __name$6 = (target, value) => __defProp$c(target, "name", { value, configurable: true });
121552
+ var initArchivistSync = /* @__PURE__ */ __name$6(async (name, inArchivist, outArchivist, frequency = 1e3, max = 1e3, traceProvider) => {
119849
121553
  const node = await MemoryNode.create({
119850
121554
  account: "random"
119851
121555
  });
@@ -119892,7 +121596,7 @@ var initArchivistSync = /* @__PURE__ */ __name$9(async (name, inArchivist, outAr
119892
121596
  }, "initArchivistSync");
119893
121597
  var initMutex = new Mutex$1();
119894
121598
  var bridgeSingletonMap = /* @__PURE__ */ new Map();
119895
- var initBridge = /* @__PURE__ */ __name$9(async (nodeUrl) => {
121599
+ var initBridge = /* @__PURE__ */ __name$6(async (nodeUrl) => {
119896
121600
  return await initMutex.runExclusive(async () => {
119897
121601
  const existing = bridgeSingletonMap.get(nodeUrl);
119898
121602
  if (existing) return existing;
@@ -119915,9 +121619,18 @@ var initBridge = /* @__PURE__ */ __name$9(async (nodeUrl) => {
119915
121619
  return bridge;
119916
121620
  });
119917
121621
  }, "initBridge");
121622
+ async function createProducerChainStakeIntentBlock(prevBlock, producerAccount, range) {
121623
+ const producerDeclarationPayload = createDeclarationIntent(producerAccount.address, "producer", range[0], range[1]);
121624
+ return await buildNextBlock(prevBlock, [], [
121625
+ producerDeclarationPayload
121626
+ ], [
121627
+ producerAccount
121628
+ ]);
121629
+ }
121630
+ __name$6(createProducerChainStakeIntentBlock, "createProducerChainStakeIntentBlock");
119918
121631
  var initMutex2 = new Mutex$1();
119919
121632
  var bridgedModuleDictionary = {};
119920
- var initBridgedModule = /* @__PURE__ */ __name$9(async ({ bridge, moduleName }) => {
121633
+ var initBridgedModule = /* @__PURE__ */ __name$6(async ({ bridge, moduleName }) => {
119921
121634
  return await initMutex2.runExclusive(async () => {
119922
121635
  const existing = bridgedModuleDictionary?.[bridge.address]?.[moduleName];
119923
121636
  if (existing) return existing;
@@ -119932,18 +121645,146 @@ var initBridgedModule = /* @__PURE__ */ __name$9(async ({ bridge, moduleName })
119932
121645
  return moduleInstance;
119933
121646
  });
119934
121647
  }, "initBridgedModule");
119935
- var initBridgedArchivistModule = /* @__PURE__ */ __name$9(async ({ bridge, moduleName }) => {
121648
+ var initBridgedArchivistModule = /* @__PURE__ */ __name$6(async ({ bridge, moduleName }) => {
119936
121649
  return assertEx(asAttachableArchivistInstance(await initBridgedModule({
119937
121650
  bridge,
119938
121651
  moduleName
119939
121652
  })), () => `Could not convert ${moduleName} to attachable archivist instance`);
119940
121653
  }, "initBridgedArchivistModule");
121654
+ var canUseChainId$1 = /* @__PURE__ */ __name$6((config) => {
121655
+ return isDefined(config.evm.chainId);
121656
+ }, "canUseChainId");
121657
+ var getChainId$1 = /* @__PURE__ */ __name$6((config) => {
121658
+ const chainId = assertEx(config.evm.chainId, () => "Missing config.evm.chainId");
121659
+ if (isHex(chainId, {
121660
+ prefix: true
121661
+ })) {
121662
+ const hex = hexFrom(chainId);
121663
+ const parsed = Number.parseInt(hex, 16);
121664
+ return parsed;
121665
+ } else {
121666
+ const parsed = Number.parseInt(chainId, 10);
121667
+ return parsed;
121668
+ }
121669
+ }, "getChainId");
119941
121670
 
119942
- var __defProp$e = Object.defineProperty;
121671
+ // src/evm/initInfuraProvider.ts
121672
+ var instance$1;
121673
+ var initInfuraProvider$1 = /* @__PURE__ */ __name$6((config) => {
121674
+ if (instance$1) return instance$1;
121675
+ const providerConfig = getInfuraProviderConfig$1(config);
121676
+ instance$1 = Promise.resolve(new InfuraProvider(...providerConfig));
121677
+ return instance$1;
121678
+ }, "initInfuraProvider");
121679
+ var canUseInfuraProvider$1 = /* @__PURE__ */ __name$6((config) => {
121680
+ return canUseChainId$1(config) && isDefined(config.evm?.infura?.projectId) && isDefined(config.evm?.infura?.projectSecret);
121681
+ }, "canUseInfuraProvider");
121682
+ var getInfuraProviderConfig$1 = /* @__PURE__ */ __name$6((config) => {
121683
+ const projectId = assertEx(config.evm?.infura?.projectId, () => "Missing config.evm.infura.projectId");
121684
+ const projectSecret = assertEx(config.evm?.infura?.projectSecret, () => "Missing config.evm.infura.projectSecret");
121685
+ return [
121686
+ getChainId$1(config),
121687
+ projectId,
121688
+ projectSecret
121689
+ ];
121690
+ }, "getInfuraProviderConfig");
121691
+ var initJsonRpcProvider$1 = /* @__PURE__ */ __name$6((config) => {
121692
+ const providerConfig = getJsonRpcProviderConfig$1(config);
121693
+ return Promise.resolve(new JsonRpcProvider(...providerConfig));
121694
+ }, "initJsonRpcProvider");
121695
+ var canUseJsonRpcProvider$1 = /* @__PURE__ */ __name$6((config) => {
121696
+ return canUseChainId$1(config) && isDefined(config.evm.jsonRpc?.url);
121697
+ }, "canUseJsonRpcProvider");
121698
+ var getJsonRpcProviderConfig$1 = /* @__PURE__ */ __name$6((config) => {
121699
+ const jsonRpcUrl = assertEx(config.evm.jsonRpc?.url, () => "Missing config.evm.jsonRpc.url");
121700
+ return [
121701
+ jsonRpcUrl,
121702
+ getChainId$1(config)
121703
+ ];
121704
+ }, "getJsonRpcProviderConfig");
121705
+
121706
+ // src/evm/initEvmProvider.ts
121707
+ var provider$1;
121708
+ var initEvmProvider$1 = /* @__PURE__ */ __name$6(async ({ config }) => {
121709
+ if (provider$1) return provider$1;
121710
+ if (canUseInfuraProvider$1(config)) {
121711
+ provider$1 = initInfuraProvider$1(config);
121712
+ } else if (canUseJsonRpcProvider$1(config)) {
121713
+ provider$1 = initJsonRpcProvider$1(config);
121714
+ }
121715
+ return assertEx(await provider$1, () => "No provider available");
121716
+ }, "initEvmProvider");
121717
+ var canUseEvmProvider$1 = /* @__PURE__ */ __name$6(({ config }) => {
121718
+ return canUseInfuraProvider$1(config) || canUseJsonRpcProvider$1(config);
121719
+ }, "canUseEvmProvider");
121720
+
121721
+ // src/initChainStakeViewer.ts
121722
+ async function initEvmChainStakeViewer(config, logger) {
121723
+ const provider2 = await initEvmProvider$1({
121724
+ config,
121725
+ logger
121726
+ });
121727
+ const contractAddress = assertEx(config.chain.id, () => "Missing config.evm.chainId");
121728
+ const contract = StakedXyoChainV2__factory.connect(toEthAddress(contractAddress), provider2);
121729
+ const stakeEventsViewer = await EthereumChainStakeEvents.create({
121730
+ contract,
121731
+ logger
121732
+ });
121733
+ assertEx(await stakeEventsViewer.start(), () => "Failed to start EthereumChainStakeEvents reader");
121734
+ const stakeChainViewer = await EthereumChainStakeViewer.create({
121735
+ contract,
121736
+ stakeEventsViewer,
121737
+ logger
121738
+ });
121739
+ assertEx(await stakeChainViewer.start(), () => "Failed to start EthereumChainStake viewer");
121740
+ return stakeChainViewer;
121741
+ }
121742
+ __name$6(initEvmChainStakeViewer, "initEvmChainStakeViewer");
121743
+ async function initSimpleStakeViewer(config, logger) {
121744
+ const stakeChainViewer = await SimpleChainStakeViewer.create({
121745
+ logger,
121746
+ positions: []
121747
+ });
121748
+ assertEx(await stakeChainViewer.start(), () => "Failed to start SimpleChainStake viewer");
121749
+ return stakeChainViewer;
121750
+ }
121751
+ __name$6(initSimpleStakeViewer, "initSimpleStakeViewer");
121752
+ async function initChainStakeViewer(config, logger) {
121753
+ if (canUseEvmProvider$1({
121754
+ config
121755
+ })) {
121756
+ return await initEvmChainStakeViewer(config, logger);
121757
+ } else {
121758
+ console.warn("[API] Infura configuration not found. Using SimpleChainStakeViewer with no positions. This means no staking data will be available.");
121759
+ return await initSimpleStakeViewer(config, logger);
121760
+ }
121761
+ }
121762
+ __name$6(initChainStakeViewer, "initChainStakeViewer");
121763
+ var accountServiceSingleton;
121764
+ var initProducerAccount = /* @__PURE__ */ __name$6(async ({ config, logger }) => {
121765
+ if (accountServiceSingleton) return accountServiceSingleton;
121766
+ let walletPhrase = config.producer.mnemonic;
121767
+ if (isUndefined$1(walletPhrase)) {
121768
+ logger?.warn("[Producer] No wallet mnemonic specified!");
121769
+ const randomMnemonic = HDWallet.generateMnemonic();
121770
+ logger?.warn(`[Producer] Using randomly generated mnemonic:
121771
+
121772
+ ${randomMnemonic}
121773
+
121774
+ `);
121775
+ walletPhrase = randomMnemonic;
121776
+ }
121777
+ const wallet = await generateXyoBaseWalletFromPhrase(walletPhrase);
121778
+ const account = await wallet.derivePath(ADDRESS_INDEX.XYO);
121779
+ accountServiceSingleton = account;
121780
+ return accountServiceSingleton;
121781
+ }, "initProducerAccount");
121782
+
121783
+ var __defProp$b = Object.defineProperty;
119943
121784
  var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
119944
121785
  var __getProtoOf$3 = Object.getPrototypeOf;
119945
121786
  var __reflectGet$3 = Reflect.get;
119946
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
121787
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
119947
121788
  var __decorateClass$5 = (decorators, target, key, kind) => {
119948
121789
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
119949
121790
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
@@ -211323,904 +213164,6 @@ function requireExpress () {
211323
213164
  var expressExports = requireExpress();
211324
213165
  var express2 = /*@__PURE__*/getDefaultExportFromCjs(expressExports);
211325
213166
 
211326
- var __defProp$d = Object.defineProperty;
211327
- var __name$8 = (target, value) => __defProp$d(target, "name", { value, configurable: true });
211328
- var NodeXyoViewer = class extends AbstractCreatable {
211329
- static {
211330
- __name$8(this, "NodeXyoViewer");
211331
- }
211332
- // TODO: Make configurable with defaults
211333
- _tracer;
211334
- addressBalanceDivinerPath = "XYOChain:Chain:AddressBalanceDiviner";
211335
- finalizedArchivistPath = "XYOChain:Chain:Finalized";
211336
- headValidationDivinerPath = "XYOChain:Chain:HeadValidationDiviner";
211337
- transferBalanceDivinerPath = "XYOChain:Chain:AddressTransferDiviner";
211338
- _addressBalanceDiviner;
211339
- _chainId;
211340
- _finalizedArchivist;
211341
- _rewardMultipliers;
211342
- _signedHydratedBlockCache;
211343
- _signedHydratedTransactionCache;
211344
- _transferBalanceDiviner;
211345
- get context() {
211346
- return assertEx(this.params.context, () => "NodeXyoViewer requires a context");
211347
- }
211348
- get initRewardsCache() {
211349
- return this.params.initRewardsCache ?? true;
211350
- }
211351
- get node() {
211352
- return this.params.node;
211353
- }
211354
- get rewardMultipliers() {
211355
- this._rewardMultipliers = this._rewardMultipliers ?? this.params.rewardMultipliers ?? {};
211356
- return this._rewardMultipliers;
211357
- }
211358
- get stake() {
211359
- return this.context.stake;
211360
- }
211361
- get transfersSummaryContext() {
211362
- return this.params.transfersSummaryContext ?? {
211363
- ...this.context
211364
- };
211365
- }
211366
- async accountBalance(address) {
211367
- return await spanRootAsync("accountBalance", async () => {
211368
- const diviner = await this.getAddressBalanceDiviner();
211369
- const query = new PayloadBuilder({
211370
- schema: AddressSchema
211371
- }).fields({
211372
- address
211373
- }).build();
211374
- const result = await diviner.divine([
211375
- query
211376
- ]);
211377
- const chainSummary = assertEx(result.find(isChainSummaryBalances), () => "Failed to divine chain summary balances");
211378
- const balances = chainSummary.balances;
211379
- const signedBalance = balances[address] === void 0 ? 0n : parseSignedBigInt(balances[address]);
211380
- return asAttoXL1(signedBalance > 0n ? signedBalance : 0n);
211381
- }, this.tracer);
211382
- }
211383
- async accountBalanceHistory(address, rangeOrHash) {
211384
- return await spanRootAsync("accountHistory", async () => {
211385
- const range = asRange(rangeOrHash);
211386
- const startingRange = asXL1BlockRange(range ?? [
211387
- 0,
211388
- await this.currentBlockNumber()
211389
- ], {
211390
- name: "accountBalanceHistory"
211391
- });
211392
- const blockNumbers = await this.distillTransferHistory(address, startingRange);
211393
- const blocks = (await Promise.all(blockNumbers.map(async (bn) => await this.blockByNumber(bn)))).filter(exists$1);
211394
- const result = [];
211395
- for (const block of blocks) {
211396
- const transferIndexes = block[0].payload_schemas.map((schema, index) => schema === TransferSchema ? index : void 0).filter(exists$1);
211397
- const transfers = transferIndexes.map((index) => {
211398
- const hash = block[0].payload_hashes[index];
211399
- return assertEx(block[1].find((p) => p._hash === hash), () => `Could not find Transfer with hash ${hash} in block ${block[0]._hash}`);
211400
- }).filter(exists$1).filter((t) => t.from === address || isDefined(t.transfers[address]));
211401
- if (transfers.length === 0) {
211402
- continue;
211403
- }
211404
- const pairs = transfers.map((transfer) => {
211405
- return [
211406
- block[0],
211407
- transfer
211408
- ];
211409
- });
211410
- result.push(...pairs.map(([block2, transfer]) => [
211411
- block2,
211412
- null,
211413
- transfer
211414
- ]));
211415
- }
211416
- return result;
211417
- }, this.tracer);
211418
- }
211419
- async blockByHash(hash) {
211420
- return await spanRootAsync("blockByHash", async () => {
211421
- const cache = await this.getHydratedBlockCache();
211422
- return await cache.get(hash);
211423
- }, this.tracer);
211424
- }
211425
- async blockByNumber(blockNumber) {
211426
- return await spanRootAsync("blockByNumber", async () => {
211427
- return await hydratedBlockByNumber(this.context, blockNumber);
211428
- }, this.tracer);
211429
- }
211430
- async blocksByHash(hash, limit = 10) {
211431
- return await spanRootAsync("blocksByHash", async () => {
211432
- assertEx(limit > 0, () => "limit must be greater than 0");
211433
- assertEx(limit <= 100, () => "limit must be less than 100");
211434
- const blocks = [];
211435
- let current = await this.blockByHash(hash);
211436
- while (current && blocks.length < limit) {
211437
- blocks.push(current);
211438
- const previousHash = current[0].previous;
211439
- if (previousHash === null) break;
211440
- current = await this.blockByHash(previousHash);
211441
- }
211442
- return blocks;
211443
- }, this.tracer);
211444
- }
211445
- async chainId() {
211446
- return await spanRootAsync("chainId", async () => {
211447
- if (this._chainId !== void 0) return this._chainId;
211448
- const block = await this.currentBlock();
211449
- this._chainId = block[0].chain;
211450
- return this._chainId;
211451
- }, this.tracer);
211452
- }
211453
- async chainIdAtBlock(blockNumber) {
211454
- return await spanRootAsync("chainIdAtBlock", async () => {
211455
- if (this._chainId !== void 0) return this._chainId;
211456
- const block = await this.blockByNumber(blockNumber);
211457
- this._chainId = block?.[0].chain;
211458
- return this._chainId;
211459
- }, this.tracer);
211460
- }
211461
- async currentBlock() {
211462
- return await spanRootAsync("currentBlock", async () => {
211463
- const currentHead = assertEx(await this.getCurrentHead(), () => "Could not find most recent block");
211464
- const cache = await this.getHydratedBlockCache();
211465
- const block = await cache.get(currentHead._hash);
211466
- if (!block) {
211467
- console.log(`Could not find current block with hash ${currentHead._hash}`);
211468
- }
211469
- return assertEx(block, () => "Could not find current block");
211470
- }, this.tracer);
211471
- }
211472
- async currentBlockHash() {
211473
- return await spanRootAsync("currentBlockHash", async () => {
211474
- const currentHead = assertEx(await this.getCurrentHead(), () => "Could not find most recent block");
211475
- return currentHead._hash;
211476
- }, this.tracer);
211477
- }
211478
- async currentBlockNumber() {
211479
- return await spanRootAsync("currentBlockNumber", async () => {
211480
- const currentHead = assertEx(await this.getCurrentHead(), () => "Could not find most recent block");
211481
- return asXL1BlockNumber(currentHead.block, {
211482
- name: "currentBlockNumber"
211483
- });
211484
- }, this.tracer);
211485
- }
211486
- forkHistory() {
211487
- throw new Error("Method not implemented.");
211488
- }
211489
- networkStakeStepRewardAddressHistory(_address) {
211490
- throw new Error("Method not implemented.");
211491
- }
211492
- networkStakeStepRewardAddressReward(_context, _address) {
211493
- throw new Error("Method not implemented.");
211494
- }
211495
- networkStakeStepRewardAddressShare(_context, _address) {
211496
- throw new Error("Method not implemented.");
211497
- }
211498
- networkStakeStepRewardClaimedByAddress(_address) {
211499
- throw new Error("Method not implemented.");
211500
- }
211501
- async networkStakeStepRewardForPosition(position, range) {
211502
- return await timeBudget("networkStakeStepRewardForPosition", this.logger, async () => {
211503
- const externalRange = await externalBlockRangeFromXL1BlockRange(this.context, range);
211504
- const positionCount = await this.context.events.positionCount(externalRange);
211505
- if (positionCount === 0) {
211506
- return [
211507
- 0n,
211508
- 0n
211509
- ];
211510
- }
211511
- const steps = blockRangeSteps(range, [
211512
- 3,
211513
- 4,
211514
- 5,
211515
- 6,
211516
- 7
211517
- ]);
211518
- const rewards = await Promise.all(steps.map((step) => this.networkStakeStepRewardForStepForPosition(step, position)));
211519
- const positionReward = rewards.reduce((a, b) => a + b[0], 0n);
211520
- const totalReward = rewards.reduce((a, b) => a + b[1], 0n);
211521
- return [
211522
- positionReward,
211523
- totalReward
211524
- ];
211525
- }, 100);
211526
- }
211527
- async networkStakeStepRewardForStep(stepContext) {
211528
- return await stepRewardTotal(this.context, stepContext, this.rewardMultipliers);
211529
- }
211530
- async networkStakeStepRewardForStepForPosition(stepIdentity, position) {
211531
- const stepIdentityString = toStepIdentityString(stepIdentity);
211532
- const cacheKey = `${stepIdentityString}|${position}`;
211533
- return await withContextCacheResponse(this.context, "NodeXyoViewer-networkStakeStepRewardForStepForPosition", cacheKey, async () => {
211534
- const range = await externalBlockRangeFromStep(this.context, stepIdentity);
211535
- const stake = await this.stakeById(position);
211536
- const numerator = stake.staked === XYO_NETWORK_STAKING_ADDRESS ? await weightedStakeForRangeByPosition(this.context, range, position) : 0n;
211537
- const denominator = await this.stepWeightedDenominator(stepIdentity);
211538
- const totalReward = await this.networkStakeStepRewardForStep(stepIdentity);
211539
- const positionReward = denominator > 0n ? totalReward * numerator / denominator : 0n;
211540
- const result = [
211541
- positionReward,
211542
- totalReward
211543
- ];
211544
- return result;
211545
- });
211546
- }
211547
- async networkStakeStepRewardPoolRewards(step) {
211548
- const stakes = await this.context.stake.stakesByStaked(XYO_NETWORK_STAKING_ADDRESS);
211549
- const rewards = [];
211550
- for (const stake of stakes) {
211551
- rewards.push([
211552
- stake.staker,
211553
- await this.networkStakeStepRewardForStepForPosition(step, stake.id)
211554
- ]);
211555
- }
211556
- const result = {};
211557
- for (const [staker, reward] of rewards) {
211558
- result[staker] = (result[staker] ?? 0n) + reward[0];
211559
- }
211560
- const filtered = Object.fromEntries(Object.entries(result).filter(([_, v]) => v > 0n));
211561
- return filtered;
211562
- }
211563
- networkStakeStepRewardPoolShares(_context) {
211564
- throw new Error("Method not implemented.");
211565
- }
211566
- async networkStakeStepRewardPositionWeight(stepContext, position) {
211567
- return await networkStakeStepRewardPositionWeight(this.context, stepContext, position);
211568
- }
211569
- networkStakeStepRewardPotentialPositionLoss(_context, _position) {
211570
- throw new Error("Method not implemented.");
211571
- }
211572
- networkStakeStepRewardRandomizer(_context) {
211573
- throw new Error("Method not implemented.");
211574
- }
211575
- async networkStakeStepRewardStakerCount(stepContext) {
211576
- return Object.keys(await allStakersForStep(this.context, stepContext, XYO_NETWORK_STAKING_ADDRESS)).length;
211577
- }
211578
- networkStakeStepRewardUnclaimedByAddress(_address) {
211579
- throw new Error("Method not implemented.");
211580
- }
211581
- networkStakeStepRewardWeightForAddress(_context, _address) {
211582
- throw new Error("Method not implemented.");
211583
- }
211584
- async networkStakeStepRewardsForPosition(position, range) {
211585
- const steps = blockRangeSteps(range, [
211586
- 3,
211587
- 4,
211588
- 5,
211589
- 6,
211590
- 7,
211591
- 8
211592
- ]);
211593
- const rewards = await Promise.all(steps.map(async (step) => {
211594
- return [
211595
- toStepIdentityString(step),
211596
- await this.networkStakeStepRewardForStepForPosition(step, position)
211597
- ];
211598
- }));
211599
- const result = {};
211600
- for (const [step, reward] of rewards) {
211601
- result[step] = reward;
211602
- }
211603
- const filtered = Object.fromEntries(Object.entries(result).filter(([_, v]) => v[0] > 0n));
211604
- return filtered;
211605
- }
211606
- async networkStakeStepRewardsForRange(range) {
211607
- return await timeBudget("networkStakeStepRewardsForRange", this.logger, async () => {
211608
- const steps = blockRangeSteps(range, [
211609
- 3,
211610
- 4,
211611
- 5,
211612
- 6,
211613
- 7,
211614
- 8
211615
- ]);
211616
- const rewards = await Promise.all(steps.map(async (step) => {
211617
- return await this.networkStakeStepRewardForStep(step);
211618
- }));
211619
- return rewards.reduce((a, b) => a + b, 0n);
211620
- }, 100);
211621
- }
211622
- async networkStakeStepRewardsForStepLevel(stepLevel, range) {
211623
- const steps = blockRangeSteps(range, [
211624
- stepLevel
211625
- ]);
211626
- const rewards = await Promise.all(steps.map(async (step) => {
211627
- return await this.networkStakeStepRewardForStep(step);
211628
- }));
211629
- return rewards.reduce((a, b) => a + b, 0n);
211630
- }
211631
- async stakeById(id) {
211632
- return await this.stake.stakeById(id);
211633
- }
211634
- async stakeByStaker(staker, slot) {
211635
- return await this.stake.stakeByStaker(staker, slot);
211636
- }
211637
- async stakedByStaker(staker) {
211638
- const result = /* @__PURE__ */ new Set();
211639
- let slot = 0;
211640
- while (true) {
211641
- try {
211642
- const ethStake = await this.stake.stakeByStaker(staker, slot);
211643
- result.add(toAddress(ethStake.staked));
211644
- slot++;
211645
- } catch {
211646
- break;
211647
- }
211648
- }
211649
- return [
211650
- ...result
211651
- ];
211652
- }
211653
- async stakesByStaked(staked) {
211654
- return await this.stake.stakesByStaked(staked);
211655
- }
211656
- async stakesByStaker(staker) {
211657
- return await this.stake.stakesByStaker(staker);
211658
- }
211659
- async transactionByBlockHashAndIndex(blockHash, transactionIndex = 0) {
211660
- return await spanRootAsync("transactionByBlockHashAndIndex", async () => {
211661
- assertEx(transactionIndex >= 0, () => "transactionIndex must be greater than or equal to 0");
211662
- try {
211663
- const block = await this.blockByHash(blockHash);
211664
- if (!block) return null;
211665
- const blockBoundWitnessIndexes = block[0].payload_schemas.map((schema, index) => schema === BoundWitnessSchema ? index : void 0).filter(exists$1);
211666
- const blockBoundWitnessHashes = new Set(blockBoundWitnessIndexes.map((index) => block[0].payload_hashes[index]));
211667
- const blockBoundWitnesses = block[1].filter((payload) => blockBoundWitnessHashes.has(payload._hash) || blockBoundWitnessHashes.has(payload._dataHash));
211668
- const blockTransactionBoundWitnesses = blockBoundWitnesses.filter(isTransactionBoundWitnessWithStorageMeta);
211669
- const transaction = blockTransactionBoundWitnesses.at(transactionIndex);
211670
- if (!transaction) return null;
211671
- return await this.transactionByHash(transaction._hash);
211672
- } catch {
211673
- return null;
211674
- }
211675
- }, this.tracer);
211676
- }
211677
- async transactionByBlockNumberAndIndex(blockNumber, transactionIndex = 0) {
211678
- return await spanRootAsync("transactionByBlockNumberAndIndex", async () => {
211679
- try {
211680
- const block = await this.blockByNumber(blockNumber);
211681
- if (!block) return null;
211682
- return await this.transactionByBlockHashAndIndex(block[0]._hash, transactionIndex);
211683
- } catch {
211684
- return null;
211685
- }
211686
- }, this.tracer);
211687
- }
211688
- async transactionByHash(transactionHash) {
211689
- return await spanRootAsync("transactionByHash", async () => {
211690
- try {
211691
- const cache = await this.getHydratedTransactionCache();
211692
- const hydratedTransaction = await cache.get(transactionHash);
211693
- return hydratedTransaction ?? null;
211694
- } catch {
211695
- return null;
211696
- }
211697
- }, this.tracer);
211698
- }
211699
- async transferBalance(address) {
211700
- return await spanRootAsync("transferBalance", async () => {
211701
- const diviner = await this.getTransferBalanceDiviner();
211702
- const query = new PayloadBuilder({
211703
- schema: AddressSchema
211704
- }).fields({
211705
- address
211706
- }).build();
211707
- const result = await diviner.divine([
211708
- query
211709
- ]);
211710
- const chainSummary = result.find(isChainSummaryTransfers);
211711
- const transfers = chainSummary?.transfers ?? {};
211712
- let transferBalance = 0n;
211713
- for (const [from, transfer] of Object.entries(transfers)) {
211714
- if (from === address) {
211715
- for (const [, amount] of Object.entries(transfer)) {
211716
- transferBalance += parseSignedBigInt(amount);
211717
- }
211718
- }
211719
- }
211720
- return asAttoXL1(transferBalance > 0n ? transferBalance : 0n);
211721
- }, this.tracer);
211722
- }
211723
- transferBalanceHistory(_address) {
211724
- throw new Error("Method not implemented.");
211725
- }
211726
- async transferPairBalance(pair) {
211727
- return await spanRootAsync("transferPairBalance", async () => {
211728
- const diviner = await this.getTransferBalanceDiviner();
211729
- const query = new PayloadBuilder({
211730
- schema: AddressPairSchema
211731
- }).fields({
211732
- addresses: [
211733
- pair[0],
211734
- pair[1]
211735
- ]
211736
- }).build();
211737
- const result = await diviner.divine([
211738
- query
211739
- ]);
211740
- const chainSummary = assertEx(result.find(isChainSummaryTransfers), () => "Failed to divine chain summary transfers");
211741
- const transfers = chainSummary.transfers;
211742
- const balance = transfers[pair[0]]?.[pair[1]];
211743
- return isDefined(balance) ? asAttoXL1(parseSignedBigInt(balance) * -1n) : asAttoXL1(0n);
211744
- }, this.tracer);
211745
- }
211746
- transferPairBalanceHistory(_pair) {
211747
- throw new Error("Method not implemented.");
211748
- }
211749
- getAddressBalanceDiviner = /* @__PURE__ */ __name$8(async () => {
211750
- if (this._addressBalanceDiviner) return this._addressBalanceDiviner;
211751
- const resolved = await this.getDiviner(this.addressBalanceDivinerPath);
211752
- this._addressBalanceDiviner = resolved;
211753
- return assertEx(this._addressBalanceDiviner, () => `Could not resolve ${this.addressBalanceDivinerPath} to a diviner instance`);
211754
- }, "getAddressBalanceDiviner");
211755
- getArchivist = /* @__PURE__ */ __name$8(async (identifier) => {
211756
- const archivist = await this.node.resolve(identifier);
211757
- return assertEx(asAttachableArchivistInstance(archivist), () => `Could not resolve ${identifier} to an archivist instance`);
211758
- }, "getArchivist");
211759
- async getCurrentHead() {
211760
- const chainArchivist = await this.getFinalizedArchivist();
211761
- return await findMostRecentBlock(chainArchivist);
211762
- }
211763
- getDiviner = /* @__PURE__ */ __name$8(async (identifier) => {
211764
- const diviner = await this.node.resolve(identifier);
211765
- return assertEx(asDivinerInstance(diviner), () => `Could not resolve ${identifier} to a diviner instance`);
211766
- }, "getDiviner");
211767
- getFinalizedArchivist = /* @__PURE__ */ __name$8(async () => {
211768
- if (this._finalizedArchivist) return this._finalizedArchivist;
211769
- const resolved = await this.getArchivist(this.finalizedArchivistPath);
211770
- this._finalizedArchivist = resolved;
211771
- return assertEx(this._finalizedArchivist, () => `Could not resolve finalized archivist at ${this.finalizedArchivistPath}`);
211772
- }, "getFinalizedArchivist");
211773
- getFinalizedPayloadMap = /* @__PURE__ */ __name$8(async () => {
211774
- const archivist = this.getFinalizedArchivist();
211775
- return readPayloadMapFromStore(await archivist);
211776
- }, "getFinalizedPayloadMap");
211777
- async getHydratedBlockCache() {
211778
- if (this._signedHydratedBlockCache) return this._signedHydratedBlockCache;
211779
- const chainMap = await this.getFinalizedPayloadMap();
211780
- this._signedHydratedBlockCache = new HydratedCache(chainMap, hydrateBlock, 200);
211781
- return this._signedHydratedBlockCache;
211782
- }
211783
- async getHydratedTransactionCache() {
211784
- if (this._signedHydratedTransactionCache) return this._signedHydratedTransactionCache;
211785
- const chainMap = await this.getFinalizedPayloadMap();
211786
- this._signedHydratedTransactionCache = new HydratedCache(chainMap, tryHydrateTransaction, 200);
211787
- return this._signedHydratedTransactionCache;
211788
- }
211789
- getTransferBalanceDiviner = /* @__PURE__ */ __name$8(async () => {
211790
- if (this._transferBalanceDiviner) return this._transferBalanceDiviner;
211791
- const resolved = await this.getDiviner(this.transferBalanceDivinerPath);
211792
- this._transferBalanceDiviner = resolved;
211793
- return assertEx(this._transferBalanceDiviner, () => `Could not resolve ${this.transferBalanceDivinerPath} to a diviner instance`);
211794
- }, "getTransferBalanceDiviner");
211795
- async startHandler() {
211796
- const currentBlockNumber = await this.currentBlockNumber();
211797
- await this.transferBalance(XYO_ZERO_ADDRESS);
211798
- await this.accountBalance(XYO_ZERO_ADDRESS);
211799
- if (this.initRewardsCache) {
211800
- const externalRange = await externalBlockRangeFromXL1BlockRange(this.context, asXL1BlockRange([
211801
- 0,
211802
- currentBlockNumber
211803
- ], {
211804
- name: "startHandler"
211805
- }));
211806
- const positionCount = await this.context.events.positionCount(externalRange);
211807
- this.logger?.log(`NodeXyoViewer: Precomputing networkStakeStepRewardForPosition up to position ${positionCount - 1}`);
211808
- for (let position = 0; position < positionCount; position++) {
211809
- await this.networkStakeStepRewardForPosition(position, asXL1BlockRange([
211810
- 0,
211811
- currentBlockNumber
211812
- ], {
211813
- name: "startHandler"
211814
- }));
211815
- }
211816
- this.logger?.log(`NodeXyoViewer: Precomputed networkStakeStepRewardForPosition up to position ${positionCount - 1}`);
211817
- }
211818
- }
211819
- async stepWeightedDenominator(stepIdentity) {
211820
- const cacheKey = toStepIdentityString(stepIdentity);
211821
- return await withContextCacheResponse(this.context, "NodeXyoViewer-networkStakeStepRewardForStepForPosition-denominator", cacheKey, async () => {
211822
- const range = await externalBlockRangeFromStep(this.context, stepIdentity);
211823
- return await weightedStakeForRangeByPosition(this.context, range);
211824
- });
211825
- }
211826
- async distillTransferHistory(address, range, max = 50) {
211827
- if (range[1] - range[0] <= StepSizes[0] || max <= 1) {
211828
- return Array.from({
211829
- length: range[1] - range[0] + 1
211830
- }, (_, i) => range[1] - i).slice(0, max).map((n) => asXL1BlockNumber(n, {
211831
- name: "distillTransferHistory"
211832
- }));
211833
- }
211834
- const frames = deepCalculateFramesFromRange(asXL1BlockRange(range, {
211835
- name: "distillTransferHistory"
211836
- }));
211837
- const transferSummaryPairs = await Promise.all(frames.map(async (frame) => {
211838
- return [
211839
- frame,
211840
- await transfersStepSummaryFromRange(this.transfersSummaryContext, frame)
211841
- ];
211842
- }));
211843
- const filteredTransferSummaryPairs = transferSummaryPairs.filter(([_, summary]) => Object.keys(summary.transfers).includes(address));
211844
- const sortedTransferSummaryPairs = filteredTransferSummaryPairs.toSorted((a, b) => {
211845
- return b[0][1] - a[0][1];
211846
- });
211847
- const resultBlockNumbers = /* @__PURE__ */ new Set();
211848
- for (const [frame] of sortedTransferSummaryPairs) {
211849
- if (frame[1] - frame[0] + 1 > StepSizes[0]) {
211850
- const values = await this.distillTransferHistory(address, asXL1BlockRange([
211851
- frame[0],
211852
- frame[1] - 1
211853
- ], {
211854
- name: "distillTransferHistory"
211855
- }), max - resultBlockNumbers.size);
211856
- for (const value of values) {
211857
- resultBlockNumbers.add(value);
211858
- }
211859
- resultBlockNumbers.add(frame[1]);
211860
- } else {
211861
- for (let i = frame[0]; i <= frame[1]; i++) {
211862
- resultBlockNumbers.add(i);
211863
- }
211864
- }
211865
- if (resultBlockNumbers.size >= max) {
211866
- break;
211867
- }
211868
- }
211869
- return [
211870
- ...resultBlockNumbers
211871
- ].toSorted((a, b) => b - a).slice(0, max);
211872
- }
211873
- };
211874
-
211875
- var __defProp$c = Object.defineProperty;
211876
- var __name$7 = (target, value) => __defProp$c(target, "name", { value, configurable: true });
211877
- async function networkStakeStepRewardEarnedForPosition(context, stepIdentity, position, rewardMultipliers = {}) {
211878
- const cacheKey = `${stepIdentity.block}|${stepIdentity.step}|${position.id}`;
211879
- return await withContextCacheResponse(context, "networkStakeStepRewardEarnedForPosition", cacheKey, async () => {
211880
- const range = await externalBlockRangeFromStep(context, stepIdentity);
211881
- const numerator = position.staked === XYO_NETWORK_STAKING_ADDRESS ? await weightedStakeForRangeByPosition(context, range, position.id) : 0n;
211882
- const denominator = await weightedStakeForRangeByPosition(context, range);
211883
- const totalReward = await stepRewardTotal(context, stepIdentity, rewardMultipliers);
211884
- const positionReward = denominator > 0n ? totalReward * numerator / denominator : 0n;
211885
- const result = [
211886
- positionReward,
211887
- totalReward
211888
- ];
211889
- return result;
211890
- });
211891
- }
211892
- __name$7(networkStakeStepRewardEarnedForPosition, "networkStakeStepRewardEarnedForPosition");
211893
-
211894
- // src/primitives/networkStakeStepRewardEarned.ts
211895
- async function networkStakeStepRewardEarned(context, stepIdentity, rewardMultipliers = {}) {
211896
- const cacheKey = `${stepIdentity.block}|${stepIdentity.step}`;
211897
- return await withContextCacheResponse(context, "networkStakeStepRewardEarned", cacheKey, async () => {
211898
- const positions = await context.stake.stakesByStaked(XYO_NETWORK_STAKING_ADDRESS);
211899
- const results = await Promise.all(positions.map((pos) => {
211900
- return networkStakeStepRewardEarnedForPosition(context, stepIdentity, pos, rewardMultipliers);
211901
- }));
211902
- const numerator = results.reduce((acc, [positionReward]) => acc + positionReward, 0n);
211903
- const result = results.length > 0 ? [
211904
- numerator,
211905
- results[0][1]
211906
- ] : [
211907
- 0n,
211908
- 0n
211909
- ];
211910
- return result;
211911
- });
211912
- }
211913
- __name$7(networkStakeStepRewardEarned, "networkStakeStepRewardEarned");
211914
- async function networkStakeStepRewardEarnedForStaker(context, stepIdentity, staker, rewardMultipliers = {}) {
211915
- const stepId = toStepIdentityString(stepIdentity);
211916
- return await withContextCacheResponse(context, "networkStakeStepRewardEarnedForStaker", `${stepId}-${staker}`, async () => {
211917
- const positions = (await context.stake.stakesByStaker(staker)).filter((pos) => pos.staked === XYO_NETWORK_STAKING_ADDRESS);
211918
- const results = await Promise.all(positions.map((pos) => {
211919
- return networkStakeStepRewardEarnedForPosition(context, stepIdentity, pos, rewardMultipliers);
211920
- }));
211921
- const numerator = results.reduce((acc, [positionReward]) => acc + positionReward, 0n);
211922
- const result = results.length > 0 ? [
211923
- numerator,
211924
- results[0][1]
211925
- ] : [
211926
- 0n,
211927
- 0n
211928
- ];
211929
- return result;
211930
- });
211931
- }
211932
- __name$7(networkStakeStepRewardEarnedForStaker, "networkStakeStepRewardEarnedForStaker");
211933
- var SimpleStepRewardsByPositionViewer = class extends AbstractCreatable {
211934
- static {
211935
- __name$7(this, "SimpleStepRewardsByPositionViewer");
211936
- }
211937
- get context() {
211938
- return this.params.context;
211939
- }
211940
- get rewardMultipliers() {
211941
- return this.params.rewardMultipliers ?? {};
211942
- }
211943
- async bonus({ range, positions } = {}) {
211944
- const total = await this.total({
211945
- range,
211946
- positions
211947
- });
211948
- const earned = await this.earned({
211949
- range,
211950
- positions
211951
- });
211952
- const result = {};
211953
- for (const pos of Object.keys(total).map(Number)) {
211954
- result[pos] = asAttoXL1(total[pos] - (earned[pos] ?? 0n));
211955
- }
211956
- return result;
211957
- }
211958
- claimed(_options) {
211959
- throw new Error("Method not implemented.");
211960
- }
211961
- async earned({ range, positions } = {}) {
211962
- return await this.calculateRewards({
211963
- range,
211964
- positions
211965
- });
211966
- }
211967
- async total({ range, positions } = {}) {
211968
- return await this.calculateRewards({
211969
- range,
211970
- positions
211971
- }, this.rewardMultipliers);
211972
- }
211973
- unclaimed(_options = {}) {
211974
- throw new Error("Method not implemented.");
211975
- }
211976
- async calculateRewards({ range, positions } = {}, rewardMultipliers) {
211977
- const result = {};
211978
- const steps = blockRangeSteps(asXL1BlockRange(range ?? [
211979
- 0,
211980
- (await this.context.head())[1]
211981
- ], {
211982
- name: "NodeStepRewardsByPositionViewer"
211983
- }), [
211984
- 3,
211985
- 4,
211986
- 5,
211987
- 6,
211988
- 7
211989
- ]);
211990
- for (const step of steps) {
211991
- if (isArray$1(positions)) {
211992
- for (const positionId of positions) {
211993
- const position = await this.context.stake.stakeById(positionId);
211994
- result[positionId] = asAttoXL1((result[positionId] ?? 0n) + (await networkStakeStepRewardEarnedForPosition(this.context, step, position, rewardMultipliers))[0]);
211995
- }
211996
- }
211997
- }
211998
- return result;
211999
- }
212000
- };
212001
- var SimpleStepRewardsByStakerViewer = class extends AbstractCreatable {
212002
- static {
212003
- __name$7(this, "SimpleStepRewardsByStakerViewer");
212004
- }
212005
- get context() {
212006
- return this.params.context;
212007
- }
212008
- get rewardMultipliers() {
212009
- return this.params.rewardMultipliers ?? {};
212010
- }
212011
- get stakedChainContext() {
212012
- return this.params.context;
212013
- }
212014
- async bonus({ range, stakers } = {}) {
212015
- const total = await this.total({
212016
- range,
212017
- stakers
212018
- });
212019
- const earned = await this.earned({
212020
- range,
212021
- stakers
212022
- });
212023
- const result = {};
212024
- for (const staker of Object.keys(total)) {
212025
- result[staker] = asAttoXL1(total[staker] - (earned[staker] ?? 0n));
212026
- }
212027
- return result;
212028
- }
212029
- claimed(_options) {
212030
- throw new Error("Method not implemented.");
212031
- }
212032
- async earned(options = {}) {
212033
- return await this.calculateRewards(options);
212034
- }
212035
- async total(options = {}) {
212036
- return await this.calculateRewards(options, this.rewardMultipliers);
212037
- }
212038
- unclaimed(_options = {}) {
212039
- throw new Error("Method not implemented.");
212040
- }
212041
- async calculateRewards({ range, stakers } = {}, rewardMultipliers) {
212042
- const result = {};
212043
- const steps = blockRangeSteps(asXL1BlockRange(range ?? [
212044
- 0,
212045
- (await this.context.head())[1]
212046
- ], {
212047
- name: "NodeStepRewardsByStakerViewer"
212048
- }), [
212049
- 3,
212050
- 4,
212051
- 5,
212052
- 6,
212053
- 7
212054
- ]);
212055
- for (const step of steps) {
212056
- if (isArray$1(stakers)) {
212057
- for (const staker of stakers) {
212058
- result[staker] = asAttoXL1((result[staker] ?? 0n) + (await networkStakeStepRewardEarnedForStaker(this.context, step, staker, rewardMultipliers))[0]);
212059
- }
212060
- }
212061
- }
212062
- return result;
212063
- }
212064
- };
212065
- var SimpleStepRewardsByStepViewer = class extends AbstractCreatable {
212066
- static {
212067
- __name$7(this, "SimpleStepRewardsByStepViewer");
212068
- }
212069
- get context() {
212070
- return this.params.context;
212071
- }
212072
- get rewardMultipliers() {
212073
- return this.params.rewardMultipliers ?? {};
212074
- }
212075
- async bonus({ range, steps } = {}) {
212076
- const total = await this.total({
212077
- range,
212078
- steps
212079
- });
212080
- const earned = await this.earned({
212081
- range,
212082
- steps
212083
- });
212084
- const result = {};
212085
- for (const stepString of Object.keys(total)) {
212086
- result[stepString] = asAttoXL1(total[stepString] - (earned[stepString] ?? 0n));
212087
- }
212088
- return result;
212089
- }
212090
- claimed(_options) {
212091
- throw new Error("Method not implemented.");
212092
- }
212093
- async earned({ range, steps } = {}) {
212094
- const result = {};
212095
- const resolvedSteps = steps ?? blockRangeSteps(asXL1BlockRange(range ?? [
212096
- 0,
212097
- (await this.context.head())[1]
212098
- ], {
212099
- name: "NodeStepRewardsByStepViewer"
212100
- }), [
212101
- 3,
212102
- 4,
212103
- 5,
212104
- 6,
212105
- 7
212106
- ]);
212107
- for (const step of resolvedSteps) {
212108
- const stepIdentityString = toStepIdentityString(step);
212109
- result[stepIdentityString] = asAttoXL1((result[stepIdentityString] ?? 0n) + (await networkStakeStepRewardEarned(this.context, step))[0]);
212110
- }
212111
- return result;
212112
- }
212113
- async total({ range, steps } = {}) {
212114
- const result = {};
212115
- const resolvedSteps = steps ?? blockRangeSteps(asXL1BlockRange(range ?? [
212116
- 0,
212117
- (await this.context.head())[1]
212118
- ], {
212119
- name: "NodeStepRewardsByStepViewer"
212120
- }), [
212121
- 3,
212122
- 4,
212123
- 5,
212124
- 6,
212125
- 7
212126
- ]);
212127
- for (const step of resolvedSteps) {
212128
- const stepIdentityString = toStepIdentityString(step);
212129
- result[stepIdentityString] = asAttoXL1((result[stepIdentityString] ?? 0n) + (await networkStakeStepRewardEarned(this.context, step, this.rewardMultipliers))[0]);
212130
- }
212131
- return result;
212132
- }
212133
- unclaimed(_options = {}) {
212134
- throw new Error("Method not implemented.");
212135
- }
212136
- };
212137
- var SimpleStepRewardsViewer = class extends AbstractCreatable {
212138
- static {
212139
- __name$7(this, "SimpleStepRewardsViewer");
212140
- }
212141
- _position;
212142
- _staker;
212143
- _step;
212144
- get position() {
212145
- return assertEx(this._position, () => "Position viewer not initialized");
212146
- }
212147
- get staker() {
212148
- return assertEx(this._staker, () => "Position viewer not initialized");
212149
- }
212150
- get step() {
212151
- return assertEx(this._step, () => "Step viewer not initialized");
212152
- }
212153
- get total() {
212154
- throw new Error("Method not implemented.");
212155
- }
212156
- get context() {
212157
- return this.params.context;
212158
- }
212159
- get rewardMultipliers() {
212160
- return this.params.rewardMultipliers;
212161
- }
212162
- async createHandler() {
212163
- await super.createHandler();
212164
- this._position = await SimpleStepRewardsByPositionViewer.create({
212165
- context: this.context,
212166
- rewardMultipliers: this.rewardMultipliers
212167
- });
212168
- this._staker = await SimpleStepRewardsByStakerViewer.create({
212169
- context: this.context,
212170
- rewardMultipliers: this.rewardMultipliers
212171
- });
212172
- this._step = await SimpleStepRewardsByStepViewer.create({
212173
- context: this.context,
212174
- rewardMultipliers: this.rewardMultipliers
212175
- });
212176
- }
212177
- async startHandler() {
212178
- await super.startHandler();
212179
- await assertEx(this._position, () => "Position viewer not created").start();
212180
- await assertEx(this._staker, () => "Staker viewer not created").start();
212181
- await assertEx(this._step, () => "Step viewer not created").start();
212182
- }
212183
- };
212184
- var SimpleNetworkStakeViewer = class extends AbstractCreatable {
212185
- static {
212186
- __name$7(this, "SimpleNetworkStakeViewer");
212187
- }
212188
- _stepRewardsViewer;
212189
- get context() {
212190
- return this.params.context;
212191
- }
212192
- get rewardMultipliers() {
212193
- return this.params.rewardMultipliers;
212194
- }
212195
- get stepRewards() {
212196
- return assertEx(this._stepRewardsViewer, () => "Step rewards viewer not initialized");
212197
- }
212198
- async active(blockNumber) {
212199
- const resolvedBlockNumber = blockNumber ?? (await this.context.head())[1];
212200
- return [
212201
- await this.context.stake.active(resolvedBlockNumber),
212202
- resolvedBlockNumber
212203
- ];
212204
- }
212205
- async createHandler() {
212206
- await super.createHandler();
212207
- this._stepRewardsViewer = await SimpleStepRewardsViewer.create({
212208
- context: this.context,
212209
- rewardMultipliers: this.rewardMultipliers
212210
- });
212211
- }
212212
- async startHandler() {
212213
- await super.startHandler();
212214
- const stepRewardsByPositionViewer = await SimpleStepRewardsByPositionViewer.create({
212215
- context: this.context,
212216
- rewardMultipliers: this.rewardMultipliers
212217
- });
212218
- console.log("Initializing NodeStepRewardsByPositionViewer...");
212219
- await stepRewardsByPositionViewer.start();
212220
- console.log("Initialized NodeStepRewardsByPositionViewer.");
212221
- }
212222
- };
212223
-
212224
213167
  /**
212225
213168
  * JsonRpcEngine only accepts callback-based middleware directly.
212226
213169
  * createAsyncMiddleware exists to enable consumers to pass in async middleware
@@ -214332,78 +215275,78 @@ function v4(options, buf, offset) {
214332
215275
  return _v4(options);
214333
215276
  }
214334
215277
 
214335
- var __defProp$b = Object.defineProperty;
214336
- var __name$6 = (target, value) => __defProp$b(target, "name", { value, configurable: true });
215278
+ var __defProp$a = Object.defineProperty;
215279
+ var __name$5 = (target, value) => __defProp$a(target, "name", { value, configurable: true });
214337
215280
 
214338
215281
  // src/engine/requestSchemas.ts
214339
215282
  var requestSchemas = {};
214340
215283
 
214341
215284
  // src/engine/rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer.ts
214342
- var rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer = /* @__PURE__ */ __name$6((viewer) => {
215285
+ var rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer = /* @__PURE__ */ __name$5((viewer) => {
214343
215286
  return {
214344
- networkStakingStepRewardsByPositionViewer_bonus: /* @__PURE__ */ __name$6((params) => viewer.bonus(...params ?? []), "networkStakingStepRewardsByPositionViewer_bonus"),
214345
- networkStakingStepRewardsByPositionViewer_claimed: /* @__PURE__ */ __name$6((params) => viewer.claimed(...params ?? []), "networkStakingStepRewardsByPositionViewer_claimed"),
214346
- networkStakingStepRewardsByPositionViewer_earned: /* @__PURE__ */ __name$6((params) => viewer.earned(...params ?? []), "networkStakingStepRewardsByPositionViewer_earned"),
214347
- networkStakingStepRewardsByPositionViewer_total: /* @__PURE__ */ __name$6((params) => viewer.total(...params ?? []), "networkStakingStepRewardsByPositionViewer_total"),
214348
- networkStakingStepRewardsByPositionViewer_unclaimed: /* @__PURE__ */ __name$6((params) => viewer.unclaimed(...params ?? []), "networkStakingStepRewardsByPositionViewer_unclaimed")
215287
+ networkStakingStepRewardsByPositionViewer_bonus: /* @__PURE__ */ __name$5((params) => viewer.bonus(...params ?? []), "networkStakingStepRewardsByPositionViewer_bonus"),
215288
+ networkStakingStepRewardsByPositionViewer_claimed: /* @__PURE__ */ __name$5((params) => viewer.claimed(...params ?? []), "networkStakingStepRewardsByPositionViewer_claimed"),
215289
+ networkStakingStepRewardsByPositionViewer_earned: /* @__PURE__ */ __name$5((params) => viewer.earned(...params ?? []), "networkStakingStepRewardsByPositionViewer_earned"),
215290
+ networkStakingStepRewardsByPositionViewer_total: /* @__PURE__ */ __name$5((params) => viewer.total(...params ?? []), "networkStakingStepRewardsByPositionViewer_total"),
215291
+ networkStakingStepRewardsByPositionViewer_unclaimed: /* @__PURE__ */ __name$5((params) => viewer.unclaimed(...params ?? []), "networkStakingStepRewardsByPositionViewer_unclaimed")
214349
215292
  };
214350
215293
  }, "rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer");
214351
215294
 
214352
215295
  // src/engine/rpcMethodHandlersFromRunner.ts
214353
- var rpcMethodHandlersFromRunner = /* @__PURE__ */ __name$6((runner) => {
215296
+ var rpcMethodHandlersFromRunner = /* @__PURE__ */ __name$5((runner) => {
214354
215297
  return {
214355
- xyoRunner_broadcastTransaction: /* @__PURE__ */ __name$6((params) => runner.broadcastTransaction(...params ?? []), "xyoRunner_broadcastTransaction")
215298
+ xyoRunner_broadcastTransaction: /* @__PURE__ */ __name$5((params) => runner.broadcastTransaction(...params ?? []), "xyoRunner_broadcastTransaction")
214356
215299
  };
214357
215300
  }, "rpcMethodHandlersFromRunner");
214358
215301
 
214359
215302
  // src/engine/rpcMethodHandlersFromViewer.ts
214360
- var rpcMethodHandlersFromViewer = /* @__PURE__ */ __name$6((viewer) => {
215303
+ var rpcMethodHandlersFromViewer = /* @__PURE__ */ __name$5((viewer) => {
214361
215304
  return {
214362
- xyoViewer_networkStakeStepRewardClaimedByAddress: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardClaimedByAddress(...params ?? []), "xyoViewer_networkStakeStepRewardClaimedByAddress"),
214363
- xyoViewer_networkStakeStepRewardAddressReward: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardAddressReward(...params ?? []), "xyoViewer_networkStakeStepRewardAddressReward"),
214364
- xyoViewer_networkStakeStepRewardAddressHistory: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardAddressHistory(...params ?? []), "xyoViewer_networkStakeStepRewardAddressHistory"),
214365
- xyoViewer_networkStakeStepRewardAddressShare: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardAddressShare(...params ?? []), "xyoViewer_networkStakeStepRewardAddressShare"),
214366
- xyoViewer_networkStakeStepRewardWeightForAddress: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardWeightForAddress?.(...params ?? []), "xyoViewer_networkStakeStepRewardWeightForAddress"),
214367
- xyoViewer_networkStakeStepRewardUnclaimedByAddress: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardUnclaimedByAddress(...params ?? []), "xyoViewer_networkStakeStepRewardUnclaimedByAddress"),
214368
- xyoViewer_networkStakeStepRewardPoolShares: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardPoolShares(...params ?? []), "xyoViewer_networkStakeStepRewardPoolShares"),
214369
- xyoViewer_networkStakeStepRewardPoolRewards: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardPoolRewards(...params ?? []), "xyoViewer_networkStakeStepRewardPoolRewards"),
214370
- xyoViewer_networkStakeStepRewardPositionWeight: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardPositionWeight?.(...params ?? []), "xyoViewer_networkStakeStepRewardPositionWeight"),
214371
- xyoViewer_networkStakeStepRewardPotentialPositionLoss: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardPotentialPositionLoss?.(...params ?? []), "xyoViewer_networkStakeStepRewardPotentialPositionLoss"),
214372
- xyoViewer_networkStakeStepRewardForStep: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardForStep?.(...params ?? []), "xyoViewer_networkStakeStepRewardForStep"),
214373
- xyoViewer_networkStakeStepRewardRandomizer: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardRandomizer?.(...params ?? []), "xyoViewer_networkStakeStepRewardRandomizer"),
214374
- xyoViewer_networkStakeStepRewardStakerCount: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardStakerCount?.(...params ?? []), "xyoViewer_networkStakeStepRewardStakerCount"),
214375
- xyoViewer_networkStakeStepRewardForStepForPosition: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardForStepForPosition?.(...params ?? []), "xyoViewer_networkStakeStepRewardForStepForPosition"),
214376
- xyoViewer_networkStakeStepRewardForPosition: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardForPosition?.(...params ?? []), "xyoViewer_networkStakeStepRewardForPosition"),
214377
- xyoViewer_networkStakeStepRewardsForPosition: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardsForPosition?.(...params ?? []), "xyoViewer_networkStakeStepRewardsForPosition"),
214378
- xyoViewer_networkStakeStepRewardsForRange: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardsForRange?.(...params ?? []), "xyoViewer_networkStakeStepRewardsForRange"),
214379
- xyoViewer_networkStakeStepRewardsForStepLevel: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardsForStepLevel?.(...params ?? []), "xyoViewer_networkStakeStepRewardsForStepLevel"),
214380
- xyoViewer_accountBalance: /* @__PURE__ */ __name$6((params) => viewer.accountBalance(...params ?? []), "xyoViewer_accountBalance"),
214381
- xyoViewer_accountBalanceHistory: /* @__PURE__ */ __name$6((params) => viewer.accountBalanceHistory(...params ?? []), "xyoViewer_accountBalanceHistory"),
214382
- xyoViewer_blockByHash: /* @__PURE__ */ __name$6((params) => viewer.blockByHash(...params ?? []), "xyoViewer_blockByHash"),
214383
- xyoViewer_blockByNumber: /* @__PURE__ */ __name$6((params) => viewer.blockByNumber(...params ?? []), "xyoViewer_blockByNumber"),
214384
- xyoViewer_blocksByHash: /* @__PURE__ */ __name$6((params) => viewer.blocksByHash(...params ?? []), "xyoViewer_blocksByHash"),
214385
- xyoViewer_chainId: /* @__PURE__ */ __name$6((params) => viewer.chainId(...params ?? []), "xyoViewer_chainId"),
214386
- xyoViewer_chainIdAtBlock: /* @__PURE__ */ __name$6((params) => viewer.chainIdAtBlock(...params ?? []), "xyoViewer_chainIdAtBlock"),
214387
- xyoViewer_currentBlock: /* @__PURE__ */ __name$6((params) => viewer.currentBlock(...params ?? []), "xyoViewer_currentBlock"),
214388
- xyoViewer_currentBlockHash: /* @__PURE__ */ __name$6((params) => viewer.currentBlockHash(...params ?? []), "xyoViewer_currentBlockHash"),
214389
- xyoViewer_currentBlockNumber: /* @__PURE__ */ __name$6((params) => viewer.currentBlockNumber(...params ?? []), "xyoViewer_currentBlockNumber"),
214390
- xyoViewer_forkHistory: /* @__PURE__ */ __name$6((params) => viewer.forkHistory(...params ?? []), "xyoViewer_forkHistory"),
214391
- xyoViewer_stakeById: /* @__PURE__ */ __name$6((params) => viewer.stakeById(...params ?? []), "xyoViewer_stakeById"),
214392
- xyoViewer_stakeByStaker: /* @__PURE__ */ __name$6((params) => viewer.stakeByStaker(...params ?? []), "xyoViewer_stakeByStaker"),
214393
- xyoViewer_stakesByStaked: /* @__PURE__ */ __name$6((params) => viewer.stakesByStaked(...params ?? []), "xyoViewer_stakesByStaked"),
214394
- xyoViewer_stakesByStaker: /* @__PURE__ */ __name$6((params) => viewer.stakesByStaker(...params ?? []), "xyoViewer_stakesByStaker"),
214395
- xyoViewer_transactionByBlockHashAndIndex: /* @__PURE__ */ __name$6((params) => viewer.transactionByBlockHashAndIndex(...params ?? []), "xyoViewer_transactionByBlockHashAndIndex"),
214396
- xyoViewer_transactionByBlockNumberAndIndex: /* @__PURE__ */ __name$6((params) => viewer.transactionByBlockNumberAndIndex(...params ?? []), "xyoViewer_transactionByBlockNumberAndIndex"),
214397
- xyoViewer_transactionByHash: /* @__PURE__ */ __name$6((params) => viewer.transactionByHash(...params ?? []), "xyoViewer_transactionByHash"),
214398
- xyoViewer_transferBalance: /* @__PURE__ */ __name$6((params) => viewer.transferBalance(...params ?? []), "xyoViewer_transferBalance"),
214399
- xyoViewer_transferBalanceHistory: /* @__PURE__ */ __name$6((params) => viewer.transferBalanceHistory(...params ?? []), "xyoViewer_transferBalanceHistory"),
214400
- xyoViewer_transferPairBalance: /* @__PURE__ */ __name$6((params) => viewer.transferPairBalance(...params ?? []), "xyoViewer_transferPairBalance"),
214401
- xyoViewer_transferPairBalanceHistory: /* @__PURE__ */ __name$6((params) => viewer.transferPairBalanceHistory(...params ?? []), "xyoViewer_transferPairBalanceHistory")
215305
+ xyoViewer_networkStakeStepRewardClaimedByAddress: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardClaimedByAddress(...params ?? []), "xyoViewer_networkStakeStepRewardClaimedByAddress"),
215306
+ xyoViewer_networkStakeStepRewardAddressReward: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardAddressReward(...params ?? []), "xyoViewer_networkStakeStepRewardAddressReward"),
215307
+ xyoViewer_networkStakeStepRewardAddressHistory: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardAddressHistory(...params ?? []), "xyoViewer_networkStakeStepRewardAddressHistory"),
215308
+ xyoViewer_networkStakeStepRewardAddressShare: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardAddressShare(...params ?? []), "xyoViewer_networkStakeStepRewardAddressShare"),
215309
+ xyoViewer_networkStakeStepRewardWeightForAddress: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardWeightForAddress?.(...params ?? []), "xyoViewer_networkStakeStepRewardWeightForAddress"),
215310
+ xyoViewer_networkStakeStepRewardUnclaimedByAddress: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardUnclaimedByAddress(...params ?? []), "xyoViewer_networkStakeStepRewardUnclaimedByAddress"),
215311
+ xyoViewer_networkStakeStepRewardPoolShares: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardPoolShares(...params ?? []), "xyoViewer_networkStakeStepRewardPoolShares"),
215312
+ xyoViewer_networkStakeStepRewardPoolRewards: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardPoolRewards(...params ?? []), "xyoViewer_networkStakeStepRewardPoolRewards"),
215313
+ xyoViewer_networkStakeStepRewardPositionWeight: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardPositionWeight?.(...params ?? []), "xyoViewer_networkStakeStepRewardPositionWeight"),
215314
+ xyoViewer_networkStakeStepRewardPotentialPositionLoss: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardPotentialPositionLoss?.(...params ?? []), "xyoViewer_networkStakeStepRewardPotentialPositionLoss"),
215315
+ xyoViewer_networkStakeStepRewardForStep: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardForStep?.(...params ?? []), "xyoViewer_networkStakeStepRewardForStep"),
215316
+ xyoViewer_networkStakeStepRewardRandomizer: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardRandomizer?.(...params ?? []), "xyoViewer_networkStakeStepRewardRandomizer"),
215317
+ xyoViewer_networkStakeStepRewardStakerCount: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardStakerCount?.(...params ?? []), "xyoViewer_networkStakeStepRewardStakerCount"),
215318
+ xyoViewer_networkStakeStepRewardForStepForPosition: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardForStepForPosition?.(...params ?? []), "xyoViewer_networkStakeStepRewardForStepForPosition"),
215319
+ xyoViewer_networkStakeStepRewardForPosition: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardForPosition?.(...params ?? []), "xyoViewer_networkStakeStepRewardForPosition"),
215320
+ xyoViewer_networkStakeStepRewardsForPosition: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardsForPosition?.(...params ?? []), "xyoViewer_networkStakeStepRewardsForPosition"),
215321
+ xyoViewer_networkStakeStepRewardsForRange: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardsForRange?.(...params ?? []), "xyoViewer_networkStakeStepRewardsForRange"),
215322
+ xyoViewer_networkStakeStepRewardsForStepLevel: /* @__PURE__ */ __name$5((params) => viewer.networkStakeStepRewardsForStepLevel?.(...params ?? []), "xyoViewer_networkStakeStepRewardsForStepLevel"),
215323
+ xyoViewer_accountBalance: /* @__PURE__ */ __name$5((params) => viewer.accountBalance(...params ?? []), "xyoViewer_accountBalance"),
215324
+ xyoViewer_accountBalanceHistory: /* @__PURE__ */ __name$5((params) => viewer.accountBalanceHistory(...params ?? []), "xyoViewer_accountBalanceHistory"),
215325
+ xyoViewer_blockByHash: /* @__PURE__ */ __name$5((params) => viewer.blockByHash(...params ?? []), "xyoViewer_blockByHash"),
215326
+ xyoViewer_blockByNumber: /* @__PURE__ */ __name$5((params) => viewer.blockByNumber(...params ?? []), "xyoViewer_blockByNumber"),
215327
+ xyoViewer_blocksByHash: /* @__PURE__ */ __name$5((params) => viewer.blocksByHash(...params ?? []), "xyoViewer_blocksByHash"),
215328
+ xyoViewer_chainId: /* @__PURE__ */ __name$5((params) => viewer.chainId(...params ?? []), "xyoViewer_chainId"),
215329
+ xyoViewer_chainIdAtBlock: /* @__PURE__ */ __name$5((params) => viewer.chainIdAtBlock(...params ?? []), "xyoViewer_chainIdAtBlock"),
215330
+ xyoViewer_currentBlock: /* @__PURE__ */ __name$5((params) => viewer.currentBlock(...params ?? []), "xyoViewer_currentBlock"),
215331
+ xyoViewer_currentBlockHash: /* @__PURE__ */ __name$5((params) => viewer.currentBlockHash(...params ?? []), "xyoViewer_currentBlockHash"),
215332
+ xyoViewer_currentBlockNumber: /* @__PURE__ */ __name$5((params) => viewer.currentBlockNumber(...params ?? []), "xyoViewer_currentBlockNumber"),
215333
+ xyoViewer_forkHistory: /* @__PURE__ */ __name$5((params) => viewer.forkHistory(...params ?? []), "xyoViewer_forkHistory"),
215334
+ xyoViewer_stakeById: /* @__PURE__ */ __name$5((params) => viewer.stakeById(...params ?? []), "xyoViewer_stakeById"),
215335
+ xyoViewer_stakeByStaker: /* @__PURE__ */ __name$5((params) => viewer.stakeByStaker(...params ?? []), "xyoViewer_stakeByStaker"),
215336
+ xyoViewer_stakesByStaked: /* @__PURE__ */ __name$5((params) => viewer.stakesByStaked(...params ?? []), "xyoViewer_stakesByStaked"),
215337
+ xyoViewer_stakesByStaker: /* @__PURE__ */ __name$5((params) => viewer.stakesByStaker(...params ?? []), "xyoViewer_stakesByStaker"),
215338
+ xyoViewer_transactionByBlockHashAndIndex: /* @__PURE__ */ __name$5((params) => viewer.transactionByBlockHashAndIndex(...params ?? []), "xyoViewer_transactionByBlockHashAndIndex"),
215339
+ xyoViewer_transactionByBlockNumberAndIndex: /* @__PURE__ */ __name$5((params) => viewer.transactionByBlockNumberAndIndex(...params ?? []), "xyoViewer_transactionByBlockNumberAndIndex"),
215340
+ xyoViewer_transactionByHash: /* @__PURE__ */ __name$5((params) => viewer.transactionByHash(...params ?? []), "xyoViewer_transactionByHash"),
215341
+ xyoViewer_transferBalance: /* @__PURE__ */ __name$5((params) => viewer.transferBalance(...params ?? []), "xyoViewer_transferBalance"),
215342
+ xyoViewer_transferBalanceHistory: /* @__PURE__ */ __name$5((params) => viewer.transferBalanceHistory(...params ?? []), "xyoViewer_transferBalanceHistory"),
215343
+ xyoViewer_transferPairBalance: /* @__PURE__ */ __name$5((params) => viewer.transferPairBalance(...params ?? []), "xyoViewer_transferPairBalance"),
215344
+ xyoViewer_transferPairBalanceHistory: /* @__PURE__ */ __name$5((params) => viewer.transferPairBalanceHistory(...params ?? []), "xyoViewer_transferPairBalanceHistory")
214402
215345
  };
214403
215346
  }, "rpcMethodHandlersFromViewer");
214404
215347
 
214405
215348
  // src/engine/rpcMethodHandlersFromConnection.ts
214406
- var rpcMethodHandlersFromConnection = /* @__PURE__ */ __name$6((connection, networkStakeViewer) => {
215349
+ var rpcMethodHandlersFromConnection = /* @__PURE__ */ __name$5((connection, networkStakeViewer) => {
214407
215350
  const { runner, viewer } = connection;
214408
215351
  let result = {};
214409
215352
  if (runner) result = {
@@ -214482,7 +215425,7 @@ function base64Encode(u8) {
214482
215425
  }
214483
215426
  return btoa(binary);
214484
215427
  }
214485
- __name$6(base64Encode, "base64Encode");
215428
+ __name$5(base64Encode, "base64Encode");
214486
215429
  function base64Decode(b64) {
214487
215430
  if (typeof Buffer !== "undefined" && typeof Buffer.from === "function") {
214488
215431
  return new Uint8Array(Buffer.from(b64, "base64"));
@@ -214492,7 +215435,7 @@ function base64Decode(b64) {
214492
215435
  for (let i = 0; i < binary.length; i++) u8[i] = binary.charCodeAt(i);
214493
215436
  return u8;
214494
215437
  }
214495
- __name$6(base64Decode, "base64Decode");
215438
+ __name$5(base64Decode, "base64Decode");
214496
215439
  var ArrayBufferToJsonZod = _instanceof(ArrayBuffer).transform((x) => {
214497
215440
  const u8 = new Uint8Array(x);
214498
215441
  return base64Encode(u8);
@@ -215491,7 +216434,7 @@ var AllRpcSchemas = {
215491
216434
  ...XyoPermissionsRpcSchemas,
215492
216435
  ...NetworkStakeViewerRpcSchemas
215493
216436
  };
215494
- var createRequestSchema = /* @__PURE__ */ __name$6((methodName, paramsSchema = _undefined()) => object$3({
216437
+ var createRequestSchema = /* @__PURE__ */ __name$5((methodName, paramsSchema = _undefined()) => object$3({
215495
216438
  id: union$1([
215496
216439
  string$2(),
215497
216440
  number$3()
@@ -215500,7 +216443,7 @@ var createRequestSchema = /* @__PURE__ */ __name$6((methodName, paramsSchema = _
215500
216443
  method: literal$2(methodName),
215501
216444
  params: paramsSchema
215502
216445
  }), "createRequestSchema");
215503
- var createResponseSchema = /* @__PURE__ */ __name$6((resultSchema = _undefined()) => object$3({
216446
+ var createResponseSchema = /* @__PURE__ */ __name$5((resultSchema = _undefined()) => object$3({
215504
216447
  id: union$1([
215505
216448
  string$2(),
215506
216449
  number$3()
@@ -215909,7 +216852,7 @@ var createResponseSchema = /* @__PURE__ */ __name$6((resultSchema = _undefined()
215909
216852
  });
215910
216853
 
215911
216854
  // src/engine-node/rpcEngineFromConnection.ts
215912
- var rpcEngineFromConnection = /* @__PURE__ */ __name$6((connection, networkStakeViewer) => {
216855
+ var rpcEngineFromConnection = /* @__PURE__ */ __name$5((connection, networkStakeViewer) => {
215913
216856
  const engine = new JsonRpcEngine();
215914
216857
  const handlers = rpcMethodHandlersFromConnection(connection, networkStakeViewer);
215915
216858
  engine.push(createAsyncMiddleware(async (req, res) => {
@@ -215949,7 +216892,7 @@ var rpcEngineFromConnection = /* @__PURE__ */ __name$6((connection, networkStake
215949
216892
  }, "rpcEngineFromConnection");
215950
216893
  var HttpRpcTransport = class {
215951
216894
  static {
215952
- __name$6(this, "HttpRpcTransport");
216895
+ __name$5(this, "HttpRpcTransport");
215953
216896
  }
215954
216897
  _rpcUrl;
215955
216898
  _schemas;
@@ -215988,7 +216931,7 @@ var HttpRpcTransport = class {
215988
216931
  };
215989
216932
  (class {
215990
216933
  static {
215991
- __name$6(this, "MemoryRpcTransport");
216934
+ __name$5(this, "MemoryRpcTransport");
215992
216935
  }
215993
216936
  _rpcEngine;
215994
216937
  _schemas;
@@ -216026,7 +216969,7 @@ var HttpRpcTransport = class {
216026
216969
  // src/provider/runner/JsonRpcXyoRunner.ts
216027
216970
  var JsonRpcXyoRunner = class {
216028
216971
  static {
216029
- __name$6(this, "JsonRpcXyoRunner");
216972
+ __name$5(this, "JsonRpcXyoRunner");
216030
216973
  }
216031
216974
  transport;
216032
216975
  constructor(transport) {
@@ -216040,7 +216983,7 @@ var JsonRpcXyoRunner = class {
216040
216983
  };
216041
216984
  var NodeXyoRunner = class {
216042
216985
  static {
216043
- __name$6(this, "NodeXyoRunner");
216986
+ __name$5(this, "NodeXyoRunner");
216044
216987
  }
216045
216988
  // TODO: Make configurable with defaults
216046
216989
  node;
@@ -216063,11 +217006,11 @@ var NodeXyoRunner = class {
216063
217006
  ]);
216064
217007
  return txHash;
216065
217008
  }
216066
- getArchivist = /* @__PURE__ */ __name$6(async (identifier) => {
217009
+ getArchivist = /* @__PURE__ */ __name$5(async (identifier) => {
216067
217010
  const archivist = await this.node.resolve(identifier);
216068
217011
  return assertEx(asArchivistInstance(archivist), () => `Could not resolve ${identifier} to an archivist instance`);
216069
217012
  }, "getArchivist");
216070
- getPendingArchivist = /* @__PURE__ */ __name$6(async () => {
217013
+ getPendingArchivist = /* @__PURE__ */ __name$5(async () => {
216071
217014
  if (this._pendingArchivist) return this._pendingArchivist;
216072
217015
  this._pendingArchivist = await this.getArchivist(this.pendingArchivistPath);
216073
217016
  return assertEx(this._pendingArchivist, () => `Could not resolve pending archivist at ${this.pendingArchivistPath}`);
@@ -216077,7 +217020,7 @@ var NodeXyoRunner = class {
216077
217020
  // src/provider/viewer/JsonRpcViewer.ts
216078
217021
  var JsonRpcViewer = class {
216079
217022
  static {
216080
- __name$6(this, "JsonRpcViewer");
217023
+ __name$5(this, "JsonRpcViewer");
216081
217024
  }
216082
217025
  transport;
216083
217026
  constructor(transport) {
@@ -216088,14 +217031,14 @@ var JsonRpcViewer = class {
216088
217031
  // src/provider/viewer/JsonRpcNetworkStakingStepRewardsViewer/JsonRpcNetworkStakingStepRewardsViewerMethods.ts
216089
217032
  var JsonRpcNetworkStakingStepRewardsViewerMethods = class extends JsonRpcViewer {
216090
217033
  static {
216091
- __name$6(this, "JsonRpcNetworkStakingStepRewardsViewerMethods");
217034
+ __name$5(this, "JsonRpcNetworkStakingStepRewardsViewerMethods");
216092
217035
  }
216093
217036
  };
216094
217037
 
216095
217038
  // src/provider/viewer/JsonRpcNetworkStakingStepRewardsViewer/JsonRpcNetworkStakingStepRewardsViewer.ts
216096
217039
  var JsonRpcNetworkStakingStepRewardsViewer = class extends JsonRpcNetworkStakingStepRewardsViewerMethods {
216097
217040
  static {
216098
- __name$6(this, "JsonRpcNetworkStakingStepRewardsViewer");
217041
+ __name$5(this, "JsonRpcNetworkStakingStepRewardsViewer");
216099
217042
  }
216100
217043
  providers;
216101
217044
  constructor(transport, providers) {
@@ -216119,7 +217062,7 @@ var JsonRpcNetworkStakingStepRewardsViewer = class extends JsonRpcNetworkStaking
216119
217062
  // src/provider/viewer/JsonRpcNetworkStakeViewer/JsonRpcNetworkStakeViewerMethods.ts
216120
217063
  var JsonRpcNetworkStakeViewerMethods = class extends JsonRpcViewer {
216121
217064
  static {
216122
- __name$6(this, "JsonRpcNetworkStakeViewerMethods");
217065
+ __name$5(this, "JsonRpcNetworkStakeViewerMethods");
216123
217066
  }
216124
217067
  async active(blockNumber) {
216125
217068
  return await this.transport.sendRequest("networkStakeViewer_active", [
@@ -216131,7 +217074,7 @@ var JsonRpcNetworkStakeViewerMethods = class extends JsonRpcViewer {
216131
217074
  // src/provider/viewer/JsonRpcNetworkStakeViewer/JsonRpcNetworkStakeViewer.ts
216132
217075
  var JsonRpcNetworkStakeViewer = class extends JsonRpcNetworkStakeViewerMethods {
216133
217076
  static {
216134
- __name$6(this, "JsonRpcNetworkStakeViewer");
217077
+ __name$5(this, "JsonRpcNetworkStakeViewer");
216135
217078
  }
216136
217079
  _stepRewards;
216137
217080
  constructor(transport) {
@@ -216146,7 +217089,7 @@ var JsonRpcNetworkStakeViewer = class extends JsonRpcNetworkStakeViewerMethods {
216146
217089
  // src/provider/viewer/JsonRpcTimeSyncViewer/JsonRpcTimeSyncViewerMethods.ts
216147
217090
  var JsonRpcTimeSyncViewerMethods = class {
216148
217091
  static {
216149
- __name$6(this, "JsonRpcTimeSyncViewerMethods");
217092
+ __name$5(this, "JsonRpcTimeSyncViewerMethods");
216150
217093
  }
216151
217094
  transport;
216152
217095
  constructor(transport) {
@@ -216177,7 +217120,7 @@ var JsonRpcTimeSyncViewerMethods = class {
216177
217120
  // src/provider/viewer/JsonRpcTimeSyncViewer/JsonRpcTimeSyncViewer.ts
216178
217121
  (class extends JsonRpcTimeSyncViewerMethods {
216179
217122
  static {
216180
- __name$6(this, "JsonRpcTimeSyncViewer");
217123
+ __name$5(this, "JsonRpcTimeSyncViewer");
216181
217124
  }
216182
217125
  constructor(transport) {
216183
217126
  super(transport);
@@ -216185,7 +217128,7 @@ var JsonRpcTimeSyncViewerMethods = class {
216185
217128
  });
216186
217129
  var JsonRpcXyoViewer = class {
216187
217130
  static {
216188
- __name$6(this, "JsonRpcXyoViewer");
217131
+ __name$5(this, "JsonRpcXyoViewer");
216189
217132
  }
216190
217133
  providers;
216191
217134
  transport;
@@ -216416,7 +217359,7 @@ var JsonRpcXyoViewer = class {
216416
217359
  // src/provider/connection/XyoBaseConnection.ts
216417
217360
  var XyoBaseConnection = class {
216418
217361
  static {
216419
- __name$6(this, "XyoBaseConnection");
217362
+ __name$5(this, "XyoBaseConnection");
216420
217363
  }
216421
217364
  _network;
216422
217365
  _runner;
@@ -216445,7 +217388,7 @@ var XyoBaseConnection = class {
216445
217388
  // src/provider/connection/HttpRpcXyoConnection.ts
216446
217389
  var HttpRpcXyoConnection = class extends XyoBaseConnection {
216447
217390
  static {
216448
- __name$6(this, "HttpRpcXyoConnection");
217391
+ __name$5(this, "HttpRpcXyoConnection");
216449
217392
  }
216450
217393
  constructor(params) {
216451
217394
  const { endpoint, storage: storageParam } = params;
@@ -216471,7 +217414,7 @@ var HttpRpcXyoConnection = class extends XyoBaseConnection {
216471
217414
  // src/provider/datalake/JsonRpcDataLakeViewerMethods.ts
216472
217415
  var JsonRpcDataLakeViewerMethods = class extends JsonRpcViewer {
216473
217416
  static {
216474
- __name$6(this, "JsonRpcDataLakeViewerMethods");
217417
+ __name$5(this, "JsonRpcDataLakeViewerMethods");
216475
217418
  }
216476
217419
  get(_id) {
216477
217420
  throw new Error("Method not implemented.");
@@ -216487,7 +217430,7 @@ var JsonRpcDataLakeViewerMethods = class extends JsonRpcViewer {
216487
217430
  // src/provider/datalake/JsonRpcDataLakeViewer.ts
216488
217431
  (class extends JsonRpcDataLakeViewerMethods {
216489
217432
  static {
216490
- __name$6(this, "JsonRpcDataLakeViewer");
217433
+ __name$5(this, "JsonRpcDataLakeViewer");
216491
217434
  }
216492
217435
  constructor(transport) {
216493
217436
  super(transport);
@@ -216497,7 +217440,7 @@ var JsonRpcDataLakeViewerMethods = class extends JsonRpcViewer {
216497
217440
  // src/provider/permissions/RpcXyoPermissions.ts
216498
217441
  (class {
216499
217442
  static {
216500
- __name$6(this, "RpcXyoPermissions");
217443
+ __name$5(this, "RpcXyoPermissions");
216501
217444
  }
216502
217445
  transport;
216503
217446
  constructor(transport) {
@@ -216520,7 +217463,7 @@ var JsonRpcDataLakeViewerMethods = class extends JsonRpcViewer {
216520
217463
  // src/provider/signer/JsonRpcXyoSigner.ts
216521
217464
  (class {
216522
217465
  static {
216523
- __name$6(this, "RpcXyoSigner");
217466
+ __name$5(this, "RpcXyoSigner");
216524
217467
  }
216525
217468
  transport;
216526
217469
  constructor(transport) {
@@ -216931,601 +217874,6 @@ var getBiosExternalInterface = async () => {
216931
217874
  // src/external/boot.ts
216932
217875
  var boot = () => genericBoot(getBiosExternalInterface);
216933
217876
 
216934
- var __defProp$a = Object.defineProperty;
216935
- var __name$5 = (target, value) => __defProp$a(target, "name", { value, configurable: true });
216936
-
216937
- // src/BaseEthProvider.ts
216938
- (class {
216939
- static {
216940
- __name$5(this, "BaseEthProvider");
216941
- }
216942
- eth_accounts() {
216943
- throw new Error("Method not implemented.");
216944
- }
216945
- eth_blockNumber() {
216946
- throw new Error("Method not implemented.");
216947
- }
216948
- eth_call(_transaction, _blockNumber) {
216949
- throw new Error("Method not implemented.");
216950
- }
216951
- eth_clearSubscriptions(_keepSyncing) {
216952
- throw new Error("Method not implemented.");
216953
- }
216954
- eth_coinbase() {
216955
- throw new Error("Method not implemented.");
216956
- }
216957
- eth_compileLLL(_code) {
216958
- throw new Error("Method not implemented.");
216959
- }
216960
- eth_compileSerpent(_code) {
216961
- throw new Error("Method not implemented.");
216962
- }
216963
- eth_compileSolidity(_code) {
216964
- throw new Error("Method not implemented.");
216965
- }
216966
- eth_estimateGas(_transaction, _blockNumber) {
216967
- throw new Error("Method not implemented.");
216968
- }
216969
- eth_feeHistory(_blockCount, _newestBlock, _rewardPercentiles) {
216970
- throw new Error("Method not implemented.");
216971
- }
216972
- eth_gasPrice() {
216973
- throw new Error("Method not implemented.");
216974
- }
216975
- eth_getBalance(_address, _blockNumber) {
216976
- throw new Error("Method not implemented.");
216977
- }
216978
- eth_getBlockByHash(_blockHash, _hydrated) {
216979
- throw new Error("Method not implemented.");
216980
- }
216981
- eth_getBlockByNumber(_blockNumber, _hydrated) {
216982
- throw new Error("Method not implemented.");
216983
- }
216984
- eth_getBlockTransactionCountByHash(_blockHash) {
216985
- throw new Error("Method not implemented.");
216986
- }
216987
- eth_getBlockTransactionCountByNumber(_blockNumber) {
216988
- throw new Error("Method not implemented.");
216989
- }
216990
- eth_getCode(_address, _blockNumber) {
216991
- throw new Error("Method not implemented.");
216992
- }
216993
- eth_getCompilers() {
216994
- throw new Error("Method not implemented.");
216995
- }
216996
- eth_getFilterChanges(_filterIdentifier) {
216997
- throw new Error("Method not implemented.");
216998
- }
216999
- eth_getFilterLogs(_filterIdentifier) {
217000
- throw new Error("Method not implemented.");
217001
- }
217002
- eth_getLogs(_filter) {
217003
- throw new Error("Method not implemented.");
217004
- }
217005
- eth_getStorageAt(_address, _storageSlot, _blockNumber) {
217006
- throw new Error("Method not implemented.");
217007
- }
217008
- eth_getTransactionByBlockHashAndIndex(_blockHash, _transactionIndex) {
217009
- throw new Error("Method not implemented.");
217010
- }
217011
- eth_getTransactionByBlockNumberAndIndex(_blockNumber, _transactionIndex) {
217012
- throw new Error("Method not implemented.");
217013
- }
217014
- eth_getTransactionByHash(_transactionHash) {
217015
- throw new Error("Method not implemented.");
217016
- }
217017
- eth_getTransactionCount(_address, _blockNumber) {
217018
- throw new Error("Method not implemented.");
217019
- }
217020
- eth_getTransactionReceipt(_transactionHash) {
217021
- throw new Error("Method not implemented.");
217022
- }
217023
- eth_getUncleByBlockHashAndIndex(_blockHash, _uncleIndex) {
217024
- throw new Error("Method not implemented.");
217025
- }
217026
- eth_getUncleByBlockNumberAndIndex(_blockNumber, _uncleIndex) {
217027
- throw new Error("Method not implemented.");
217028
- }
217029
- eth_getUncleCountByBlockHash(_blockHash) {
217030
- throw new Error("Method not implemented.");
217031
- }
217032
- eth_getUncleCountByBlockNumber(_blockNumber) {
217033
- throw new Error("Method not implemented.");
217034
- }
217035
- eth_getWork() {
217036
- throw new Error("Method not implemented.");
217037
- }
217038
- eth_hashrate() {
217039
- throw new Error("Method not implemented.");
217040
- }
217041
- eth_maxPriorityFeePerGas() {
217042
- throw new Error("Method not implemented.");
217043
- }
217044
- eth_mining() {
217045
- throw new Error("Method not implemented.");
217046
- }
217047
- eth_newBlockFilter() {
217048
- throw new Error("Method not implemented.");
217049
- }
217050
- eth_newFilter(_filter) {
217051
- throw new Error("Method not implemented.");
217052
- }
217053
- eth_newPendingTransactionFilter() {
217054
- throw new Error("Method not implemented.");
217055
- }
217056
- eth_protocolVersion() {
217057
- throw new Error("Method not implemented.");
217058
- }
217059
- eth_sendRawTransaction(_transaction) {
217060
- throw new Error("Method not implemented.");
217061
- }
217062
- eth_sendTransaction(_transaction) {
217063
- throw new Error("Method not implemented.");
217064
- }
217065
- eth_sign(_address, _message) {
217066
- throw new Error("Method not implemented.");
217067
- }
217068
- eth_signTransaction(_transaction) {
217069
- throw new Error("Method not implemented.");
217070
- }
217071
- eth_submitHashrate(_hashRate, _id) {
217072
- throw new Error("Method not implemented.");
217073
- }
217074
- eth_submitWork(_nonce, _hash, _digest) {
217075
- throw new Error("Method not implemented.");
217076
- }
217077
- eth_subscribe(..._params) {
217078
- throw new Error("Method not implemented.");
217079
- }
217080
- eth_syncing() {
217081
- throw new Error("Method not implemented.");
217082
- }
217083
- eth_uninstallFilter(_filterIdentifier) {
217084
- throw new Error("Method not implemented.");
217085
- }
217086
- eth_unsubscribe(_subscriptionId) {
217087
- throw new Error("Method not implemented.");
217088
- }
217089
- });
217090
- var createChainContract = /* @__PURE__ */ __name$5(async (signer, stakingTokenAddress, genesisBlockHash, rewardsContractAddress, minWithdrawalBlocks, gas = {}) => {
217091
- try {
217092
- const xyoChainFactory = new StakedXyoChain__factory(signer);
217093
- const contractTransactionResponse = await (await xyoChainFactory.deploy(ETH_ZERO_ADDRESS, 0n, hexToBigInt(genesisBlockHash), toEthAddress(rewardsContractAddress), minWithdrawalBlocks, toEthAddress(stakingTokenAddress), gas)).waitForDeployment();
217094
- const xyoChainContractAddress = await contractTransactionResponse.getAddress();
217095
- return assertEx(asAddress(xyoChainContractAddress), () => "Invalid staking contract address");
217096
- } catch (ex) {
217097
- console.log(ex);
217098
- throw ex;
217099
- }
217100
- }, "createChainContract");
217101
- var gasConfig = /* @__PURE__ */ __name$5(() => {
217102
- return {
217103
- gasLimit: 2e6,
217104
- gasPrice: parseUnits$1("100", "gwei")
217105
- };
217106
- }, "gasConfig");
217107
- var createChainRewardsContract = /* @__PURE__ */ __name$5(async (signer, genesisReward = 0n, gas = gasConfig()) => {
217108
- try {
217109
- const xyoChainRewardsFactory = new XyoChainRewards__factory(signer);
217110
- const xyoChainRewardsFactoryResponse = await (await xyoChainRewardsFactory.deploy(toFixedPoint(1000n), 1000000n, 95n, 100n, toFixedPoint(30n), genesisReward, 18n, gas)).waitForDeployment();
217111
- const xyoChainRewardsAddress = await xyoChainRewardsFactoryResponse.getAddress();
217112
- return assertEx(asAddress(xyoChainRewardsAddress), () => "Invalid rewards contract address");
217113
- } catch (ex) {
217114
- console.log(ex);
217115
- throw ex;
217116
- }
217117
- }, "createChainRewardsContract");
217118
- var nextContractAddressForAddress = /* @__PURE__ */ __name$5(async (address, provider) => {
217119
- const deployerAddress = toEthAddress(address);
217120
- const nonce = await provider.getTransactionCount(deployerAddress);
217121
- const contractAddress = getCreateAddress({
217122
- from: deployerAddress,
217123
- nonce
217124
- });
217125
- return assertEx(asAddress(contractAddress), () => "Unable to convert contract address to address");
217126
- }, "nextContractAddressForAddress");
217127
- var nextContractAddress = /* @__PURE__ */ __name$5(async (signer) => {
217128
- const provider = assertEx(signer.provider, () => "Unable to obtain provider from signer");
217129
- const address = assertEx(asAddress(await signer.getAddress()), () => "Unable to obtain address from signer");
217130
- return await nextContractAddressForAddress(address, provider);
217131
- }, "nextContractAddress");
217132
-
217133
- // src/createChain.ts
217134
- async function createChain(signer, stakingTokenAddress, initialBlockProducer, rewardsContractAddress, genesisBlockRewardAmount, genesisBlockRewardAddress, minWithdrawalBlocks, gas) {
217135
- const ethStakingTokenAddress = toEthAddress(stakingTokenAddress);
217136
- const rewardContractAddressResolved = rewardsContractAddress ?? await createChainRewardsContract(signer, genesisBlockRewardAmount, gas);
217137
- const contractAddress = await nextContractAddress(signer);
217138
- const genesisBlock = await createGenesisBlock(initialBlockProducer, contractAddress, genesisBlockRewardAmount, genesisBlockRewardAddress);
217139
- const chainId = toAddress(await createChainContract(signer, ethStakingTokenAddress, await PayloadBuilder.hash(genesisBlock[0]), rewardContractAddressResolved, minWithdrawalBlocks, gas));
217140
- return [
217141
- chainId,
217142
- genesisBlock,
217143
- rewardContractAddressResolved
217144
- ];
217145
- }
217146
- __name$5(createChain, "createChain");
217147
- function _ts_decorate(decorators, target, key, desc) {
217148
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
217149
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
217150
- 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;
217151
- return c > 3 && r && Object.defineProperty(target, key, r), r;
217152
- }
217153
- __name$5(_ts_decorate, "_ts_decorate");
217154
- var ethStakeToStake = /* @__PURE__ */ __name$5((ethStake) => {
217155
- const stake = {
217156
- id: Number(ethStake.id),
217157
- staked: toAddress(ethStake.staked),
217158
- staker: toAddress(ethStake.staker),
217159
- amount: asAttoXL1(ethStake.amount),
217160
- addBlock: Number(ethStake.addBlock),
217161
- removeBlock: Number(ethStake.removeBlock),
217162
- withdrawBlock: Number(ethStake.withdrawBlock)
217163
- };
217164
- return stake;
217165
- }, "ethStakeToStake");
217166
- var EthereumChainStakeViewer = class extends AbstractCreatable {
217167
- static {
217168
- __name$5(this, "EthereumChainStakeViewer");
217169
- }
217170
- callMutex = new Mutex$1();
217171
- deploymentBlock = 0;
217172
- stakeCache = /* @__PURE__ */ new Map();
217173
- get contract() {
217174
- return assertEx(this.params.contract, () => new Error("Contract not defined"));
217175
- }
217176
- get minWithdrawalBlocks() {
217177
- return 0;
217178
- }
217179
- get rewardsContract() {
217180
- return toAddress("0x000000000000000000000000000000");
217181
- }
217182
- get stakeEventsViewer() {
217183
- return this.params.stakeEventsViewer;
217184
- }
217185
- get stakingTokenAddress() {
217186
- return toAddress("0x000000000000000000000000000011");
217187
- }
217188
- async active() {
217189
- return await this.callMutex.runExclusive(async () => {
217190
- return await this.contract.active();
217191
- });
217192
- }
217193
- async activeByAddressStaked(address) {
217194
- return await this.callMutex.runExclusive(async () => {
217195
- return await this.contract.activeByAddressStaked(toEthAddress(address));
217196
- });
217197
- }
217198
- async activeByStaker(address) {
217199
- return await this.callMutex.runExclusive(async () => {
217200
- return await this.contract.activeByStaker(toEthAddress(address));
217201
- });
217202
- }
217203
- async pending() {
217204
- return await this.callMutex.runExclusive(async () => {
217205
- return await this.contract.pending();
217206
- });
217207
- }
217208
- async pendingByStaker(staker) {
217209
- return await this.callMutex.runExclusive(async () => {
217210
- return await this.contract.pendingByStaker(toEthAddress(staker));
217211
- });
217212
- }
217213
- async stakeById(id) {
217214
- return await this.callMutex.runExclusive(async () => {
217215
- const startTime = Date.now();
217216
- const cachedStake = this.stakeCache.get(id);
217217
- if (cachedStake) {
217218
- return cachedStake;
217219
- }
217220
- const ethResult = await this.contract.getStakeById(id);
217221
- const stake = ethStakeToStake(ethResult);
217222
- this.stakeCache.set(stake.id, stake);
217223
- this.logger?.log(`EthereumChainStake: stakeById(${id}) took ${Date.now() - startTime}ms`);
217224
- return stake;
217225
- });
217226
- }
217227
- async stakeByStaker(staker, slot) {
217228
- return await this.callMutex.runExclusive(async () => {
217229
- const ethResult = await this.contract.getStake(toEthAddress(staker), slot);
217230
- const stake = ethStakeToStake(ethResult);
217231
- this.stakeCache.set(stake.id, stake);
217232
- return stake;
217233
- });
217234
- }
217235
- async stakesByStaked(staked, range = [
217236
- 0,
217237
- void 0
217238
- ]) {
217239
- const events = await this.stakeEventsViewer.stakeEvents([
217240
- Math.max(range[0], this.deploymentBlock),
217241
- range.at(1) ?? "latest"
217242
- ], {
217243
- name: "StakeAdded",
217244
- args: {
217245
- staked
217246
- }
217247
- });
217248
- const result = [];
217249
- for (const event of events) {
217250
- if (toAddress(event.args.staked) === toAddress(staked)) {
217251
- result.push(await this.stakeById(event.args.id));
217252
- }
217253
- }
217254
- return result;
217255
- }
217256
- async stakesByStaker(staker, range = [
217257
- 0,
217258
- void 0
217259
- ]) {
217260
- const events = await this.stakeEventsViewer.stakeEvents([
217261
- Math.max(range[0], this.deploymentBlock),
217262
- range.at(1) ?? "latest"
217263
- ], {
217264
- name: "StakeAdded",
217265
- args: {
217266
- staker
217267
- }
217268
- });
217269
- const result = [];
217270
- for (const event of events) {
217271
- if (toAddress(event.args.staker) === toAddress(staker)) {
217272
- result.push(await this.stakeById(event.args.id));
217273
- }
217274
- }
217275
- return result;
217276
- }
217277
- withdrawn() {
217278
- throw new Error("Method not implemented.");
217279
- }
217280
- withdrawnByStaker(_staker) {
217281
- throw new Error("Method not implemented.");
217282
- }
217283
- async startHandler() {
217284
- await this.contract.on(this.contract.getEvent("StakeAdded"), (staked, staker, id, amount, event) => {
217285
- this.stakeCache.set(Number(id), {
217286
- id: Number(id),
217287
- staked: toAddress(staked),
217288
- staker: toAddress(staker),
217289
- amount: asAttoXL1(amount),
217290
- addBlock: event.blockNumber,
217291
- removeBlock: 0,
217292
- withdrawBlock: 0
217293
- });
217294
- });
217295
- await this.contract.on(this.contract.getEvent("StakeRemoved"), (staked, staker, id, amount, event) => {
217296
- const stake = assertEx(this.stakeCache.get(Number(id)));
217297
- this.stakeCache.set(Number(id), {
217298
- ...stake,
217299
- removeBlock: event.blockNumber
217300
- });
217301
- });
217302
- await this.contract.on(this.contract.getEvent("StakeWithdrawn"), (staked, staker, id, amount, event) => {
217303
- const stake = assertEx(this.stakeCache.get(Number(id)));
217304
- this.stakeCache.set(Number(id), {
217305
- ...stake,
217306
- withdrawBlock: event.blockNumber
217307
- });
217308
- });
217309
- const allStakeEvents = (await Promise.all([
217310
- this.stakeEventsViewer.stakeEvents([
217311
- this.deploymentBlock,
217312
- "latest"
217313
- ], {
217314
- name: "StakeAdded"
217315
- }),
217316
- this.stakeEventsViewer.stakeEvents([
217317
- this.deploymentBlock,
217318
- "latest"
217319
- ], {
217320
- name: "StakeRemoved"
217321
- }),
217322
- this.stakeEventsViewer.stakeEvents([
217323
- this.deploymentBlock,
217324
- "latest"
217325
- ], {
217326
- name: "StakeWithdrawn"
217327
- })
217328
- ])).flat().toSorted((a, b) => a.time - b.time);
217329
- for (const event of allStakeEvents) {
217330
- switch (event.name) {
217331
- case "StakeAdded": {
217332
- this.stakeCache.set(event.args.id, {
217333
- id: event.args.id,
217334
- staked: event.args.staked,
217335
- staker: event.args.staker,
217336
- amount: event.args.amount,
217337
- addBlock: event.time,
217338
- removeBlock: 0,
217339
- withdrawBlock: 0
217340
- });
217341
- break;
217342
- }
217343
- case "StakeRemoved": {
217344
- const stake = assertEx(this.stakeCache.get(event.args.id));
217345
- this.stakeCache.set(event.args.id, {
217346
- ...stake,
217347
- removeBlock: event.time
217348
- });
217349
- break;
217350
- }
217351
- case "StakeWithdrawn": {
217352
- const stake = assertEx(this.stakeCache.get(event.args.id));
217353
- this.stakeCache.set(event.args.id, {
217354
- ...stake,
217355
- withdrawBlock: event.time
217356
- });
217357
- break;
217358
- }
217359
- }
217360
- }
217361
- for (const event of allStakeEvents) {
217362
- await this.stakeById(event.args.id);
217363
- }
217364
- }
217365
- };
217366
- EthereumChainStakeViewer = _ts_decorate([
217367
- creatable()
217368
- ], EthereumChainStakeViewer);
217369
- function _ts_decorate2(decorators, target, key, desc) {
217370
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
217371
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
217372
- 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;
217373
- return c > 3 && r && Object.defineProperty(target, key, r), r;
217374
- }
217375
- __name$5(_ts_decorate2, "_ts_decorate");
217376
- var isStakeLogEventName = /* @__PURE__ */ __name$5((name) => {
217377
- return isString$1(name) && [
217378
- "StakeAdded",
217379
- "StakeRemoved",
217380
- "StakeWithdrawn"
217381
- ].includes(name);
217382
- }, "isStakeLogEventName");
217383
- var EthereumChainStakeEvents = class extends AbstractCreatable {
217384
- static {
217385
- __name$5(this, "EthereumChainStakeEvents");
217386
- }
217387
- eventCache = /* @__PURE__ */ new Map();
217388
- get contract() {
217389
- return assertEx(this.params.contract, () => new Error("Contract not defined"));
217390
- }
217391
- get deploymentBlock() {
217392
- return this.params.deploymentBlock ?? 0;
217393
- }
217394
- async positionCount(range) {
217395
- const events = await this.stakeEvents(range);
217396
- const positionIds = events.map((e) => e.args.id);
217397
- return Math.max(-1, ...positionIds) + 1;
217398
- }
217399
- stakeEvents(range = [
217400
- 0,
217401
- "latest"
217402
- ], filter) {
217403
- const allEvents = [
217404
- ...this.eventCache.values()
217405
- ];
217406
- const result = allEvents.filter((e) => {
217407
- if (range[1] !== "latest" && e.time > range[1]) {
217408
- return false;
217409
- }
217410
- if (e.time < range[0]) {
217411
- return false;
217412
- }
217413
- if (isDefined(filter?.name) && e.name !== filter.name) {
217414
- return false;
217415
- }
217416
- if (isDefined(filter?.args?.id) && e.args.id !== filter.args.id) {
217417
- return false;
217418
- }
217419
- if (isDefined(filter?.args?.staked) && e.args.staked !== filter.args.staked) {
217420
- return false;
217421
- }
217422
- if (isDefined(filter?.args?.staker) && e.args.staker !== filter.args.staker) {
217423
- return false;
217424
- }
217425
- return true;
217426
- });
217427
- return result;
217428
- }
217429
- onEventHandler(staked, staker, id, amount, { eventName, blockNumber }) {
217430
- if (blockNumber === void 0) {
217431
- this.logger?.warn(`Received ${eventName} event with ${blockNumber} blockNumber, ignoring...`);
217432
- return;
217433
- }
217434
- if (!isStakeLogEventName(eventName)) {
217435
- this.logger?.warn(`Received event with unsupported name '${eventName}'`);
217436
- return;
217437
- }
217438
- this.logger?.log(`Processing ${eventName} event for stake ID ${id} at block ${blockNumber}`);
217439
- const cacheKey = `${Number(id)}|${eventName}|${staker}`;
217440
- const existingStakeEvent = this.eventCache.get(cacheKey);
217441
- const stakeEvent = {
217442
- name: eventName,
217443
- args: {
217444
- id: Number(id),
217445
- staked: toAddress(staked),
217446
- staker: toAddress(staker),
217447
- amount: asAttoXL1(amount)
217448
- },
217449
- time: blockNumber
217450
- };
217451
- if (isDefined(existingStakeEvent)) {
217452
- this.logger?.warn(`Received ${eventName} event for stake ID ${id} that is already cached, updating cache...`);
217453
- this.logger?.warn("1");
217454
- this.logger?.warn("Previous event", existingStakeEvent);
217455
- this.logger?.warn("2");
217456
- this.logger?.warn("New event", stakeEvent);
217457
- this.logger?.warn("3");
217458
- }
217459
- this.eventCache.set(cacheKey, stakeEvent);
217460
- return stakeEvent;
217461
- }
217462
- async startHandler() {
217463
- try {
217464
- const currentEthBlock = assertEx(await this.contract.runner?.provider?.getBlockNumber(), () => new Error("Failed to egt currentEthBlock"));
217465
- await this.contract.on(this.contract.getEvent("StakeAdded"), (staked, staker, id, amount, event) => {
217466
- this.onEventHandler(staked, staker, id, amount, event);
217467
- });
217468
- await this.contract.on(this.contract.getEvent("StakeRemoved"), (staked, staker, id, amount, event) => {
217469
- this.onEventHandler(staked, staker, id, amount, event);
217470
- });
217471
- await this.contract.on(this.contract.getEvent("StakeWithdrawn"), (staked, staker, id, amount, event) => {
217472
- this.onEventHandler(staked, staker, id, amount, event);
217473
- });
217474
- const allStakeEvents = (await Promise.all([
217475
- this.stakeEventsNative([
217476
- this.deploymentBlock,
217477
- currentEthBlock
217478
- ], {
217479
- name: "StakeAdded"
217480
- }),
217481
- this.stakeEventsNative([
217482
- this.deploymentBlock,
217483
- currentEthBlock
217484
- ], {
217485
- name: "StakeRemoved"
217486
- }),
217487
- this.stakeEventsNative([
217488
- this.deploymentBlock,
217489
- currentEthBlock
217490
- ], {
217491
- name: "StakeWithdrawn"
217492
- })
217493
- ])).flat().toSorted((a, b) => a.time - b.time);
217494
- console.warn(`Caching ${allStakeEvents.length} stake events from chain starting at block ${this.deploymentBlock}`);
217495
- for (const event of allStakeEvents) {
217496
- this.eventCache.set(`${Number(event.args.id)}|${event.name}|${event.args.staker}`, event);
217497
- }
217498
- } catch (error) {
217499
- this.logger?.error("EthereumChainStakeEvents failed to start:", error);
217500
- throw error;
217501
- }
217502
- }
217503
- async stakeEventsNative(range = [
217504
- 0,
217505
- "latest"
217506
- ], filter) {
217507
- const name = filter?.name;
217508
- if (isDefined(name)) {
217509
- const stakedFilter = filter?.args?.staked;
217510
- const stakerFilter = filter?.args?.staker;
217511
- const stakedFilterEth = isDefined(stakedFilter) ? toEthAddress(stakedFilter) : void 0;
217512
- const stakerFilterEth = isDefined(stakerFilter) ? toEthAddress(stakerFilter) : void 0;
217513
- let ethEvents = [];
217514
- const ethFilter = this.contract.filters[name](stakedFilterEth, stakerFilterEth);
217515
- ethEvents = await this.contract.queryFilter(ethFilter, range[0], range[1]);
217516
- return ethEvents.map((e) => {
217517
- assertEx(e.eventName === name, () => `Event name mismatch expected '${name}' but got '${e.eventName}'`);
217518
- return this.onEventHandler(e.args.staked, e.args.by, e.args.id, e.args.amount, e);
217519
- }).filter(exists$1);
217520
- } else {
217521
- throw new Error("Only filtered stake events (by name) are supported");
217522
- }
217523
- }
217524
- };
217525
- EthereumChainStakeEvents = _ts_decorate2([
217526
- creatable()
217527
- ], EthereumChainStakeEvents);
217528
-
217529
217877
  var lib$6 = {};
217530
217878
 
217531
217879
  var admin$2 = {};
@@ -363555,6 +363903,7 @@ var ViewArchivist = class extends AbstractArchivist {
363555
363903
  this._originArchivistInstance = this._originArchivistInstance ?? assertEx(await this.resolve(this.originArchivist, { identity: isArchivistInstance, required: true }));
363556
363904
  return this._originArchivistInstance;
363557
363905
  }
363906
+ /** @deprecated use next instead */
363558
363907
  async allHandler() {
363559
363908
  return await (await this.originArchivistInstance()).all?.() ?? [];
363560
363909
  }
@@ -363629,7 +363978,7 @@ var MemoryBoundWitnessDiviner = class extends BoundWitnessDiviner {
363629
363978
  const filter = assertEx(payloads?.filter(isBoundWitnessDivinerQueryPayload)?.pop(), () => "Missing query payload");
363630
363979
  if (!filter) return [];
363631
363980
  const archivist = assertEx(await this.archivistInstance(), () => "Unable to resolve archivist");
363632
- let bws = (await archivist?.all?.() ?? []).filter(isBoundWitnessWithStorageMeta);
363981
+ let bws = (await archivist?.next({ limit: 1e4 }) ?? []).filter(isBoundWitnessWithStorageMeta);
363633
363982
  return applyBoundWitnessDivinerQueryPayload(filter, bws);
363634
363983
  }
363635
363984
  };
@@ -364424,35 +364773,6 @@ var getApp$3 = /* @__PURE__ */ __name$4(async (node, transferSummaryMap, stakedC
364424
364773
  app.use(standardErrors);
364425
364774
  return app;
364426
364775
  }, "getApp");
364427
- var getChainId$1 = /* @__PURE__ */ __name$4((config) => {
364428
- const chainId = assertEx(config.evm.chainId, () => "Missing config.evm.chainId");
364429
- if (isHex(chainId, {
364430
- prefix: true
364431
- })) {
364432
- const hex = hexFrom(chainId);
364433
- const parsed = Number.parseInt(hex, 16);
364434
- return parsed;
364435
- } else {
364436
- const parsed = Number.parseInt(chainId, 10);
364437
- return parsed;
364438
- }
364439
- }, "getChainId");
364440
- var instance$1;
364441
- var initInfuraProvider$1 = /* @__PURE__ */ __name$4((config) => {
364442
- if (instance$1) return instance$1;
364443
- const providerConfig = getInfuraProviderConfig$1(config);
364444
- instance$1 = Promise.resolve(new InfuraWebSocketProvider(providerConfig[0], providerConfig[1]));
364445
- return instance$1;
364446
- }, "initInfuraProvider");
364447
- var getInfuraProviderConfig$1 = /* @__PURE__ */ __name$4((config) => {
364448
- const projectId = assertEx(config.evm?.infura?.projectId, () => "Missing config.evm.infura.projectId");
364449
- const projectSecret = assertEx(config.evm?.infura?.projectSecret, () => "Missing config.evm.infura.projectSecret");
364450
- return [
364451
- getChainId$1(config),
364452
- projectId,
364453
- projectSecret
364454
- ];
364455
- }, "getInfuraProviderConfig");
364456
364776
  async function getTransferSummaryMap(config) {
364457
364777
  const mongoConfig = config.storage?.mongo;
364458
364778
  if (hasMongoConfig(mongoConfig)) {
@@ -364468,13 +364788,18 @@ async function getTransferSummaryMap(config) {
364468
364788
  ...payloadSdkConfig,
364469
364789
  collection: "transfer_summary_map"
364470
364790
  });
364471
- return await MongoMap.create({
364791
+ const result = await MongoMap.create({
364472
364792
  sdk: sdkTransferSummaryMap,
364473
364793
  getCache: {
364474
364794
  enabled: true,
364475
364795
  maxEntries: 5e3
364476
364796
  }
364477
364797
  });
364798
+ assertEx(await result.start(), () => "Failed to start transfer summary map");
364799
+ return result;
364800
+ } else {
364801
+ console.warn("[API] Mongo configuration not found. Using MemoryMap for TransferSummaryMap.");
364802
+ return new MemoryMap();
364478
364803
  }
364479
364804
  }
364480
364805
  __name$4(getTransferSummaryMap, "getTransferSummaryMap");
@@ -364993,33 +365318,43 @@ var getServer$3 = /* @__PURE__ */ __name$4(async (context) => {
364993
365318
  const bios = await boot();
364994
365319
  const seedPhrase = isDefined(mnemonic) ? mnemonic : await getSeedPhrase$2(bios, config, logger);
364995
365320
  const wallet = await HDWallet.fromPhrase(seedPhrase);
364996
- const provider = await initInfuraProvider$1(config);
364997
- const contractAddress = assertEx(config.chain.id, () => "Missing config.evm.chainId");
364998
- const contract = StakedXyoChainV2__factory.connect(toEthAddress(contractAddress), provider);
365321
+ const stakeChainViewer = await initChainStakeViewer(config, logger);
364999
365322
  const nodeContext = {
365000
365323
  wallet,
365001
365324
  logger,
365002
365325
  config
365003
365326
  };
365004
- const stakeEventsViewer = await EthereumChainStakeEvents.create({
365005
- contract,
365006
- logger
365007
- });
365008
- assertEx(await stakeEventsViewer.start(), () => "Failed to start EthereumChainStakeEvents reader");
365009
- const stakeChainViewer = await EthereumChainStakeViewer.create({
365010
- contract,
365011
- stakeEventsViewer,
365012
- logger
365013
- });
365014
- assertEx(await stakeChainViewer.start(), () => "Failed to start EthereumChainStake viewer");
365015
365327
  const resolvedNode = node ?? await getNode$2(nodeContext);
365016
365328
  const chainArchivist = assertEx(asArchivistInstance(await resolvedNode.resolve("Chain:Validated"), {
365017
365329
  required: true
365018
365330
  }), () => "FinalizedArchivist not found in node");
365019
365331
  const chainMap = readPayloadMapFromStore(chainArchivist);
365332
+ const payloads = await chainArchivist.next();
365333
+ if (payloads.length === 0) {
365334
+ logger?.warn("[API] No blocks found in chain archivist, creating genesis block");
365335
+ const producerAccount = await initProducerAccount({
365336
+ config,
365337
+ logger
365338
+ });
365339
+ const chainId = stakeChainViewer.chainId;
365340
+ const block0 = await createGenesisBlock(producerAccount, chainId, 1000000n, producerAccount.address);
365341
+ await chainArchivist.insert([
365342
+ ...block0[1].flat(),
365343
+ block0[0]
365344
+ ]);
365345
+ console.log("[API] Genesis block created and inserted into chain archivist");
365346
+ const block1 = await createProducerChainStakeIntentBlock(block0[0], producerAccount, asXL1BlockRange([
365347
+ 0,
365348
+ 1e4
365349
+ ], true));
365350
+ await chainArchivist.insert([
365351
+ ...block1[1].flat(),
365352
+ block1[0]
365353
+ ]);
365354
+ console.log(`[API] Producer declared: ${producerAccount.address}`);
365355
+ }
365020
365356
  const stakedChainContext = {
365021
- chainId: contractAddress,
365022
- events: stakeEventsViewer,
365357
+ chainId: stakeChainViewer.chainId,
365023
365358
  stake: stakeChainViewer,
365024
365359
  store: {
365025
365360
  chainMap
@@ -365028,7 +365363,7 @@ var getServer$3 = /* @__PURE__ */ __name$4(async (context) => {
365028
365363
  const head = await findMostRecentBlock(chainArchivist);
365029
365364
  return [
365030
365365
  assertEx(head?._hash, () => "No head found in chainArchivist"),
365031
- assertEx(head?.block, () => "No head found in chainArchivist")
365366
+ head?.block ?? 0
365032
365367
  ];
365033
365368
  }, "head")
365034
365369
  };
@@ -374227,25 +374562,6 @@ async function initTransferSummaryMap(params) {
374227
374562
  });
374228
374563
  }
374229
374564
  __name(initTransferSummaryMap, "initTransferSummaryMap");
374230
- var accountServiceSingleton;
374231
- var initAccount = /* @__PURE__ */ __name(async ({ config: config2, logger }) => {
374232
- if (accountServiceSingleton) return accountServiceSingleton;
374233
- let walletPhrase = config2.producer.mnemonic;
374234
- if (isUndefined$1(walletPhrase)) {
374235
- logger?.warn("[Producer] No wallet mnemonic specified!");
374236
- const randomMnemonic = HDWallet.generateMnemonic();
374237
- logger?.warn(`[Producer] Using randomly generated mnemonic:
374238
-
374239
- ${randomMnemonic}
374240
-
374241
- `);
374242
- walletPhrase = randomMnemonic;
374243
- }
374244
- const wallet = await generateXyoBaseWalletFromPhrase(walletPhrase);
374245
- const account = await wallet.derivePath(ADDRESS_INDEX.XYO);
374246
- accountServiceSingleton = account;
374247
- return accountServiceSingleton;
374248
- }, "initAccount");
374249
374565
  var balanceServiceSingleton;
374250
374566
  var initBalanceService = /* @__PURE__ */ __name(async (params) => {
374251
374567
  if (balanceServiceSingleton) return balanceServiceSingleton;
@@ -374770,7 +375086,7 @@ var initServices = /* @__PURE__ */ __name(async (context) => {
374770
375086
  };
374771
375087
  const [{ traceProvider, meterProvider }, account] = await Promise.all([
374772
375088
  startupSpanAsync("initTelemetry", () => initTelemetry(telemetryConfig)),
374773
- startupSpanAsync("initAccount", () => initAccount(context))
375089
+ startupSpanAsync("initProducerAccount", () => initProducerAccount(context))
374774
375090
  ]);
374775
375091
  const allowedRewardRedeemers = config2.validation?.allowedRewardRedeemers ?? [];
374776
375092
  const allowedRewardEscrowAccountSigners = config2.validation?.allowedRewardEscrowAccountSigners ?? [];
@@ -375087,7 +375403,7 @@ var waitForHostPort = /* @__PURE__ */ __name((host, port) => {
375087
375403
 
375088
375404
  // src/runCLI.ts
375089
375405
  var configuration;
375090
- var version = isDefined("1.16.18") ? "1.16.18" : "unknown";
375406
+ var version = isDefined("1.16.20") ? "1.16.20" : "unknown";
375091
375407
  var getContextFromConfig = /* @__PURE__ */ __name((configuration2) => {
375092
375408
  const logger = initLogger(configuration2);
375093
375409
  const orchestrator = new Orchestrator(logger);