@xyo-network/xl1-cli 1.16.20 → 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 +1890 -1838
  2. package/package.json +10 -10
package/dist/cli-min.mjs CHANGED
@@ -23,6 +23,9 @@ import { ConsoleSpanExporter, BatchSpanProcessor, AlwaysOnSampler, BasicTracerPr
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");
@@ -83018,7 +83002,7 @@ var StatusNetworks = {
83018
83002
  }
83019
83003
  async makeRequest(url3) {
83020
83004
  try {
83021
- const response = await axios$1.get(url3);
83005
+ const response = await axios.get(url3);
83022
83006
  if (isNetworkStatus(response.data)) {
83023
83007
  return response.data;
83024
83008
  } else {
@@ -117789,116 +117773,6 @@ BaseTimeSyncService = _ts_decorate14([
117789
117773
  creatable()
117790
117774
  ], BaseTimeSyncService);
117791
117775
 
117792
- var __defProp$i = Object.defineProperty;
117793
- var __name$a = (target, value) => __defProp$i(target, "name", { value, configurable: true });
117794
- var initContextManager = /* @__PURE__ */ __name$a(() => {
117795
- const contextManager = new AsyncLocalStorageContextManager();
117796
- context.setGlobalContextManager(contextManager.enable());
117797
- }, "initContextManager");
117798
- var initPropagation = /* @__PURE__ */ __name$a(() => {
117799
- propagation.setGlobalPropagator(new CompositePropagator({
117800
- propagators: [
117801
- new W3CTraceContextPropagator(),
117802
- new W3CBaggagePropagator()
117803
- ]
117804
- }));
117805
- }, "initPropagation");
117806
- var initResource = /* @__PURE__ */ __name$a((attributes) => {
117807
- const detectedResource = detectResources({
117808
- detectors: [
117809
- // hostDetector,
117810
- // osDetector,
117811
- // processDetector,
117812
- serviceInstanceIdDetector
117813
- ]
117814
- });
117815
- const staticResource = resourceFromAttributes({
117816
- [ATTR_SERVICE_NAME]: attributes.serviceName,
117817
- [ATTR_SERVICE_VERSION]: attributes.serviceName
117818
- });
117819
- const resource = detectedResource.merge(staticResource);
117820
- return resource;
117821
- }, "initResource");
117822
- var initHostMetrics = /* @__PURE__ */ __name$a((meterProvider) => {
117823
- const hostMetrics = new HostMetrics({
117824
- meterProvider,
117825
- name: "host-metrics"
117826
- });
117827
- hostMetrics.start();
117828
- }, "initHostMetrics");
117829
- var initNodeMetrics = /* @__PURE__ */ __name$a((meterProvider) => {
117830
- const instrumentation = new RuntimeNodeInstrumentation({
117831
- monitoringPrecision: 5e3
117832
- });
117833
- instrumentation.setMeterProvider(meterProvider);
117834
- instrumentation.enable();
117835
- }, "initNodeMetrics");
117836
- var initMetricsExporter = /* @__PURE__ */ __name$a((metricsConfig) => {
117837
- const { port, endpoint } = metricsConfig;
117838
- const exporter = new PrometheusExporter({
117839
- port,
117840
- endpoint
117841
- }, (err) => {
117842
- if (err) console.error("Error initializing Prometheus exporter", err);
117843
- });
117844
- return exporter;
117845
- }, "initMetricsExporter");
117846
- var initMeterProvider = /* @__PURE__ */ __name$a((resource, readers) => {
117847
- const meterProvider = new MeterProvider({
117848
- readers,
117849
- resource,
117850
- views: [
117851
- {
117852
- aggregation: void 0,
117853
- instrumentName: "*",
117854
- instrumentType: void 0,
117855
- meterName: "*"
117856
- }
117857
- ]
117858
- });
117859
- metrics$3.setGlobalMeterProvider(meterProvider);
117860
- return meterProvider;
117861
- }, "initMeterProvider");
117862
- var initTraceProvider = /* @__PURE__ */ __name$a((otlpEndpoint, resource) => {
117863
- const spanProcessors = [];
117864
- if (isDefined(otlpEndpoint)) {
117865
- const isHttp = otlpEndpoint.includes("/v1/traces") || otlpEndpoint.includes(":4318") || otlpEndpoint.startsWith("http");
117866
- const exporter = isHttp ? new OTLPTraceExporter({
117867
- url: otlpEndpoint
117868
- }) : new OTLPTraceExporter$1({
117869
- url: otlpEndpoint
117870
- });
117871
- const batchSpanProcessorConfig = {};
117872
- const spanProcessor = new BatchSpanProcessor(exporter, batchSpanProcessorConfig);
117873
- spanProcessors.push(spanProcessor);
117874
- }
117875
- const config = {
117876
- resource,
117877
- sampler: new AlwaysOnSampler(),
117878
- spanProcessors
117879
- };
117880
- const traceProvider = new BasicTracerProvider(config);
117881
- trace.setGlobalTracerProvider(traceProvider);
117882
- return traceProvider;
117883
- }, "initTraceProvider");
117884
- var initTelemetry = /* @__PURE__ */ __name$a((params) => {
117885
- const { attributes, metricsConfig, otlpEndpoint } = params;
117886
- initContextManager();
117887
- initPropagation();
117888
- const resource = initResource(attributes);
117889
- const exporter = initMetricsExporter(metricsConfig);
117890
- const meterProvider = initMeterProvider(resource, [
117891
- exporter
117892
- ]);
117893
- initHostMetrics(meterProvider);
117894
- initNodeMetrics(meterProvider);
117895
- const traceProvider = initTraceProvider(otlpEndpoint, resource);
117896
- return {
117897
- meterProvider,
117898
- traceProvider
117899
- };
117900
- }, "initTelemetry");
117901
-
117902
117776
  // src/AbstractNode.ts
117903
117777
  var AbstractNode = class _AbstractNode extends AbstractModuleInstance {
117904
117778
  static configSchemas = [...super.configSchemas, NodeConfigSchema];
@@ -118834,9 +118708,9 @@ factory.create(requiredAttachableBridgeInstanceFunctions, [
118834
118708
  // src/Config.ts
118835
118709
  var BridgeConfigSchema = "network.xyo.bridge.config";
118836
118710
 
118837
- var __defProp$h = Object.defineProperty;
118711
+ var __defProp$i = Object.defineProperty;
118838
118712
  var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
118839
- 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;
118840
118714
  var __decorateClass$7 = (decorators, target, key, kind) => {
118841
118715
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target;
118842
118716
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
@@ -119750,11 +119624,11 @@ var AbstractModuleProxy = class extends AbstractModuleInstance {
119750
119624
  }
119751
119625
  };
119752
119626
 
119753
- var __defProp$g = Object.defineProperty;
119627
+ var __defProp$h = Object.defineProperty;
119754
119628
  var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor;
119755
119629
  var __getProtoOf$4 = Object.getPrototypeOf;
119756
119630
  var __reflectGet$4 = Reflect.get;
119757
- 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;
119758
119632
  var __decorateClass$6 = (decorators, target, key, kind) => {
119759
119633
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target;
119760
119634
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
@@ -120044,7 +119918,7 @@ var HttpBridge = class extends AbstractBridge {
120044
119918
  return [];
120045
119919
  }
120046
119920
  };
120047
- __publicField$6(HttpBridge, "axios", new AxiosJson());
119921
+ __publicField$6(HttpBridge, "axios", new Axios(axiosJsonConfig()));
120048
119922
  __publicField$6(HttpBridge, "configSchemas", [...__superGet$4(HttpBridge, HttpBridge, "configSchemas"), HttpBridgeConfigSchema]);
120049
119923
  __publicField$6(HttpBridge, "defaultConfigSchema", HttpBridgeConfigSchema);
120050
119924
  __publicField$6(HttpBridge, "defaultFailureRetryTime", 1e3 * 60);
@@ -120055,9 +119929,1627 @@ HttpBridge = __decorateClass$6([
120055
119929
  creatableModule()
120056
119930
  ], HttpBridge);
120057
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
+
120058
120536
  var __defProp$f = Object.defineProperty;
120059
120537
  var __name$9 = (target, value) => __defProp$f(target, "name", { value, configurable: true });
120060
- 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) => {
120061
121553
  const node = await MemoryNode.create({
120062
121554
  account: "random"
120063
121555
  });
@@ -120104,7 +121596,7 @@ var initArchivistSync = /* @__PURE__ */ __name$9(async (name, inArchivist, outAr
120104
121596
  }, "initArchivistSync");
120105
121597
  var initMutex = new Mutex$1();
120106
121598
  var bridgeSingletonMap = /* @__PURE__ */ new Map();
120107
- var initBridge = /* @__PURE__ */ __name$9(async (nodeUrl) => {
121599
+ var initBridge = /* @__PURE__ */ __name$6(async (nodeUrl) => {
120108
121600
  return await initMutex.runExclusive(async () => {
120109
121601
  const existing = bridgeSingletonMap.get(nodeUrl);
120110
121602
  if (existing) return existing;
@@ -120127,9 +121619,18 @@ var initBridge = /* @__PURE__ */ __name$9(async (nodeUrl) => {
120127
121619
  return bridge;
120128
121620
  });
120129
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");
120130
121631
  var initMutex2 = new Mutex$1();
120131
121632
  var bridgedModuleDictionary = {};
120132
- var initBridgedModule = /* @__PURE__ */ __name$9(async ({ bridge, moduleName }) => {
121633
+ var initBridgedModule = /* @__PURE__ */ __name$6(async ({ bridge, moduleName }) => {
120133
121634
  return await initMutex2.runExclusive(async () => {
120134
121635
  const existing = bridgedModuleDictionary?.[bridge.address]?.[moduleName];
120135
121636
  if (existing) return existing;
@@ -120144,18 +121645,146 @@ var initBridgedModule = /* @__PURE__ */ __name$9(async ({ bridge, moduleName })
120144
121645
  return moduleInstance;
120145
121646
  });
120146
121647
  }, "initBridgedModule");
120147
- var initBridgedArchivistModule = /* @__PURE__ */ __name$9(async ({ bridge, moduleName }) => {
121648
+ var initBridgedArchivistModule = /* @__PURE__ */ __name$6(async ({ bridge, moduleName }) => {
120148
121649
  return assertEx(asAttachableArchivistInstance(await initBridgedModule({
120149
121650
  bridge,
120150
121651
  moduleName
120151
121652
  })), () => `Could not convert ${moduleName} to attachable archivist instance`);
120152
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");
120153
121670
 
120154
- 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;
120155
121784
  var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
120156
121785
  var __getProtoOf$3 = Object.getPrototypeOf;
120157
121786
  var __reflectGet$3 = Reflect.get;
120158
- 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;
120159
121788
  var __decorateClass$5 = (decorators, target, key, kind) => {
120160
121789
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
120161
121790
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
@@ -211535,910 +213164,6 @@ function requireExpress () {
211535
213164
  var expressExports = requireExpress();
211536
213165
  var express2 = /*@__PURE__*/getDefaultExportFromCjs(expressExports);
211537
213166
 
211538
- var __defProp$d = Object.defineProperty;
211539
- var __name$8 = (target, value) => __defProp$d(target, "name", { value, configurable: true });
211540
- var NodeXyoViewer = class extends AbstractCreatable {
211541
- static {
211542
- __name$8(this, "NodeXyoViewer");
211543
- }
211544
- // TODO: Make configurable with defaults
211545
- _tracer;
211546
- addressBalanceDivinerPath = "XYOChain:Chain:AddressBalanceDiviner";
211547
- finalizedArchivistPath = "XYOChain:Chain:Finalized";
211548
- headValidationDivinerPath = "XYOChain:Chain:HeadValidationDiviner";
211549
- transferBalanceDivinerPath = "XYOChain:Chain:AddressTransferDiviner";
211550
- _addressBalanceDiviner;
211551
- _chainId;
211552
- _finalizedArchivist;
211553
- _rewardMultipliers;
211554
- _signedHydratedBlockCache;
211555
- _signedHydratedTransactionCache;
211556
- _transferBalanceDiviner;
211557
- get context() {
211558
- return assertEx(this.params.context, () => "NodeXyoViewer requires a context");
211559
- }
211560
- get initRewardsCache() {
211561
- return this.params.initRewardsCache ?? true;
211562
- }
211563
- get node() {
211564
- return this.params.node;
211565
- }
211566
- get rewardMultipliers() {
211567
- this._rewardMultipliers = this._rewardMultipliers ?? this.params.rewardMultipliers ?? {};
211568
- return this._rewardMultipliers;
211569
- }
211570
- get stake() {
211571
- return this.context.stake;
211572
- }
211573
- get transfersSummaryContext() {
211574
- return this.params.transfersSummaryContext ?? {
211575
- ...this.context
211576
- };
211577
- }
211578
- async accountBalance(address) {
211579
- return await spanRootAsync("accountBalance", async () => {
211580
- const diviner = await this.getAddressBalanceDiviner();
211581
- const query = new PayloadBuilder({
211582
- schema: AddressSchema
211583
- }).fields({
211584
- address
211585
- }).build();
211586
- const result = await diviner.divine([
211587
- query
211588
- ]);
211589
- const chainSummary = assertEx(result.find(isChainSummaryBalances), () => "Failed to divine chain summary balances");
211590
- const balances = chainSummary.balances;
211591
- const signedBalance = balances[address] === void 0 ? 0n : parseSignedBigInt(balances[address]);
211592
- return asAttoXL1(signedBalance > 0n ? signedBalance : 0n);
211593
- }, this.tracer);
211594
- }
211595
- async accountBalanceHistory(address, rangeOrHash) {
211596
- return await spanRootAsync("accountHistory", async () => {
211597
- const range = asRange(rangeOrHash);
211598
- const startingRange = asXL1BlockRange(range ?? [
211599
- 0,
211600
- await this.currentBlockNumber()
211601
- ], {
211602
- name: "accountBalanceHistory"
211603
- });
211604
- const blockNumbers = await this.distillTransferHistory(address, startingRange);
211605
- const blocks = (await Promise.all(blockNumbers.map(async (bn) => await this.blockByNumber(bn)))).filter(exists$1);
211606
- const result = [];
211607
- for (const block of blocks) {
211608
- const transferIndexes = block[0].payload_schemas.map((schema, index) => schema === TransferSchema ? index : void 0).filter(exists$1);
211609
- const transfers = transferIndexes.map((index) => {
211610
- const hash = block[0].payload_hashes[index];
211611
- return assertEx(block[1].find((p) => p._hash === hash), () => `Could not find Transfer with hash ${hash} in block ${block[0]._hash}`);
211612
- }).filter(exists$1).filter((t) => t.from === address || isDefined(t.transfers[address]));
211613
- if (transfers.length === 0) {
211614
- continue;
211615
- }
211616
- const pairs = transfers.map((transfer) => {
211617
- return [
211618
- block[0],
211619
- transfer
211620
- ];
211621
- });
211622
- result.push(...pairs.map(([block2, transfer]) => [
211623
- block2,
211624
- null,
211625
- transfer
211626
- ]));
211627
- }
211628
- return result;
211629
- }, this.tracer);
211630
- }
211631
- async blockByHash(hash) {
211632
- return await spanRootAsync("blockByHash", async () => {
211633
- const cache = await this.getHydratedBlockCache();
211634
- return await cache.get(hash);
211635
- }, this.tracer);
211636
- }
211637
- async blockByNumber(blockNumber) {
211638
- return await spanRootAsync("blockByNumber", async () => {
211639
- return await hydratedBlockByNumber(this.context, blockNumber);
211640
- }, this.tracer);
211641
- }
211642
- async blocksByHash(hash, limit = 10) {
211643
- return await spanRootAsync("blocksByHash", async () => {
211644
- assertEx(limit > 0, () => "limit must be greater than 0");
211645
- assertEx(limit <= 100, () => "limit must be less than 100");
211646
- const blocks = [];
211647
- let current = await this.blockByHash(hash);
211648
- while (current && blocks.length < limit) {
211649
- blocks.push(current);
211650
- const previousHash = current[0].previous;
211651
- if (previousHash === null) break;
211652
- current = await this.blockByHash(previousHash);
211653
- }
211654
- return blocks;
211655
- }, this.tracer);
211656
- }
211657
- async chainId() {
211658
- return await spanRootAsync("chainId", async () => {
211659
- if (this._chainId !== void 0) return this._chainId;
211660
- const block = await this.currentBlock();
211661
- this._chainId = block[0].chain;
211662
- return this._chainId;
211663
- }, this.tracer);
211664
- }
211665
- async chainIdAtBlock(blockNumber) {
211666
- return await spanRootAsync("chainIdAtBlock", async () => {
211667
- if (this._chainId !== void 0) return this._chainId;
211668
- const block = await this.blockByNumber(blockNumber);
211669
- this._chainId = block?.[0].chain;
211670
- return this._chainId;
211671
- }, this.tracer);
211672
- }
211673
- async currentBlock() {
211674
- return await spanRootAsync("currentBlock", async () => {
211675
- const currentHead = assertEx(await this.getCurrentHead(), () => "Could not find most recent block");
211676
- const cache = await this.getHydratedBlockCache();
211677
- const block = await cache.get(currentHead._hash);
211678
- if (!block) {
211679
- console.log(`Could not find current block with hash ${currentHead._hash}`);
211680
- }
211681
- return assertEx(block, () => "Could not find current block");
211682
- }, this.tracer);
211683
- }
211684
- async currentBlockHash() {
211685
- return await spanRootAsync("currentBlockHash", async () => {
211686
- const currentHead = assertEx(await this.getCurrentHead(), () => "Could not find most recent block");
211687
- return currentHead._hash;
211688
- }, this.tracer);
211689
- }
211690
- async currentBlockNumber() {
211691
- return await spanRootAsync("currentBlockNumber", async () => {
211692
- const currentHead = assertEx(await this.getCurrentHead(), () => "Could not find most recent block");
211693
- return asXL1BlockNumber(currentHead.block, {
211694
- name: "currentBlockNumber"
211695
- });
211696
- }, this.tracer);
211697
- }
211698
- forkHistory() {
211699
- throw new Error("Method not implemented.");
211700
- }
211701
- networkStakeStepRewardAddressHistory(_address) {
211702
- throw new Error("Method not implemented.");
211703
- }
211704
- networkStakeStepRewardAddressReward(_context, _address) {
211705
- throw new Error("Method not implemented.");
211706
- }
211707
- networkStakeStepRewardAddressShare(_context, _address) {
211708
- throw new Error("Method not implemented.");
211709
- }
211710
- networkStakeStepRewardClaimedByAddress(_address) {
211711
- throw new Error("Method not implemented.");
211712
- }
211713
- async networkStakeStepRewardForPosition(position, range) {
211714
- return await timeBudget("networkStakeStepRewardForPosition", this.logger, async () => {
211715
- const externalRange = await externalBlockRangeFromXL1BlockRange(this.context, range);
211716
- const positionCount = await this.context.stake.stakeEvents.positionCount(externalRange);
211717
- if (positionCount === 0) {
211718
- return [
211719
- 0n,
211720
- 0n
211721
- ];
211722
- }
211723
- const steps = blockRangeSteps(range, [
211724
- 3,
211725
- 4,
211726
- 5,
211727
- 6,
211728
- 7
211729
- ]);
211730
- const rewards = await Promise.all(steps.map((step) => this.networkStakeStepRewardForStepForPosition(step, position)));
211731
- const positionReward = rewards.reduce((a, b) => a + b[0], 0n);
211732
- const totalReward = rewards.reduce((a, b) => a + b[1], 0n);
211733
- return [
211734
- positionReward,
211735
- totalReward
211736
- ];
211737
- }, 100);
211738
- }
211739
- async networkStakeStepRewardForStep(stepContext) {
211740
- return await stepRewardTotal(this.context, stepContext, this.rewardMultipliers);
211741
- }
211742
- async networkStakeStepRewardForStepForPosition(stepIdentity, position) {
211743
- const stepIdentityString = toStepIdentityString(stepIdentity);
211744
- const cacheKey = `${stepIdentityString}|${position}`;
211745
- return await withContextCacheResponse(this.context, "NodeXyoViewer-networkStakeStepRewardForStepForPosition", cacheKey, async () => {
211746
- const range = await externalBlockRangeFromStep(this.context, stepIdentity);
211747
- const stake = await this.stakeById(position);
211748
- const numerator = stake.staked === XYO_NETWORK_STAKING_ADDRESS ? await weightedStakeForRangeByPosition(this.context, range, position) : 0n;
211749
- const denominator = await this.stepWeightedDenominator(stepIdentity);
211750
- const totalReward = await this.networkStakeStepRewardForStep(stepIdentity);
211751
- const positionReward = denominator > 0n ? totalReward * numerator / denominator : 0n;
211752
- const result = [
211753
- positionReward,
211754
- totalReward
211755
- ];
211756
- return result;
211757
- });
211758
- }
211759
- async networkStakeStepRewardPoolRewards(step) {
211760
- const stakes = await this.context.stake.stakesByStaked(XYO_NETWORK_STAKING_ADDRESS);
211761
- const rewards = [];
211762
- for (const stake of stakes) {
211763
- rewards.push([
211764
- stake.staker,
211765
- await this.networkStakeStepRewardForStepForPosition(step, stake.id)
211766
- ]);
211767
- }
211768
- const result = {};
211769
- for (const [staker, reward] of rewards) {
211770
- result[staker] = (result[staker] ?? 0n) + reward[0];
211771
- }
211772
- const filtered = Object.fromEntries(Object.entries(result).filter(([_, v]) => v > 0n));
211773
- return filtered;
211774
- }
211775
- networkStakeStepRewardPoolShares(_context) {
211776
- throw new Error("Method not implemented.");
211777
- }
211778
- async networkStakeStepRewardPositionWeight(stepContext, position) {
211779
- return await networkStakeStepRewardPositionWeight(this.context, stepContext, position);
211780
- }
211781
- networkStakeStepRewardPotentialPositionLoss(_context, _position) {
211782
- throw new Error("Method not implemented.");
211783
- }
211784
- networkStakeStepRewardRandomizer(_context) {
211785
- throw new Error("Method not implemented.");
211786
- }
211787
- async networkStakeStepRewardStakerCount(stepContext) {
211788
- return Object.keys(await allStakersForStep(this.context, stepContext, XYO_NETWORK_STAKING_ADDRESS)).length;
211789
- }
211790
- networkStakeStepRewardUnclaimedByAddress(_address) {
211791
- throw new Error("Method not implemented.");
211792
- }
211793
- networkStakeStepRewardWeightForAddress(_context, _address) {
211794
- throw new Error("Method not implemented.");
211795
- }
211796
- async networkStakeStepRewardsForPosition(position, range) {
211797
- const steps = blockRangeSteps(range, [
211798
- 3,
211799
- 4,
211800
- 5,
211801
- 6,
211802
- 7,
211803
- 8
211804
- ]);
211805
- const rewards = await Promise.all(steps.map(async (step) => {
211806
- return [
211807
- toStepIdentityString(step),
211808
- await this.networkStakeStepRewardForStepForPosition(step, position)
211809
- ];
211810
- }));
211811
- const result = {};
211812
- for (const [step, reward] of rewards) {
211813
- result[step] = reward;
211814
- }
211815
- const filtered = Object.fromEntries(Object.entries(result).filter(([_, v]) => v[0] > 0n));
211816
- return filtered;
211817
- }
211818
- async networkStakeStepRewardsForRange(range) {
211819
- return await timeBudget("networkStakeStepRewardsForRange", this.logger, async () => {
211820
- const steps = blockRangeSteps(range, [
211821
- 3,
211822
- 4,
211823
- 5,
211824
- 6,
211825
- 7,
211826
- 8
211827
- ]);
211828
- const rewards = await Promise.all(steps.map(async (step) => {
211829
- return await this.networkStakeStepRewardForStep(step);
211830
- }));
211831
- return rewards.reduce((a, b) => a + b, 0n);
211832
- }, 100);
211833
- }
211834
- async networkStakeStepRewardsForStepLevel(stepLevel, range) {
211835
- const steps = blockRangeSteps(range, [
211836
- stepLevel
211837
- ]);
211838
- const rewards = await Promise.all(steps.map(async (step) => {
211839
- return await this.networkStakeStepRewardForStep(step);
211840
- }));
211841
- return rewards.reduce((a, b) => a + b, 0n);
211842
- }
211843
- async stakeById(id) {
211844
- return await this.stake.stakeById(id);
211845
- }
211846
- async stakeByStaker(staker, slot) {
211847
- return await this.stake.stakeByStaker(staker, slot);
211848
- }
211849
- async stakedByStaker(staker) {
211850
- const result = /* @__PURE__ */ new Set();
211851
- let slot = 0;
211852
- while (true) {
211853
- try {
211854
- const ethStake = await this.stake.stakeByStaker(staker, slot);
211855
- result.add(toAddress(ethStake.staked));
211856
- slot++;
211857
- } catch {
211858
- break;
211859
- }
211860
- }
211861
- return [
211862
- ...result
211863
- ];
211864
- }
211865
- async stakesByStaked(staked) {
211866
- return await this.stake.stakesByStaked(staked);
211867
- }
211868
- async stakesByStaker(staker) {
211869
- return await this.stake.stakesByStaker(staker);
211870
- }
211871
- async transactionByBlockHashAndIndex(blockHash, transactionIndex = 0) {
211872
- return await spanRootAsync("transactionByBlockHashAndIndex", async () => {
211873
- assertEx(transactionIndex >= 0, () => "transactionIndex must be greater than or equal to 0");
211874
- try {
211875
- const block = await this.blockByHash(blockHash);
211876
- if (!block) return null;
211877
- const blockBoundWitnessIndexes = block[0].payload_schemas.map((schema, index) => schema === BoundWitnessSchema ? index : void 0).filter(exists$1);
211878
- const blockBoundWitnessHashes = new Set(blockBoundWitnessIndexes.map((index) => block[0].payload_hashes[index]));
211879
- const blockBoundWitnesses = block[1].filter((payload) => blockBoundWitnessHashes.has(payload._hash) || blockBoundWitnessHashes.has(payload._dataHash));
211880
- const blockTransactionBoundWitnesses = blockBoundWitnesses.filter(isTransactionBoundWitnessWithStorageMeta);
211881
- const transaction = blockTransactionBoundWitnesses.at(transactionIndex);
211882
- if (!transaction) return null;
211883
- return await this.transactionByHash(transaction._hash);
211884
- } catch {
211885
- return null;
211886
- }
211887
- }, this.tracer);
211888
- }
211889
- async transactionByBlockNumberAndIndex(blockNumber, transactionIndex = 0) {
211890
- return await spanRootAsync("transactionByBlockNumberAndIndex", async () => {
211891
- try {
211892
- const block = await this.blockByNumber(blockNumber);
211893
- if (!block) return null;
211894
- return await this.transactionByBlockHashAndIndex(block[0]._hash, transactionIndex);
211895
- } catch {
211896
- return null;
211897
- }
211898
- }, this.tracer);
211899
- }
211900
- async transactionByHash(transactionHash) {
211901
- return await spanRootAsync("transactionByHash", async () => {
211902
- try {
211903
- const cache = await this.getHydratedTransactionCache();
211904
- const hydratedTransaction = await cache.get(transactionHash);
211905
- return hydratedTransaction ?? null;
211906
- } catch {
211907
- return null;
211908
- }
211909
- }, this.tracer);
211910
- }
211911
- async transferBalance(address) {
211912
- return await spanRootAsync("transferBalance", async () => {
211913
- const diviner = await this.getTransferBalanceDiviner();
211914
- const query = new PayloadBuilder({
211915
- schema: AddressSchema
211916
- }).fields({
211917
- address
211918
- }).build();
211919
- const result = await diviner.divine([
211920
- query
211921
- ]);
211922
- const chainSummary = result.find(isChainSummaryTransfers);
211923
- const transfers = chainSummary?.transfers ?? {};
211924
- let transferBalance = 0n;
211925
- for (const [from, transfer] of Object.entries(transfers)) {
211926
- if (from === address) {
211927
- for (const [, amount] of Object.entries(transfer)) {
211928
- transferBalance += parseSignedBigInt(amount);
211929
- }
211930
- }
211931
- }
211932
- return asAttoXL1(transferBalance > 0n ? transferBalance : 0n);
211933
- }, this.tracer);
211934
- }
211935
- transferBalanceHistory(_address) {
211936
- throw new Error("Method not implemented.");
211937
- }
211938
- async transferPairBalance(pair) {
211939
- return await spanRootAsync("transferPairBalance", async () => {
211940
- const diviner = await this.getTransferBalanceDiviner();
211941
- const query = new PayloadBuilder({
211942
- schema: AddressPairSchema
211943
- }).fields({
211944
- addresses: [
211945
- pair[0],
211946
- pair[1]
211947
- ]
211948
- }).build();
211949
- const result = await diviner.divine([
211950
- query
211951
- ]);
211952
- const chainSummary = assertEx(result.find(isChainSummaryTransfers), () => "Failed to divine chain summary transfers");
211953
- const transfers = chainSummary.transfers;
211954
- const balance = transfers[pair[0]]?.[pair[1]];
211955
- return isDefined(balance) ? asAttoXL1(parseSignedBigInt(balance) * -1n) : asAttoXL1(0n);
211956
- }, this.tracer);
211957
- }
211958
- transferPairBalanceHistory(_pair) {
211959
- throw new Error("Method not implemented.");
211960
- }
211961
- getAddressBalanceDiviner = /* @__PURE__ */ __name$8(async () => {
211962
- if (this._addressBalanceDiviner) return this._addressBalanceDiviner;
211963
- const resolved = await this.getDiviner(this.addressBalanceDivinerPath);
211964
- this._addressBalanceDiviner = resolved;
211965
- return assertEx(this._addressBalanceDiviner, () => `Could not resolve ${this.addressBalanceDivinerPath} to a diviner instance`);
211966
- }, "getAddressBalanceDiviner");
211967
- getArchivist = /* @__PURE__ */ __name$8(async (identifier) => {
211968
- const archivist = await this.node.resolve(identifier);
211969
- return assertEx(asAttachableArchivistInstance(archivist), () => `Could not resolve ${identifier} to an archivist instance`);
211970
- }, "getArchivist");
211971
- async getCurrentHead() {
211972
- const chainArchivist = await this.getFinalizedArchivist();
211973
- return await findMostRecentBlock(chainArchivist);
211974
- }
211975
- getDiviner = /* @__PURE__ */ __name$8(async (identifier) => {
211976
- const diviner = await this.node.resolve(identifier);
211977
- return assertEx(asDivinerInstance(diviner), () => `Could not resolve ${identifier} to a diviner instance`);
211978
- }, "getDiviner");
211979
- getFinalizedArchivist = /* @__PURE__ */ __name$8(async () => {
211980
- if (this._finalizedArchivist) return this._finalizedArchivist;
211981
- const resolved = await this.getArchivist(this.finalizedArchivistPath);
211982
- this._finalizedArchivist = resolved;
211983
- return assertEx(this._finalizedArchivist, () => `Could not resolve finalized archivist at ${this.finalizedArchivistPath}`);
211984
- }, "getFinalizedArchivist");
211985
- getFinalizedPayloadMap = /* @__PURE__ */ __name$8(async () => {
211986
- const archivist = this.getFinalizedArchivist();
211987
- return readPayloadMapFromStore(await archivist);
211988
- }, "getFinalizedPayloadMap");
211989
- async getHydratedBlockCache() {
211990
- if (this._signedHydratedBlockCache) return this._signedHydratedBlockCache;
211991
- const chainMap = await this.getFinalizedPayloadMap();
211992
- this._signedHydratedBlockCache = new HydratedCache(chainMap, hydrateBlock, 200);
211993
- return this._signedHydratedBlockCache;
211994
- }
211995
- async getHydratedTransactionCache() {
211996
- if (this._signedHydratedTransactionCache) return this._signedHydratedTransactionCache;
211997
- const chainMap = await this.getFinalizedPayloadMap();
211998
- this._signedHydratedTransactionCache = new HydratedCache(chainMap, tryHydrateTransaction, 200);
211999
- return this._signedHydratedTransactionCache;
212000
- }
212001
- getTransferBalanceDiviner = /* @__PURE__ */ __name$8(async () => {
212002
- if (this._transferBalanceDiviner) return this._transferBalanceDiviner;
212003
- const resolved = await this.getDiviner(this.transferBalanceDivinerPath);
212004
- this._transferBalanceDiviner = resolved;
212005
- return assertEx(this._transferBalanceDiviner, () => `Could not resolve ${this.transferBalanceDivinerPath} to a diviner instance`);
212006
- }, "getTransferBalanceDiviner");
212007
- async startHandler() {
212008
- try {
212009
- const currentBlockNumber = await this.currentBlockNumber();
212010
- await this.transferBalance(XYO_ZERO_ADDRESS);
212011
- await this.accountBalance(XYO_ZERO_ADDRESS);
212012
- if (this.initRewardsCache) {
212013
- const externalRange = await externalBlockRangeFromXL1BlockRange(this.context, asXL1BlockRange([
212014
- 0,
212015
- currentBlockNumber
212016
- ], {
212017
- name: "startHandler"
212018
- }));
212019
- const positionCount = await this.context.stake.stakeEvents.positionCount(externalRange);
212020
- this.logger?.log(`NodeXyoViewer: Precomputing networkStakeStepRewardForPosition up to position ${positionCount - 1}`);
212021
- for (let position = 0; position < positionCount; position++) {
212022
- await this.networkStakeStepRewardForPosition(position, asXL1BlockRange([
212023
- 0,
212024
- currentBlockNumber
212025
- ], {
212026
- name: "startHandler"
212027
- }));
212028
- }
212029
- this.logger?.log(`NodeXyoViewer: Precomputed networkStakeStepRewardForPosition up to position ${positionCount - 1}`);
212030
- }
212031
- } catch (ex) {
212032
- this.logger?.error(`NodeXyoViewer: Error during startHandler initialization: ${ex.message}`);
212033
- this.logger?.error(ex.stack ?? "<No Stack>");
212034
- throw ex;
212035
- }
212036
- }
212037
- async stepWeightedDenominator(stepIdentity) {
212038
- const cacheKey = toStepIdentityString(stepIdentity);
212039
- return await withContextCacheResponse(this.context, "NodeXyoViewer-networkStakeStepRewardForStepForPosition-denominator", cacheKey, async () => {
212040
- const range = await externalBlockRangeFromStep(this.context, stepIdentity);
212041
- return await weightedStakeForRangeByPosition(this.context, range);
212042
- });
212043
- }
212044
- async distillTransferHistory(address, range, max = 50) {
212045
- if (range[1] - range[0] <= StepSizes[0] || max <= 1) {
212046
- return Array.from({
212047
- length: range[1] - range[0] + 1
212048
- }, (_, i) => range[1] - i).slice(0, max).map((n) => asXL1BlockNumber(n, {
212049
- name: "distillTransferHistory"
212050
- }));
212051
- }
212052
- const frames = deepCalculateFramesFromRange(asXL1BlockRange(range, {
212053
- name: "distillTransferHistory"
212054
- }));
212055
- const transferSummaryPairs = await Promise.all(frames.map(async (frame) => {
212056
- return [
212057
- frame,
212058
- await transfersStepSummaryFromRange(this.transfersSummaryContext, frame)
212059
- ];
212060
- }));
212061
- const filteredTransferSummaryPairs = transferSummaryPairs.filter(([_, summary]) => Object.keys(summary.transfers).includes(address));
212062
- const sortedTransferSummaryPairs = filteredTransferSummaryPairs.toSorted((a, b) => {
212063
- return b[0][1] - a[0][1];
212064
- });
212065
- const resultBlockNumbers = /* @__PURE__ */ new Set();
212066
- for (const [frame] of sortedTransferSummaryPairs) {
212067
- if (frame[1] - frame[0] + 1 > StepSizes[0]) {
212068
- const values = await this.distillTransferHistory(address, asXL1BlockRange([
212069
- frame[0],
212070
- frame[1] - 1
212071
- ], {
212072
- name: "distillTransferHistory"
212073
- }), max - resultBlockNumbers.size);
212074
- for (const value of values) {
212075
- resultBlockNumbers.add(value);
212076
- }
212077
- resultBlockNumbers.add(frame[1]);
212078
- } else {
212079
- for (let i = frame[0]; i <= frame[1]; i++) {
212080
- resultBlockNumbers.add(i);
212081
- }
212082
- }
212083
- if (resultBlockNumbers.size >= max) {
212084
- break;
212085
- }
212086
- }
212087
- return [
212088
- ...resultBlockNumbers
212089
- ].toSorted((a, b) => b - a).slice(0, max);
212090
- }
212091
- };
212092
-
212093
- var __defProp$c = Object.defineProperty;
212094
- var __name$7 = (target, value) => __defProp$c(target, "name", { value, configurable: true });
212095
- async function networkStakeStepRewardEarnedForPosition(context, stepIdentity, position, rewardMultipliers = {}) {
212096
- const cacheKey = `${stepIdentity.block}|${stepIdentity.step}|${position.id}`;
212097
- return await withContextCacheResponse(context, "networkStakeStepRewardEarnedForPosition", cacheKey, async () => {
212098
- const range = await externalBlockRangeFromStep(context, stepIdentity);
212099
- const numerator = position.staked === XYO_NETWORK_STAKING_ADDRESS ? await weightedStakeForRangeByPosition(context, range, position.id) : 0n;
212100
- const denominator = await weightedStakeForRangeByPosition(context, range);
212101
- const totalReward = await stepRewardTotal(context, stepIdentity, rewardMultipliers);
212102
- const positionReward = denominator > 0n ? totalReward * numerator / denominator : 0n;
212103
- const result = [
212104
- positionReward,
212105
- totalReward
212106
- ];
212107
- return result;
212108
- });
212109
- }
212110
- __name$7(networkStakeStepRewardEarnedForPosition, "networkStakeStepRewardEarnedForPosition");
212111
-
212112
- // src/primitives/networkStakeStepRewardEarned.ts
212113
- async function networkStakeStepRewardEarned(context, stepIdentity, rewardMultipliers = {}) {
212114
- const cacheKey = `${stepIdentity.block}|${stepIdentity.step}`;
212115
- return await withContextCacheResponse(context, "networkStakeStepRewardEarned", cacheKey, async () => {
212116
- const positions = await context.stake.stakesByStaked(XYO_NETWORK_STAKING_ADDRESS);
212117
- const results = await Promise.all(positions.map((pos) => {
212118
- return networkStakeStepRewardEarnedForPosition(context, stepIdentity, pos, rewardMultipliers);
212119
- }));
212120
- const numerator = results.reduce((acc, [positionReward]) => acc + positionReward, 0n);
212121
- const result = results.length > 0 ? [
212122
- numerator,
212123
- results[0][1]
212124
- ] : [
212125
- 0n,
212126
- 0n
212127
- ];
212128
- return result;
212129
- });
212130
- }
212131
- __name$7(networkStakeStepRewardEarned, "networkStakeStepRewardEarned");
212132
- async function networkStakeStepRewardEarnedForStaker(context, stepIdentity, staker, rewardMultipliers = {}) {
212133
- const stepId = toStepIdentityString(stepIdentity);
212134
- return await withContextCacheResponse(context, "networkStakeStepRewardEarnedForStaker", `${stepId}-${staker}`, async () => {
212135
- const positions = (await context.stake.stakesByStaker(staker)).filter((pos) => pos.staked === XYO_NETWORK_STAKING_ADDRESS);
212136
- const results = await Promise.all(positions.map((pos) => {
212137
- return networkStakeStepRewardEarnedForPosition(context, stepIdentity, pos, rewardMultipliers);
212138
- }));
212139
- const numerator = results.reduce((acc, [positionReward]) => acc + positionReward, 0n);
212140
- const result = results.length > 0 ? [
212141
- numerator,
212142
- results[0][1]
212143
- ] : [
212144
- 0n,
212145
- 0n
212146
- ];
212147
- return result;
212148
- });
212149
- }
212150
- __name$7(networkStakeStepRewardEarnedForStaker, "networkStakeStepRewardEarnedForStaker");
212151
- var SimpleStepRewardsByPositionViewer = class extends AbstractCreatable {
212152
- static {
212153
- __name$7(this, "SimpleStepRewardsByPositionViewer");
212154
- }
212155
- get context() {
212156
- return this.params.context;
212157
- }
212158
- get rewardMultipliers() {
212159
- return this.params.rewardMultipliers ?? {};
212160
- }
212161
- async bonus({ range, positions } = {}) {
212162
- const total = await this.total({
212163
- range,
212164
- positions
212165
- });
212166
- const earned = await this.earned({
212167
- range,
212168
- positions
212169
- });
212170
- const result = {};
212171
- for (const pos of Object.keys(total).map(Number)) {
212172
- result[pos] = asAttoXL1(total[pos] - (earned[pos] ?? 0n));
212173
- }
212174
- return result;
212175
- }
212176
- claimed(_options) {
212177
- throw new Error("Method not implemented.");
212178
- }
212179
- async earned({ range, positions } = {}) {
212180
- return await this.calculateRewards({
212181
- range,
212182
- positions
212183
- });
212184
- }
212185
- async total({ range, positions } = {}) {
212186
- return await this.calculateRewards({
212187
- range,
212188
- positions
212189
- }, this.rewardMultipliers);
212190
- }
212191
- unclaimed(_options = {}) {
212192
- throw new Error("Method not implemented.");
212193
- }
212194
- async calculateRewards({ range, positions } = {}, rewardMultipliers) {
212195
- const result = {};
212196
- const steps = blockRangeSteps(asXL1BlockRange(range ?? [
212197
- 0,
212198
- (await this.context.head())[1]
212199
- ], {
212200
- name: "NodeStepRewardsByPositionViewer"
212201
- }), [
212202
- 3,
212203
- 4,
212204
- 5,
212205
- 6,
212206
- 7
212207
- ]);
212208
- for (const step of steps) {
212209
- if (isArray$1(positions)) {
212210
- for (const positionId of positions) {
212211
- const position = await this.context.stake.stakeById(positionId);
212212
- result[positionId] = asAttoXL1((result[positionId] ?? 0n) + (await networkStakeStepRewardEarnedForPosition(this.context, step, position, rewardMultipliers))[0]);
212213
- }
212214
- }
212215
- }
212216
- return result;
212217
- }
212218
- };
212219
- var SimpleStepRewardsByStakerViewer = class extends AbstractCreatable {
212220
- static {
212221
- __name$7(this, "SimpleStepRewardsByStakerViewer");
212222
- }
212223
- get context() {
212224
- return this.params.context;
212225
- }
212226
- get rewardMultipliers() {
212227
- return this.params.rewardMultipliers ?? {};
212228
- }
212229
- get stakedChainContext() {
212230
- return this.params.context;
212231
- }
212232
- async bonus({ range, stakers } = {}) {
212233
- const total = await this.total({
212234
- range,
212235
- stakers
212236
- });
212237
- const earned = await this.earned({
212238
- range,
212239
- stakers
212240
- });
212241
- const result = {};
212242
- for (const staker of Object.keys(total)) {
212243
- result[staker] = asAttoXL1(total[staker] - (earned[staker] ?? 0n));
212244
- }
212245
- return result;
212246
- }
212247
- claimed(_options) {
212248
- throw new Error("Method not implemented.");
212249
- }
212250
- async earned(options = {}) {
212251
- return await this.calculateRewards(options);
212252
- }
212253
- async total(options = {}) {
212254
- return await this.calculateRewards(options, this.rewardMultipliers);
212255
- }
212256
- unclaimed(_options = {}) {
212257
- throw new Error("Method not implemented.");
212258
- }
212259
- async calculateRewards({ range, stakers } = {}, rewardMultipliers) {
212260
- const result = {};
212261
- const steps = blockRangeSteps(asXL1BlockRange(range ?? [
212262
- 0,
212263
- (await this.context.head())[1]
212264
- ], {
212265
- name: "NodeStepRewardsByStakerViewer"
212266
- }), [
212267
- 3,
212268
- 4,
212269
- 5,
212270
- 6,
212271
- 7
212272
- ]);
212273
- for (const step of steps) {
212274
- if (isArray$1(stakers)) {
212275
- for (const staker of stakers) {
212276
- result[staker] = asAttoXL1((result[staker] ?? 0n) + (await networkStakeStepRewardEarnedForStaker(this.context, step, staker, rewardMultipliers))[0]);
212277
- }
212278
- }
212279
- }
212280
- return result;
212281
- }
212282
- };
212283
- var SimpleStepRewardsByStepViewer = class extends AbstractCreatable {
212284
- static {
212285
- __name$7(this, "SimpleStepRewardsByStepViewer");
212286
- }
212287
- get context() {
212288
- return this.params.context;
212289
- }
212290
- get rewardMultipliers() {
212291
- return this.params.rewardMultipliers ?? {};
212292
- }
212293
- async bonus({ range, steps } = {}) {
212294
- const total = await this.total({
212295
- range,
212296
- steps
212297
- });
212298
- const earned = await this.earned({
212299
- range,
212300
- steps
212301
- });
212302
- const result = {};
212303
- for (const stepString of Object.keys(total)) {
212304
- result[stepString] = asAttoXL1(total[stepString] - (earned[stepString] ?? 0n));
212305
- }
212306
- return result;
212307
- }
212308
- claimed(_options) {
212309
- throw new Error("Method not implemented.");
212310
- }
212311
- async earned({ range, steps } = {}) {
212312
- const result = {};
212313
- const resolvedSteps = steps ?? blockRangeSteps(asXL1BlockRange(range ?? [
212314
- 0,
212315
- (await this.context.head())[1]
212316
- ], {
212317
- name: "NodeStepRewardsByStepViewer"
212318
- }), [
212319
- 3,
212320
- 4,
212321
- 5,
212322
- 6,
212323
- 7
212324
- ]);
212325
- for (const step of resolvedSteps) {
212326
- const stepIdentityString = toStepIdentityString(step);
212327
- result[stepIdentityString] = asAttoXL1((result[stepIdentityString] ?? 0n) + (await networkStakeStepRewardEarned(this.context, step))[0]);
212328
- }
212329
- return result;
212330
- }
212331
- async total({ range, steps } = {}) {
212332
- const result = {};
212333
- const resolvedSteps = steps ?? blockRangeSteps(asXL1BlockRange(range ?? [
212334
- 0,
212335
- (await this.context.head())[1]
212336
- ], {
212337
- name: "NodeStepRewardsByStepViewer"
212338
- }), [
212339
- 3,
212340
- 4,
212341
- 5,
212342
- 6,
212343
- 7
212344
- ]);
212345
- for (const step of resolvedSteps) {
212346
- const stepIdentityString = toStepIdentityString(step);
212347
- result[stepIdentityString] = asAttoXL1((result[stepIdentityString] ?? 0n) + (await networkStakeStepRewardEarned(this.context, step, this.rewardMultipliers))[0]);
212348
- }
212349
- return result;
212350
- }
212351
- unclaimed(_options = {}) {
212352
- throw new Error("Method not implemented.");
212353
- }
212354
- };
212355
- var SimpleStepRewardsViewer = class extends AbstractCreatable {
212356
- static {
212357
- __name$7(this, "SimpleStepRewardsViewer");
212358
- }
212359
- _position;
212360
- _staker;
212361
- _step;
212362
- get position() {
212363
- return assertEx(this._position, () => "Position viewer not initialized");
212364
- }
212365
- get staker() {
212366
- return assertEx(this._staker, () => "Position viewer not initialized");
212367
- }
212368
- get step() {
212369
- return assertEx(this._step, () => "Step viewer not initialized");
212370
- }
212371
- get total() {
212372
- throw new Error("Method not implemented.");
212373
- }
212374
- get context() {
212375
- return this.params.context;
212376
- }
212377
- get rewardMultipliers() {
212378
- return this.params.rewardMultipliers;
212379
- }
212380
- async createHandler() {
212381
- await super.createHandler();
212382
- this._position = await SimpleStepRewardsByPositionViewer.create({
212383
- context: this.context,
212384
- rewardMultipliers: this.rewardMultipliers
212385
- });
212386
- this._staker = await SimpleStepRewardsByStakerViewer.create({
212387
- context: this.context,
212388
- rewardMultipliers: this.rewardMultipliers
212389
- });
212390
- this._step = await SimpleStepRewardsByStepViewer.create({
212391
- context: this.context,
212392
- rewardMultipliers: this.rewardMultipliers
212393
- });
212394
- }
212395
- async startHandler() {
212396
- await super.startHandler();
212397
- await assertEx(this._position, () => "Position viewer not created").start();
212398
- await assertEx(this._staker, () => "Staker viewer not created").start();
212399
- await assertEx(this._step, () => "Step viewer not created").start();
212400
- }
212401
- };
212402
- var SimpleNetworkStakeViewer = class extends AbstractCreatable {
212403
- static {
212404
- __name$7(this, "SimpleNetworkStakeViewer");
212405
- }
212406
- _stepRewardsViewer;
212407
- get context() {
212408
- return this.params.context;
212409
- }
212410
- get rewardMultipliers() {
212411
- return this.params.rewardMultipliers;
212412
- }
212413
- get stepRewards() {
212414
- return assertEx(this._stepRewardsViewer, () => "Step rewards viewer not initialized");
212415
- }
212416
- async active(blockNumber) {
212417
- const resolvedBlockNumber = blockNumber ?? (await this.context.head())[1];
212418
- return [
212419
- await this.context.stake.active(resolvedBlockNumber),
212420
- resolvedBlockNumber
212421
- ];
212422
- }
212423
- async createHandler() {
212424
- await super.createHandler();
212425
- this._stepRewardsViewer = await SimpleStepRewardsViewer.create({
212426
- context: this.context,
212427
- rewardMultipliers: this.rewardMultipliers
212428
- });
212429
- }
212430
- async startHandler() {
212431
- await super.startHandler();
212432
- const stepRewardsByPositionViewer = await SimpleStepRewardsByPositionViewer.create({
212433
- context: this.context,
212434
- rewardMultipliers: this.rewardMultipliers
212435
- });
212436
- console.log("Initializing NodeStepRewardsByPositionViewer...");
212437
- await stepRewardsByPositionViewer.start();
212438
- console.log("Initialized NodeStepRewardsByPositionViewer.");
212439
- }
212440
- };
212441
-
212442
213167
  /**
212443
213168
  * JsonRpcEngine only accepts callback-based middleware directly.
212444
213169
  * createAsyncMiddleware exists to enable consumers to pass in async middleware
@@ -214550,78 +215275,78 @@ function v4(options, buf, offset) {
214550
215275
  return _v4(options);
214551
215276
  }
214552
215277
 
214553
- var __defProp$b = Object.defineProperty;
214554
- 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 });
214555
215280
 
214556
215281
  // src/engine/requestSchemas.ts
214557
215282
  var requestSchemas = {};
214558
215283
 
214559
215284
  // src/engine/rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer.ts
214560
- var rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer = /* @__PURE__ */ __name$6((viewer) => {
215285
+ var rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer = /* @__PURE__ */ __name$5((viewer) => {
214561
215286
  return {
214562
- networkStakingStepRewardsByPositionViewer_bonus: /* @__PURE__ */ __name$6((params) => viewer.bonus(...params ?? []), "networkStakingStepRewardsByPositionViewer_bonus"),
214563
- networkStakingStepRewardsByPositionViewer_claimed: /* @__PURE__ */ __name$6((params) => viewer.claimed(...params ?? []), "networkStakingStepRewardsByPositionViewer_claimed"),
214564
- networkStakingStepRewardsByPositionViewer_earned: /* @__PURE__ */ __name$6((params) => viewer.earned(...params ?? []), "networkStakingStepRewardsByPositionViewer_earned"),
214565
- networkStakingStepRewardsByPositionViewer_total: /* @__PURE__ */ __name$6((params) => viewer.total(...params ?? []), "networkStakingStepRewardsByPositionViewer_total"),
214566
- 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")
214567
215292
  };
214568
215293
  }, "rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer");
214569
215294
 
214570
215295
  // src/engine/rpcMethodHandlersFromRunner.ts
214571
- var rpcMethodHandlersFromRunner = /* @__PURE__ */ __name$6((runner) => {
215296
+ var rpcMethodHandlersFromRunner = /* @__PURE__ */ __name$5((runner) => {
214572
215297
  return {
214573
- xyoRunner_broadcastTransaction: /* @__PURE__ */ __name$6((params) => runner.broadcastTransaction(...params ?? []), "xyoRunner_broadcastTransaction")
215298
+ xyoRunner_broadcastTransaction: /* @__PURE__ */ __name$5((params) => runner.broadcastTransaction(...params ?? []), "xyoRunner_broadcastTransaction")
214574
215299
  };
214575
215300
  }, "rpcMethodHandlersFromRunner");
214576
215301
 
214577
215302
  // src/engine/rpcMethodHandlersFromViewer.ts
214578
- var rpcMethodHandlersFromViewer = /* @__PURE__ */ __name$6((viewer) => {
215303
+ var rpcMethodHandlersFromViewer = /* @__PURE__ */ __name$5((viewer) => {
214579
215304
  return {
214580
- xyoViewer_networkStakeStepRewardClaimedByAddress: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardClaimedByAddress(...params ?? []), "xyoViewer_networkStakeStepRewardClaimedByAddress"),
214581
- xyoViewer_networkStakeStepRewardAddressReward: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardAddressReward(...params ?? []), "xyoViewer_networkStakeStepRewardAddressReward"),
214582
- xyoViewer_networkStakeStepRewardAddressHistory: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardAddressHistory(...params ?? []), "xyoViewer_networkStakeStepRewardAddressHistory"),
214583
- xyoViewer_networkStakeStepRewardAddressShare: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardAddressShare(...params ?? []), "xyoViewer_networkStakeStepRewardAddressShare"),
214584
- xyoViewer_networkStakeStepRewardWeightForAddress: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardWeightForAddress?.(...params ?? []), "xyoViewer_networkStakeStepRewardWeightForAddress"),
214585
- xyoViewer_networkStakeStepRewardUnclaimedByAddress: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardUnclaimedByAddress(...params ?? []), "xyoViewer_networkStakeStepRewardUnclaimedByAddress"),
214586
- xyoViewer_networkStakeStepRewardPoolShares: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardPoolShares(...params ?? []), "xyoViewer_networkStakeStepRewardPoolShares"),
214587
- xyoViewer_networkStakeStepRewardPoolRewards: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardPoolRewards(...params ?? []), "xyoViewer_networkStakeStepRewardPoolRewards"),
214588
- xyoViewer_networkStakeStepRewardPositionWeight: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardPositionWeight?.(...params ?? []), "xyoViewer_networkStakeStepRewardPositionWeight"),
214589
- xyoViewer_networkStakeStepRewardPotentialPositionLoss: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardPotentialPositionLoss?.(...params ?? []), "xyoViewer_networkStakeStepRewardPotentialPositionLoss"),
214590
- xyoViewer_networkStakeStepRewardForStep: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardForStep?.(...params ?? []), "xyoViewer_networkStakeStepRewardForStep"),
214591
- xyoViewer_networkStakeStepRewardRandomizer: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardRandomizer?.(...params ?? []), "xyoViewer_networkStakeStepRewardRandomizer"),
214592
- xyoViewer_networkStakeStepRewardStakerCount: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardStakerCount?.(...params ?? []), "xyoViewer_networkStakeStepRewardStakerCount"),
214593
- xyoViewer_networkStakeStepRewardForStepForPosition: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardForStepForPosition?.(...params ?? []), "xyoViewer_networkStakeStepRewardForStepForPosition"),
214594
- xyoViewer_networkStakeStepRewardForPosition: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardForPosition?.(...params ?? []), "xyoViewer_networkStakeStepRewardForPosition"),
214595
- xyoViewer_networkStakeStepRewardsForPosition: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardsForPosition?.(...params ?? []), "xyoViewer_networkStakeStepRewardsForPosition"),
214596
- xyoViewer_networkStakeStepRewardsForRange: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardsForRange?.(...params ?? []), "xyoViewer_networkStakeStepRewardsForRange"),
214597
- xyoViewer_networkStakeStepRewardsForStepLevel: /* @__PURE__ */ __name$6((params) => viewer.networkStakeStepRewardsForStepLevel?.(...params ?? []), "xyoViewer_networkStakeStepRewardsForStepLevel"),
214598
- xyoViewer_accountBalance: /* @__PURE__ */ __name$6((params) => viewer.accountBalance(...params ?? []), "xyoViewer_accountBalance"),
214599
- xyoViewer_accountBalanceHistory: /* @__PURE__ */ __name$6((params) => viewer.accountBalanceHistory(...params ?? []), "xyoViewer_accountBalanceHistory"),
214600
- xyoViewer_blockByHash: /* @__PURE__ */ __name$6((params) => viewer.blockByHash(...params ?? []), "xyoViewer_blockByHash"),
214601
- xyoViewer_blockByNumber: /* @__PURE__ */ __name$6((params) => viewer.blockByNumber(...params ?? []), "xyoViewer_blockByNumber"),
214602
- xyoViewer_blocksByHash: /* @__PURE__ */ __name$6((params) => viewer.blocksByHash(...params ?? []), "xyoViewer_blocksByHash"),
214603
- xyoViewer_chainId: /* @__PURE__ */ __name$6((params) => viewer.chainId(...params ?? []), "xyoViewer_chainId"),
214604
- xyoViewer_chainIdAtBlock: /* @__PURE__ */ __name$6((params) => viewer.chainIdAtBlock(...params ?? []), "xyoViewer_chainIdAtBlock"),
214605
- xyoViewer_currentBlock: /* @__PURE__ */ __name$6((params) => viewer.currentBlock(...params ?? []), "xyoViewer_currentBlock"),
214606
- xyoViewer_currentBlockHash: /* @__PURE__ */ __name$6((params) => viewer.currentBlockHash(...params ?? []), "xyoViewer_currentBlockHash"),
214607
- xyoViewer_currentBlockNumber: /* @__PURE__ */ __name$6((params) => viewer.currentBlockNumber(...params ?? []), "xyoViewer_currentBlockNumber"),
214608
- xyoViewer_forkHistory: /* @__PURE__ */ __name$6((params) => viewer.forkHistory(...params ?? []), "xyoViewer_forkHistory"),
214609
- xyoViewer_stakeById: /* @__PURE__ */ __name$6((params) => viewer.stakeById(...params ?? []), "xyoViewer_stakeById"),
214610
- xyoViewer_stakeByStaker: /* @__PURE__ */ __name$6((params) => viewer.stakeByStaker(...params ?? []), "xyoViewer_stakeByStaker"),
214611
- xyoViewer_stakesByStaked: /* @__PURE__ */ __name$6((params) => viewer.stakesByStaked(...params ?? []), "xyoViewer_stakesByStaked"),
214612
- xyoViewer_stakesByStaker: /* @__PURE__ */ __name$6((params) => viewer.stakesByStaker(...params ?? []), "xyoViewer_stakesByStaker"),
214613
- xyoViewer_transactionByBlockHashAndIndex: /* @__PURE__ */ __name$6((params) => viewer.transactionByBlockHashAndIndex(...params ?? []), "xyoViewer_transactionByBlockHashAndIndex"),
214614
- xyoViewer_transactionByBlockNumberAndIndex: /* @__PURE__ */ __name$6((params) => viewer.transactionByBlockNumberAndIndex(...params ?? []), "xyoViewer_transactionByBlockNumberAndIndex"),
214615
- xyoViewer_transactionByHash: /* @__PURE__ */ __name$6((params) => viewer.transactionByHash(...params ?? []), "xyoViewer_transactionByHash"),
214616
- xyoViewer_transferBalance: /* @__PURE__ */ __name$6((params) => viewer.transferBalance(...params ?? []), "xyoViewer_transferBalance"),
214617
- xyoViewer_transferBalanceHistory: /* @__PURE__ */ __name$6((params) => viewer.transferBalanceHistory(...params ?? []), "xyoViewer_transferBalanceHistory"),
214618
- xyoViewer_transferPairBalance: /* @__PURE__ */ __name$6((params) => viewer.transferPairBalance(...params ?? []), "xyoViewer_transferPairBalance"),
214619
- 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")
214620
215345
  };
214621
215346
  }, "rpcMethodHandlersFromViewer");
214622
215347
 
214623
215348
  // src/engine/rpcMethodHandlersFromConnection.ts
214624
- var rpcMethodHandlersFromConnection = /* @__PURE__ */ __name$6((connection, networkStakeViewer) => {
215349
+ var rpcMethodHandlersFromConnection = /* @__PURE__ */ __name$5((connection, networkStakeViewer) => {
214625
215350
  const { runner, viewer } = connection;
214626
215351
  let result = {};
214627
215352
  if (runner) result = {
@@ -214700,7 +215425,7 @@ function base64Encode(u8) {
214700
215425
  }
214701
215426
  return btoa(binary);
214702
215427
  }
214703
- __name$6(base64Encode, "base64Encode");
215428
+ __name$5(base64Encode, "base64Encode");
214704
215429
  function base64Decode(b64) {
214705
215430
  if (typeof Buffer !== "undefined" && typeof Buffer.from === "function") {
214706
215431
  return new Uint8Array(Buffer.from(b64, "base64"));
@@ -214710,7 +215435,7 @@ function base64Decode(b64) {
214710
215435
  for (let i = 0; i < binary.length; i++) u8[i] = binary.charCodeAt(i);
214711
215436
  return u8;
214712
215437
  }
214713
- __name$6(base64Decode, "base64Decode");
215438
+ __name$5(base64Decode, "base64Decode");
214714
215439
  var ArrayBufferToJsonZod = _instanceof(ArrayBuffer).transform((x) => {
214715
215440
  const u8 = new Uint8Array(x);
214716
215441
  return base64Encode(u8);
@@ -215709,7 +216434,7 @@ var AllRpcSchemas = {
215709
216434
  ...XyoPermissionsRpcSchemas,
215710
216435
  ...NetworkStakeViewerRpcSchemas
215711
216436
  };
215712
- var createRequestSchema = /* @__PURE__ */ __name$6((methodName, paramsSchema = _undefined()) => object$3({
216437
+ var createRequestSchema = /* @__PURE__ */ __name$5((methodName, paramsSchema = _undefined()) => object$3({
215713
216438
  id: union$1([
215714
216439
  string$2(),
215715
216440
  number$3()
@@ -215718,7 +216443,7 @@ var createRequestSchema = /* @__PURE__ */ __name$6((methodName, paramsSchema = _
215718
216443
  method: literal$2(methodName),
215719
216444
  params: paramsSchema
215720
216445
  }), "createRequestSchema");
215721
- var createResponseSchema = /* @__PURE__ */ __name$6((resultSchema = _undefined()) => object$3({
216446
+ var createResponseSchema = /* @__PURE__ */ __name$5((resultSchema = _undefined()) => object$3({
215722
216447
  id: union$1([
215723
216448
  string$2(),
215724
216449
  number$3()
@@ -216127,7 +216852,7 @@ var createResponseSchema = /* @__PURE__ */ __name$6((resultSchema = _undefined()
216127
216852
  });
216128
216853
 
216129
216854
  // src/engine-node/rpcEngineFromConnection.ts
216130
- var rpcEngineFromConnection = /* @__PURE__ */ __name$6((connection, networkStakeViewer) => {
216855
+ var rpcEngineFromConnection = /* @__PURE__ */ __name$5((connection, networkStakeViewer) => {
216131
216856
  const engine = new JsonRpcEngine();
216132
216857
  const handlers = rpcMethodHandlersFromConnection(connection, networkStakeViewer);
216133
216858
  engine.push(createAsyncMiddleware(async (req, res) => {
@@ -216167,7 +216892,7 @@ var rpcEngineFromConnection = /* @__PURE__ */ __name$6((connection, networkStake
216167
216892
  }, "rpcEngineFromConnection");
216168
216893
  var HttpRpcTransport = class {
216169
216894
  static {
216170
- __name$6(this, "HttpRpcTransport");
216895
+ __name$5(this, "HttpRpcTransport");
216171
216896
  }
216172
216897
  _rpcUrl;
216173
216898
  _schemas;
@@ -216206,7 +216931,7 @@ var HttpRpcTransport = class {
216206
216931
  };
216207
216932
  (class {
216208
216933
  static {
216209
- __name$6(this, "MemoryRpcTransport");
216934
+ __name$5(this, "MemoryRpcTransport");
216210
216935
  }
216211
216936
  _rpcEngine;
216212
216937
  _schemas;
@@ -216244,7 +216969,7 @@ var HttpRpcTransport = class {
216244
216969
  // src/provider/runner/JsonRpcXyoRunner.ts
216245
216970
  var JsonRpcXyoRunner = class {
216246
216971
  static {
216247
- __name$6(this, "JsonRpcXyoRunner");
216972
+ __name$5(this, "JsonRpcXyoRunner");
216248
216973
  }
216249
216974
  transport;
216250
216975
  constructor(transport) {
@@ -216258,7 +216983,7 @@ var JsonRpcXyoRunner = class {
216258
216983
  };
216259
216984
  var NodeXyoRunner = class {
216260
216985
  static {
216261
- __name$6(this, "NodeXyoRunner");
216986
+ __name$5(this, "NodeXyoRunner");
216262
216987
  }
216263
216988
  // TODO: Make configurable with defaults
216264
216989
  node;
@@ -216281,11 +217006,11 @@ var NodeXyoRunner = class {
216281
217006
  ]);
216282
217007
  return txHash;
216283
217008
  }
216284
- getArchivist = /* @__PURE__ */ __name$6(async (identifier) => {
217009
+ getArchivist = /* @__PURE__ */ __name$5(async (identifier) => {
216285
217010
  const archivist = await this.node.resolve(identifier);
216286
217011
  return assertEx(asArchivistInstance(archivist), () => `Could not resolve ${identifier} to an archivist instance`);
216287
217012
  }, "getArchivist");
216288
- getPendingArchivist = /* @__PURE__ */ __name$6(async () => {
217013
+ getPendingArchivist = /* @__PURE__ */ __name$5(async () => {
216289
217014
  if (this._pendingArchivist) return this._pendingArchivist;
216290
217015
  this._pendingArchivist = await this.getArchivist(this.pendingArchivistPath);
216291
217016
  return assertEx(this._pendingArchivist, () => `Could not resolve pending archivist at ${this.pendingArchivistPath}`);
@@ -216295,7 +217020,7 @@ var NodeXyoRunner = class {
216295
217020
  // src/provider/viewer/JsonRpcViewer.ts
216296
217021
  var JsonRpcViewer = class {
216297
217022
  static {
216298
- __name$6(this, "JsonRpcViewer");
217023
+ __name$5(this, "JsonRpcViewer");
216299
217024
  }
216300
217025
  transport;
216301
217026
  constructor(transport) {
@@ -216306,14 +217031,14 @@ var JsonRpcViewer = class {
216306
217031
  // src/provider/viewer/JsonRpcNetworkStakingStepRewardsViewer/JsonRpcNetworkStakingStepRewardsViewerMethods.ts
216307
217032
  var JsonRpcNetworkStakingStepRewardsViewerMethods = class extends JsonRpcViewer {
216308
217033
  static {
216309
- __name$6(this, "JsonRpcNetworkStakingStepRewardsViewerMethods");
217034
+ __name$5(this, "JsonRpcNetworkStakingStepRewardsViewerMethods");
216310
217035
  }
216311
217036
  };
216312
217037
 
216313
217038
  // src/provider/viewer/JsonRpcNetworkStakingStepRewardsViewer/JsonRpcNetworkStakingStepRewardsViewer.ts
216314
217039
  var JsonRpcNetworkStakingStepRewardsViewer = class extends JsonRpcNetworkStakingStepRewardsViewerMethods {
216315
217040
  static {
216316
- __name$6(this, "JsonRpcNetworkStakingStepRewardsViewer");
217041
+ __name$5(this, "JsonRpcNetworkStakingStepRewardsViewer");
216317
217042
  }
216318
217043
  providers;
216319
217044
  constructor(transport, providers) {
@@ -216337,7 +217062,7 @@ var JsonRpcNetworkStakingStepRewardsViewer = class extends JsonRpcNetworkStaking
216337
217062
  // src/provider/viewer/JsonRpcNetworkStakeViewer/JsonRpcNetworkStakeViewerMethods.ts
216338
217063
  var JsonRpcNetworkStakeViewerMethods = class extends JsonRpcViewer {
216339
217064
  static {
216340
- __name$6(this, "JsonRpcNetworkStakeViewerMethods");
217065
+ __name$5(this, "JsonRpcNetworkStakeViewerMethods");
216341
217066
  }
216342
217067
  async active(blockNumber) {
216343
217068
  return await this.transport.sendRequest("networkStakeViewer_active", [
@@ -216349,7 +217074,7 @@ var JsonRpcNetworkStakeViewerMethods = class extends JsonRpcViewer {
216349
217074
  // src/provider/viewer/JsonRpcNetworkStakeViewer/JsonRpcNetworkStakeViewer.ts
216350
217075
  var JsonRpcNetworkStakeViewer = class extends JsonRpcNetworkStakeViewerMethods {
216351
217076
  static {
216352
- __name$6(this, "JsonRpcNetworkStakeViewer");
217077
+ __name$5(this, "JsonRpcNetworkStakeViewer");
216353
217078
  }
216354
217079
  _stepRewards;
216355
217080
  constructor(transport) {
@@ -216364,7 +217089,7 @@ var JsonRpcNetworkStakeViewer = class extends JsonRpcNetworkStakeViewerMethods {
216364
217089
  // src/provider/viewer/JsonRpcTimeSyncViewer/JsonRpcTimeSyncViewerMethods.ts
216365
217090
  var JsonRpcTimeSyncViewerMethods = class {
216366
217091
  static {
216367
- __name$6(this, "JsonRpcTimeSyncViewerMethods");
217092
+ __name$5(this, "JsonRpcTimeSyncViewerMethods");
216368
217093
  }
216369
217094
  transport;
216370
217095
  constructor(transport) {
@@ -216395,7 +217120,7 @@ var JsonRpcTimeSyncViewerMethods = class {
216395
217120
  // src/provider/viewer/JsonRpcTimeSyncViewer/JsonRpcTimeSyncViewer.ts
216396
217121
  (class extends JsonRpcTimeSyncViewerMethods {
216397
217122
  static {
216398
- __name$6(this, "JsonRpcTimeSyncViewer");
217123
+ __name$5(this, "JsonRpcTimeSyncViewer");
216399
217124
  }
216400
217125
  constructor(transport) {
216401
217126
  super(transport);
@@ -216403,7 +217128,7 @@ var JsonRpcTimeSyncViewerMethods = class {
216403
217128
  });
216404
217129
  var JsonRpcXyoViewer = class {
216405
217130
  static {
216406
- __name$6(this, "JsonRpcXyoViewer");
217131
+ __name$5(this, "JsonRpcXyoViewer");
216407
217132
  }
216408
217133
  providers;
216409
217134
  transport;
@@ -216634,7 +217359,7 @@ var JsonRpcXyoViewer = class {
216634
217359
  // src/provider/connection/XyoBaseConnection.ts
216635
217360
  var XyoBaseConnection = class {
216636
217361
  static {
216637
- __name$6(this, "XyoBaseConnection");
217362
+ __name$5(this, "XyoBaseConnection");
216638
217363
  }
216639
217364
  _network;
216640
217365
  _runner;
@@ -216663,7 +217388,7 @@ var XyoBaseConnection = class {
216663
217388
  // src/provider/connection/HttpRpcXyoConnection.ts
216664
217389
  var HttpRpcXyoConnection = class extends XyoBaseConnection {
216665
217390
  static {
216666
- __name$6(this, "HttpRpcXyoConnection");
217391
+ __name$5(this, "HttpRpcXyoConnection");
216667
217392
  }
216668
217393
  constructor(params) {
216669
217394
  const { endpoint, storage: storageParam } = params;
@@ -216689,7 +217414,7 @@ var HttpRpcXyoConnection = class extends XyoBaseConnection {
216689
217414
  // src/provider/datalake/JsonRpcDataLakeViewerMethods.ts
216690
217415
  var JsonRpcDataLakeViewerMethods = class extends JsonRpcViewer {
216691
217416
  static {
216692
- __name$6(this, "JsonRpcDataLakeViewerMethods");
217417
+ __name$5(this, "JsonRpcDataLakeViewerMethods");
216693
217418
  }
216694
217419
  get(_id) {
216695
217420
  throw new Error("Method not implemented.");
@@ -216705,7 +217430,7 @@ var JsonRpcDataLakeViewerMethods = class extends JsonRpcViewer {
216705
217430
  // src/provider/datalake/JsonRpcDataLakeViewer.ts
216706
217431
  (class extends JsonRpcDataLakeViewerMethods {
216707
217432
  static {
216708
- __name$6(this, "JsonRpcDataLakeViewer");
217433
+ __name$5(this, "JsonRpcDataLakeViewer");
216709
217434
  }
216710
217435
  constructor(transport) {
216711
217436
  super(transport);
@@ -216715,7 +217440,7 @@ var JsonRpcDataLakeViewerMethods = class extends JsonRpcViewer {
216715
217440
  // src/provider/permissions/RpcXyoPermissions.ts
216716
217441
  (class {
216717
217442
  static {
216718
- __name$6(this, "RpcXyoPermissions");
217443
+ __name$5(this, "RpcXyoPermissions");
216719
217444
  }
216720
217445
  transport;
216721
217446
  constructor(transport) {
@@ -216738,7 +217463,7 @@ var JsonRpcDataLakeViewerMethods = class extends JsonRpcViewer {
216738
217463
  // src/provider/signer/JsonRpcXyoSigner.ts
216739
217464
  (class {
216740
217465
  static {
216741
- __name$6(this, "RpcXyoSigner");
217466
+ __name$5(this, "RpcXyoSigner");
216742
217467
  }
216743
217468
  transport;
216744
217469
  constructor(transport) {
@@ -217149,610 +217874,6 @@ var getBiosExternalInterface = async () => {
217149
217874
  // src/external/boot.ts
217150
217875
  var boot = () => genericBoot(getBiosExternalInterface);
217151
217876
 
217152
- var __defProp$a = Object.defineProperty;
217153
- var __name$5 = (target, value) => __defProp$a(target, "name", { value, configurable: true });
217154
-
217155
- // src/BaseEthProvider.ts
217156
- (class {
217157
- static {
217158
- __name$5(this, "BaseEthProvider");
217159
- }
217160
- eth_accounts() {
217161
- throw new Error("Method not implemented.");
217162
- }
217163
- eth_blockNumber() {
217164
- throw new Error("Method not implemented.");
217165
- }
217166
- eth_call(_transaction, _blockNumber) {
217167
- throw new Error("Method not implemented.");
217168
- }
217169
- eth_clearSubscriptions(_keepSyncing) {
217170
- throw new Error("Method not implemented.");
217171
- }
217172
- eth_coinbase() {
217173
- throw new Error("Method not implemented.");
217174
- }
217175
- eth_compileLLL(_code) {
217176
- throw new Error("Method not implemented.");
217177
- }
217178
- eth_compileSerpent(_code) {
217179
- throw new Error("Method not implemented.");
217180
- }
217181
- eth_compileSolidity(_code) {
217182
- throw new Error("Method not implemented.");
217183
- }
217184
- eth_estimateGas(_transaction, _blockNumber) {
217185
- throw new Error("Method not implemented.");
217186
- }
217187
- eth_feeHistory(_blockCount, _newestBlock, _rewardPercentiles) {
217188
- throw new Error("Method not implemented.");
217189
- }
217190
- eth_gasPrice() {
217191
- throw new Error("Method not implemented.");
217192
- }
217193
- eth_getBalance(_address, _blockNumber) {
217194
- throw new Error("Method not implemented.");
217195
- }
217196
- eth_getBlockByHash(_blockHash, _hydrated) {
217197
- throw new Error("Method not implemented.");
217198
- }
217199
- eth_getBlockByNumber(_blockNumber, _hydrated) {
217200
- throw new Error("Method not implemented.");
217201
- }
217202
- eth_getBlockTransactionCountByHash(_blockHash) {
217203
- throw new Error("Method not implemented.");
217204
- }
217205
- eth_getBlockTransactionCountByNumber(_blockNumber) {
217206
- throw new Error("Method not implemented.");
217207
- }
217208
- eth_getCode(_address, _blockNumber) {
217209
- throw new Error("Method not implemented.");
217210
- }
217211
- eth_getCompilers() {
217212
- throw new Error("Method not implemented.");
217213
- }
217214
- eth_getFilterChanges(_filterIdentifier) {
217215
- throw new Error("Method not implemented.");
217216
- }
217217
- eth_getFilterLogs(_filterIdentifier) {
217218
- throw new Error("Method not implemented.");
217219
- }
217220
- eth_getLogs(_filter) {
217221
- throw new Error("Method not implemented.");
217222
- }
217223
- eth_getStorageAt(_address, _storageSlot, _blockNumber) {
217224
- throw new Error("Method not implemented.");
217225
- }
217226
- eth_getTransactionByBlockHashAndIndex(_blockHash, _transactionIndex) {
217227
- throw new Error("Method not implemented.");
217228
- }
217229
- eth_getTransactionByBlockNumberAndIndex(_blockNumber, _transactionIndex) {
217230
- throw new Error("Method not implemented.");
217231
- }
217232
- eth_getTransactionByHash(_transactionHash) {
217233
- throw new Error("Method not implemented.");
217234
- }
217235
- eth_getTransactionCount(_address, _blockNumber) {
217236
- throw new Error("Method not implemented.");
217237
- }
217238
- eth_getTransactionReceipt(_transactionHash) {
217239
- throw new Error("Method not implemented.");
217240
- }
217241
- eth_getUncleByBlockHashAndIndex(_blockHash, _uncleIndex) {
217242
- throw new Error("Method not implemented.");
217243
- }
217244
- eth_getUncleByBlockNumberAndIndex(_blockNumber, _uncleIndex) {
217245
- throw new Error("Method not implemented.");
217246
- }
217247
- eth_getUncleCountByBlockHash(_blockHash) {
217248
- throw new Error("Method not implemented.");
217249
- }
217250
- eth_getUncleCountByBlockNumber(_blockNumber) {
217251
- throw new Error("Method not implemented.");
217252
- }
217253
- eth_getWork() {
217254
- throw new Error("Method not implemented.");
217255
- }
217256
- eth_hashrate() {
217257
- throw new Error("Method not implemented.");
217258
- }
217259
- eth_maxPriorityFeePerGas() {
217260
- throw new Error("Method not implemented.");
217261
- }
217262
- eth_mining() {
217263
- throw new Error("Method not implemented.");
217264
- }
217265
- eth_newBlockFilter() {
217266
- throw new Error("Method not implemented.");
217267
- }
217268
- eth_newFilter(_filter) {
217269
- throw new Error("Method not implemented.");
217270
- }
217271
- eth_newPendingTransactionFilter() {
217272
- throw new Error("Method not implemented.");
217273
- }
217274
- eth_protocolVersion() {
217275
- throw new Error("Method not implemented.");
217276
- }
217277
- eth_sendRawTransaction(_transaction) {
217278
- throw new Error("Method not implemented.");
217279
- }
217280
- eth_sendTransaction(_transaction) {
217281
- throw new Error("Method not implemented.");
217282
- }
217283
- eth_sign(_address, _message) {
217284
- throw new Error("Method not implemented.");
217285
- }
217286
- eth_signTransaction(_transaction) {
217287
- throw new Error("Method not implemented.");
217288
- }
217289
- eth_submitHashrate(_hashRate, _id) {
217290
- throw new Error("Method not implemented.");
217291
- }
217292
- eth_submitWork(_nonce, _hash, _digest) {
217293
- throw new Error("Method not implemented.");
217294
- }
217295
- eth_subscribe(..._params) {
217296
- throw new Error("Method not implemented.");
217297
- }
217298
- eth_syncing() {
217299
- throw new Error("Method not implemented.");
217300
- }
217301
- eth_uninstallFilter(_filterIdentifier) {
217302
- throw new Error("Method not implemented.");
217303
- }
217304
- eth_unsubscribe(_subscriptionId) {
217305
- throw new Error("Method not implemented.");
217306
- }
217307
- });
217308
- var createChainContract = /* @__PURE__ */ __name$5(async (signer, stakingTokenAddress, genesisBlockHash, rewardsContractAddress, minWithdrawalBlocks, gas = {}) => {
217309
- try {
217310
- const xyoChainFactory = new StakedXyoChain__factory(signer);
217311
- const contractTransactionResponse = await (await xyoChainFactory.deploy(ETH_ZERO_ADDRESS, 0n, hexToBigInt(genesisBlockHash), toEthAddress(rewardsContractAddress), minWithdrawalBlocks, toEthAddress(stakingTokenAddress), gas)).waitForDeployment();
217312
- const xyoChainContractAddress = await contractTransactionResponse.getAddress();
217313
- return assertEx(asAddress(xyoChainContractAddress), () => "Invalid staking contract address");
217314
- } catch (ex) {
217315
- console.log(ex);
217316
- throw ex;
217317
- }
217318
- }, "createChainContract");
217319
- var gasConfig = /* @__PURE__ */ __name$5(() => {
217320
- return {
217321
- gasLimit: 2e6,
217322
- gasPrice: parseUnits$1("100", "gwei")
217323
- };
217324
- }, "gasConfig");
217325
- var createChainRewardsContract = /* @__PURE__ */ __name$5(async (signer, genesisReward = 0n, gas = gasConfig()) => {
217326
- try {
217327
- const xyoChainRewardsFactory = new XyoChainRewards__factory(signer);
217328
- const xyoChainRewardsFactoryResponse = await (await xyoChainRewardsFactory.deploy(toFixedPoint(1000n), 1000000n, 95n, 100n, toFixedPoint(30n), genesisReward, 18n, gas)).waitForDeployment();
217329
- const xyoChainRewardsAddress = await xyoChainRewardsFactoryResponse.getAddress();
217330
- return assertEx(asAddress(xyoChainRewardsAddress), () => "Invalid rewards contract address");
217331
- } catch (ex) {
217332
- console.log(ex);
217333
- throw ex;
217334
- }
217335
- }, "createChainRewardsContract");
217336
- var nextContractAddressForAddress = /* @__PURE__ */ __name$5(async (address, provider) => {
217337
- const deployerAddress = toEthAddress(address);
217338
- const nonce = await provider.getTransactionCount(deployerAddress);
217339
- const contractAddress = getCreateAddress({
217340
- from: deployerAddress,
217341
- nonce
217342
- });
217343
- return assertEx(asAddress(contractAddress), () => "Unable to convert contract address to address");
217344
- }, "nextContractAddressForAddress");
217345
- var nextContractAddress = /* @__PURE__ */ __name$5(async (signer) => {
217346
- const provider = assertEx(signer.provider, () => "Unable to obtain provider from signer");
217347
- const address = assertEx(asAddress(await signer.getAddress()), () => "Unable to obtain address from signer");
217348
- return await nextContractAddressForAddress(address, provider);
217349
- }, "nextContractAddress");
217350
-
217351
- // src/createChain.ts
217352
- async function createChain(signer, stakingTokenAddress, initialBlockProducer, rewardsContractAddress, genesisBlockRewardAmount, genesisBlockRewardAddress, minWithdrawalBlocks, gas) {
217353
- const ethStakingTokenAddress = toEthAddress(stakingTokenAddress);
217354
- const rewardContractAddressResolved = rewardsContractAddress ?? await createChainRewardsContract(signer, genesisBlockRewardAmount, gas);
217355
- const contractAddress = await nextContractAddress(signer);
217356
- const genesisBlock = await createGenesisBlock(initialBlockProducer, contractAddress, genesisBlockRewardAmount, genesisBlockRewardAddress);
217357
- const chainId = toAddress(await createChainContract(signer, ethStakingTokenAddress, await PayloadBuilder.hash(genesisBlock[0]), rewardContractAddressResolved, minWithdrawalBlocks, gas));
217358
- return [
217359
- chainId,
217360
- genesisBlock,
217361
- rewardContractAddressResolved
217362
- ];
217363
- }
217364
- __name$5(createChain, "createChain");
217365
- function _ts_decorate(decorators, target, key, desc) {
217366
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
217367
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
217368
- 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;
217369
- return c > 3 && r && Object.defineProperty(target, key, r), r;
217370
- }
217371
- __name$5(_ts_decorate, "_ts_decorate");
217372
- var ethStakeToStake = /* @__PURE__ */ __name$5((ethStake) => {
217373
- const stake = {
217374
- id: Number(ethStake.id),
217375
- staked: toAddress(ethStake.staked),
217376
- staker: toAddress(ethStake.staker),
217377
- amount: asAttoXL1(ethStake.amount),
217378
- addBlock: Number(ethStake.addBlock),
217379
- removeBlock: Number(ethStake.removeBlock),
217380
- withdrawBlock: Number(ethStake.withdrawBlock)
217381
- };
217382
- return stake;
217383
- }, "ethStakeToStake");
217384
- var EthereumChainStakeViewer = class extends AbstractCreatable {
217385
- static {
217386
- __name$5(this, "EthereumChainStakeViewer");
217387
- }
217388
- _callMutex = new Mutex$1();
217389
- _chainId;
217390
- _deploymentBlock = 0;
217391
- _stakeCache = /* @__PURE__ */ new Map();
217392
- get chainId() {
217393
- return assertEx(this._chainId, () => "Chain ID not set");
217394
- }
217395
- get contract() {
217396
- return assertEx(this.params.contract, () => new Error("Contract not defined"));
217397
- }
217398
- get minWithdrawalBlocks() {
217399
- return 0;
217400
- }
217401
- get rewardsContract() {
217402
- return toAddress("0x000000000000000000000000000000");
217403
- }
217404
- get stakeEvents() {
217405
- return this.params.stakeEventsViewer;
217406
- }
217407
- get stakingTokenAddress() {
217408
- return toAddress("0x000000000000000000000000000011");
217409
- }
217410
- async active() {
217411
- return await this._callMutex.runExclusive(async () => {
217412
- return await this.contract.active();
217413
- });
217414
- }
217415
- async activeByAddressStaked(address) {
217416
- return await this._callMutex.runExclusive(async () => {
217417
- return await this.contract.activeByAddressStaked(toEthAddress(address));
217418
- });
217419
- }
217420
- async activeByStaker(address) {
217421
- return await this._callMutex.runExclusive(async () => {
217422
- return await this.contract.activeByStaker(toEthAddress(address));
217423
- });
217424
- }
217425
- async pending() {
217426
- return await this._callMutex.runExclusive(async () => {
217427
- return await this.contract.pending();
217428
- });
217429
- }
217430
- async pendingByStaker(staker) {
217431
- return await this._callMutex.runExclusive(async () => {
217432
- return await this.contract.pendingByStaker(toEthAddress(staker));
217433
- });
217434
- }
217435
- async stakeById(id) {
217436
- return await this._callMutex.runExclusive(async () => {
217437
- const startTime = Date.now();
217438
- const cachedStake = this._stakeCache.get(id);
217439
- if (cachedStake) {
217440
- return cachedStake;
217441
- }
217442
- const ethResult = await this.contract.getStakeById(id);
217443
- const stake = ethStakeToStake(ethResult);
217444
- this._stakeCache.set(stake.id, stake);
217445
- this.logger?.log(`EthereumChainStake: stakeById(${id}) took ${Date.now() - startTime}ms`);
217446
- return stake;
217447
- });
217448
- }
217449
- async stakeByStaker(staker, slot) {
217450
- return await this._callMutex.runExclusive(async () => {
217451
- const ethResult = await this.contract.getStake(toEthAddress(staker), slot);
217452
- const stake = ethStakeToStake(ethResult);
217453
- this._stakeCache.set(stake.id, stake);
217454
- return stake;
217455
- });
217456
- }
217457
- async stakesByStaked(staked, range = [
217458
- 0,
217459
- void 0
217460
- ]) {
217461
- const events = await this.stakeEvents.stakeEvents([
217462
- Math.max(range[0], this._deploymentBlock),
217463
- range.at(1) ?? "latest"
217464
- ], {
217465
- name: "StakeAdded",
217466
- args: {
217467
- staked
217468
- }
217469
- });
217470
- const result = [];
217471
- for (const event of events) {
217472
- if (toAddress(event.args.staked) === toAddress(staked)) {
217473
- result.push(await this.stakeById(event.args.id));
217474
- }
217475
- }
217476
- return result;
217477
- }
217478
- async stakesByStaker(staker, range = [
217479
- 0,
217480
- void 0
217481
- ]) {
217482
- const events = await this.stakeEvents.stakeEvents([
217483
- Math.max(range[0], this._deploymentBlock),
217484
- range.at(1) ?? "latest"
217485
- ], {
217486
- name: "StakeAdded",
217487
- args: {
217488
- staker
217489
- }
217490
- });
217491
- const result = [];
217492
- for (const event of events) {
217493
- if (toAddress(event.args.staker) === toAddress(staker)) {
217494
- result.push(await this.stakeById(event.args.id));
217495
- }
217496
- }
217497
- return result;
217498
- }
217499
- async withdrawn() {
217500
- return await this._callMutex.runExclusive(async () => {
217501
- return await this.contract.withdrawn();
217502
- });
217503
- }
217504
- async withdrawnByStaker(staker) {
217505
- return await this._callMutex.runExclusive(async () => {
217506
- return await this.contract.withdrawnByStaker(toEthAddress(staker));
217507
- });
217508
- }
217509
- async startHandler() {
217510
- this._chainId = toAddress(await this.contract.chainId());
217511
- await this.contract.on(this.contract.getEvent("StakeAdded"), (staked, staker, id, amount, event) => {
217512
- this._stakeCache.set(Number(id), {
217513
- id: Number(id),
217514
- staked: toAddress(staked),
217515
- staker: toAddress(staker),
217516
- amount: asAttoXL1(amount),
217517
- addBlock: event.blockNumber,
217518
- removeBlock: 0,
217519
- withdrawBlock: 0
217520
- });
217521
- });
217522
- await this.contract.on(this.contract.getEvent("StakeRemoved"), (staked, staker, id, amount, event) => {
217523
- const stake = assertEx(this._stakeCache.get(Number(id)));
217524
- this._stakeCache.set(Number(id), {
217525
- ...stake,
217526
- removeBlock: event.blockNumber
217527
- });
217528
- });
217529
- await this.contract.on(this.contract.getEvent("StakeWithdrawn"), (staked, staker, id, amount, event) => {
217530
- const stake = assertEx(this._stakeCache.get(Number(id)));
217531
- this._stakeCache.set(Number(id), {
217532
- ...stake,
217533
- withdrawBlock: event.blockNumber
217534
- });
217535
- });
217536
- const allStakeEvents = (await Promise.all([
217537
- this.stakeEvents.stakeEvents([
217538
- this._deploymentBlock,
217539
- "latest"
217540
- ], {
217541
- name: "StakeAdded"
217542
- }),
217543
- this.stakeEvents.stakeEvents([
217544
- this._deploymentBlock,
217545
- "latest"
217546
- ], {
217547
- name: "StakeRemoved"
217548
- }),
217549
- this.stakeEvents.stakeEvents([
217550
- this._deploymentBlock,
217551
- "latest"
217552
- ], {
217553
- name: "StakeWithdrawn"
217554
- })
217555
- ])).flat().toSorted((a, b) => a.time - b.time);
217556
- for (const event of allStakeEvents) {
217557
- switch (event.name) {
217558
- case "StakeAdded": {
217559
- this._stakeCache.set(event.args.id, {
217560
- id: event.args.id,
217561
- staked: event.args.staked,
217562
- staker: event.args.staker,
217563
- amount: event.args.amount,
217564
- addBlock: event.time,
217565
- removeBlock: 0,
217566
- withdrawBlock: 0
217567
- });
217568
- break;
217569
- }
217570
- case "StakeRemoved": {
217571
- const stake = assertEx(this._stakeCache.get(event.args.id));
217572
- this._stakeCache.set(event.args.id, {
217573
- ...stake,
217574
- removeBlock: event.time
217575
- });
217576
- break;
217577
- }
217578
- case "StakeWithdrawn": {
217579
- const stake = assertEx(this._stakeCache.get(event.args.id));
217580
- this._stakeCache.set(event.args.id, {
217581
- ...stake,
217582
- withdrawBlock: event.time
217583
- });
217584
- break;
217585
- }
217586
- }
217587
- }
217588
- for (const event of allStakeEvents) {
217589
- await this.stakeById(event.args.id);
217590
- }
217591
- }
217592
- };
217593
- EthereumChainStakeViewer = _ts_decorate([
217594
- creatable()
217595
- ], EthereumChainStakeViewer);
217596
- function _ts_decorate2(decorators, target, key, desc) {
217597
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
217598
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
217599
- 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;
217600
- return c > 3 && r && Object.defineProperty(target, key, r), r;
217601
- }
217602
- __name$5(_ts_decorate2, "_ts_decorate");
217603
- var isStakeLogEventName = /* @__PURE__ */ __name$5((name) => {
217604
- return isString$1(name) && [
217605
- "StakeAdded",
217606
- "StakeRemoved",
217607
- "StakeWithdrawn"
217608
- ].includes(name);
217609
- }, "isStakeLogEventName");
217610
- var EthereumChainStakeEvents = class extends AbstractCreatable {
217611
- static {
217612
- __name$5(this, "EthereumChainStakeEvents");
217613
- }
217614
- eventCache = /* @__PURE__ */ new Map();
217615
- get contract() {
217616
- return assertEx(this.params.contract, () => new Error("Contract not defined"));
217617
- }
217618
- get deploymentBlock() {
217619
- return this.params.deploymentBlock ?? 0;
217620
- }
217621
- async positionCount(range) {
217622
- const events = await this.stakeEvents(range);
217623
- const positionIds = events.map((e) => e.args.id);
217624
- return Math.max(-1, ...positionIds) + 1;
217625
- }
217626
- stakeEvents(range = [
217627
- 0,
217628
- "latest"
217629
- ], filter) {
217630
- const allEvents = [
217631
- ...this.eventCache.values()
217632
- ];
217633
- const result = allEvents.filter((e) => {
217634
- if (range[1] !== "latest" && e.time > range[1]) {
217635
- return false;
217636
- }
217637
- if (e.time < range[0]) {
217638
- return false;
217639
- }
217640
- if (isDefined(filter?.name) && e.name !== filter.name) {
217641
- return false;
217642
- }
217643
- if (isDefined(filter?.args?.id) && e.args.id !== filter.args.id) {
217644
- return false;
217645
- }
217646
- if (isDefined(filter?.args?.staked) && e.args.staked !== filter.args.staked) {
217647
- return false;
217648
- }
217649
- if (isDefined(filter?.args?.staker) && e.args.staker !== filter.args.staker) {
217650
- return false;
217651
- }
217652
- return true;
217653
- });
217654
- return result;
217655
- }
217656
- onEventHandler(staked, staker, id, amount, { eventName, blockNumber }) {
217657
- if (blockNumber === void 0) {
217658
- this.logger?.warn(`Received ${eventName} event with ${blockNumber} blockNumber, ignoring...`);
217659
- return;
217660
- }
217661
- if (!isStakeLogEventName(eventName)) {
217662
- this.logger?.warn(`Received event with unsupported name '${eventName}'`);
217663
- return;
217664
- }
217665
- this.logger?.log(`Processing ${eventName} event for stake ID ${id} at block ${blockNumber}`);
217666
- const cacheKey = `${Number(id)}|${eventName}|${staker}`;
217667
- const existingStakeEvent = this.eventCache.get(cacheKey);
217668
- const stakeEvent = {
217669
- name: eventName,
217670
- args: {
217671
- id: Number(id),
217672
- staked: toAddress(staked),
217673
- staker: toAddress(staker),
217674
- amount: asAttoXL1(amount)
217675
- },
217676
- time: blockNumber
217677
- };
217678
- if (isDefined(existingStakeEvent)) {
217679
- this.logger?.warn(`Received ${eventName} event for stake ID ${id} that is already cached, updating cache...`);
217680
- this.logger?.warn("1");
217681
- this.logger?.warn("Previous event", existingStakeEvent);
217682
- this.logger?.warn("2");
217683
- this.logger?.warn("New event", stakeEvent);
217684
- this.logger?.warn("3");
217685
- }
217686
- this.eventCache.set(cacheKey, stakeEvent);
217687
- return stakeEvent;
217688
- }
217689
- async startHandler() {
217690
- try {
217691
- const currentEthBlock = assertEx(await this.contract.runner?.provider?.getBlockNumber(), () => new Error("Failed to egt currentEthBlock"));
217692
- await this.contract.on(this.contract.getEvent("StakeAdded"), (staked, staker, id, amount, event) => {
217693
- this.onEventHandler(staked, staker, id, amount, event);
217694
- });
217695
- await this.contract.on(this.contract.getEvent("StakeRemoved"), (staked, staker, id, amount, event) => {
217696
- this.onEventHandler(staked, staker, id, amount, event);
217697
- });
217698
- await this.contract.on(this.contract.getEvent("StakeWithdrawn"), (staked, staker, id, amount, event) => {
217699
- this.onEventHandler(staked, staker, id, amount, event);
217700
- });
217701
- const allStakeEvents = (await Promise.all([
217702
- this.stakeEventsNative([
217703
- this.deploymentBlock,
217704
- currentEthBlock
217705
- ], {
217706
- name: "StakeAdded"
217707
- }),
217708
- this.stakeEventsNative([
217709
- this.deploymentBlock,
217710
- currentEthBlock
217711
- ], {
217712
- name: "StakeRemoved"
217713
- }),
217714
- this.stakeEventsNative([
217715
- this.deploymentBlock,
217716
- currentEthBlock
217717
- ], {
217718
- name: "StakeWithdrawn"
217719
- })
217720
- ])).flat().toSorted((a, b) => a.time - b.time);
217721
- console.warn(`Caching ${allStakeEvents.length} stake events from chain starting at block ${this.deploymentBlock}`);
217722
- for (const event of allStakeEvents) {
217723
- this.eventCache.set(`${Number(event.args.id)}|${event.name}|${event.args.staker}`, event);
217724
- }
217725
- } catch (error) {
217726
- this.logger?.error("EthereumChainStakeEvents failed to start:", error);
217727
- throw error;
217728
- }
217729
- }
217730
- async stakeEventsNative(range = [
217731
- 0,
217732
- "latest"
217733
- ], filter) {
217734
- const name = filter?.name;
217735
- if (isDefined(name)) {
217736
- const stakedFilter = filter?.args?.staked;
217737
- const stakerFilter = filter?.args?.staker;
217738
- const stakedFilterEth = isDefined(stakedFilter) ? toEthAddress(stakedFilter) : void 0;
217739
- const stakerFilterEth = isDefined(stakerFilter) ? toEthAddress(stakerFilter) : void 0;
217740
- let ethEvents = [];
217741
- const ethFilter = this.contract.filters[name](stakedFilterEth, stakerFilterEth);
217742
- ethEvents = await this.contract.queryFilter(ethFilter, range[0], range[1]);
217743
- return ethEvents.map((e) => {
217744
- assertEx(e.eventName === name, () => `Event name mismatch expected '${name}' but got '${e.eventName}'`);
217745
- return this.onEventHandler(e.args.staked, e.args.by, e.args.id, e.args.amount, e);
217746
- }).filter(exists$1);
217747
- } else {
217748
- throw new Error("Only filtered stake events (by name) are supported");
217749
- }
217750
- }
217751
- };
217752
- EthereumChainStakeEvents = _ts_decorate2([
217753
- creatable()
217754
- ], EthereumChainStakeEvents);
217755
-
217756
217877
  var lib$6 = {};
217757
217878
 
217758
217879
  var admin$2 = {};
@@ -363782,6 +363903,7 @@ var ViewArchivist = class extends AbstractArchivist {
363782
363903
  this._originArchivistInstance = this._originArchivistInstance ?? assertEx(await this.resolve(this.originArchivist, { identity: isArchivistInstance, required: true }));
363783
363904
  return this._originArchivistInstance;
363784
363905
  }
363906
+ /** @deprecated use next instead */
363785
363907
  async allHandler() {
363786
363908
  return await (await this.originArchivistInstance()).all?.() ?? [];
363787
363909
  }
@@ -363856,7 +363978,7 @@ var MemoryBoundWitnessDiviner = class extends BoundWitnessDiviner {
363856
363978
  const filter = assertEx(payloads?.filter(isBoundWitnessDivinerQueryPayload)?.pop(), () => "Missing query payload");
363857
363979
  if (!filter) return [];
363858
363980
  const archivist = assertEx(await this.archivistInstance(), () => "Unable to resolve archivist");
363859
- let bws = (await archivist?.all?.() ?? []).filter(isBoundWitnessWithStorageMeta);
363981
+ let bws = (await archivist?.next({ limit: 1e4 }) ?? []).filter(isBoundWitnessWithStorageMeta);
363860
363982
  return applyBoundWitnessDivinerQueryPayload(filter, bws);
363861
363983
  }
363862
363984
  };
@@ -364651,41 +364773,6 @@ var getApp$3 = /* @__PURE__ */ __name$4(async (node, transferSummaryMap, stakedC
364651
364773
  app.use(standardErrors);
364652
364774
  return app;
364653
364775
  }, "getApp");
364654
- var canUseChainId$1 = /* @__PURE__ */ __name$4((config) => {
364655
- return isDefined(config.evm.chainId);
364656
- }, "canUseChainId");
364657
- var getChainId$1 = /* @__PURE__ */ __name$4((config) => {
364658
- const chainId = assertEx(config.evm.chainId, () => "Missing config.evm.chainId");
364659
- if (isHex(chainId, {
364660
- prefix: true
364661
- })) {
364662
- const hex = hexFrom(chainId);
364663
- const parsed = Number.parseInt(hex, 16);
364664
- return parsed;
364665
- } else {
364666
- const parsed = Number.parseInt(chainId, 10);
364667
- return parsed;
364668
- }
364669
- }, "getChainId");
364670
- var instance$1;
364671
- var initInfuraProvider$1 = /* @__PURE__ */ __name$4((config) => {
364672
- if (instance$1) return instance$1;
364673
- const providerConfig = getInfuraProviderConfig$1(config);
364674
- instance$1 = Promise.resolve(new InfuraWebSocketProvider(providerConfig[0], providerConfig[1]));
364675
- return instance$1;
364676
- }, "initInfuraProvider");
364677
- var canUseInfuraProvider$1 = /* @__PURE__ */ __name$4((config) => {
364678
- return canUseChainId$1(config) && isDefined(config.evm?.infura?.projectId) && isDefined(config.evm?.infura?.projectSecret);
364679
- }, "canUseInfuraProvider");
364680
- var getInfuraProviderConfig$1 = /* @__PURE__ */ __name$4((config) => {
364681
- const projectId = assertEx(config.evm?.infura?.projectId, () => "Missing config.evm.infura.projectId");
364682
- const projectSecret = assertEx(config.evm?.infura?.projectSecret, () => "Missing config.evm.infura.projectSecret");
364683
- return [
364684
- getChainId$1(config),
364685
- projectId,
364686
- projectSecret
364687
- ];
364688
- }, "getInfuraProviderConfig");
364689
364776
  async function getTransferSummaryMap(config) {
364690
364777
  const mongoConfig = config.storage?.mongo;
364691
364778
  if (hasMongoConfig(mongoConfig)) {
@@ -365225,41 +365312,13 @@ var getSeedPhrase$2 = /* @__PURE__ */ __name$4(async (bios, config, logger) => {
365225
365312
  }
365226
365313
  return assertEx(await bios.seedPhraseStore.get("os"), () => "Unable to acquire mnemonic from bios");
365227
365314
  }, "getSeedPhrase");
365228
- async function getStakeChainViewer(config, logger) {
365229
- if (canUseInfuraProvider$1(config)) {
365230
- const provider = await initInfuraProvider$1(config);
365231
- const contractAddress = assertEx(config.chain.id, () => "Missing config.evm.chainId");
365232
- const contract = StakedXyoChainV2__factory.connect(toEthAddress(contractAddress), provider);
365233
- const stakeEventsViewer = await EthereumChainStakeEvents.create({
365234
- contract,
365235
- logger
365236
- });
365237
- assertEx(await stakeEventsViewer.start(), () => "Failed to start EthereumChainStakeEvents reader");
365238
- const stakeChainViewer = await EthereumChainStakeViewer.create({
365239
- contract,
365240
- stakeEventsViewer,
365241
- logger
365242
- });
365243
- assertEx(await stakeChainViewer.start(), () => "Failed to start EthereumChainStake viewer");
365244
- return stakeChainViewer;
365245
- } else {
365246
- console.warn("[API] Infura configuration not found. Using SimpleChainStakeViewer with no positions. This means no staking data will be available.");
365247
- const stakeChainViewer = await SimpleChainStakeViewer.create({
365248
- logger,
365249
- positions: []
365250
- });
365251
- assertEx(await stakeChainViewer.start(), () => "Failed to start SimpleChainStake viewer");
365252
- return stakeChainViewer;
365253
- }
365254
- }
365255
- __name$4(getStakeChainViewer, "getStakeChainViewer");
365256
365315
  var getServer$3 = /* @__PURE__ */ __name$4(async (context) => {
365257
365316
  const { config, logger, node } = context;
365258
365317
  const { mnemonic, port } = context.config.api;
365259
365318
  const bios = await boot();
365260
365319
  const seedPhrase = isDefined(mnemonic) ? mnemonic : await getSeedPhrase$2(bios, config, logger);
365261
365320
  const wallet = await HDWallet.fromPhrase(seedPhrase);
365262
- const stakeChainViewer = await getStakeChainViewer(config, logger);
365321
+ const stakeChainViewer = await initChainStakeViewer(config, logger);
365263
365322
  const nodeContext = {
365264
365323
  wallet,
365265
365324
  logger,
@@ -365273,14 +365332,26 @@ var getServer$3 = /* @__PURE__ */ __name$4(async (context) => {
365273
365332
  const payloads = await chainArchivist.next();
365274
365333
  if (payloads.length === 0) {
365275
365334
  logger?.warn("[API] No blocks found in chain archivist, creating genesis block");
365276
- const initialProducer = await Account.random();
365335
+ const producerAccount = await initProducerAccount({
365336
+ config,
365337
+ logger
365338
+ });
365277
365339
  const chainId = stakeChainViewer.chainId;
365278
- const block = await createGenesisBlock(initialProducer, chainId, 1000000n, initialProducer.address);
365340
+ const block0 = await createGenesisBlock(producerAccount, chainId, 1000000n, producerAccount.address);
365279
365341
  await chainArchivist.insert([
365280
- ...block[1].flat(),
365281
- block[0]
365342
+ ...block0[1].flat(),
365343
+ block0[0]
365282
365344
  ]);
365283
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}`);
365284
365355
  }
365285
365356
  const stakedChainContext = {
365286
365357
  chainId: stakeChainViewer.chainId,
@@ -374491,25 +374562,6 @@ async function initTransferSummaryMap(params) {
374491
374562
  });
374492
374563
  }
374493
374564
  __name(initTransferSummaryMap, "initTransferSummaryMap");
374494
- var accountServiceSingleton;
374495
- var initAccount = /* @__PURE__ */ __name(async ({ config: config2, logger }) => {
374496
- if (accountServiceSingleton) return accountServiceSingleton;
374497
- let walletPhrase = config2.producer.mnemonic;
374498
- if (isUndefined$1(walletPhrase)) {
374499
- logger?.warn("[Producer] No wallet mnemonic specified!");
374500
- const randomMnemonic = HDWallet.generateMnemonic();
374501
- logger?.warn(`[Producer] Using randomly generated mnemonic:
374502
-
374503
- ${randomMnemonic}
374504
-
374505
- `);
374506
- walletPhrase = randomMnemonic;
374507
- }
374508
- const wallet = await generateXyoBaseWalletFromPhrase(walletPhrase);
374509
- const account = await wallet.derivePath(ADDRESS_INDEX.XYO);
374510
- accountServiceSingleton = account;
374511
- return accountServiceSingleton;
374512
- }, "initAccount");
374513
374565
  var balanceServiceSingleton;
374514
374566
  var initBalanceService = /* @__PURE__ */ __name(async (params) => {
374515
374567
  if (balanceServiceSingleton) return balanceServiceSingleton;
@@ -375034,7 +375086,7 @@ var initServices = /* @__PURE__ */ __name(async (context) => {
375034
375086
  };
375035
375087
  const [{ traceProvider, meterProvider }, account] = await Promise.all([
375036
375088
  startupSpanAsync("initTelemetry", () => initTelemetry(telemetryConfig)),
375037
- startupSpanAsync("initAccount", () => initAccount(context))
375089
+ startupSpanAsync("initProducerAccount", () => initProducerAccount(context))
375038
375090
  ]);
375039
375091
  const allowedRewardRedeemers = config2.validation?.allowedRewardRedeemers ?? [];
375040
375092
  const allowedRewardEscrowAccountSigners = config2.validation?.allowedRewardEscrowAccountSigners ?? [];
@@ -375351,7 +375403,7 @@ var waitForHostPort = /* @__PURE__ */ __name((host, port) => {
375351
375403
 
375352
375404
  // src/runCLI.ts
375353
375405
  var configuration;
375354
- var version = isDefined("1.16.19") ? "1.16.19" : "unknown";
375406
+ var version = isDefined("1.16.20") ? "1.16.20" : "unknown";
375355
375407
  var getContextFromConfig = /* @__PURE__ */ __name((configuration2) => {
375356
375408
  const logger = initLogger(configuration2);
375357
375409
  const orchestrator = new Orchestrator(logger);