@xyo-network/xl1-cli 1.19.8 → 1.19.9

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.
package/dist/cli-min.mjs CHANGED
@@ -1,6 +1,3 @@
1
- import * as nc from 'node:crypto';
2
- import { randomFillSync, randomUUID } from 'node:crypto';
3
- import require$$0$c, { createHmac, pbkdf2Sync, randomBytes as randomBytes$3, createHash, subtle, randomFillSync as randomFillSync$1, randomUUID as randomUUID$1 } from 'crypto';
4
1
  import require$$0$a, { format as format$4, inspect as inspect$2, debuglog } from 'util';
5
2
  import require$$0$e, { cpus } from 'os';
6
3
  import require$$0$9, { Readable } from 'stream';
@@ -22,6 +19,7 @@ import require$$1$5 from 'node:events';
22
19
  import require$$8 from 'node:path';
23
20
  import require$$2$4, { readdirSync as readdirSync$1, readFileSync as readFileSync$1 } from 'node:fs';
24
21
  import require$$2$5 from 'node:http';
22
+ import require$$0$c, { createHmac, pbkdf2Sync, randomBytes as randomBytes$3, createHash, subtle, randomFillSync as randomFillSync$1, randomUUID as randomUUID$1 } from 'crypto';
25
23
  import require$$6$1 from 'node:querystring';
26
24
  import require$$7$1 from 'node:buffer';
27
25
  import require$$1$4 from 'node:net';
@@ -30,14 +28,16 @@ import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
30
28
  import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
31
29
  import require$$1$6, { cwd } from 'process';
32
30
  import { Worker as Worker$1 } from 'worker_threads';
33
- import http2 from 'http2';
34
- import require$$0$g, { strictEqual, notStrictEqual } from 'assert';
35
- import { trace as trace$1, context, SpanStatusCode, propagation, ROOT_CONTEXT, ValueType, metrics as metrics$1 } from '@opentelemetry/api';
36
31
  import { ConsoleSpanExporter, BatchSpanProcessor, AlwaysOnSampler, BasicTracerProvider } from '@opentelemetry/sdk-trace-base';
37
32
  import process$2 from 'node:process';
38
33
  import os from 'node:os';
39
34
  import tty from 'node:tty';
40
35
  import require$$0$n from 'fs/promises';
36
+ import * as nc from 'node:crypto';
37
+ import { randomFillSync, randomUUID } from 'node:crypto';
38
+ import http2 from 'http2';
39
+ import require$$0$g, { strictEqual, notStrictEqual } from 'assert';
40
+ import { trace as trace$1, context, SpanStatusCode, propagation, ROOT_CONTEXT, ValueType, metrics as metrics$1 } from '@opentelemetry/api';
41
41
  import { open } from 'lmdb';
42
42
  import require$$0$k from 'timers';
43
43
  import require$$0$l from 'timers/promises';
@@ -22029,7 +22029,7 @@ const base64$2 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA
22029
22029
  const base64url$1 = /^[A-Za-z0-9_-]*$/;
22030
22030
  // based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
22031
22031
  // export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
22032
- const hostname$5 = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
22032
+ const hostname$4 = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
22033
22033
  const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
22034
22034
  // https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
22035
22035
  // E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15
@@ -22130,7 +22130,7 @@ var regexes$1 = /*#__PURE__*/Object.freeze({
22130
22130
  extendedDuration: extendedDuration,
22131
22131
  guid: guid$1,
22132
22132
  hex: hex$1,
22133
- hostname: hostname$5,
22133
+ hostname: hostname$4,
22134
22134
  html5Email: html5Email,
22135
22135
  idnEmail: idnEmail,
22136
22136
  integer: integer$1,
@@ -33427,8 +33427,8 @@ const ZodCustomStringFormat = /*@__PURE__*/ $constructor("ZodCustomStringFormat"
33427
33427
  function stringFormat(format, fnOrRegex, _params = {}) {
33428
33428
  return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);
33429
33429
  }
33430
- function hostname$4(_params) {
33431
- return _stringFormat(ZodCustomStringFormat, "hostname", hostname$5, _params);
33430
+ function hostname$3(_params) {
33431
+ return _stringFormat(ZodCustomStringFormat, "hostname", hostname$4, _params);
33432
33432
  }
33433
33433
  function hex(_params) {
33434
33434
  return _stringFormat(ZodCustomStringFormat, "hex", hex$1, _params);
@@ -34332,7 +34332,7 @@ var _schemas = /*#__PURE__*/Object.freeze({
34332
34332
  guid: guid,
34333
34333
  hash: hash$1,
34334
34334
  hex: hex,
34335
- hostname: hostname$4,
34335
+ hostname: hostname$3,
34336
34336
  httpUrl: httpUrl,
34337
34337
  instanceof: _instanceof,
34338
34338
  int: int$1,
@@ -35167,7 +35167,7 @@ var z$1 = /*#__PURE__*/Object.freeze({
35167
35167
  guid: guid,
35168
35168
  hash: hash$1,
35169
35169
  hex: hex,
35170
- hostname: hostname$4,
35170
+ hostname: hostname$3,
35171
35171
  httpUrl: httpUrl,
35172
35172
  includes: _includes,
35173
35173
  instanceof: _instanceof,
@@ -47824,7 +47824,7 @@ function fromBase36(value) {
47824
47824
  * getAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72")
47825
47825
  * //_error:
47826
47826
  */
47827
- function getAddress$2(address) {
47827
+ function getAddress(address) {
47828
47828
  assertArgument(typeof (address) === "string", "invalid address", "address", address);
47829
47829
  if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
47830
47830
  // Missing the 0x prefix
@@ -47869,7 +47869,7 @@ function getAddress$2(address) {
47869
47869
  * //_result:
47870
47870
  */
47871
47871
  function getCreateAddress(tx) {
47872
- const from = getAddress$2(tx.from);
47872
+ const from = getAddress(tx.from);
47873
47873
  const nonce = getBigInt(tx.nonce, "tx.nonce");
47874
47874
  let nonceHex = nonce.toString(16);
47875
47875
  if (nonceHex === "0") {
@@ -47881,7 +47881,7 @@ function getCreateAddress(tx) {
47881
47881
  else {
47882
47882
  nonceHex = "0x" + nonceHex;
47883
47883
  }
47884
- return getAddress$2(dataSlice(keccak256(encodeRlp([from, nonceHex])), 12));
47884
+ return getAddress(dataSlice(keccak256(encodeRlp([from, nonceHex])), 12));
47885
47885
  }
47886
47886
 
47887
47887
  /**
@@ -47907,7 +47907,7 @@ async function checkAddress(target, promise) {
47907
47907
  assert$1(typeof (target) !== "string", "unconfigured name", "UNCONFIGURED_NAME", { value: target });
47908
47908
  assertArgument(false, "invalid AddressLike value; did not resolve to a value address", "target", target);
47909
47909
  }
47910
- return getAddress$2(result);
47910
+ return getAddress(result);
47911
47911
  }
47912
47912
  /**
47913
47913
  * Resolves to an address for the %%target%%, which may be any
@@ -47949,7 +47949,7 @@ async function checkAddress(target, promise) {
47949
47949
  function resolveAddress(target, resolver) {
47950
47950
  if (typeof (target) === "string") {
47951
47951
  if (target.match(/^0x[0-9a-f]{40}$/i)) {
47952
- return getAddress$2(target);
47952
+ return getAddress(target);
47953
47953
  }
47954
47954
  assert$1(resolver != null, "ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { operation: "resolveName" });
47955
47955
  return checkAddress(target, resolver.resolveName(target));
@@ -48575,7 +48575,7 @@ class AddressCoder extends Coder {
48575
48575
  encode(writer, _value) {
48576
48576
  let value = Typed.dereference(_value, "string");
48577
48577
  try {
48578
- value = getAddress$2(value);
48578
+ value = getAddress(value);
48579
48579
  }
48580
48580
  catch (error) {
48581
48581
  return this._throwError(error.message, _value);
@@ -48583,7 +48583,7 @@ class AddressCoder extends Coder {
48583
48583
  return writer.writeValue(value);
48584
48584
  }
48585
48585
  decode(reader) {
48586
- return getAddress$2(toBeHex(reader.readValue(), 20));
48586
+ return getAddress(toBeHex(reader.readValue(), 20));
48587
48587
  }
48588
48588
  }
48589
48589
 
@@ -48984,7 +48984,7 @@ class TupleCoder extends Coder {
48984
48984
 
48985
48985
  function accessSetify(addr, storageKeys) {
48986
48986
  return {
48987
- address: getAddress$2(addr),
48987
+ address: getAddress(addr),
48988
48988
  storageKeys: storageKeys.map((storageKey, index) => {
48989
48989
  assertArgument(isHexString(storageKey, 32), "invalid slot", `storageKeys[${index}]`, storageKey);
48990
48990
  return storageKey.toLowerCase();
@@ -49019,7 +49019,7 @@ function accessListify(value) {
49019
49019
 
49020
49020
  function authorizationify(auth) {
49021
49021
  return {
49022
- address: getAddress$2(auth.address),
49022
+ address: getAddress(auth.address),
49023
49023
  nonce: getBigInt((auth.nonce != null) ? auth.nonce : 0),
49024
49024
  chainId: getBigInt((auth.chainId != null) ? auth.chainId : 0),
49025
49025
  signature: Signature.from(auth.signature)
@@ -49039,7 +49039,7 @@ function computeAddress(key) {
49039
49039
  else {
49040
49040
  pubkey = key.publicKey;
49041
49041
  }
49042
- return getAddress$2(keccak256("0x" + pubkey.substring(4)).substring(26));
49042
+ return getAddress(keccak256("0x" + pubkey.substring(4)).substring(26));
49043
49043
  }
49044
49044
  /**
49045
49045
  * Returns the recovered address for the private key that was
@@ -49106,7 +49106,7 @@ function handleAddress(value) {
49106
49106
  if (value === "0x") {
49107
49107
  return null;
49108
49108
  }
49109
- return getAddress$2(value);
49109
+ return getAddress(value);
49110
49110
  }
49111
49111
  function handleAccessList(value, param) {
49112
49112
  try {
@@ -49666,7 +49666,7 @@ class Transaction {
49666
49666
  return value;
49667
49667
  }
49668
49668
  set to(value) {
49669
- this.#to = (value == null) ? null : getAddress$2(value);
49669
+ this.#to = (value == null) ? null : getAddress(value);
49670
49670
  }
49671
49671
  /**
49672
49672
  * The transaction nonce.
@@ -50321,7 +50321,7 @@ function hashAuthorization(auth) {
50321
50321
  return keccak256(concat$2([
50322
50322
  "0x05", encodeRlp([
50323
50323
  (auth.chainId != null) ? toBeArray(auth.chainId) : "0x",
50324
- getAddress$2(auth.address),
50324
+ getAddress(auth.address),
50325
50325
  (auth.nonce != null) ? toBeArray(auth.nonce) : "0x",
50326
50326
  ])
50327
50327
  ]));
@@ -51568,7 +51568,7 @@ const domainChecks = {
51568
51568
  },
51569
51569
  verifyingContract: function (value) {
51570
51570
  try {
51571
- return getAddress$2(value).toLowerCase();
51571
+ return getAddress(value).toLowerCase();
51572
51572
  }
51573
51573
  catch (error) { }
51574
51574
  assertArgument(false, `invalid domain value "verifyingContract"`, "domain.verifyingContract", value);
@@ -51611,7 +51611,7 @@ function getBaseEncoder(type) {
51611
51611
  }
51612
51612
  switch (type) {
51613
51613
  case "address": return function (value) {
51614
- return zeroPadValue(getAddress$2(value), 32);
51614
+ return zeroPadValue(getAddress(value), 32);
51615
51615
  };
51616
51616
  case "bool": return function (value) {
51617
51617
  return ((!value) ? hexFalse : hexTrue);
@@ -53431,11 +53431,11 @@ function getBuiltinCallException(action, tx, data, abiCoder) {
53431
53431
  }
53432
53432
  }
53433
53433
  const transaction = {
53434
- to: (tx.to ? getAddress$2(tx.to) : null),
53434
+ to: (tx.to ? getAddress(tx.to) : null),
53435
53435
  data: (tx.data || "0x")
53436
53436
  };
53437
53437
  if (tx.from) {
53438
- transaction.from = getAddress$2(tx.from);
53438
+ transaction.from = getAddress(tx.from);
53439
53439
  }
53440
53440
  return makeError(message, "CALL_EXCEPTION", {
53441
53441
  action, data, reason, transaction, invocation, revert
@@ -57357,7 +57357,7 @@ class EnsResolver {
57357
57357
  let ethCoinType = coinType + 0x80000000;
57358
57358
  const data = await this.#fetch("addr(bytes32,uint)", [ethCoinType]);
57359
57359
  if (isHexString(data, 20)) {
57360
- return getAddress$2(data);
57360
+ return getAddress(data);
57361
57361
  }
57362
57362
  }
57363
57363
  let coinPlugin = null;
@@ -57724,7 +57724,7 @@ function formatHash(value) {
57724
57724
  return value;
57725
57725
  }
57726
57726
  const _formatLog = object$3({
57727
- address: getAddress$2,
57727
+ address: getAddress,
57728
57728
  blockHash: formatHash,
57729
57729
  blockNumber: getNumber,
57730
57730
  data: formatData,
@@ -57753,7 +57753,7 @@ const _formatBlock = object$3({
57753
57753
  receiptsRoot: allowNull(formatHash, null),
57754
57754
  blobGasUsed: allowNull(getBigInt, null),
57755
57755
  excessBlobGas: allowNull(getBigInt, null),
57756
- miner: allowNull(getAddress$2),
57756
+ miner: allowNull(getAddress),
57757
57757
  prevRandao: allowNull(formatHash, null),
57758
57758
  extraData: formatData,
57759
57759
  baseFeePerGas: allowNull(getBigInt)
@@ -57774,7 +57774,7 @@ const _formatReceiptLog = object$3({
57774
57774
  transactionIndex: getNumber,
57775
57775
  blockNumber: getNumber,
57776
57776
  transactionHash: formatHash,
57777
- address: getAddress$2,
57777
+ address: getAddress,
57778
57778
  topics: arrayOf(formatHash),
57779
57779
  data: formatData,
57780
57780
  index: getNumber,
@@ -57786,9 +57786,9 @@ function formatReceiptLog(value) {
57786
57786
  return _formatReceiptLog(value);
57787
57787
  }
57788
57788
  const _formatTransactionReceipt = object$3({
57789
- to: allowNull(getAddress$2, null),
57790
- from: allowNull(getAddress$2, null),
57791
- contractAddress: allowNull(getAddress$2, null),
57789
+ to: allowNull(getAddress, null),
57790
+ from: allowNull(getAddress, null),
57791
+ contractAddress: allowNull(getAddress, null),
57792
57792
  // should be allowNull(hash), but broken-EIP-658 support is handled in receipt
57793
57793
  index: getNumber,
57794
57794
  root: allowNull(hexlify),
@@ -57847,7 +57847,7 @@ function formatTransactionResponse(value) {
57847
57847
  sig = Object.assign({}, v, { yParity });
57848
57848
  }
57849
57849
  return {
57850
- address: getAddress$2(v.address),
57850
+ address: getAddress(v.address),
57851
57851
  chainId: getBigInt(v.chainId),
57852
57852
  nonce: getBigInt(v.nonce),
57853
57853
  signature: Signature.from(sig)
@@ -57856,18 +57856,18 @@ function formatTransactionResponse(value) {
57856
57856
  blockHash: allowNull(formatHash, null),
57857
57857
  blockNumber: allowNull(getNumber, null),
57858
57858
  transactionIndex: allowNull(getNumber, null),
57859
- from: getAddress$2,
57859
+ from: getAddress,
57860
57860
  // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas) must be set
57861
57861
  gasPrice: allowNull(getBigInt),
57862
57862
  maxPriorityFeePerGas: allowNull(getBigInt),
57863
57863
  maxFeePerGas: allowNull(getBigInt),
57864
57864
  maxFeePerBlobGas: allowNull(getBigInt, null),
57865
57865
  gasLimit: getBigInt,
57866
- to: allowNull(getAddress$2, null),
57866
+ to: allowNull(getAddress, null),
57867
57867
  value: getBigInt,
57868
57868
  nonce: getNumber,
57869
57869
  data: formatData,
57870
- creates: allowNull(getAddress$2, null),
57870
+ creates: allowNull(getAddress, null),
57871
57871
  chainId: allowNull(getBigInt, null)
57872
57872
  }, {
57873
57873
  data: ["input"],
@@ -59593,7 +59593,7 @@ class AbstractProvider {
59593
59593
  return null;
59594
59594
  }
59595
59595
  async lookupAddress(address) {
59596
- address = getAddress$2(address);
59596
+ address = getAddress(address);
59597
59597
  const node = namehash(address.substring(2).toLowerCase() + ".addr.reverse");
59598
59598
  try {
59599
59599
  const ensAddr = await EnsResolver.getEnsAddress(this);
@@ -60650,7 +60650,7 @@ class JsonRpcSigner extends AbstractSigner {
60650
60650
  address;
60651
60651
  constructor(provider, address) {
60652
60652
  super(provider);
60653
- address = getAddress$2(address);
60653
+ address = getAddress(address);
60654
60654
  defineProperties(this, { address });
60655
60655
  }
60656
60656
  connect(provider) {
@@ -61385,9 +61385,9 @@ class JsonRpcApiProvider extends AbstractProvider {
61385
61385
  accounts: accountsPromise
61386
61386
  });
61387
61387
  // Account address
61388
- address = getAddress$2(address);
61388
+ address = getAddress(address);
61389
61389
  for (const account of accounts) {
61390
- if (getAddress$2(account) === address) {
61390
+ if (getAddress(account) === address) {
61391
61391
  return new JsonRpcSigner(this, address);
61392
61392
  }
61393
61393
  }
@@ -67312,7 +67312,7 @@ class BaseWallet extends AbstractSigner {
67312
67312
  tx.from = from;
67313
67313
  }
67314
67314
  if (tx.from != null) {
67315
- assertArgument(getAddress$2((tx.from)) === this.address, "transaction from address mismatch", "tx.from", tx.from);
67315
+ assertArgument(getAddress((tx.from)) === this.address, "transaction from address mismatch", "tx.from", tx.from);
67316
67316
  delete tx.from;
67317
67317
  }
67318
67318
  // Build the transaction
@@ -67338,7 +67338,7 @@ class BaseWallet extends AbstractSigner {
67338
67338
  assertArgument(typeof (auth.address) === "string", "invalid address for authorizeSync", "auth.address", auth);
67339
67339
  const signature = this.signingKey.sign(hashAuthorization(auth));
67340
67340
  return Object.assign({}, {
67341
- address: getAddress$2(auth.address),
67341
+ address: getAddress(auth.address),
67342
67342
  nonce: getBigInt(auth.nonce || 0),
67343
67343
  chainId: getBigInt(auth.chainId || 0),
67344
67344
  }, { signature });
@@ -68278,7 +68278,7 @@ function getAccount(data, _key) {
68278
68278
  if (!check.startsWith("0x")) {
68279
68279
  check = "0x" + check;
68280
68280
  }
68281
- assertArgument(getAddress$2(check) === address, "keystore address/privateKey mismatch", "address", data.address);
68281
+ assertArgument(getAddress(check) === address, "keystore address/privateKey mismatch", "address", data.address);
68282
68282
  }
68283
68283
  const account = { address, privateKey };
68284
68284
  // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase
@@ -68989,7 +68989,7 @@ function decryptCrowdsaleJson(json, _password) {
68989
68989
  const data = JSON.parse(json);
68990
68990
  const password = getPassword(_password);
68991
68991
  // Ethereum Address
68992
- const address = getAddress$2(spelunk(data, "ethaddr:string!"));
68992
+ const address = getAddress(spelunk(data, "ethaddr:string!"));
68993
68993
  // Encrypted Seed
68994
68994
  const encseed = looseArrayify(spelunk(data, "encseed:string!"));
68995
68995
  assertArgument(encseed && (encseed.length % 16) === 0, "invalid encseed", "json", json);
@@ -70227,6 +70227,798 @@ Object.defineProperties(createChalk.prototype, styles$2);
70227
70227
  const chalk = createChalk();
70228
70228
  createChalk({level: stderrColor ? stderrColor.level : 0});
70229
70229
 
70230
+ // src/isPayload.ts
70231
+ var isAnyPayload = (value) => {
70232
+ if (isObject$5(value)) {
70233
+ return typeof value.schema === "string";
70234
+ }
70235
+ return false;
70236
+ };
70237
+ var asAnyPayload = AsObjectFactory.create(isAnyPayload);
70238
+
70239
+ // src/isPayloadOfSchemaType.ts
70240
+ function isPayloadOfSchemaType(schema) {
70241
+ return (x) => isAnyPayload(x) && x?.schema === schema;
70242
+ }
70243
+ var SchemaRegEx = /^(?:[a-z0-9]+\.)*[a-z0-9]+$/;
70244
+ var SchemaZod = z$1.string().regex(SchemaRegEx).transform((v) => v);
70245
+ var isSchema = zodIsFactory(SchemaZod);
70246
+ var asSchema = zodAsFactory(SchemaZod, "asSchema");
70247
+ var PayloadSchema = asSchema("network.xyo.payload", true);
70248
+ z$1.literal(PayloadSchema);
70249
+
70250
+ // src/Error.ts
70251
+ var ModuleErrorSchema = asSchema("network.xyo.error.module", true);
70252
+ function isPayloadOfZodType(zodSchema, schema) {
70253
+ return (x) => {
70254
+ if (!isAnyPayload(x)) return false;
70255
+ if (isDefined(schema) && x.schema !== schema) return false;
70256
+ const { schema: _, ...data } = x;
70257
+ return zodSchema.safeParse(data).success;
70258
+ };
70259
+ }
70260
+ var isLocalSequence = (value) => {
70261
+ return isHex(value) && value.length === SequenceConstants.localSequenceBytes * 2;
70262
+ };
70263
+ var isQualifiedSequence = (value) => {
70264
+ return isHex(value) && value.length === SequenceConstants.qualifiedSequenceBytes * 2;
70265
+ };
70266
+ var isSequence = (value) => {
70267
+ return isLocalSequence(value) || isQualifiedSequence(value);
70268
+ };
70269
+ var SequenceNonceComponentLengths = {
70270
+ nonceIndexBytes: 4,
70271
+ nonceHashBytes: 4
70272
+ };
70273
+ var SequenceComponentLengths = {
70274
+ ...SequenceNonceComponentLengths,
70275
+ epochBytes: 8,
70276
+ nonceBytes: SequenceNonceComponentLengths.nonceIndexBytes + SequenceNonceComponentLengths.nonceHashBytes,
70277
+ addressBytes: 20
70278
+ };
70279
+ var SequenceComponentMinMax = {
70280
+ minEpoch: "0".repeat(SequenceComponentLengths.epochBytes * 2),
70281
+ maxEpoch: "f".repeat(SequenceComponentLengths.epochBytes * 2),
70282
+ minNonce: "0".repeat(SequenceComponentLengths.nonceBytes * 2),
70283
+ maxNonce: "f".repeat(SequenceComponentLengths.nonceBytes * 2),
70284
+ minAddress: "0".repeat(SequenceComponentLengths.addressBytes * 2),
70285
+ maxAddress: "f".repeat(SequenceComponentLengths.addressBytes * 2)
70286
+ };
70287
+ var LocalSequenceConstants = {
70288
+ ...SequenceComponentLengths,
70289
+ ...SequenceComponentMinMax,
70290
+ localSequenceBytes: SequenceComponentLengths.epochBytes + SequenceComponentLengths.nonceBytes,
70291
+ minLocalSequence: SequenceComponentMinMax.minEpoch + SequenceComponentMinMax.minNonce,
70292
+ maxLocalSequence: SequenceComponentMinMax.maxEpoch + SequenceComponentMinMax.maxNonce
70293
+ };
70294
+ var QualifiedSequenceConstants = {
70295
+ qualifiedSequenceBytes: LocalSequenceConstants.localSequenceBytes + SequenceComponentLengths.addressBytes,
70296
+ minQualifiedSequence: LocalSequenceConstants.minLocalSequence + SequenceComponentMinMax.minAddress,
70297
+ maxQualifiedSequence: LocalSequenceConstants.maxLocalSequence + SequenceComponentMinMax.maxAddress
70298
+ };
70299
+ var SequenceConstants = {
70300
+ ...LocalSequenceConstants,
70301
+ ...QualifiedSequenceConstants
70302
+ };
70303
+
70304
+ // src/StorageMeta/sequence/Parser.ts
70305
+ var SequenceParser = class _SequenceParser {
70306
+ static privateConstructorKey = Date.now().toString();
70307
+ data;
70308
+ constructor(privateConstructorKey, hex) {
70309
+ assertEx(_SequenceParser.privateConstructorKey === privateConstructorKey, () => "Use create function instead of constructor");
70310
+ const paddedHex = toHex(hex, {
70311
+ prefix: false,
70312
+ bitLength: hex.length <= SequenceConstants.localSequenceBytes * 2 ? SequenceConstants.localSequenceBytes * 8 : SequenceConstants.qualifiedSequenceBytes * 8
70313
+ });
70314
+ this.data = toUint8Array(paddedHex);
70315
+ }
70316
+ get address() {
70317
+ const start = SequenceConstants.localSequenceBytes;
70318
+ const end = SequenceConstants.qualifiedSequenceBytes;
70319
+ return toAddress(this.data.slice(start, end).buffer, { prefix: false });
70320
+ }
70321
+ get epoch() {
70322
+ const start = 0;
70323
+ const end = SequenceConstants.epochBytes;
70324
+ return toHex(this.data.slice(start, end).buffer, { prefix: false });
70325
+ }
70326
+ get localSequence() {
70327
+ const start = 0;
70328
+ const end = SequenceConstants.localSequenceBytes;
70329
+ return toHex(this.data.slice(start, end).buffer, { prefix: false });
70330
+ }
70331
+ get nonce() {
70332
+ const start = SequenceConstants.epochBytes;
70333
+ const end = SequenceConstants.localSequenceBytes;
70334
+ return toHex(this.data.slice(start, end).buffer, { prefix: false });
70335
+ }
70336
+ get qualifiedSequence() {
70337
+ const start = 0;
70338
+ const end = SequenceConstants.qualifiedSequenceBytes;
70339
+ return toHex(this.data.slice(start, end).buffer, { prefix: false });
70340
+ }
70341
+ static from(timestampOrSequence, nonceOrAddress, addressOrIndex, addressOnly) {
70342
+ const address = typeof addressOrIndex === "number" ? addressOnly : addressOrIndex;
70343
+ const index = typeof addressOrIndex === "number" ? addressOrIndex : void 0;
70344
+ if (isSequence(timestampOrSequence)) {
70345
+ if (nonceOrAddress) {
70346
+ assertEx(!isQualifiedSequence(timestampOrSequence), () => "Providing both a qualified sequence and a address is not allowed");
70347
+ assertEx(isAddress(nonceOrAddress), () => "Invalid address provided");
70348
+ return new this(_SequenceParser.privateConstructorKey, timestampOrSequence + address);
70349
+ }
70350
+ return new this(_SequenceParser.privateConstructorKey, timestampOrSequence);
70351
+ }
70352
+ const epoch = _SequenceParser.toEpoch(timestampOrSequence);
70353
+ const nonce = nonceOrAddress === void 0 ? void 0 : _SequenceParser.toNonce(nonceOrAddress, index);
70354
+ const addressHex = address ? toHex(address, { bitLength: SequenceConstants.addressBytes * 8 }) : SequenceConstants.minAddress;
70355
+ const hexString = epoch + nonce + addressHex;
70356
+ assertEx(isSequence(hexString), () => `Invalid sequence [${hexString}] [${epoch}, ${nonce}, ${addressHex}]`);
70357
+ return new this(_SequenceParser.privateConstructorKey, hexString);
70358
+ }
70359
+ static parse(value) {
70360
+ const hex = toHex(value);
70361
+ if (isSequence(hex)) {
70362
+ return new this(_SequenceParser.privateConstructorKey, hex);
70363
+ }
70364
+ throw new Error(`Invalid sequence [${value}]`);
70365
+ }
70366
+ // can convert a short number/hex to an epoch (treats it as the whole value) or extract an epoch from a sequence
70367
+ static toEpoch(value) {
70368
+ assertEx(
70369
+ typeof value !== "number" || Number.isInteger(value),
70370
+ () => "Value must be in integer"
70371
+ );
70372
+ const hex = toHex(value, { prefix: false });
70373
+ if (hex.length <= SequenceConstants.epochBytes * 2) {
70374
+ return toHex(value, { prefix: false, bitLength: SequenceConstants.epochBytes * 8 });
70375
+ }
70376
+ if (isSequence(hex)) {
70377
+ return hex.slice(0, SequenceConstants.epochBytes * 2);
70378
+ }
70379
+ throw new Error(`Value could not be converted to epoch [${hex}]`);
70380
+ }
70381
+ // can convert a short number/hex to a nonce (treats it as the whole value) or extract an nonce from a sequence
70382
+ static toNonce(value, index = 0) {
70383
+ assertEx(
70384
+ typeof value !== "number" || Number.isInteger(value),
70385
+ () => "Value must be in integer"
70386
+ );
70387
+ const hex = toHex(value, { prefix: false });
70388
+ if (isSequence(hex)) {
70389
+ return hex.slice(SequenceConstants.epochBytes * 2, SequenceConstants.localSequenceBytes * 2);
70390
+ }
70391
+ const hashHex = toHex(hex, { prefix: false, bitLength: SequenceConstants.nonceHashBytes * 8 }).slice(-SequenceConstants.nonceHashBytes * 2);
70392
+ const indexHex = toHex(index, { prefix: false, bitLength: SequenceConstants.nonceIndexBytes * 8 }).slice(-SequenceConstants.nonceIndexBytes * 2);
70393
+ return (indexHex + hashHex).slice(-SequenceConstants.nonceBytes * 2);
70394
+ }
70395
+ };
70396
+
70397
+ // src/StorageMeta/sequence/Comparer.ts
70398
+ var local = (a, b) => {
70399
+ const aa = SequenceParser.from(a);
70400
+ const bb = SequenceParser.from(b);
70401
+ return aa.localSequence > bb.localSequence ? 1 : aa.localSequence < bb.localSequence ? -1 : 0;
70402
+ };
70403
+ var SequenceComparer = { local};
70404
+ var LocalSequenceRegex$1 = new RegExp(HexRegExMinMax(SequenceConstants.localSequenceBytes, SequenceConstants.localSequenceBytes));
70405
+ var LocalSequenceToStringZod$1 = z$1.string().regex(LocalSequenceRegex$1);
70406
+ var LocalSequenceFromStringZod$1 = z$1.string().regex(LocalSequenceRegex$1).transform((v) => toHex(v));
70407
+ var QualifiedSequenceRegex$1 = new RegExp(HexRegExMinMax(SequenceConstants.qualifiedSequenceBytes, SequenceConstants.qualifiedSequenceBytes));
70408
+ var QualifiedSequenceToStringZod$1 = z$1.string().regex(QualifiedSequenceRegex$1);
70409
+ var QualifiedSequenceFromStringZod$1 = z$1.string().regex(QualifiedSequenceRegex$1).transform((v) => toHex(v));
70410
+ z$1.union([LocalSequenceToStringZod$1, QualifiedSequenceToStringZod$1]);
70411
+ var SequenceFromStringZod = z$1.union([LocalSequenceFromStringZod$1, QualifiedSequenceFromStringZod$1]);
70412
+
70413
+ // src/PayloadZod.ts
70414
+ var HashMetaZod = z$1.object({
70415
+ _hash: HashZod,
70416
+ _dataHash: HashZod
70417
+ });
70418
+ var isHashMeta = zodIsFactory(HashMetaZod);
70419
+ var asHashMeta = zodAsFactory(HashMetaZod, "asHashMeta");
70420
+ z$1.object({ _sequence: SequenceFromStringZod });
70421
+ var StorageMetaZod = z$1.object({
70422
+ _hash: HashZod,
70423
+ _dataHash: HashZod,
70424
+ _sequence: SequenceFromStringZod
70425
+ });
70426
+ var isStorageMeta = zodIsFactory(StorageMetaZod);
70427
+ var PayloadZod = z$1.object({ schema: SchemaZod });
70428
+ PayloadZod.extend(StorageMetaZod.shape);
70429
+ var AnyPayloadZod = PayloadZod.loose();
70430
+ AnyPayloadZod.extend(StorageMetaZod.shape);
70431
+ function WithStorageMetaZod$1(valueZod) {
70432
+ return valueZod.extend(StorageMetaZod.shape);
70433
+ }
70434
+ function WithHashMetaZod$1(valueZod) {
70435
+ return valueZod.extend(HashMetaZod.shape);
70436
+ }
70437
+ var PayloadZodStrict = z$1.strictObject({ schema: SchemaZod });
70438
+ var PayloadZodLoose = z$1.looseObject({ schema: SchemaZod });
70439
+ var PayloadZodOfSchema = (schema) => PayloadZod.extend({ schema: z$1.literal(schema) });
70440
+ var PayloadZodStrictOfSchema = (schema) => PayloadZodStrict.extend({ schema: z$1.literal(schema) });
70441
+ var PayloadZodLooseOfSchema = (schema) => PayloadZodLoose.extend({ schema: z$1.literal(schema) });
70442
+
70443
+ // src/PayloadBundle.ts
70444
+ var PayloadBundleSchema = asSchema("network.xyo.payload.bundle", true);
70445
+ var PayloadBundleFieldsZod = z$1.object({
70446
+ payloads: PayloadZodLoose.array(),
70447
+ root: HashZod
70448
+ });
70449
+ var PayloadBundleZod = PayloadZodOfSchema(PayloadBundleSchema).extend(PayloadBundleFieldsZod.shape);
70450
+ var isPayloadBundle = zodIsFactory(PayloadBundleZod);
70451
+
70452
+ // src/PayloadSet/PayloadSetSchema.ts
70453
+ asSchema("network.xyo.payload.set", true);
70454
+
70455
+ // src/Config/Config.ts
70456
+ var ModuleConfigSchema = asSchema("network.xyo.module.config", true);
70457
+
70458
+ // src/CreatableModule/CreatableModule.ts
70459
+ function creatableModule() {
70460
+ return (constructor) => {
70461
+ };
70462
+ }
70463
+ function labeledCreatableModule() {
70464
+ return (constructor) => {
70465
+ };
70466
+ }
70467
+ var buildModuleFactory = (mod, labels) => {
70468
+ const factory5 = {
70469
+ // Destructure instance properties
70470
+ ...mod,
70471
+ configSchemas: mod.configSchemas,
70472
+ // Copy static methods
70473
+ create: mod.create.bind(mod),
70474
+ defaultConfigSchema: mod.defaultConfigSchema,
70475
+ // Merge module & supplied labels
70476
+ labels: { ...mod.labels, ...labels }
70477
+ };
70478
+ return factory5;
70479
+ };
70480
+ var registerCreatableModuleFactory = (registry, factory5, labels, primary = false) => {
70481
+ const primarySchemas = primary !== true && isTruthy(primary) ? Array.isArray(primary) ? primary : [primary] : [];
70482
+ for (const primarySchema of primarySchemas) {
70483
+ if (!factory5.configSchemas.includes(primarySchema)) {
70484
+ console.warn(`Primary schema ${primary} not found in factory configSchemas`);
70485
+ }
70486
+ }
70487
+ const isPrimaryForSchema = (schema) => {
70488
+ switch (typeof primary) {
70489
+ case "boolean": {
70490
+ return primary;
70491
+ }
70492
+ case "string": {
70493
+ return schema === primary;
70494
+ }
70495
+ case "object": {
70496
+ if (Array.isArray(primary)) {
70497
+ return primary.includes(schema);
70498
+ }
70499
+ }
70500
+ }
70501
+ throw new Error(`Invalid primary value: ${primary}`);
70502
+ };
70503
+ const factoryClone = buildModuleFactory(factory5, labels);
70504
+ registry[factory5.defaultConfigSchema] = [factoryClone, ...registry[factoryClone.defaultConfigSchema] ?? []];
70505
+ for (const schema of factoryClone.configSchemas) {
70506
+ registry[schema] = isPrimaryForSchema(schema) ? [factoryClone, ...registry[schema] ?? []] : [...registry[schema] ?? [], factoryClone];
70507
+ }
70508
+ };
70509
+ var registerCreatableModuleFactories = (factories, registry = {}, primary = false) => {
70510
+ for (const factory5 of factories) {
70511
+ registerCreatableModuleFactory(registry, factory5, void 0, primary);
70512
+ }
70513
+ return registry;
70514
+ };
70515
+
70516
+ // src/CreatableModule/LabeledCreatableModuleFactory.ts
70517
+ var hasLabels$1 = (factory5) => {
70518
+ return factory5.labels !== void 0;
70519
+ };
70520
+ var ModuleFactory = class _ModuleFactory {
70521
+ configSchemas;
70522
+ creatableModule;
70523
+ defaultConfigSchema;
70524
+ defaultLogger;
70525
+ defaultParams;
70526
+ labels;
70527
+ constructor(creatableModule2, params, labels = {}) {
70528
+ this.creatableModule = creatableModule2;
70529
+ this.defaultParams = params;
70530
+ this.configSchemas = creatableModule2.configSchemas;
70531
+ this.defaultConfigSchema = creatableModule2.defaultConfigSchema;
70532
+ assertEx(this.configSchemas.includes(this.defaultConfigSchema), () => "defaultConfigSchema must be in configSchemas");
70533
+ this.labels = Object.assign({}, creatableModule2.labels ?? {}, labels ?? {});
70534
+ }
70535
+ static withParams(creatableModule2, params, labels = {}) {
70536
+ return new _ModuleFactory(creatableModule2, params, labels);
70537
+ }
70538
+ create(params) {
70539
+ const mergedParams = {
70540
+ ...this.defaultParams,
70541
+ ...params,
70542
+ config: {
70543
+ schema: this.creatableModule.defaultConfigSchema,
70544
+ ...this.defaultParams?.config,
70545
+ ...params?.config
70546
+ }
70547
+ };
70548
+ return this.creatableModule.create(mergedParams);
70549
+ }
70550
+ factory(params, labels = {}) {
70551
+ return new _ModuleFactory(this.creatableModule, params, labels);
70552
+ }
70553
+ };
70554
+ var ModuleManifestQuerySchema = asSchema("network.xyo.query.module.manifest", true);
70555
+ var ModuleAddressQuerySchema = asSchema("network.xyo.query.module.address", true);
70556
+ var ModuleStateQuerySchema = asSchema("network.xyo.query.module.state", true);
70557
+ var ModuleSubscribeQuerySchema = asSchema("network.xyo.query.module.subscribe", true);
70558
+ var requiredModuleShape = {
70559
+ address: "string",
70560
+ queries: "array",
70561
+ query: "function"
70562
+ };
70563
+ var factory$6 = new IsObjectFactory();
70564
+ var isModuleObject = factory$6.create(requiredModuleShape);
70565
+
70566
+ // src/module/asModuleObject.ts
70567
+ var asModuleObject = AsObjectFactory.create(isModuleObject);
70568
+
70569
+ // src/module/IsModuleFactory.ts
70570
+ var IsModuleFactory = class {
70571
+ create(expectedQueries, additionalChecks) {
70572
+ const result = (obj, config) => {
70573
+ const mod = asModuleObject(obj);
70574
+ return isModuleObject(mod, config) && (expectedQueries?.reduce((prev, query) => prev && mod.queries.includes(query), true) ?? true) && (additionalChecks?.reduce((prev, check) => prev && check(obj, config), true) ?? true);
70575
+ };
70576
+ return result;
70577
+ }
70578
+ };
70579
+
70580
+ // src/module/isModule.ts
70581
+ var requiredModuleQueries = [ModuleStateQuerySchema];
70582
+ var factory2 = new IsModuleFactory();
70583
+ var isModule = factory2.create(requiredModuleQueries, [isModuleObject]);
70584
+
70585
+ // src/instance/isModuleInstance.ts
70586
+ var requiredModuleInstanceFunctions = {
70587
+ manifest: "function",
70588
+ state: "function"
70589
+ };
70590
+ var factory3 = new IsObjectFactory();
70591
+ var isModuleInstance = factory3.create(requiredModuleInstanceFunctions, [isModule]);
70592
+
70593
+ // src/instance/asModuleInstance.ts
70594
+ var asModuleInstance = AsObjectFactory.create(isModuleInstance);
70595
+ var requiredAttachableModuleInstanceFunctions = {
70596
+ downResolver: "object",
70597
+ upResolver: "object"
70598
+ };
70599
+ var factory4 = new IsObjectFactory();
70600
+ var isAttachableModuleInstance = factory4.create(requiredAttachableModuleInstanceFunctions, [
70601
+ isModuleInstance
70602
+ ]);
70603
+
70604
+ // src/instance/attachable/asAttachableInstance.ts
70605
+ var asAttachableModuleInstance = AsObjectFactory.create(isAttachableModuleInstance);
70606
+ var DeadModuleError = class _DeadModuleError extends Error {
70607
+ error;
70608
+ id;
70609
+ constructor(id, error, msg = "Dead Module Error") {
70610
+ super(`${msg} [${id}]: ${error?.message ?? toSafeJsonString(error)}`);
70611
+ this.id = id;
70612
+ this.error = error;
70613
+ Object.setPrototypeOf(this, _DeadModuleError.prototype);
70614
+ }
70615
+ };
70616
+ var IsInstanceFactory = class extends IsObjectFactory {
70617
+ };
70618
+ var ObjectResolverPriority = {
70619
+ VeryLow: 0,
70620
+ Low: 1,
70621
+ Normal: 2,
70622
+ VeryHigh: 4
70623
+ };
70624
+
70625
+ // src/Labels/Labels.ts
70626
+ var hasAllLabels = (source, required) => {
70627
+ if (!required) return true;
70628
+ return Object.entries(required).every(([key, value]) => {
70629
+ return source?.hasOwnProperty(key) && source?.[key] === value;
70630
+ });
70631
+ };
70632
+ var ModuleLimitationViewLabel = { ModuleLimitationLabelName: "view" };
70633
+
70634
+ // src/lib/duplicateModules.ts
70635
+ var duplicateModules = (value, index, array) => {
70636
+ return array.findIndex((v) => v.address === value.address) === index;
70637
+ };
70638
+
70639
+ // src/lib/serializable.ts
70640
+ var isSerializable = (value, maxDepth = 10) => {
70641
+ if (maxDepth <= 0) {
70642
+ return false;
70643
+ }
70644
+ if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
70645
+ return true;
70646
+ }
70647
+ if (Array.isArray(value)) {
70648
+ return value.every((item) => isSerializable(item, maxDepth - 1));
70649
+ }
70650
+ if (typeof value === "object") {
70651
+ if (value instanceof Date || value instanceof RegExp) {
70652
+ return true;
70653
+ }
70654
+ if (value instanceof Set || value instanceof Map) {
70655
+ return false;
70656
+ }
70657
+ if (value !== null && value !== void 0) {
70658
+ return Object.values(value).every((item) => isSerializable(item, maxDepth - 1));
70659
+ }
70660
+ }
70661
+ return false;
70662
+ };
70663
+ var MODULE_PATH_SEPARATOR = ":";
70664
+ var DisallowedModuleIdentifierCharacters = {
70665
+ " ": true,
70666
+ "!": true,
70667
+ '"': true,
70668
+ "#": true,
70669
+ "$": true,
70670
+ "%": true,
70671
+ "&": true,
70672
+ "'": true,
70673
+ "(": true,
70674
+ ")": true,
70675
+ "*": true,
70676
+ ",": true,
70677
+ ".": true,
70678
+ "/": true,
70679
+ ":": true,
70680
+ ";": true,
70681
+ "<": true,
70682
+ "=": true,
70683
+ ">": true,
70684
+ "?": true,
70685
+ "@": true,
70686
+ "[": true,
70687
+ "]": true,
70688
+ "^": true,
70689
+ "_": true,
70690
+ "{": true,
70691
+ "|": true,
70692
+ "}": true,
70693
+ "~": true
70694
+ };
70695
+ var ReservedModuleIdentifierCharacters = new Set(
70696
+ Object.keys(DisallowedModuleIdentifierCharacters)
70697
+ );
70698
+ var isModuleName = (value) => {
70699
+ return typeof value === "string" && !isAddress(value) && !includesReservedModuleIdentifierCharacter(value);
70700
+ };
70701
+ var includesReservedModuleIdentifierCharacter = (value) => {
70702
+ return typeof value === "string" && [...value].some((char) => ReservedModuleIdentifierCharacters.has(char));
70703
+ };
70704
+ var AddressSchema = asSchema("network.xyo.address", true);
70705
+ asSchema("network.xyo.address.child", true);
70706
+ var AddressPreviousHashSchema = asSchema("network.xyo.address.hash.previous", true);
70707
+ var ModuleDescriptionSchema = asSchema("network.xyo.module.description", true);
70708
+ asSchema("network.xyo.module.state", true);
70709
+
70710
+ // src/ResolveHelper/resolveAddressToInstance.ts
70711
+ var resolveAddressToInstanceDown = async (root, address, includePrivate = void 0, ignore = []) => {
70712
+ if (root.address === address) {
70713
+ return root;
70714
+ }
70715
+ const cache = root.addressCache?.("up", !!includePrivate);
70716
+ const privateChildren = (includePrivate ? await root.privateChildren?.() : []) ?? [];
70717
+ const publicChildren = await root.publicChildren?.() ?? [];
70718
+ const children = [...privateChildren, ...publicChildren];
70719
+ for (const child of children) {
70720
+ const found = await resolveAddressToInstanceDown(child, address, includePrivate, ignore);
70721
+ if (found) {
70722
+ cache?.set(address, new WeakRef(found));
70723
+ return found;
70724
+ }
70725
+ }
70726
+ cache?.set(address, null);
70727
+ };
70728
+ var resolveAddressToInstanceUp = async (root, address, includePrivate = void 0, ignore = []) => {
70729
+ const cache = root.addressCache?.("up", includePrivate ?? true);
70730
+ const parents = await root.parents?.() ?? [];
70731
+ for (const parent of parents) {
70732
+ const found = await resolveAddressToInstance(parent, address, includePrivate, ignore);
70733
+ if (found) {
70734
+ cache?.set(address, new WeakRef(found));
70735
+ return found;
70736
+ }
70737
+ }
70738
+ cache?.set(address, null);
70739
+ };
70740
+ var resolveAddressToInstanceAll = async (root, address, includePrivate = void 0, ignore = []) => {
70741
+ const cache = root.addressCache?.("all", !!includePrivate);
70742
+ const result = await resolveAddressToInstanceDown(root, address, includePrivate ?? false, ignore) ?? await resolveAddressToInstanceUp(root, address, includePrivate ?? true, ignore);
70743
+ cache?.set(address, result ? new WeakRef(result) : null);
70744
+ return result;
70745
+ };
70746
+ var resolveAddressToInstance = async (root, address, includePrivate = void 0, ignore = [], direction = "all") => {
70747
+ switch (direction) {
70748
+ case "all": {
70749
+ return await resolveAddressToInstanceAll(root, address, includePrivate, ignore);
70750
+ }
70751
+ case "up": {
70752
+ return await resolveAddressToInstanceUp(root, address, includePrivate ?? true, ignore);
70753
+ }
70754
+ case "down": {
70755
+ return await resolveAddressToInstanceDown(root, address, includePrivate ?? false, ignore);
70756
+ }
70757
+ }
70758
+ };
70759
+
70760
+ // src/ResolveHelper/resolveAll.ts
70761
+ var resolveAllUp = async (root, maxDepth = 10, exclude = []) => {
70762
+ if (maxDepth === 0) {
70763
+ return [root].filter((mod) => !exclude.includes(mod.address));
70764
+ }
70765
+ const parents = (await root.parents()).filter((mod) => !exclude.includes(mod.address));
70766
+ return (maxDepth > 1 ? [
70767
+ ...(await Promise.all(parents.map(async (mod) => await resolveAllUp(mod, maxDepth - 1, [...exclude, root.address])))).flat(),
70768
+ ...(await Promise.all(parents.map(async (mod) => await resolveAllDown(mod, maxDepth - 1, [...exclude, root.address], true)))).flat(),
70769
+ ...parents,
70770
+ root
70771
+ ] : [...parents, root]).filter((mod) => !exclude.includes(mod.address)).filter(duplicateModules);
70772
+ };
70773
+ var resolveAllDown = async (root, maxDepth = 10, exclude = [], includePrivate = false) => {
70774
+ if (maxDepth === 0) {
70775
+ return [root];
70776
+ }
70777
+ const children = (await root.publicChildren()).filter((mod) => !exclude.includes(mod.address));
70778
+ const privateChildren = includePrivate ? (await root.privateChildren()).filter((mod) => !exclude.includes(mod.address)) : [];
70779
+ return (maxDepth > 1 ? [
70780
+ ...children,
70781
+ ...(await Promise.all(children.map((child) => resolveAllDown(child, maxDepth - 1, [...exclude, root.address])))).flat(),
70782
+ ...(await Promise.all(privateChildren.map((child) => resolveAllDown(child, maxDepth - 1, [...exclude, root.address])))).flat(),
70783
+ root
70784
+ ] : [...children, root]).filter((mod) => !exclude.includes(mod.address)).filter(duplicateModules);
70785
+ };
70786
+ var resolveAll = async (root, maxDepth = 10, exclude = []) => {
70787
+ if (maxDepth === 0) {
70788
+ return [root];
70789
+ }
70790
+ return [...await resolveAllUp(root, maxDepth, exclude), ...await resolveAllDown(root, maxDepth, exclude)].filter(duplicateModules);
70791
+ };
70792
+
70793
+ // src/ResolveHelper/ResolveHelperStatic.ts
70794
+ var ResolveHelperStatic = class {
70795
+ static defaultLogger;
70796
+ // eslint-disable-next-line sonarjs/public-static-readonly
70797
+ static transformers = [];
70798
+ };
70799
+
70800
+ // src/ResolveHelper/resolveLocalNameToInstance.ts
70801
+ var resolveLocalNameToInstanceUp = async (root, modName) => {
70802
+ const parents = await root.parents?.() ?? [];
70803
+ return parents.find((parent) => parent.config.name === modName);
70804
+ };
70805
+ var resolveLocalNameToInstanceDown = async (root, modName, includePrivate = void 0) => {
70806
+ const privateChildren = (includePrivate ? await root.privateChildren?.() : []) ?? [];
70807
+ const publicChildren = await root.publicChildren?.() ?? [];
70808
+ const children = [...privateChildren, ...publicChildren];
70809
+ return children.find((child) => child.config.name === modName);
70810
+ };
70811
+ var resolveLocalNameToInstanceAll = async (root, modName, includePrivate = false) => {
70812
+ return await resolveLocalNameToInstanceDown(root, modName, includePrivate) ?? await resolveLocalNameToInstanceUp(root, modName);
70813
+ };
70814
+ var resolveLocalNameToInstance = async (root, modName, includePrivate = false, direction = "all") => {
70815
+ switch (direction) {
70816
+ case "all": {
70817
+ return await resolveLocalNameToInstanceAll(root, modName, includePrivate);
70818
+ }
70819
+ case "up": {
70820
+ return await resolveLocalNameToInstanceUp(root, modName);
70821
+ }
70822
+ case "down": {
70823
+ return await resolveLocalNameToInstanceDown(root, modName, includePrivate);
70824
+ }
70825
+ }
70826
+ };
70827
+ var resolveLocalNameToAddress = async (root, modName, includePrivate = void 0, direction = "all") => {
70828
+ return (await resolveLocalNameToInstance(root, modName, includePrivate, direction))?.address;
70829
+ };
70830
+
70831
+ // src/ResolveHelper/transformModuleIdentifier.ts
70832
+ var transformModuleIdentifier = async (id, transformers) => {
70833
+ let result = id;
70834
+ for (const transformer of transformers) {
70835
+ result = await transformer.transform(id);
70836
+ }
70837
+ return result;
70838
+ };
70839
+
70840
+ // src/ResolveHelper/resolvePathToInstance.ts
70841
+ var resolvePathToInstance = async (root, path, includePrivate = void 0, transformers = ResolveHelperStatic.transformers) => {
70842
+ const parts = path.split(MODULE_PATH_SEPARATOR);
70843
+ const first = await transformModuleIdentifier(
70844
+ assertEx(parts.shift(), () => `First part is invalid [${path}]`),
70845
+ transformers
70846
+ );
70847
+ if (!first) {
70848
+ return void 0;
70849
+ }
70850
+ const firstAddress = asAddress(first) ?? await resolveLocalNameToAddress(root, first, includePrivate);
70851
+ if (firstAddress) {
70852
+ const firstModule = await resolveAddressToInstance(root, firstAddress, includePrivate);
70853
+ if (firstModule && parts.length > 0) {
70854
+ return resolvePathToInstance(firstModule, parts.join(MODULE_PATH_SEPARATOR));
70855
+ }
70856
+ return firstModule;
70857
+ }
70858
+ };
70859
+
70860
+ // src/ResolveHelper/resolvePathToAddress.ts
70861
+ var resolvePathToAddress = async (root, path, includePrivate = void 0, transformers = ResolveHelperStatic.transformers) => {
70862
+ return (await resolvePathToInstance(root, path, includePrivate, transformers))?.address;
70863
+ };
70864
+ var traceModuleIdentifier = async (resolver, path) => {
70865
+ const parts = path.split(":");
70866
+ const first = parts.shift();
70867
+ const firstModule = asModuleInstance(
70868
+ assertEx(await resolver.resolve(first, { maxDepth: 1 }), () => `Failed to resolve [${first}]`),
70869
+ () => `Resolved invalid module instance [${first}]`
70870
+ );
70871
+ if (firstModule) {
70872
+ return parts.length > 0 ? [firstModule.address, ...await traceModuleIdentifier(firstModule, parts.join(":"))] : [firstModule.address];
70873
+ }
70874
+ return [];
70875
+ };
70876
+
70877
+ // src/ResolveHelper/ResolveHelper.ts
70878
+ var ResolveHelper = class _ResolveHelper extends ResolveHelperStatic {
70879
+ static async resolve(config, id = "*", {
70880
+ maxDepth = 3,
70881
+ required = "log",
70882
+ ...options
70883
+ } = {}) {
70884
+ const {
70885
+ transformers,
70886
+ mod,
70887
+ logger = this.defaultLogger,
70888
+ dead = false,
70889
+ upResolver,
70890
+ downResolver,
70891
+ privateResolver
70892
+ } = config;
70893
+ const log = logger ? new IdLogger(logger, () => `ResolveHelper [${mod.id}][${id}]`) : void 0;
70894
+ const downLocalOptions = {
70895
+ ...options,
70896
+ direction: "down",
70897
+ maxDepth,
70898
+ required: false
70899
+ };
70900
+ const upLocalOptions = { ...downLocalOptions, direction: "up" };
70901
+ const childOptions = {
70902
+ ...options,
70903
+ maxDepth: maxDepth - 1,
70904
+ required: false
70905
+ };
70906
+ const direction = options?.direction ?? "all";
70907
+ const up = direction === "up" || direction === "all";
70908
+ const down = direction === "down" || direction === "all";
70909
+ let result;
70910
+ log?.debug("start", id, maxDepth);
70911
+ if (id === "*") {
70912
+ if (dead) {
70913
+ log?.warn("failed [dead]", id);
70914
+ return [];
70915
+ }
70916
+ const modules = [
70917
+ ...down ? await downResolver.resolve("*", downLocalOptions) : [],
70918
+ ...up ? await upResolver.resolve("*", upLocalOptions) : []
70919
+ ].filter(duplicateModules);
70920
+ if (modules.length > 0) {
70921
+ log?.debug("modules [count]", modules.length);
70922
+ log?.debug("modules", toSafeJsonString(modules, 4));
70923
+ }
70924
+ if (maxDepth === 0) {
70925
+ return modules;
70926
+ }
70927
+ const childModules = (await Promise.all(modules.map(async (mod2) => await mod2.resolve("*", childOptions)))).flat().filter(duplicateModules);
70928
+ return [...modules, ...childModules, mod].filter(duplicateModules);
70929
+ } else {
70930
+ switch (typeof id) {
70931
+ case "string": {
70932
+ if (dead) {
70933
+ return void 0;
70934
+ }
70935
+ const resolvedId = assertEx(await resolvePathToAddress(mod, id, false, transformers) ?? id, () => "Invalid resolvedId");
70936
+ const resolvers = [
70937
+ [downResolver, downLocalOptions],
70938
+ [up ? upResolver : void 0, upLocalOptions],
70939
+ [up ? privateResolver : void 0, upLocalOptions]
70940
+ ].filter(([resolver]) => exists$2(resolver));
70941
+ for (const resolver of resolvers) {
70942
+ const [resolverInstance] = resolver;
70943
+ if (!result) {
70944
+ result = await this.resolveModuleIdentifier(resolverInstance, resolvedId);
70945
+ }
70946
+ }
70947
+ break;
70948
+ }
70949
+ }
70950
+ }
70951
+ this.validateRequiredResolve(required, result, id, logger);
70952
+ return result;
70953
+ }
70954
+ // resolves a complex module path to addresses
70955
+ static async resolveModuleIdentifier(resolver, path, required) {
70956
+ const parts = path.split(":");
70957
+ const first = parts.shift();
70958
+ const firstIsAddress = isAddress(first);
70959
+ const resolvedModule = await resolver.resolve(first, { maxDepth: firstIsAddress ? 10 : 1 }) ?? (isString$1(first) ? await resolver.resolvePrivate(first, { maxDepth: firstIsAddress ? 10 : 1 }) : void 0);
70960
+ const finalModule = required ? assertEx(resolvedModule, () => `Failed to resolve [${first}] [${firstIsAddress}]`) : resolvedModule;
70961
+ const firstModule = asModuleInstance(finalModule, () => `Resolved invalid module instance [${first}]`);
70962
+ return isDefined(firstModule) ? parts.length > 0 ? await this.resolveModuleIdentifier(firstModule, parts.join(":")) : firstModule : void 0;
70963
+ }
70964
+ // translates a complex module path to addresses
70965
+ static traceModuleIdentifier(resolver, path) {
70966
+ return traceModuleIdentifier(resolver, path);
70967
+ }
70968
+ static transformModuleIdentifier(identifier, transformers = _ResolveHelper.transformers) {
70969
+ return transformModuleIdentifier(identifier, transformers);
70970
+ }
70971
+ static validateRequiredResolve(required, result, id, logger = this.defaultLogger) {
70972
+ const log = logger ? new IdLogger(logger, () => `validateRequiredResolve [${id}][${result}]`) : void 0;
70973
+ if (isTruthy(required) && (result === void 0 || Array.isArray(result) && result.length > 0)) {
70974
+ switch (required) {
70975
+ case "warn": {
70976
+ log?.warn("resolve failed", id);
70977
+ break;
70978
+ }
70979
+ case "log": {
70980
+ log?.log("resolve failed", id);
70981
+ break;
70982
+ }
70983
+ default: {
70984
+ throw new Error(`resolve failed [${id}]`);
70985
+ }
70986
+ }
70987
+ }
70988
+ }
70989
+ };
70990
+
70991
+ // src/BoundWitness/BoundWitness.ts
70992
+ var BoundWitnessSchema = asSchema("network.xyo.boundwitness", true);
70993
+ var SignaturesMetaZod = z$1.object({ $signatures: z$1.array(z$1.union([HexZod, z$1.null()])) });
70994
+ var UnsignedSignaturesMetaZod = z$1.object({ $signatures: z$1.array(z$1.null()) });
70995
+ var SignedSignaturesMetaZod = z$1.object({ $signatures: z$1.array(HexZod).min(1) });
70996
+
70997
+ // src/BoundWitness/BoundWitness.ts
70998
+ var BoundWitnessRequiredFieldsZod = z$1.object({
70999
+ addresses: z$1.array(AddressZod),
71000
+ payload_hashes: z$1.array(HashZod),
71001
+ payload_schemas: z$1.array(SchemaZod),
71002
+ previous_hashes: z$1.array(HashZod.nullable())
71003
+ });
71004
+ var BoundWitnessMetaZod = z$1.object({
71005
+ $destination: AddressZod.optional(),
71006
+ $sourceQuery: HashZod.optional()
71007
+ }).extend(SignaturesMetaZod.shape);
71008
+ var BoundWitnessZod = PayloadZod.safeExtend({ schema: z$1.literal(BoundWitnessSchema) }).safeExtend(BoundWitnessRequiredFieldsZod.shape).safeExtend(BoundWitnessMetaZod.shape);
71009
+ var isBoundWitness = zodIsFactory(BoundWitnessZod);
71010
+ var asBoundWitness = zodAsFactory(BoundWitnessZod, "asBoundWitness");
71011
+ BoundWitnessZod.loose();
71012
+
71013
+ // src/BoundWitness/SignedBoundWitness.ts
71014
+ var SignedBoundWitnessZod = BoundWitnessZod.extend(SignedSignaturesMetaZod.shape);
71015
+ SignedBoundWitnessZod.loose();
71016
+
71017
+ // src/BoundWitness/UnsignedBoundWitness.ts
71018
+ var UnsignedBoundWitnessZod = BoundWitnessZod.extend(UnsignedSignaturesMetaZod.shape);
71019
+ UnsignedBoundWitnessZod.loose();
71020
+ var isQueryBoundWitness = (x) => isBoundWitness(x) && x?.query !== void 0;
71021
+
70230
71022
  // base64 encode/decode derived from: https://github.com/niklasvh/base64-arraybuffer
70231
71023
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
70232
71024
  /* eslint-disable functional/no-expression-statements, functional/immutable-data, @typescript-eslint/no-magic-numbers, no-bitwise, no-plusplus, @typescript-eslint/no-non-null-assertion */
@@ -71578,798 +72370,6 @@ Account = __decorateClass$f([
71578
72370
  staticImplements()
71579
72371
  ], Account);
71580
72372
 
71581
- // src/isPayload.ts
71582
- var isAnyPayload = (value) => {
71583
- if (isObject$5(value)) {
71584
- return typeof value.schema === "string";
71585
- }
71586
- return false;
71587
- };
71588
- var asAnyPayload = AsObjectFactory.create(isAnyPayload);
71589
-
71590
- // src/isPayloadOfSchemaType.ts
71591
- function isPayloadOfSchemaType(schema) {
71592
- return (x) => isAnyPayload(x) && x?.schema === schema;
71593
- }
71594
- var SchemaRegEx = /^(?:[a-z0-9]+\.)*[a-z0-9]+$/;
71595
- var SchemaZod = z$1.string().regex(SchemaRegEx).transform((v) => v);
71596
- var isSchema = zodIsFactory(SchemaZod);
71597
- var asSchema = zodAsFactory(SchemaZod, "asSchema");
71598
- var PayloadSchema = asSchema("network.xyo.payload", true);
71599
- z$1.literal(PayloadSchema);
71600
-
71601
- // src/Error.ts
71602
- var ModuleErrorSchema = asSchema("network.xyo.error.module", true);
71603
- function isPayloadOfZodType(zodSchema, schema) {
71604
- return (x) => {
71605
- if (!isAnyPayload(x)) return false;
71606
- if (isDefined(schema) && x.schema !== schema) return false;
71607
- const { schema: _, ...data } = x;
71608
- return zodSchema.safeParse(data).success;
71609
- };
71610
- }
71611
- var isLocalSequence = (value) => {
71612
- return isHex(value) && value.length === SequenceConstants.localSequenceBytes * 2;
71613
- };
71614
- var isQualifiedSequence = (value) => {
71615
- return isHex(value) && value.length === SequenceConstants.qualifiedSequenceBytes * 2;
71616
- };
71617
- var isSequence = (value) => {
71618
- return isLocalSequence(value) || isQualifiedSequence(value);
71619
- };
71620
- var SequenceNonceComponentLengths = {
71621
- nonceIndexBytes: 4,
71622
- nonceHashBytes: 4
71623
- };
71624
- var SequenceComponentLengths = {
71625
- ...SequenceNonceComponentLengths,
71626
- epochBytes: 8,
71627
- nonceBytes: SequenceNonceComponentLengths.nonceIndexBytes + SequenceNonceComponentLengths.nonceHashBytes,
71628
- addressBytes: 20
71629
- };
71630
- var SequenceComponentMinMax = {
71631
- minEpoch: "0".repeat(SequenceComponentLengths.epochBytes * 2),
71632
- maxEpoch: "f".repeat(SequenceComponentLengths.epochBytes * 2),
71633
- minNonce: "0".repeat(SequenceComponentLengths.nonceBytes * 2),
71634
- maxNonce: "f".repeat(SequenceComponentLengths.nonceBytes * 2),
71635
- minAddress: "0".repeat(SequenceComponentLengths.addressBytes * 2),
71636
- maxAddress: "f".repeat(SequenceComponentLengths.addressBytes * 2)
71637
- };
71638
- var LocalSequenceConstants = {
71639
- ...SequenceComponentLengths,
71640
- ...SequenceComponentMinMax,
71641
- localSequenceBytes: SequenceComponentLengths.epochBytes + SequenceComponentLengths.nonceBytes,
71642
- minLocalSequence: SequenceComponentMinMax.minEpoch + SequenceComponentMinMax.minNonce,
71643
- maxLocalSequence: SequenceComponentMinMax.maxEpoch + SequenceComponentMinMax.maxNonce
71644
- };
71645
- var QualifiedSequenceConstants = {
71646
- qualifiedSequenceBytes: LocalSequenceConstants.localSequenceBytes + SequenceComponentLengths.addressBytes,
71647
- minQualifiedSequence: LocalSequenceConstants.minLocalSequence + SequenceComponentMinMax.minAddress,
71648
- maxQualifiedSequence: LocalSequenceConstants.maxLocalSequence + SequenceComponentMinMax.maxAddress
71649
- };
71650
- var SequenceConstants = {
71651
- ...LocalSequenceConstants,
71652
- ...QualifiedSequenceConstants
71653
- };
71654
-
71655
- // src/StorageMeta/sequence/Parser.ts
71656
- var SequenceParser = class _SequenceParser {
71657
- static privateConstructorKey = Date.now().toString();
71658
- data;
71659
- constructor(privateConstructorKey, hex) {
71660
- assertEx(_SequenceParser.privateConstructorKey === privateConstructorKey, () => "Use create function instead of constructor");
71661
- const paddedHex = toHex(hex, {
71662
- prefix: false,
71663
- bitLength: hex.length <= SequenceConstants.localSequenceBytes * 2 ? SequenceConstants.localSequenceBytes * 8 : SequenceConstants.qualifiedSequenceBytes * 8
71664
- });
71665
- this.data = toUint8Array(paddedHex);
71666
- }
71667
- get address() {
71668
- const start = SequenceConstants.localSequenceBytes;
71669
- const end = SequenceConstants.qualifiedSequenceBytes;
71670
- return toAddress(this.data.slice(start, end).buffer, { prefix: false });
71671
- }
71672
- get epoch() {
71673
- const start = 0;
71674
- const end = SequenceConstants.epochBytes;
71675
- return toHex(this.data.slice(start, end).buffer, { prefix: false });
71676
- }
71677
- get localSequence() {
71678
- const start = 0;
71679
- const end = SequenceConstants.localSequenceBytes;
71680
- return toHex(this.data.slice(start, end).buffer, { prefix: false });
71681
- }
71682
- get nonce() {
71683
- const start = SequenceConstants.epochBytes;
71684
- const end = SequenceConstants.localSequenceBytes;
71685
- return toHex(this.data.slice(start, end).buffer, { prefix: false });
71686
- }
71687
- get qualifiedSequence() {
71688
- const start = 0;
71689
- const end = SequenceConstants.qualifiedSequenceBytes;
71690
- return toHex(this.data.slice(start, end).buffer, { prefix: false });
71691
- }
71692
- static from(timestampOrSequence, nonceOrAddress, addressOrIndex, addressOnly) {
71693
- const address = typeof addressOrIndex === "number" ? addressOnly : addressOrIndex;
71694
- const index = typeof addressOrIndex === "number" ? addressOrIndex : void 0;
71695
- if (isSequence(timestampOrSequence)) {
71696
- if (nonceOrAddress) {
71697
- assertEx(!isQualifiedSequence(timestampOrSequence), () => "Providing both a qualified sequence and a address is not allowed");
71698
- assertEx(isAddress(nonceOrAddress), () => "Invalid address provided");
71699
- return new this(_SequenceParser.privateConstructorKey, timestampOrSequence + address);
71700
- }
71701
- return new this(_SequenceParser.privateConstructorKey, timestampOrSequence);
71702
- }
71703
- const epoch = _SequenceParser.toEpoch(timestampOrSequence);
71704
- const nonce = nonceOrAddress === void 0 ? void 0 : _SequenceParser.toNonce(nonceOrAddress, index);
71705
- const addressHex = address ? toHex(address, { bitLength: SequenceConstants.addressBytes * 8 }) : SequenceConstants.minAddress;
71706
- const hexString = epoch + nonce + addressHex;
71707
- assertEx(isSequence(hexString), () => `Invalid sequence [${hexString}] [${epoch}, ${nonce}, ${addressHex}]`);
71708
- return new this(_SequenceParser.privateConstructorKey, hexString);
71709
- }
71710
- static parse(value) {
71711
- const hex = toHex(value);
71712
- if (isSequence(hex)) {
71713
- return new this(_SequenceParser.privateConstructorKey, hex);
71714
- }
71715
- throw new Error(`Invalid sequence [${value}]`);
71716
- }
71717
- // can convert a short number/hex to an epoch (treats it as the whole value) or extract an epoch from a sequence
71718
- static toEpoch(value) {
71719
- assertEx(
71720
- typeof value !== "number" || Number.isInteger(value),
71721
- () => "Value must be in integer"
71722
- );
71723
- const hex = toHex(value, { prefix: false });
71724
- if (hex.length <= SequenceConstants.epochBytes * 2) {
71725
- return toHex(value, { prefix: false, bitLength: SequenceConstants.epochBytes * 8 });
71726
- }
71727
- if (isSequence(hex)) {
71728
- return hex.slice(0, SequenceConstants.epochBytes * 2);
71729
- }
71730
- throw new Error(`Value could not be converted to epoch [${hex}]`);
71731
- }
71732
- // can convert a short number/hex to a nonce (treats it as the whole value) or extract an nonce from a sequence
71733
- static toNonce(value, index = 0) {
71734
- assertEx(
71735
- typeof value !== "number" || Number.isInteger(value),
71736
- () => "Value must be in integer"
71737
- );
71738
- const hex = toHex(value, { prefix: false });
71739
- if (isSequence(hex)) {
71740
- return hex.slice(SequenceConstants.epochBytes * 2, SequenceConstants.localSequenceBytes * 2);
71741
- }
71742
- const hashHex = toHex(hex, { prefix: false, bitLength: SequenceConstants.nonceHashBytes * 8 }).slice(-SequenceConstants.nonceHashBytes * 2);
71743
- const indexHex = toHex(index, { prefix: false, bitLength: SequenceConstants.nonceIndexBytes * 8 }).slice(-SequenceConstants.nonceIndexBytes * 2);
71744
- return (indexHex + hashHex).slice(-SequenceConstants.nonceBytes * 2);
71745
- }
71746
- };
71747
-
71748
- // src/StorageMeta/sequence/Comparer.ts
71749
- var local = (a, b) => {
71750
- const aa = SequenceParser.from(a);
71751
- const bb = SequenceParser.from(b);
71752
- return aa.localSequence > bb.localSequence ? 1 : aa.localSequence < bb.localSequence ? -1 : 0;
71753
- };
71754
- var SequenceComparer = { local};
71755
- var LocalSequenceRegex$1 = new RegExp(HexRegExMinMax(SequenceConstants.localSequenceBytes, SequenceConstants.localSequenceBytes));
71756
- var LocalSequenceToStringZod$1 = z$1.string().regex(LocalSequenceRegex$1);
71757
- var LocalSequenceFromStringZod$1 = z$1.string().regex(LocalSequenceRegex$1).transform((v) => toHex(v));
71758
- var QualifiedSequenceRegex$1 = new RegExp(HexRegExMinMax(SequenceConstants.qualifiedSequenceBytes, SequenceConstants.qualifiedSequenceBytes));
71759
- var QualifiedSequenceToStringZod$1 = z$1.string().regex(QualifiedSequenceRegex$1);
71760
- var QualifiedSequenceFromStringZod$1 = z$1.string().regex(QualifiedSequenceRegex$1).transform((v) => toHex(v));
71761
- z$1.union([LocalSequenceToStringZod$1, QualifiedSequenceToStringZod$1]);
71762
- var SequenceFromStringZod = z$1.union([LocalSequenceFromStringZod$1, QualifiedSequenceFromStringZod$1]);
71763
-
71764
- // src/PayloadZod.ts
71765
- var HashMetaZod = z$1.object({
71766
- _hash: HashZod,
71767
- _dataHash: HashZod
71768
- });
71769
- var isHashMeta = zodIsFactory(HashMetaZod);
71770
- var asHashMeta = zodAsFactory(HashMetaZod, "asHashMeta");
71771
- z$1.object({ _sequence: SequenceFromStringZod });
71772
- var StorageMetaZod = z$1.object({
71773
- _hash: HashZod,
71774
- _dataHash: HashZod,
71775
- _sequence: SequenceFromStringZod
71776
- });
71777
- var isStorageMeta = zodIsFactory(StorageMetaZod);
71778
- var PayloadZod = z$1.object({ schema: SchemaZod });
71779
- PayloadZod.extend(StorageMetaZod.shape);
71780
- var AnyPayloadZod = PayloadZod.loose();
71781
- AnyPayloadZod.extend(StorageMetaZod.shape);
71782
- function WithStorageMetaZod$1(valueZod) {
71783
- return valueZod.extend(StorageMetaZod.shape);
71784
- }
71785
- function WithHashMetaZod$1(valueZod) {
71786
- return valueZod.extend(HashMetaZod.shape);
71787
- }
71788
- var PayloadZodStrict = z$1.strictObject({ schema: SchemaZod });
71789
- var PayloadZodLoose = z$1.looseObject({ schema: SchemaZod });
71790
- var PayloadZodOfSchema = (schema) => PayloadZod.extend({ schema: z$1.literal(schema) });
71791
- var PayloadZodStrictOfSchema = (schema) => PayloadZodStrict.extend({ schema: z$1.literal(schema) });
71792
- var PayloadZodLooseOfSchema = (schema) => PayloadZodLoose.extend({ schema: z$1.literal(schema) });
71793
-
71794
- // src/PayloadBundle.ts
71795
- var PayloadBundleSchema = asSchema("network.xyo.payload.bundle", true);
71796
- var PayloadBundleFieldsZod = z$1.object({
71797
- payloads: PayloadZodLoose.array(),
71798
- root: HashZod
71799
- });
71800
- var PayloadBundleZod = PayloadZodOfSchema(PayloadBundleSchema).extend(PayloadBundleFieldsZod.shape);
71801
- var isPayloadBundle = zodIsFactory(PayloadBundleZod);
71802
-
71803
- // src/PayloadSet/PayloadSetSchema.ts
71804
- asSchema("network.xyo.payload.set", true);
71805
-
71806
- // src/Config/Config.ts
71807
- var ModuleConfigSchema = asSchema("network.xyo.module.config", true);
71808
-
71809
- // src/CreatableModule/CreatableModule.ts
71810
- function creatableModule() {
71811
- return (constructor) => {
71812
- };
71813
- }
71814
- function labeledCreatableModule() {
71815
- return (constructor) => {
71816
- };
71817
- }
71818
- var buildModuleFactory = (mod, labels) => {
71819
- const factory5 = {
71820
- // Destructure instance properties
71821
- ...mod,
71822
- configSchemas: mod.configSchemas,
71823
- // Copy static methods
71824
- create: mod.create.bind(mod),
71825
- defaultConfigSchema: mod.defaultConfigSchema,
71826
- // Merge module & supplied labels
71827
- labels: { ...mod.labels, ...labels }
71828
- };
71829
- return factory5;
71830
- };
71831
- var registerCreatableModuleFactory = (registry, factory5, labels, primary = false) => {
71832
- const primarySchemas = primary !== true && isTruthy(primary) ? Array.isArray(primary) ? primary : [primary] : [];
71833
- for (const primarySchema of primarySchemas) {
71834
- if (!factory5.configSchemas.includes(primarySchema)) {
71835
- console.warn(`Primary schema ${primary} not found in factory configSchemas`);
71836
- }
71837
- }
71838
- const isPrimaryForSchema = (schema) => {
71839
- switch (typeof primary) {
71840
- case "boolean": {
71841
- return primary;
71842
- }
71843
- case "string": {
71844
- return schema === primary;
71845
- }
71846
- case "object": {
71847
- if (Array.isArray(primary)) {
71848
- return primary.includes(schema);
71849
- }
71850
- }
71851
- }
71852
- throw new Error(`Invalid primary value: ${primary}`);
71853
- };
71854
- const factoryClone = buildModuleFactory(factory5, labels);
71855
- registry[factory5.defaultConfigSchema] = [factoryClone, ...registry[factoryClone.defaultConfigSchema] ?? []];
71856
- for (const schema of factoryClone.configSchemas) {
71857
- registry[schema] = isPrimaryForSchema(schema) ? [factoryClone, ...registry[schema] ?? []] : [...registry[schema] ?? [], factoryClone];
71858
- }
71859
- };
71860
- var registerCreatableModuleFactories = (factories, registry = {}, primary = false) => {
71861
- for (const factory5 of factories) {
71862
- registerCreatableModuleFactory(registry, factory5, void 0, primary);
71863
- }
71864
- return registry;
71865
- };
71866
-
71867
- // src/CreatableModule/LabeledCreatableModuleFactory.ts
71868
- var hasLabels$1 = (factory5) => {
71869
- return factory5.labels !== void 0;
71870
- };
71871
- var ModuleFactory = class _ModuleFactory {
71872
- configSchemas;
71873
- creatableModule;
71874
- defaultConfigSchema;
71875
- defaultLogger;
71876
- defaultParams;
71877
- labels;
71878
- constructor(creatableModule2, params, labels = {}) {
71879
- this.creatableModule = creatableModule2;
71880
- this.defaultParams = params;
71881
- this.configSchemas = creatableModule2.configSchemas;
71882
- this.defaultConfigSchema = creatableModule2.defaultConfigSchema;
71883
- assertEx(this.configSchemas.includes(this.defaultConfigSchema), () => "defaultConfigSchema must be in configSchemas");
71884
- this.labels = Object.assign({}, creatableModule2.labels ?? {}, labels ?? {});
71885
- }
71886
- static withParams(creatableModule2, params, labels = {}) {
71887
- return new _ModuleFactory(creatableModule2, params, labels);
71888
- }
71889
- create(params) {
71890
- const mergedParams = {
71891
- ...this.defaultParams,
71892
- ...params,
71893
- config: {
71894
- schema: this.creatableModule.defaultConfigSchema,
71895
- ...this.defaultParams?.config,
71896
- ...params?.config
71897
- }
71898
- };
71899
- return this.creatableModule.create(mergedParams);
71900
- }
71901
- factory(params, labels = {}) {
71902
- return new _ModuleFactory(this.creatableModule, params, labels);
71903
- }
71904
- };
71905
- var ModuleManifestQuerySchema = asSchema("network.xyo.query.module.manifest", true);
71906
- var ModuleAddressQuerySchema = asSchema("network.xyo.query.module.address", true);
71907
- var ModuleStateQuerySchema = asSchema("network.xyo.query.module.state", true);
71908
- var ModuleSubscribeQuerySchema = asSchema("network.xyo.query.module.subscribe", true);
71909
- var requiredModuleShape = {
71910
- address: "string",
71911
- queries: "array",
71912
- query: "function"
71913
- };
71914
- var factory$6 = new IsObjectFactory();
71915
- var isModuleObject = factory$6.create(requiredModuleShape);
71916
-
71917
- // src/module/asModuleObject.ts
71918
- var asModuleObject = AsObjectFactory.create(isModuleObject);
71919
-
71920
- // src/module/IsModuleFactory.ts
71921
- var IsModuleFactory = class {
71922
- create(expectedQueries, additionalChecks) {
71923
- const result = (obj, config) => {
71924
- const mod = asModuleObject(obj);
71925
- return isModuleObject(mod, config) && (expectedQueries?.reduce((prev, query) => prev && mod.queries.includes(query), true) ?? true) && (additionalChecks?.reduce((prev, check) => prev && check(obj, config), true) ?? true);
71926
- };
71927
- return result;
71928
- }
71929
- };
71930
-
71931
- // src/module/isModule.ts
71932
- var requiredModuleQueries = [ModuleStateQuerySchema];
71933
- var factory2 = new IsModuleFactory();
71934
- var isModule = factory2.create(requiredModuleQueries, [isModuleObject]);
71935
-
71936
- // src/instance/isModuleInstance.ts
71937
- var requiredModuleInstanceFunctions = {
71938
- manifest: "function",
71939
- state: "function"
71940
- };
71941
- var factory3 = new IsObjectFactory();
71942
- var isModuleInstance = factory3.create(requiredModuleInstanceFunctions, [isModule]);
71943
-
71944
- // src/instance/asModuleInstance.ts
71945
- var asModuleInstance = AsObjectFactory.create(isModuleInstance);
71946
- var requiredAttachableModuleInstanceFunctions = {
71947
- downResolver: "object",
71948
- upResolver: "object"
71949
- };
71950
- var factory4 = new IsObjectFactory();
71951
- var isAttachableModuleInstance = factory4.create(requiredAttachableModuleInstanceFunctions, [
71952
- isModuleInstance
71953
- ]);
71954
-
71955
- // src/instance/attachable/asAttachableInstance.ts
71956
- var asAttachableModuleInstance = AsObjectFactory.create(isAttachableModuleInstance);
71957
- var DeadModuleError = class _DeadModuleError extends Error {
71958
- error;
71959
- id;
71960
- constructor(id, error, msg = "Dead Module Error") {
71961
- super(`${msg} [${id}]: ${error?.message ?? toSafeJsonString(error)}`);
71962
- this.id = id;
71963
- this.error = error;
71964
- Object.setPrototypeOf(this, _DeadModuleError.prototype);
71965
- }
71966
- };
71967
- var IsInstanceFactory = class extends IsObjectFactory {
71968
- };
71969
- var ObjectResolverPriority = {
71970
- VeryLow: 0,
71971
- Low: 1,
71972
- Normal: 2,
71973
- VeryHigh: 4
71974
- };
71975
-
71976
- // src/Labels/Labels.ts
71977
- var hasAllLabels = (source, required) => {
71978
- if (!required) return true;
71979
- return Object.entries(required).every(([key, value]) => {
71980
- return source?.hasOwnProperty(key) && source?.[key] === value;
71981
- });
71982
- };
71983
- var ModuleLimitationViewLabel = { ModuleLimitationLabelName: "view" };
71984
-
71985
- // src/lib/duplicateModules.ts
71986
- var duplicateModules = (value, index, array) => {
71987
- return array.findIndex((v) => v.address === value.address) === index;
71988
- };
71989
-
71990
- // src/lib/serializable.ts
71991
- var isSerializable = (value, maxDepth = 10) => {
71992
- if (maxDepth <= 0) {
71993
- return false;
71994
- }
71995
- if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
71996
- return true;
71997
- }
71998
- if (Array.isArray(value)) {
71999
- return value.every((item) => isSerializable(item, maxDepth - 1));
72000
- }
72001
- if (typeof value === "object") {
72002
- if (value instanceof Date || value instanceof RegExp) {
72003
- return true;
72004
- }
72005
- if (value instanceof Set || value instanceof Map) {
72006
- return false;
72007
- }
72008
- if (value !== null && value !== void 0) {
72009
- return Object.values(value).every((item) => isSerializable(item, maxDepth - 1));
72010
- }
72011
- }
72012
- return false;
72013
- };
72014
- var MODULE_PATH_SEPARATOR = ":";
72015
- var DisallowedModuleIdentifierCharacters = {
72016
- " ": true,
72017
- "!": true,
72018
- '"': true,
72019
- "#": true,
72020
- "$": true,
72021
- "%": true,
72022
- "&": true,
72023
- "'": true,
72024
- "(": true,
72025
- ")": true,
72026
- "*": true,
72027
- ",": true,
72028
- ".": true,
72029
- "/": true,
72030
- ":": true,
72031
- ";": true,
72032
- "<": true,
72033
- "=": true,
72034
- ">": true,
72035
- "?": true,
72036
- "@": true,
72037
- "[": true,
72038
- "]": true,
72039
- "^": true,
72040
- "_": true,
72041
- "{": true,
72042
- "|": true,
72043
- "}": true,
72044
- "~": true
72045
- };
72046
- var ReservedModuleIdentifierCharacters = new Set(
72047
- Object.keys(DisallowedModuleIdentifierCharacters)
72048
- );
72049
- var isModuleName = (value) => {
72050
- return typeof value === "string" && !isAddress(value) && !includesReservedModuleIdentifierCharacter(value);
72051
- };
72052
- var includesReservedModuleIdentifierCharacter = (value) => {
72053
- return typeof value === "string" && [...value].some((char) => ReservedModuleIdentifierCharacters.has(char));
72054
- };
72055
- var AddressSchema = asSchema("network.xyo.address", true);
72056
- asSchema("network.xyo.address.child", true);
72057
- var AddressPreviousHashSchema = asSchema("network.xyo.address.hash.previous", true);
72058
- var ModuleDescriptionSchema = asSchema("network.xyo.module.description", true);
72059
- asSchema("network.xyo.module.state", true);
72060
-
72061
- // src/ResolveHelper/resolveAddressToInstance.ts
72062
- var resolveAddressToInstanceDown = async (root, address, includePrivate = void 0, ignore = []) => {
72063
- if (root.address === address) {
72064
- return root;
72065
- }
72066
- const cache = root.addressCache?.("up", !!includePrivate);
72067
- const privateChildren = (includePrivate ? await root.privateChildren?.() : []) ?? [];
72068
- const publicChildren = await root.publicChildren?.() ?? [];
72069
- const children = [...privateChildren, ...publicChildren];
72070
- for (const child of children) {
72071
- const found = await resolveAddressToInstanceDown(child, address, includePrivate, ignore);
72072
- if (found) {
72073
- cache?.set(address, new WeakRef(found));
72074
- return found;
72075
- }
72076
- }
72077
- cache?.set(address, null);
72078
- };
72079
- var resolveAddressToInstanceUp = async (root, address, includePrivate = void 0, ignore = []) => {
72080
- const cache = root.addressCache?.("up", includePrivate ?? true);
72081
- const parents = await root.parents?.() ?? [];
72082
- for (const parent of parents) {
72083
- const found = await resolveAddressToInstance(parent, address, includePrivate, ignore);
72084
- if (found) {
72085
- cache?.set(address, new WeakRef(found));
72086
- return found;
72087
- }
72088
- }
72089
- cache?.set(address, null);
72090
- };
72091
- var resolveAddressToInstanceAll = async (root, address, includePrivate = void 0, ignore = []) => {
72092
- const cache = root.addressCache?.("all", !!includePrivate);
72093
- const result = await resolveAddressToInstanceDown(root, address, includePrivate ?? false, ignore) ?? await resolveAddressToInstanceUp(root, address, includePrivate ?? true, ignore);
72094
- cache?.set(address, result ? new WeakRef(result) : null);
72095
- return result;
72096
- };
72097
- var resolveAddressToInstance = async (root, address, includePrivate = void 0, ignore = [], direction = "all") => {
72098
- switch (direction) {
72099
- case "all": {
72100
- return await resolveAddressToInstanceAll(root, address, includePrivate, ignore);
72101
- }
72102
- case "up": {
72103
- return await resolveAddressToInstanceUp(root, address, includePrivate ?? true, ignore);
72104
- }
72105
- case "down": {
72106
- return await resolveAddressToInstanceDown(root, address, includePrivate ?? false, ignore);
72107
- }
72108
- }
72109
- };
72110
-
72111
- // src/ResolveHelper/resolveAll.ts
72112
- var resolveAllUp = async (root, maxDepth = 10, exclude = []) => {
72113
- if (maxDepth === 0) {
72114
- return [root].filter((mod) => !exclude.includes(mod.address));
72115
- }
72116
- const parents = (await root.parents()).filter((mod) => !exclude.includes(mod.address));
72117
- return (maxDepth > 1 ? [
72118
- ...(await Promise.all(parents.map(async (mod) => await resolveAllUp(mod, maxDepth - 1, [...exclude, root.address])))).flat(),
72119
- ...(await Promise.all(parents.map(async (mod) => await resolveAllDown(mod, maxDepth - 1, [...exclude, root.address], true)))).flat(),
72120
- ...parents,
72121
- root
72122
- ] : [...parents, root]).filter((mod) => !exclude.includes(mod.address)).filter(duplicateModules);
72123
- };
72124
- var resolveAllDown = async (root, maxDepth = 10, exclude = [], includePrivate = false) => {
72125
- if (maxDepth === 0) {
72126
- return [root];
72127
- }
72128
- const children = (await root.publicChildren()).filter((mod) => !exclude.includes(mod.address));
72129
- const privateChildren = includePrivate ? (await root.privateChildren()).filter((mod) => !exclude.includes(mod.address)) : [];
72130
- return (maxDepth > 1 ? [
72131
- ...children,
72132
- ...(await Promise.all(children.map((child) => resolveAllDown(child, maxDepth - 1, [...exclude, root.address])))).flat(),
72133
- ...(await Promise.all(privateChildren.map((child) => resolveAllDown(child, maxDepth - 1, [...exclude, root.address])))).flat(),
72134
- root
72135
- ] : [...children, root]).filter((mod) => !exclude.includes(mod.address)).filter(duplicateModules);
72136
- };
72137
- var resolveAll = async (root, maxDepth = 10, exclude = []) => {
72138
- if (maxDepth === 0) {
72139
- return [root];
72140
- }
72141
- return [...await resolveAllUp(root, maxDepth, exclude), ...await resolveAllDown(root, maxDepth, exclude)].filter(duplicateModules);
72142
- };
72143
-
72144
- // src/ResolveHelper/ResolveHelperStatic.ts
72145
- var ResolveHelperStatic = class {
72146
- static defaultLogger;
72147
- // eslint-disable-next-line sonarjs/public-static-readonly
72148
- static transformers = [];
72149
- };
72150
-
72151
- // src/ResolveHelper/resolveLocalNameToInstance.ts
72152
- var resolveLocalNameToInstanceUp = async (root, modName) => {
72153
- const parents = await root.parents?.() ?? [];
72154
- return parents.find((parent) => parent.config.name === modName);
72155
- };
72156
- var resolveLocalNameToInstanceDown = async (root, modName, includePrivate = void 0) => {
72157
- const privateChildren = (includePrivate ? await root.privateChildren?.() : []) ?? [];
72158
- const publicChildren = await root.publicChildren?.() ?? [];
72159
- const children = [...privateChildren, ...publicChildren];
72160
- return children.find((child) => child.config.name === modName);
72161
- };
72162
- var resolveLocalNameToInstanceAll = async (root, modName, includePrivate = false) => {
72163
- return await resolveLocalNameToInstanceDown(root, modName, includePrivate) ?? await resolveLocalNameToInstanceUp(root, modName);
72164
- };
72165
- var resolveLocalNameToInstance = async (root, modName, includePrivate = false, direction = "all") => {
72166
- switch (direction) {
72167
- case "all": {
72168
- return await resolveLocalNameToInstanceAll(root, modName, includePrivate);
72169
- }
72170
- case "up": {
72171
- return await resolveLocalNameToInstanceUp(root, modName);
72172
- }
72173
- case "down": {
72174
- return await resolveLocalNameToInstanceDown(root, modName, includePrivate);
72175
- }
72176
- }
72177
- };
72178
- var resolveLocalNameToAddress = async (root, modName, includePrivate = void 0, direction = "all") => {
72179
- return (await resolveLocalNameToInstance(root, modName, includePrivate, direction))?.address;
72180
- };
72181
-
72182
- // src/ResolveHelper/transformModuleIdentifier.ts
72183
- var transformModuleIdentifier = async (id, transformers) => {
72184
- let result = id;
72185
- for (const transformer of transformers) {
72186
- result = await transformer.transform(id);
72187
- }
72188
- return result;
72189
- };
72190
-
72191
- // src/ResolveHelper/resolvePathToInstance.ts
72192
- var resolvePathToInstance = async (root, path, includePrivate = void 0, transformers = ResolveHelperStatic.transformers) => {
72193
- const parts = path.split(MODULE_PATH_SEPARATOR);
72194
- const first = await transformModuleIdentifier(
72195
- assertEx(parts.shift(), () => `First part is invalid [${path}]`),
72196
- transformers
72197
- );
72198
- if (!first) {
72199
- return void 0;
72200
- }
72201
- const firstAddress = asAddress(first) ?? await resolveLocalNameToAddress(root, first, includePrivate);
72202
- if (firstAddress) {
72203
- const firstModule = await resolveAddressToInstance(root, firstAddress, includePrivate);
72204
- if (firstModule && parts.length > 0) {
72205
- return resolvePathToInstance(firstModule, parts.join(MODULE_PATH_SEPARATOR));
72206
- }
72207
- return firstModule;
72208
- }
72209
- };
72210
-
72211
- // src/ResolveHelper/resolvePathToAddress.ts
72212
- var resolvePathToAddress = async (root, path, includePrivate = void 0, transformers = ResolveHelperStatic.transformers) => {
72213
- return (await resolvePathToInstance(root, path, includePrivate, transformers))?.address;
72214
- };
72215
- var traceModuleIdentifier = async (resolver, path) => {
72216
- const parts = path.split(":");
72217
- const first = parts.shift();
72218
- const firstModule = asModuleInstance(
72219
- assertEx(await resolver.resolve(first, { maxDepth: 1 }), () => `Failed to resolve [${first}]`),
72220
- () => `Resolved invalid module instance [${first}]`
72221
- );
72222
- if (firstModule) {
72223
- return parts.length > 0 ? [firstModule.address, ...await traceModuleIdentifier(firstModule, parts.join(":"))] : [firstModule.address];
72224
- }
72225
- return [];
72226
- };
72227
-
72228
- // src/ResolveHelper/ResolveHelper.ts
72229
- var ResolveHelper = class _ResolveHelper extends ResolveHelperStatic {
72230
- static async resolve(config, id = "*", {
72231
- maxDepth = 3,
72232
- required = "log",
72233
- ...options
72234
- } = {}) {
72235
- const {
72236
- transformers,
72237
- mod,
72238
- logger = this.defaultLogger,
72239
- dead = false,
72240
- upResolver,
72241
- downResolver,
72242
- privateResolver
72243
- } = config;
72244
- const log = logger ? new IdLogger(logger, () => `ResolveHelper [${mod.id}][${id}]`) : void 0;
72245
- const downLocalOptions = {
72246
- ...options,
72247
- direction: "down",
72248
- maxDepth,
72249
- required: false
72250
- };
72251
- const upLocalOptions = { ...downLocalOptions, direction: "up" };
72252
- const childOptions = {
72253
- ...options,
72254
- maxDepth: maxDepth - 1,
72255
- required: false
72256
- };
72257
- const direction = options?.direction ?? "all";
72258
- const up = direction === "up" || direction === "all";
72259
- const down = direction === "down" || direction === "all";
72260
- let result;
72261
- log?.debug("start", id, maxDepth);
72262
- if (id === "*") {
72263
- if (dead) {
72264
- log?.warn("failed [dead]", id);
72265
- return [];
72266
- }
72267
- const modules = [
72268
- ...down ? await downResolver.resolve("*", downLocalOptions) : [],
72269
- ...up ? await upResolver.resolve("*", upLocalOptions) : []
72270
- ].filter(duplicateModules);
72271
- if (modules.length > 0) {
72272
- log?.debug("modules [count]", modules.length);
72273
- log?.debug("modules", toSafeJsonString(modules, 4));
72274
- }
72275
- if (maxDepth === 0) {
72276
- return modules;
72277
- }
72278
- const childModules = (await Promise.all(modules.map(async (mod2) => await mod2.resolve("*", childOptions)))).flat().filter(duplicateModules);
72279
- return [...modules, ...childModules, mod].filter(duplicateModules);
72280
- } else {
72281
- switch (typeof id) {
72282
- case "string": {
72283
- if (dead) {
72284
- return void 0;
72285
- }
72286
- const resolvedId = assertEx(await resolvePathToAddress(mod, id, false, transformers) ?? id, () => "Invalid resolvedId");
72287
- const resolvers = [
72288
- [downResolver, downLocalOptions],
72289
- [up ? upResolver : void 0, upLocalOptions],
72290
- [up ? privateResolver : void 0, upLocalOptions]
72291
- ].filter(([resolver]) => exists$2(resolver));
72292
- for (const resolver of resolvers) {
72293
- const [resolverInstance] = resolver;
72294
- if (!result) {
72295
- result = await this.resolveModuleIdentifier(resolverInstance, resolvedId);
72296
- }
72297
- }
72298
- break;
72299
- }
72300
- }
72301
- }
72302
- this.validateRequiredResolve(required, result, id, logger);
72303
- return result;
72304
- }
72305
- // resolves a complex module path to addresses
72306
- static async resolveModuleIdentifier(resolver, path, required) {
72307
- const parts = path.split(":");
72308
- const first = parts.shift();
72309
- const firstIsAddress = isAddress(first);
72310
- const resolvedModule = await resolver.resolve(first, { maxDepth: firstIsAddress ? 10 : 1 }) ?? (isString$1(first) ? await resolver.resolvePrivate(first, { maxDepth: firstIsAddress ? 10 : 1 }) : void 0);
72311
- const finalModule = required ? assertEx(resolvedModule, () => `Failed to resolve [${first}] [${firstIsAddress}]`) : resolvedModule;
72312
- const firstModule = asModuleInstance(finalModule, () => `Resolved invalid module instance [${first}]`);
72313
- return isDefined(firstModule) ? parts.length > 0 ? await this.resolveModuleIdentifier(firstModule, parts.join(":")) : firstModule : void 0;
72314
- }
72315
- // translates a complex module path to addresses
72316
- static traceModuleIdentifier(resolver, path) {
72317
- return traceModuleIdentifier(resolver, path);
72318
- }
72319
- static transformModuleIdentifier(identifier, transformers = _ResolveHelper.transformers) {
72320
- return transformModuleIdentifier(identifier, transformers);
72321
- }
72322
- static validateRequiredResolve(required, result, id, logger = this.defaultLogger) {
72323
- const log = logger ? new IdLogger(logger, () => `validateRequiredResolve [${id}][${result}]`) : void 0;
72324
- if (isTruthy(required) && (result === void 0 || Array.isArray(result) && result.length > 0)) {
72325
- switch (required) {
72326
- case "warn": {
72327
- log?.warn("resolve failed", id);
72328
- break;
72329
- }
72330
- case "log": {
72331
- log?.log("resolve failed", id);
72332
- break;
72333
- }
72334
- default: {
72335
- throw new Error(`resolve failed [${id}]`);
72336
- }
72337
- }
72338
- }
72339
- }
72340
- };
72341
-
72342
- // src/BoundWitness/BoundWitness.ts
72343
- var BoundWitnessSchema = asSchema("network.xyo.boundwitness", true);
72344
- var SignaturesMetaZod = z$1.object({ $signatures: z$1.array(z$1.union([HexZod, z$1.null()])) });
72345
- var UnsignedSignaturesMetaZod = z$1.object({ $signatures: z$1.array(z$1.null()) });
72346
- var SignedSignaturesMetaZod = z$1.object({ $signatures: z$1.array(HexZod).min(1) });
72347
-
72348
- // src/BoundWitness/BoundWitness.ts
72349
- var BoundWitnessRequiredFieldsZod = z$1.object({
72350
- addresses: z$1.array(AddressZod),
72351
- payload_hashes: z$1.array(HashZod),
72352
- payload_schemas: z$1.array(SchemaZod),
72353
- previous_hashes: z$1.array(HashZod.nullable())
72354
- });
72355
- var BoundWitnessMetaZod = z$1.object({
72356
- $destination: AddressZod.optional(),
72357
- $sourceQuery: HashZod.optional()
72358
- }).extend(SignaturesMetaZod.shape);
72359
- var BoundWitnessZod = PayloadZod.safeExtend({ schema: z$1.literal(BoundWitnessSchema) }).safeExtend(BoundWitnessRequiredFieldsZod.shape).safeExtend(BoundWitnessMetaZod.shape);
72360
- var isBoundWitness = zodIsFactory(BoundWitnessZod);
72361
- var asBoundWitness = zodAsFactory(BoundWitnessZod, "asBoundWitness");
72362
- BoundWitnessZod.loose();
72363
-
72364
- // src/BoundWitness/SignedBoundWitness.ts
72365
- var SignedBoundWitnessZod = BoundWitnessZod.extend(SignedSignaturesMetaZod.shape);
72366
- SignedBoundWitnessZod.loose();
72367
-
72368
- // src/BoundWitness/UnsignedBoundWitness.ts
72369
- var UnsignedBoundWitnessZod = BoundWitnessZod.extend(UnsignedSignaturesMetaZod.shape);
72370
- UnsignedBoundWitnessZod.loose();
72371
- var isQueryBoundWitness = (x) => isBoundWitness(x) && x?.query !== void 0;
72372
-
72373
72373
  var srcExports = requireSrc$1();
72374
72374
  var debug$3 = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
72375
72375
 
@@ -84255,6 +84255,7 @@ var SignedHydratedTransactionZod = tuple([
84255
84255
  SignedTransactionBoundWitnessZod,
84256
84256
  array$1(PayloadZodLoose)
84257
84257
  ]);
84258
+ var isSignedHydratedTransaction = zodIsFactory(SignedHydratedTransactionZod);
84258
84259
  var asSignedHydratedTransaction = zodAsFactory(SignedHydratedTransactionZod, "asSignedHydratedTransaction");
84259
84260
  var SignedHydratedTransactionWithHashMetaZod = tuple([
84260
84261
  WithHashMetaZod$1(SignedTransactionBoundWitnessZod),
@@ -84603,9 +84604,6 @@ var StorageConfigZod = object$4({
84603
84604
  type: "string"
84604
84605
  })
84605
84606
  }).describe("Storage configuration options");
84606
- var DefaultMetricsScrapePorts = {
84607
- api: 9465,
84608
- mempool: 9466};
84609
84607
  var MetricsScrapeConfigZod = object$4({
84610
84608
  path: string$2().default("/metrics").register(globalRegistry, {
84611
84609
  default: "/metrics",
@@ -84961,7 +84959,6 @@ var ActorsConfigZod = object$4({
84961
84959
  rewardRedemption: RewardRedemptionConfigZod.parse({})
84962
84960
  });
84963
84961
  var ConfigZod = BaseConfigZod.extend(object$4({ actors: ActorsConfigZod.default(ActorsConfigZod.parse({})) }).describe("Actor-specific configurations that override the base configuration when the actor is running").shape);
84964
- var getDefaultConfig = () => ConfigZod.parse({});
84965
84962
  var DescriptionSchema = string$2();
84966
84963
  var TitleSchema = string$2();
84967
84964
  var JSONSchemaMetaSchema = object$4({
@@ -85357,7 +85354,7 @@ var Actor = class extends AbstractCreatable {
85357
85354
  // eslint-disable-next-line @typescript-eslint/no-deprecated
85358
85355
  static initContext(params) {
85359
85356
  const logger = params?.context?.logger;
85360
- const config = params?.context?.config ?? getDefaultConfig();
85357
+ const config = params?.context?.config ?? ConfigZod.parse({});
85361
85358
  const singletons = params?.context?.singletons ?? {};
85362
85359
  const locator = params.context?.locator ?? new ProviderFactoryLocator({
85363
85360
  ...params?.context,
@@ -87804,11 +87801,17 @@ var SimpleXyoGatewayRunner = class _SimpleXyoGatewayRunner extends AbstractCreat
87804
87801
  const connection = this.connection;
87805
87802
  const signer = this.signer;
87806
87803
  const runner = assertEx(connection.runner, () => "No runner available on connection");
87807
- const signedTx = await signer.signTransaction(tx);
87804
+ let signedTx;
87805
+ if (isSignedHydratedTransaction(tx)) {
87806
+ const [bw, payloads] = tx;
87807
+ const hashedBw = await PayloadBuilder.addHashMeta(bw);
87808
+ const hashedPayloads = await PayloadBuilder.addHashMeta(payloads);
87809
+ signedTx = [hashedBw, hashedPayloads];
87810
+ } else {
87811
+ signedTx = await signer.signTransaction(tx);
87812
+ }
87808
87813
  await this.addPayloadsToDataLakes([...signedTx[1], ...offChain ?? [], signedTx[0]]);
87809
- return [await runner.broadcastTransaction(
87810
- [signedTx[0], signedTx[1]]
87811
- ), signedTx];
87814
+ return [await runner.broadcastTransaction([signedTx[0], signedTx[1]]), signedTx];
87812
87815
  }
87813
87816
  async confirmSubmittedTransaction(txHash, options) {
87814
87817
  return await confirmSubmittedTransaction(
@@ -92216,6 +92219,18 @@ var createRequestSchema = (methodName, paramsSchema = _undefined()) => object$4(
92216
92219
  method: literal$2(methodName),
92217
92220
  params: paramsSchema
92218
92221
  });
92222
+ var FinalizationViewerRpcSchemas = {
92223
+ finalizationViewer_head: {
92224
+ params: {
92225
+ to: array$1(any$1()).length(0).optional(),
92226
+ from: array$1(any$1()).length(0).optional()
92227
+ },
92228
+ result: {
92229
+ to: SignedHydratedBlockWithHashMetaZod,
92230
+ from: SignedHydratedBlockWithHashMetaZod
92231
+ }
92232
+ }
92233
+ };
92219
92234
 
92220
92235
  // src/engine-node/rpcEngineFromConnection.ts
92221
92236
  var rpcEngineFromConnection = (connection) => {
@@ -92449,6 +92464,38 @@ __publicField$3(JsonRpcBlockViewer, "monikers", [BlockViewerMoniker]);
92449
92464
  JsonRpcBlockViewer = __decorateClass$3([
92450
92465
  creatableProvider()
92451
92466
  ], JsonRpcBlockViewer);
92467
+ var JsonRpcFinalizationViewerMethods = class extends AbstractJsonRpcViewer {
92468
+ moniker = FinalizationViewerMoniker;
92469
+ async head() {
92470
+ const result = await this.transport.sendRequest(
92471
+ "finalizationViewer_head",
92472
+ []
92473
+ );
92474
+ return result;
92475
+ }
92476
+ schemas() {
92477
+ return FinalizationViewerRpcSchemas;
92478
+ }
92479
+ };
92480
+
92481
+ // src/provider/viewer/JsonRpcFinalizationViewer/JsonRpcFinalizationViewer.ts
92482
+ var JsonRpcFinalizationViewer = class extends JsonRpcFinalizationViewerMethods {
92483
+ async headBlock() {
92484
+ return (await this.head())[0];
92485
+ }
92486
+ async headHash() {
92487
+ return (await this.head())[0]._hash;
92488
+ }
92489
+ async headNumber() {
92490
+ return (await this.head())[0].block;
92491
+ }
92492
+ };
92493
+ __publicField$3(JsonRpcFinalizationViewer, "defaultMoniker", FinalizationViewerMoniker);
92494
+ __publicField$3(JsonRpcFinalizationViewer, "dependencies", []);
92495
+ __publicField$3(JsonRpcFinalizationViewer, "monikers", [FinalizationViewerMoniker]);
92496
+ JsonRpcFinalizationViewer = __decorateClass$3([
92497
+ creatableProvider()
92498
+ ], JsonRpcFinalizationViewer);
92452
92499
  var JsonRpcMempoolViewerMethods = class extends AbstractJsonRpcViewer {
92453
92500
  moniker = MempoolViewerMoniker;
92454
92501
  async pendingBlocks(options) {
@@ -93442,8 +93489,8 @@ __publicField$2(NodeXyoViewer, "getArchivist", async (node, identifier) => {
93442
93489
  NodeXyoViewer = __decorateClass$2([
93443
93490
  creatableProvider()
93444
93491
  ], NodeXyoViewer);
93445
- var SimpleXyoConnection = class extends AbstractCreatableProvider {
93446
- moniker = SimpleXyoConnection.defaultMoniker;
93492
+ var SimpleXyoConnectionRunner = class extends AbstractCreatableProvider {
93493
+ moniker = SimpleXyoConnectionRunner.defaultMoniker;
93447
93494
  _network;
93448
93495
  _runner;
93449
93496
  _storage;
@@ -93469,15 +93516,15 @@ var SimpleXyoConnection = class extends AbstractCreatableProvider {
93469
93516
  this._storage = dataLakeRunner ?? dataLakeViewer;
93470
93517
  }
93471
93518
  };
93472
- __publicField$2(SimpleXyoConnection, "defaultMoniker", XyoConnectionMoniker);
93473
- __publicField$2(SimpleXyoConnection, "dependencies", [XyoRunnerMoniker, XyoViewerMoniker, DataLakeRunnerMoniker, DataLakeViewerMoniker]);
93474
- __publicField$2(SimpleXyoConnection, "monikers", [XyoConnectionMoniker]);
93475
- SimpleXyoConnection = __decorateClass$2([
93519
+ __publicField$2(SimpleXyoConnectionRunner, "defaultMoniker", XyoConnectionMoniker);
93520
+ __publicField$2(SimpleXyoConnectionRunner, "dependencies", [XyoRunnerMoniker, XyoViewerMoniker, DataLakeRunnerMoniker, DataLakeViewerMoniker]);
93521
+ __publicField$2(SimpleXyoConnectionRunner, "monikers", [XyoConnectionMoniker]);
93522
+ SimpleXyoConnectionRunner = __decorateClass$2([
93476
93523
  creatableProvider()
93477
- ], SimpleXyoConnection);
93524
+ ], SimpleXyoConnectionRunner);
93478
93525
  var registerGatewayWithLocator = (locator, account) => {
93479
93526
  locator.registerMany([
93480
- SimpleXyoConnection.factory(SimpleXyoConnection.dependencies, {}),
93527
+ SimpleXyoConnectionRunner.factory(SimpleXyoConnectionRunner.dependencies, {}),
93481
93528
  SimpleXyoGateway.factory(SimpleXyoGateway.dependencies, {})
93482
93529
  ]);
93483
93530
  if (account) {
@@ -93979,23 +94026,6 @@ function buildProviderLocator({ context = getEmptyProviderContext(ConfigZod.pars
93979
94026
  caches
93980
94027
  }, locator?.registry);
93981
94028
  }
93982
- function buildSimpleProviderLocator(params) {
93983
- const locator = buildProviderLocator(params);
93984
- const positions = [];
93985
- locator.registerMany([
93986
- SimpleStakeViewer.factory(SimpleStakeViewer.dependencies, { positions }),
93987
- SimpleStakeEventsViewer.factory(SimpleStakeEventsViewer.dependencies, { positions }),
93988
- SimpleNetworkStakeViewer.factory(SimpleNetworkStakeViewer.dependencies, {}),
93989
- SimpleTimeSyncViewer.factory(SimpleTimeSyncViewer.dependencies, {}),
93990
- SimpleStepViewer.factory(SimpleStepViewer.dependencies, {}),
93991
- SimpleStepRewardsViewer.factory(SimpleStepRewardsViewer.dependencies, {}),
93992
- SimpleStepRewardsByPositionViewer.factory(SimpleStepRewardsByPositionViewer.dependencies, {}),
93993
- SimpleStepRewardsByStakerViewer.factory(SimpleStepRewardsByStakerViewer.dependencies, {}),
93994
- SimpleStepRewardsByStepViewer.factory(SimpleStepRewardsByStepViewer.dependencies, {}),
93995
- SimpleStepRewardsTotalViewer.factory(SimpleStepRewardsTotalViewer.dependencies, {})
93996
- ]);
93997
- return registerGatewayWithLocator(locator, params?.signerAccount);
93998
- }
93999
94029
  async function buildJsonRpcProviderLocator(params) {
94000
94030
  const locator = buildProviderLocator(params);
94001
94031
  const transportFactory = params.transportFactory;
@@ -94030,28 +94060,33 @@ async function buildJsonRpcProviderLocator(params) {
94030
94060
  ]);
94031
94061
  return registerGatewayWithLocator(locator, params?.signerAccount);
94032
94062
  }
94033
- function buildLocalProviderLocator(params) {
94034
- const locator = buildSimpleProviderLocator(params);
94035
- const {
94036
- pendingTransactionsArchivist,
94037
- pendingBlocksArchivist,
94038
- balancesSummaryMap,
94039
- transfersSummaryMap,
94040
- finalizedArchivist,
94041
- node
94042
- } = params;
94043
- locator.registerMany([
94044
- SimpleMempoolViewer.factory(SimpleMempoolViewer.dependencies, { pendingTransactionsArchivist, pendingBlocksArchivist }),
94045
- SimpleMempoolRunner.factory(SimpleMempoolRunner.dependencies, { pendingTransactionsArchivist, pendingBlocksArchivist }),
94046
- SimpleAccountBalanceViewer.factory(SimpleAccountBalanceViewer.dependencies, { balancesSummaryMap, transfersSummaryMap }),
94047
- SimpleFinalizationViewer.factory(SimpleFinalizationViewer.dependencies, { finalizedArchivist }),
94048
- SimpleBlockViewer.factory(SimpleBlockViewer.dependencies, { finalizedArchivist }),
94049
- SimpleXyoRunner.factory(SimpleXyoRunner.dependencies, {}),
94050
- SimpleWindowedBlockViewer.factory(SimpleWindowedBlockViewer.dependencies, { maxWindowSize: 1e4, syncInterval: 1e4 }),
94051
- NodeXyoViewer.factory(NodeXyoViewer.dependencies, { node })
94052
- ]);
94053
- return registerGatewayWithLocator(locator, params?.signerAccount);
94054
- }
94063
+ var SimpleXyoConnectionViewer = class extends AbstractCreatableProvider {
94064
+ moniker = SimpleXyoConnectionViewer.defaultMoniker;
94065
+ _network;
94066
+ _storage;
94067
+ _viewer;
94068
+ get network() {
94069
+ return this._network;
94070
+ }
94071
+ get storage() {
94072
+ return this._storage;
94073
+ }
94074
+ get viewer() {
94075
+ return this._viewer;
94076
+ }
94077
+ async createHandler() {
94078
+ await super.createHandler();
94079
+ this._viewer = await this.locator.getInstance(XyoViewerMoniker);
94080
+ const dataLakeViewer = await this.locator.tryGetInstance(DataLakeViewerMoniker);
94081
+ this._storage = dataLakeViewer;
94082
+ }
94083
+ };
94084
+ __publicField$2(SimpleXyoConnectionViewer, "defaultMoniker", XyoConnectionMoniker);
94085
+ __publicField$2(SimpleXyoConnectionViewer, "dependencies", [XyoRunnerMoniker, XyoViewerMoniker, DataLakeRunnerMoniker, DataLakeViewerMoniker]);
94086
+ __publicField$2(SimpleXyoConnectionViewer, "monikers", [XyoConnectionMoniker]);
94087
+ SimpleXyoConnectionViewer = __decorateClass$2([
94088
+ creatableProvider()
94089
+ ], SimpleXyoConnectionViewer);
94055
94090
 
94056
94091
  // src/boundwitness/BlockBoundWitness.ts
94057
94092
  var BlockBoundWitnessJsonSchema = {
@@ -161993,11 +162028,6 @@ var expressMungExports = requireExpressMung();
161993
162028
  var mung = /*@__PURE__*/getDefaultExportFromCjs(expressMungExports);
161994
162029
 
161995
162030
  // src/Handler/asyncHandler.ts
161996
- function asyncHandler(fn) {
161997
- return (req, res, next) => {
161998
- return Promise.resolve(fn(req, res, next)).catch(next);
161999
- };
162000
- }
162001
162031
  var {
162002
162032
  colorize,
162003
162033
  combine,
@@ -175875,13 +175905,13 @@ var createGenesisBlock = /* @__PURE__ */ __name$e(async (initialBlockProducer, n
175875
175905
 
175876
175906
  // src/block/buildRandomChain.ts
175877
175907
  assertEx(asAddress("fa7f0bb865a4bfff3d5e2c726d3e063297014da9"));
175878
- function _ts_decorate$6(decorators, target, key, desc) {
175908
+ function _ts_decorate$9(decorators, target, key, desc) {
175879
175909
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
175880
175910
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
175881
175911
  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;
175882
175912
  return c > 3 && r && Object.defineProperty(target, key, r), r;
175883
175913
  }
175884
- __name$e(_ts_decorate$6, "_ts_decorate");
175914
+ __name$e(_ts_decorate$9, "_ts_decorate");
175885
175915
  var SynchronousLmdbMap = class extends AbstractCreatable {
175886
175916
  static {
175887
175917
  __name$e(this, "SynchronousLmdbMap");
@@ -175945,7 +175975,7 @@ var SynchronousLmdbMap = class extends AbstractCreatable {
175945
175975
  });
175946
175976
  }
175947
175977
  };
175948
- SynchronousLmdbMap = _ts_decorate$6([
175978
+ SynchronousLmdbMap = _ts_decorate$9([
175949
175979
  creatable()
175950
175980
  ], SynchronousLmdbMap);
175951
175981
  function _ts_decorate2$4(decorators, target, key, desc) {
@@ -198526,13 +198556,13 @@ var AbstractEvmRunner = class extends AbstractEvmViewer {
198526
198556
  };
198527
198557
  }
198528
198558
  };
198529
- function _ts_decorate$5(decorators, target, key, desc) {
198559
+ function _ts_decorate$8(decorators, target, key, desc) {
198530
198560
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
198531
198561
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
198532
198562
  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;
198533
198563
  return c > 3 && r && Object.defineProperty(target, key, r), r;
198534
198564
  }
198535
- __name$d(_ts_decorate$5, "_ts_decorate");
198565
+ __name$d(_ts_decorate$8, "_ts_decorate");
198536
198566
  var EvmChainContractViewer = class _EvmChainContractViewer extends AbstractEvmViewer {
198537
198567
  static {
198538
198568
  __name$d(this, "EvmChainContractViewer");
@@ -198615,7 +198645,7 @@ var EvmChainContractViewer = class _EvmChainContractViewer extends AbstractEvmVi
198615
198645
  return IStakedXyoChain__factory.connect(address, this.params.provider);
198616
198646
  }
198617
198647
  };
198618
- EvmChainContractViewer = _ts_decorate$5([
198648
+ EvmChainContractViewer = _ts_decorate$8([
198619
198649
  creatableProvider()
198620
198650
  ], EvmChainContractViewer);
198621
198651
  function _ts_decorate2$3(decorators, target, key, desc) {
@@ -198636,7 +198666,7 @@ var EvmStakeRunner = class _EvmStakeRunner extends AbstractEvmRunner {
198636
198666
  ];
198637
198667
  moniker = _EvmStakeRunner.defaultMoniker;
198638
198668
  async addStake(staked, amount) {
198639
- const result = await this.contract.addStake(getAddress$2(toEthAddress(staked)), amount);
198669
+ const result = await this.contract.addStake(getAddress(toEthAddress(staked)), amount);
198640
198670
  await result.wait();
198641
198671
  return true;
198642
198672
  }
@@ -198657,13 +198687,13 @@ var EvmStakeRunner = class _EvmStakeRunner extends AbstractEvmRunner {
198657
198687
  EvmStakeRunner = _ts_decorate2$3([
198658
198688
  creatableProvider()
198659
198689
  ], EvmStakeRunner);
198660
- function _ts_decorate3$3(decorators, target, key, desc) {
198690
+ function _ts_decorate3$2(decorators, target, key, desc) {
198661
198691
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
198662
198692
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
198663
198693
  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;
198664
198694
  return c > 3 && r && Object.defineProperty(target, key, r), r;
198665
198695
  }
198666
- __name$d(_ts_decorate3$3, "_ts_decorate");
198696
+ __name$d(_ts_decorate3$2, "_ts_decorate");
198667
198697
  var EvmStakeTotalsViewer = class _EvmStakeTotalsViewer extends AbstractEvmViewer {
198668
198698
  static {
198669
198699
  __name$d(this, "EvmStakeTotalsViewer");
@@ -198678,28 +198708,28 @@ var EvmStakeTotalsViewer = class _EvmStakeTotalsViewer extends AbstractEvmViewer
198678
198708
  return await this.contract.active();
198679
198709
  }
198680
198710
  async activeByStaked(staked) {
198681
- return await this.contract.activeByAddressStaked(getAddress$2(toEthAddress(staked)));
198711
+ return await this.contract.activeByAddressStaked(getAddress(toEthAddress(staked)));
198682
198712
  }
198683
198713
  async activeByStaker(address) {
198684
- return await this.contract.activeByStaker(getAddress$2(toEthAddress(address)));
198714
+ return await this.contract.activeByStaker(getAddress(toEthAddress(address)));
198685
198715
  }
198686
198716
  async pending() {
198687
198717
  return await this.contract.pending();
198688
198718
  }
198689
198719
  async pendingByStaker(staker) {
198690
- return await this.contract.pendingByStaker(getAddress$2(toEthAddress(staker)));
198720
+ return await this.contract.pendingByStaker(getAddress(toEthAddress(staker)));
198691
198721
  }
198692
198722
  async withdrawn() {
198693
198723
  return await this.contract.withdrawn();
198694
198724
  }
198695
198725
  async withdrawnByStaker(staker) {
198696
- return await this.contract.withdrawnByStaker(getAddress$2(staker));
198726
+ return await this.contract.withdrawnByStaker(getAddress(staker));
198697
198727
  }
198698
198728
  connectContract(address) {
198699
198729
  return IStakedXyoChain__factory.connect(address, this.params.provider);
198700
198730
  }
198701
198731
  };
198702
- EvmStakeTotalsViewer = _ts_decorate3$3([
198732
+ EvmStakeTotalsViewer = _ts_decorate3$2([
198703
198733
  creatableProvider()
198704
198734
  ], EvmStakeTotalsViewer);
198705
198735
  var EthHashRegEx = HexRegExMinMaxMixedCaseWithPrefix(32, 32);
@@ -199613,13 +199643,13 @@ var BlockRewardDiviner = class extends AbstractDiviner {
199613
199643
  };
199614
199644
  asSchema("network.xyo.block.reward", true);
199615
199645
  var FixedPercentageBlockRewardDivinerConfigSchema = asSchema("network.xyo.diviner.chain.block.reward.fixed.percent.config", true);
199616
- function _ts_decorate$4(decorators, target, key, desc) {
199646
+ function _ts_decorate$7(decorators, target, key, desc) {
199617
199647
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
199618
199648
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
199619
199649
  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;
199620
199650
  return c > 3 && r && Object.defineProperty(target, key, r), r;
199621
199651
  }
199622
- __name$b(_ts_decorate$4, "_ts_decorate");
199652
+ __name$b(_ts_decorate$7, "_ts_decorate");
199623
199653
  var FixedPercentageBlockRewardDiviner = class extends BlockRewardDiviner {
199624
199654
  static {
199625
199655
  __name$b(this, "FixedPercentageBlockRewardDiviner");
@@ -199688,7 +199718,7 @@ var FixedPercentageBlockRewardDiviner = class extends BlockRewardDiviner {
199688
199718
  return rewards.filter(exists$2);
199689
199719
  }
199690
199720
  };
199691
- FixedPercentageBlockRewardDiviner = _ts_decorate$4([
199721
+ FixedPercentageBlockRewardDiviner = _ts_decorate$7([
199692
199722
  creatableModule()
199693
199723
  ], FixedPercentageBlockRewardDiviner);
199694
199724
  var countDecimalPlaces = /* @__PURE__ */ __name$b((num) => {
@@ -199763,13 +199793,13 @@ var BlockValidationDiviner = class extends AbstractDiviner {
199763
199793
  BlockValidationDiviner = _ts_decorate2$2([
199764
199794
  creatableModule()
199765
199795
  ], BlockValidationDiviner);
199766
- function _ts_decorate3$2(decorators, target, key, desc) {
199796
+ function _ts_decorate3$1(decorators, target, key, desc) {
199767
199797
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
199768
199798
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
199769
199799
  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;
199770
199800
  return c > 3 && r && Object.defineProperty(target, key, r), r;
199771
199801
  }
199772
- __name$b(_ts_decorate3$2, "_ts_decorate");
199802
+ __name$b(_ts_decorate3$1, "_ts_decorate");
199773
199803
  var HeadValidationDivinerConfigSchema = asSchema("network.xyo.diviner.chain.head.validation.config", true);
199774
199804
  var HeadValidationDiviner = class extends AbstractDiviner {
199775
199805
  static {
@@ -199879,10 +199909,10 @@ var HeadValidationDiviner = class extends AbstractDiviner {
199879
199909
  });
199880
199910
  }
199881
199911
  };
199882
- HeadValidationDiviner = _ts_decorate3$2([
199912
+ HeadValidationDiviner = _ts_decorate3$1([
199883
199913
  creatableModule()
199884
199914
  ], HeadValidationDiviner);
199885
- async function processPendingBlocks({ blockViewer, context, finalizedArchivist, logger, mempoolViewer }) {
199915
+ async function processPendingBlocks({ blockViewer, context, logger, mempoolViewer, finalizationRunner }) {
199886
199916
  logger?.info("Starting processPendingBlocks");
199887
199917
  const start = Date.now();
199888
199918
  const currentBlock = await blockViewer.currentBlock();
@@ -199909,14 +199939,13 @@ async function processPendingBlocks({ blockViewer, context, finalizedArchivist,
199909
199939
  const blocksToFinalize = bestHeadChain.filter((b) => {
199910
199940
  return isDefined(oldHeadBlock) ? b[0].block > oldHeadBlock.block : true;
199911
199941
  });
199912
- const payloadsToFinalize = blocksToFinalize.flatMap((b) => flattenHydratedBlock(b));
199913
199942
  logger?.info("Validated new HeadBlock head from (block) in", `${Date.now() - start}ms`, newHeadBlock.block, "to", oldHeadBlock?.block);
199914
199943
  logger?.info("Validated new HeadBlock head from (hash) in", `${Date.now() - start}ms`, newHeadBlock._hash, "to", oldHeadBlock?._hash);
199915
- if (payloadsToFinalize.length > 0) {
199916
- await finalizedArchivist.insert(payloadsToFinalize);
199944
+ if (blocksToFinalize.length > 0) {
199945
+ await finalizationRunner.finalizeBlocks(blocksToFinalize);
199917
199946
  }
199918
199947
  await headSelector.finalizeChainFragment(blocksToFinalize);
199919
- return payloadsToFinalize;
199948
+ return blocksToFinalize;
199920
199949
  } else {
199921
199950
  logger?.info("No head found to validate", currentBlock?.[0]._hash);
199922
199951
  }
@@ -200947,13 +200976,13 @@ __name$a(spanDurationInMillis, "spanDurationInMillis");
200947
200976
 
200948
200977
  var __defProp$b = Object.defineProperty;
200949
200978
  var __name$9 = (target, value) => __defProp$b(target, "name", { value, configurable: true });
200950
- function _ts_decorate$3(decorators, target, key, desc) {
200979
+ function _ts_decorate$6(decorators, target, key, desc) {
200951
200980
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
200952
200981
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
200953
200982
  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;
200954
200983
  return c > 3 && r && Object.defineProperty(target, key, r), r;
200955
200984
  }
200956
- __name$9(_ts_decorate$3, "_ts_decorate");
200985
+ __name$9(_ts_decorate$6, "_ts_decorate");
200957
200986
  var EvmBlockRewardViewer = class _EvmBlockRewardViewer extends AbstractCreatable {
200958
200987
  static {
200959
200988
  __name$9(this, "EvmBlockRewardViewer");
@@ -200987,7 +201016,7 @@ var EvmBlockRewardViewer = class _EvmBlockRewardViewer extends AbstractCreatable
200987
201016
  }
200988
201017
  }
200989
201018
  };
200990
- EvmBlockRewardViewer = _ts_decorate$3([
201019
+ EvmBlockRewardViewer = _ts_decorate$6([
200991
201020
  creatable()
200992
201021
  ], EvmBlockRewardViewer);
200993
201022
  (class extends AbstractCreatableProvider {
@@ -201087,13 +201116,13 @@ var createBootstrapHead = /* @__PURE__ */ __name$9(async (account, chainId, gene
201087
201116
  chain.push(producerDeclarationBlock);
201088
201117
  return chain;
201089
201118
  }, "createBootstrapHead");
201090
- function _ts_decorate3$1(decorators, target, key, desc) {
201119
+ function _ts_decorate3(decorators, target, key, desc) {
201091
201120
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
201092
201121
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
201093
201122
  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;
201094
201123
  return c > 3 && r && Object.defineProperty(target, key, r), r;
201095
201124
  }
201096
- __name$9(_ts_decorate3$1, "_ts_decorate");
201125
+ __name$9(_ts_decorate3, "_ts_decorate");
201097
201126
  var BaseNetworkStakeStepRewardService = class _BaseNetworkStakeStepRewardService extends AbstractCreatableProvider {
201098
201127
  static {
201099
201128
  __name$9(this, "BaseNetworkStakeStepRewardService");
@@ -201159,7 +201188,7 @@ var BaseNetworkStakeStepRewardService = class _BaseNetworkStakeStepRewardService
201159
201188
  throw new Error("Method [networkStakeStepRewardsForStepLevel] not implemented.");
201160
201189
  }
201161
201190
  };
201162
- BaseNetworkStakeStepRewardService = _ts_decorate3$1([
201191
+ BaseNetworkStakeStepRewardService = _ts_decorate3([
201163
201192
  creatableProvider()
201164
201193
  ], BaseNetworkStakeStepRewardService);
201165
201194
  var bundledPayloadToHydratedTransaction = /* @__PURE__ */ __name$9(async (payload) => {
@@ -293913,151 +293942,36 @@ var boot = /* @__PURE__ */ __name$7(() => genericBoot(getBiosExternalInterface),
293913
293942
 
293914
293943
  var __defProp$6 = Object.defineProperty;
293915
293944
  var __name$6 = (target, value) => __defProp$6(target, "name", { value, configurable: true });
293916
- (class extends Actor {
293917
- static {
293918
- __name$6(this, "BalanceActor");
293919
- }
293920
- _updateMutex = new Mutex$1();
293921
- get accountBalanceViewer() {
293922
- return assertEx(this.params.accountBalanceViewer, () => "balanceService not set");
293923
- }
293924
- get blockViewer() {
293925
- return assertEx(this.params.blockViewer, () => "blockViewer not set");
293926
- }
293927
- async startHandler() {
293928
- await super.startHandler();
293929
- this.registerTimer(
293930
- "BalanceTimer",
293931
- async () => {
293932
- await this.updateBalance();
293933
- },
293934
- 1e3,
293935
- 1e4
293936
- /* 1000 */
293937
- );
293938
- }
293939
- async updateBalance() {
293940
- if (this._updateMutex.isLocked()) return;
293941
- await this._updateMutex.runExclusive(async () => {
293942
- const head = await this.blockViewer.currentBlockHash();
293943
- await this.accountBalanceViewer.accountBalances([], {
293944
- head
293945
- });
293946
- });
293947
- }
293948
- });
293949
- function _ts_decorate$2(decorators, target, key, desc) {
293950
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
293951
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
293952
- 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;
293953
- return c > 3 && r && Object.defineProperty(target, key, r), r;
293954
- }
293955
- __name$6(_ts_decorate$2, "_ts_decorate");
293956
- var MempoolActor = class extends Actor {
293957
- static {
293958
- __name$6(this, "MempoolActor");
293959
- }
293960
- _blockTimerId = null;
293961
- _blockTimerMutex = new Mutex$1();
293962
- _transactionTimerId = null;
293963
- _transactionTimerMutex = new Mutex$1();
293964
- get mempoolRunner() {
293965
- return this.params.mempoolRunner;
293966
- }
293967
- get pendingBlocksArchivist() {
293968
- return this.params.pendingBlocksArchivist;
293969
- }
293970
- get pendingTransactionsArchivist() {
293971
- return this.params.pendingTransactionsArchivist;
293972
- }
293973
- static async paramsHandler(params) {
293974
- return {
293975
- ...await super.paramsHandler(params),
293976
- mempoolRunner: assertEx(params?.mempoolRunner, () => "mempoolRunner is required for MempoolActor"),
293977
- pendingBlocksArchivist: assertEx(params?.pendingBlocksArchivist, () => "pendingBlocksArchivist is required for MempoolActor"),
293978
- pendingTransactionsArchivist: assertEx(params?.pendingTransactionsArchivist, () => "pendingTransactionsArchivist is required for MempoolActor")
293979
- };
293980
- }
293981
- async startHandler() {
293982
- await super.startHandler();
293983
- this.restartBlockTimer();
293984
- }
293985
- async stopHandler() {
293986
- await super.stopHandler();
293987
- this.stopBlockTimer();
293988
- }
293989
- restartBlockTimer() {
293990
- this.stopBlockTimer();
293991
- this._blockTimerId = setInterval(() => {
293992
- if (this._blockTimerMutex.isLocked()) {
293993
- return;
293994
- }
293995
- void this._blockTimerMutex.runExclusive(async () => {
293996
- await this.mempoolRunner.prunePendingBlocks({
293997
- batchSize: 50
293998
- });
293999
- });
294000
- }, 1e3);
294001
- }
294002
- restartTransactionTimer() {
294003
- this.stopTransactionTimer();
294004
- this._transactionTimerId = setInterval(() => {
294005
- if (this._transactionTimerMutex.isLocked()) {
294006
- return;
294007
- }
294008
- void this._transactionTimerMutex.runExclusive(async () => {
294009
- await this.mempoolRunner.prunePendingTransactions({
294010
- batchSize: 50
294011
- });
294012
- });
294013
- }, 1e3);
294014
- }
294015
- stopBlockTimer() {
294016
- if (this._blockTimerId !== null) {
294017
- clearInterval(this._blockTimerId);
294018
- }
294019
- this._blockTimerId = null;
294020
- }
294021
- stopTransactionTimer() {
294022
- if (this._transactionTimerId !== null) {
294023
- clearInterval(this._transactionTimerId);
294024
- }
294025
- this._transactionTimerId = null;
294026
- }
294027
- };
294028
- MempoolActor = _ts_decorate$2([
294029
- creatable()
294030
- ], MempoolActor);
294031
- function _ts_decorate2(decorators, target, key, desc) {
293945
+ function _ts_decorate$5(decorators, target, key, desc) {
294032
293946
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
294033
293947
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
294034
293948
  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;
294035
293949
  return c > 3 && r && Object.defineProperty(target, key, r), r;
294036
293950
  }
294037
- __name$6(_ts_decorate2, "_ts_decorate");
294038
- var ValidatorActor = class extends Actor {
293951
+ __name$6(_ts_decorate$5, "_ts_decorate");
293952
+ var ValidatorActor = class extends ActorV3 {
294039
293953
  static {
294040
293954
  __name$6(this, "ValidatorActor");
294041
293955
  }
293956
+ _blockViewer;
293957
+ _finalizationRunner;
294042
293958
  _lastValidatedBlock;
294043
293959
  _lastValidatedBlockHash;
293960
+ _mempoolViewer;
294044
293961
  get blockViewer() {
294045
- return this.params.blockViewer;
293962
+ return this._blockViewer;
294046
293963
  }
294047
- get finalizedArchivist() {
294048
- return assertEx(this.params.finalizedArchivist, () => "finalizedArchivist not set");
293964
+ get finalizationRunner() {
293965
+ return this._finalizationRunner;
294049
293966
  }
294050
293967
  get mempoolViewer() {
294051
- return this.params.mempoolViewer;
293968
+ return this._mempoolViewer;
294052
293969
  }
294053
- static async paramsHandler(params) {
294054
- return {
294055
- ...await super.paramsHandler(params),
294056
- mempoolViewer: assertEx(params?.mempoolViewer, () => "mempoolViewer is required for ValidatorActor"),
294057
- blockViewer: assertEx(params?.blockViewer, () => "blockViewer is required for ValidatorActor"),
294058
- finalizedArchivist: assertEx(params?.finalizedArchivist, () => "finalizedArchivist is required for ValidatorActor"),
294059
- account: assertEx(params?.account, () => "account is required for ValidatorActor")
294060
- };
293970
+ async createHandler() {
293971
+ await super.startHandler();
293972
+ this._blockViewer = await this.locator.getInstance(BlockViewerMoniker);
293973
+ this._finalizationRunner = await this.locator.getInstance(FinalizationRunnerMoniker);
293974
+ this._mempoolViewer = await this.locator.getInstance(MempoolViewerMoniker);
294061
293975
  }
294062
293976
  async startHandler() {
294063
293977
  await super.startHandler();
@@ -294071,7 +293985,7 @@ var ValidatorActor = class extends Actor {
294071
293985
  logger: this.logger,
294072
293986
  mempoolViewer: this.mempoolViewer,
294073
293987
  blockViewer: this.blockViewer,
294074
- finalizedArchivist: this.finalizedArchivist
293988
+ finalizationRunner: this.finalizationRunner
294075
293989
  });
294076
293990
  }, {
294077
293991
  ...this.context,
@@ -294083,18 +293997,8 @@ var ValidatorActor = class extends Actor {
294083
293997
  /* 500 */
294084
293998
  );
294085
293999
  }
294086
- async slashInvalidBlock(_block) {
294087
- const slashed = await Promise.resolve(true);
294088
- return slashed;
294089
- }
294090
- async validateBlock(block) {
294091
- const valid = await Promise.resolve(true);
294092
- this._lastValidatedBlock = block;
294093
- this._lastValidatedBlockHash = await PayloadBuilder.hash(block);
294094
- return valid;
294095
- }
294096
294000
  };
294097
- ValidatorActor = _ts_decorate2([
294001
+ ValidatorActor = _ts_decorate$5([
294098
294002
  creatable()
294099
294003
  ], ValidatorActor);
294100
294004
  var DEFAULT_STORAGE_ROOT = path__default.join(process.cwd(), ".store");
@@ -294291,58 +294195,6 @@ var initEvmProvider = /* @__PURE__ */ __name$6(async ({ config }) => {
294291
294195
  var canUseEvmProvider = /* @__PURE__ */ __name$6(({ config }) => {
294292
294196
  return canUseInfuraProvider(config) || canUseJsonRpcProvider(config);
294293
294197
  }, "canUseEvmProvider");
294294
- var sendStatus = /* @__PURE__ */ __name$6((res, status, errorCode) => {
294295
- const statusCode = status === "started" ? 200 : errorCode;
294296
- res.writeHead(statusCode, {
294297
- "Content-Type": "application/json"
294298
- });
294299
- res.end(JSON.stringify({
294300
- status
294301
- }));
294302
- }, "sendStatus");
294303
- var notFound = /* @__PURE__ */ __name$6((res) => {
294304
- res.writeHead(404, {
294305
- "Content-Type": "application/json"
294306
- });
294307
- res.end(JSON.stringify({
294308
- status: "not found"
294309
- }));
294310
- }, "notFound");
294311
- var createHealthServer = /* @__PURE__ */ __name$6((port, statusMonitor, logger) => {
294312
- const server = require$$0$d.createServer((req, res) => {
294313
- const url = req.url ?? "";
294314
- const status = statusMonitor.getGlobalStatus();
294315
- switch (url) {
294316
- case "/healthz": {
294317
- sendStatus(res, status, 500);
294318
- break;
294319
- }
294320
- case "/livez": {
294321
- sendStatus(res, status, 503);
294322
- break;
294323
- }
294324
- case "/readyz": {
294325
- sendStatus(res, status, 503);
294326
- break;
294327
- }
294328
- default: {
294329
- notFound(res);
294330
- }
294331
- }
294332
- });
294333
- server.listen(port, () => {
294334
- logger.log(`Health server running on http://localhost:${port}`);
294335
- logger.log(" - /healthz");
294336
- logger.log(" - /livez");
294337
- logger.log(" - /readyz");
294338
- });
294339
- return server;
294340
- }, "createHealthServer");
294341
- var initHealthEndpoints = /* @__PURE__ */ __name$6((params) => {
294342
- const { config, logger, statusReporter } = params;
294343
- const { healthCheckPort } = config.actors.producer;
294344
- return isDefined(healthCheckPort) ? createHealthServer(healthCheckPort, statusReporter, logger) : void 0;
294345
- }, "initHealthEndpoints");
294346
294198
 
294347
294199
  // src/host/implementation/DefaultHost.ts
294348
294200
  (class {
@@ -294851,6 +294703,14 @@ async function initApiWallet({ config, logger }) {
294851
294703
  }, mnemonic);
294852
294704
  }
294853
294705
  __name$6(initApiWallet, "initApiWallet");
294706
+ async function initBridgeWallet({ config, logger }) {
294707
+ const { mnemonic } = config.actors.bridge;
294708
+ return await initWallet({
294709
+ config,
294710
+ logger
294711
+ }, mnemonic);
294712
+ }
294713
+ __name$6(initBridgeWallet, "initBridgeWallet");
294854
294714
  async function initMempoolWallet({ config, logger }) {
294855
294715
  const { mnemonic } = config.actors.mempool;
294856
294716
  return await initWallet({
@@ -294875,13 +294735,21 @@ async function initRewardsRedemptionApiWallet({ config, logger }) {
294875
294735
  }, mnemonic);
294876
294736
  }
294877
294737
  __name$6(initRewardsRedemptionApiWallet, "initRewardsRedemptionApiWallet");
294878
- function _ts_decorate3(decorators, target, key, desc) {
294738
+ async function initValidatorWallet({ config, logger }) {
294739
+ const { mnemonic } = config.actors.mempool;
294740
+ return await initWallet({
294741
+ config,
294742
+ logger
294743
+ }, mnemonic);
294744
+ }
294745
+ __name$6(initValidatorWallet, "initValidatorWallet");
294746
+ function _ts_decorate2(decorators, target, key, desc) {
294879
294747
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
294880
294748
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
294881
294749
  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;
294882
294750
  return c > 3 && r && Object.defineProperty(target, key, r), r;
294883
294751
  }
294884
- __name$6(_ts_decorate3, "_ts_decorate");
294752
+ __name$6(_ts_decorate2, "_ts_decorate");
294885
294753
  var Orchestrator = class extends AbstractCreatable {
294886
294754
  static {
294887
294755
  __name$6(this, "Orchestrator");
@@ -294934,13 +294802,13 @@ var Orchestrator = class extends AbstractCreatable {
294934
294802
  this.logger?.log("[Orchestrator] Stopped...");
294935
294803
  }
294936
294804
  };
294937
- Orchestrator = _ts_decorate3([
294805
+ Orchestrator = _ts_decorate2([
294938
294806
  creatable()
294939
294807
  ], Orchestrator);
294940
294808
 
294941
294809
  var __defProp$5 = Object.defineProperty;
294942
294810
  var __name$5 = (target, value) => __defProp$5(target, "name", { value, configurable: true });
294943
- var addInstrumentation$3 = /* @__PURE__ */ __name$5(() => {
294811
+ var addInstrumentation$2 = /* @__PURE__ */ __name$5(() => {
294944
294812
  const instrumentations = [
294945
294813
  new HttpInstrumentation(),
294946
294814
  new ExpressInstrumentation()
@@ -294949,147 +294817,19 @@ var addInstrumentation$3 = /* @__PURE__ */ __name$5(() => {
294949
294817
  instrumentations
294950
294818
  });
294951
294819
  }, "addInstrumentation");
294952
- var handler$1 = /* @__PURE__ */ __name$5(async (req, res, next) => {
294953
- const { address: moduleIdentifier } = req.params;
294954
- const { node } = req.app.context;
294955
- const address = asAddress(moduleIdentifier);
294956
- if (isDefined(address)) {
294957
- let mod = node.address === address ? node : await node.resolve(address, {
294958
- direction: "down"
294959
- });
294960
- if (mod) {
294961
- res.json(await mod.state());
294962
- return;
294963
- }
294964
- }
294965
- if (isModuleName(moduleIdentifier)) {
294966
- const mod = await node.resolve(moduleIdentifier, {
294967
- direction: "down"
294968
- });
294969
- if (mod) {
294970
- res.redirect(StatusCodes.MOVED_TEMPORARILY, `/${mod.address}`);
294971
- return;
294972
- }
294973
- }
294974
- next("route");
294975
- }, "handler");
294976
- var getAddress$1 = asyncHandler(handler$1);
294977
- var DEFAULT_DEPTH$1 = 5;
294978
- var getQueryConfig$1 = /* @__PURE__ */ __name$5((mod, req, bw, payloads) => {
294979
- const nestedBwAddresses = payloads?.flat(DEFAULT_DEPTH$1).filter((payload) => payload?.schema === BoundWitnessSchema).map((bw2) => bw2.addresses) ?? [];
294980
- const addresses = [
294981
- bw.addresses,
294982
- ...nestedBwAddresses
294983
- ].filter((address) => address.length > 0);
294984
- const allowed = addresses.length > 0 ? Object.fromEntries(mod.queries.map((schema) => [
294985
- schema,
294986
- addresses
294987
- ])) : {};
294988
- const security = {
294989
- allowed
294990
- };
294991
- return {
294992
- schema: ModuleConfigSchema,
294993
- security
294994
- };
294995
- }, "getQueryConfig");
294996
-
294997
- // src/server/routes/address/post/post.ts
294998
- var handler2$1 = /* @__PURE__ */ __name$5(async (req, res, next) => {
294999
- const returnError = /* @__PURE__ */ __name$5((code, message = "An error occurred", details) => {
295000
- const error = new ModuleErrorBuilder().message(message).details(details).build();
295001
- res.locals.rawResponse = false;
295002
- res.status(code).json(error);
295003
- next();
295004
- }, "returnError");
295005
- const { address } = req.params;
295006
- const { node } = req.app.context;
295007
- const [bw, payloads] = Array.isArray(req.body) ? req.body : [];
295008
- if (!isAddress(address)) {
295009
- return returnError(StatusCodes.BAD_REQUEST, "Missing address");
295010
- }
295011
- if (!bw) {
295012
- return returnError(StatusCodes.BAD_REQUEST, "Missing boundwitness");
295013
- }
295014
- if (!isQueryBoundWitness(bw)) {
295015
- return returnError(StatusCodes.BAD_REQUEST, "Invalid query boundwitness");
295016
- }
295017
- let modules = [];
295018
- const normalizedAddress = toAddress(address);
295019
- if (node.address === normalizedAddress) modules = [
295020
- node
295021
- ];
295022
- else {
295023
- const typedAddress = asAddress(address);
295024
- const byAddress = typedAddress === void 0 ? void 0 : await node.resolve(typedAddress, {
295025
- maxDepth: 10
295026
- });
295027
- if (byAddress) modules = [
295028
- byAddress
295029
- ];
295030
- else {
295031
- const byName = await node.resolve(address, {
295032
- direction: "down"
295033
- });
295034
- if (byName) {
295035
- const moduleAddress = assertEx(byName?.address, () => "Error redirecting to module by address");
295036
- res.redirect(StatusCodes.TEMPORARY_REDIRECT, `/${moduleAddress}`);
295037
- return;
295038
- } else {
295039
- return returnError(StatusCodes.NOT_FOUND, "Module not found", {
295040
- address
295041
- });
295042
- }
295043
- }
295044
- }
295045
- if (modules.length > 0) {
295046
- const mod = modules[0];
295047
- const queryConfig = getQueryConfig$1(mod, req, bw, payloads);
295048
- try {
295049
- const queryResult = await mod.query(bw, payloads, queryConfig);
295050
- res.json(queryResult);
295051
- } catch (ex) {
295052
- return returnError(StatusCodes.INTERNAL_SERVER_ERROR, "Query Failed", {
295053
- message: ex?.message ?? "Unknown Error"
295054
- });
295055
- }
295056
- } else {
295057
- return returnError(StatusCodes.NOT_FOUND, "Module not found", {
295058
- address
295059
- });
295060
- }
295061
- }, "handler");
295062
- var postAddress$1 = asyncHandler(handler2$1);
295063
-
295064
- // src/server/routes/address/addNodeRoutes.ts
295065
- var addNodeRoutes$1 = /* @__PURE__ */ __name$5((app) => {
295066
- const defaultModule = app.context.node;
295067
- const address = defaultModule.address;
295068
- const defaultModuleEndpoint = `/${address}`;
295069
- app.get("/", (_req, res) => res.redirect(StatusCodes.MOVED_TEMPORARILY, defaultModuleEndpoint));
295070
- app.post("/", (_req, res) => res.redirect(StatusCodes.TEMPORARY_REDIRECT, defaultModuleEndpoint));
295071
- app.get("/:address", getAddress$1);
295072
- app.post("/:address", postAddress$1);
295073
- app.get("/:hash", (_req, res) => {
295074
- res.sendStatus(StatusCodes.NOT_FOUND);
295075
- });
295076
- app.post("/:hash", (_req, res) => {
295077
- res.sendStatus(StatusCodes.NOT_FOUND);
295078
- });
295079
- }, "addNodeRoutes");
295080
- var resolveArchivist$2 = /* @__PURE__ */ __name$5(async (node, archivistModuleIdentifier) => {
294820
+ var resolveArchivist$1 = /* @__PURE__ */ __name$5(async (node, archivistModuleIdentifier) => {
295081
294821
  const mod = await node.resolve(archivistModuleIdentifier);
295082
294822
  return asArchivistInstance(mod, {
295083
294823
  required: true
295084
294824
  });
295085
294825
  }, "resolveArchivist");
295086
- var archivistInstance$2;
295087
- var getArchivist$2 = /* @__PURE__ */ __name$5(async (node, archivistModuleIdentifier) => {
295088
- if (isDefined(archivistInstance$2)) return archivistInstance$2;
295089
- archivistInstance$2 = await resolveArchivist$2(node, archivistModuleIdentifier);
295090
- return archivistInstance$2;
294826
+ var archivistInstance$1;
294827
+ var getArchivist$1 = /* @__PURE__ */ __name$5(async (node, archivistModuleIdentifier) => {
294828
+ if (isDefined(archivistInstance$1)) return archivistInstance$1;
294829
+ archivistInstance$1 = await resolveArchivist$1(node, archivistModuleIdentifier);
294830
+ return archivistInstance$1;
295091
294831
  }, "getArchivist");
295092
- var archivistMiddleware$2 = /* @__PURE__ */ __name$5((options) => {
294832
+ var archivistMiddleware$1 = /* @__PURE__ */ __name$5((options) => {
295093
294833
  const { node, archivistModuleIdentifier } = options;
295094
294834
  const router = express2.Router({
295095
294835
  mergeParams: true
@@ -295100,7 +294840,7 @@ var archivistMiddleware$2 = /* @__PURE__ */ __name$5((options) => {
295100
294840
  req.body
295101
294841
  ];
295102
294842
  const payloads = (await PayloadBuilder.hashPairs(body)).map((p) => p[0]);
295103
- const archivist = await getArchivist$2(node, archivistModuleIdentifier);
294843
+ const archivist = await getArchivist$1(node, archivistModuleIdentifier);
295104
294844
  const result = await archivist.insert(payloads);
295105
294845
  res.status(200).json(result);
295106
294846
  });
@@ -295116,14 +294856,14 @@ var archivistMiddleware$2 = /* @__PURE__ */ __name$5((options) => {
295116
294856
  order,
295117
294857
  cursor
295118
294858
  };
295119
- const archivist = await getArchivist$2(node, archivistModuleIdentifier);
294859
+ const archivist = await getArchivist$1(node, archivistModuleIdentifier);
295120
294860
  const result = await archivist.next(options2);
295121
294861
  res.status(200).json(result);
295122
294862
  });
295123
294863
  router.post("/next", async (req, res) => {
295124
294864
  setRawResponseFormat(res);
295125
294865
  const options2 = req.body;
295126
- const archivist = await getArchivist$2(node, archivistModuleIdentifier);
294866
+ const archivist = await getArchivist$1(node, archivistModuleIdentifier);
295127
294867
  const result = await (isDefined(options2) ? archivist.next(options2) : archivist.next());
295128
294868
  res.status(200).json(result);
295129
294869
  });
@@ -295132,7 +294872,7 @@ var archivistMiddleware$2 = /* @__PURE__ */ __name$5((options) => {
295132
294872
  const { hash: rawHash } = req.params;
295133
294873
  const hash = asHash(rawHash);
295134
294874
  if (isDefined(hash)) {
295135
- const archivist = await getArchivist$2(node, archivistModuleIdentifier);
294875
+ const archivist = await getArchivist$1(node, archivistModuleIdentifier);
295136
294876
  const [payload] = await archivist.get([
295137
294877
  hash
295138
294878
  ]);
@@ -295147,10 +294887,10 @@ var archivistMiddleware$2 = /* @__PURE__ */ __name$5((options) => {
295147
294887
  }, "archivistMiddleware");
295148
294888
 
295149
294889
  // src/server/routes/dataLake/addDataLakeRoutes.ts
295150
- var addDataLakeRoutes$2 = /* @__PURE__ */ __name$5((app) => {
294890
+ var addDataLakeRoutes$1 = /* @__PURE__ */ __name$5((app) => {
295151
294891
  const { node } = app.context;
295152
294892
  const archivistModuleIdentifier = "Chain:Finalized";
295153
- app.use("/chain", archivistMiddleware$2({
294893
+ app.use("/chain", archivistMiddleware$1({
295154
294894
  node,
295155
294895
  archivistModuleIdentifier
295156
294896
  }));
@@ -295169,15 +294909,14 @@ var addRpcRoutes = /* @__PURE__ */ __name$5(async (app) => {
295169
294909
  }, "addRpcRoutes");
295170
294910
 
295171
294911
  // src/server/routes/addRoutes.ts
295172
- var addRoutes$3 = /* @__PURE__ */ __name$5(async (app) => {
294912
+ var addRoutes$2 = /* @__PURE__ */ __name$5(async (app) => {
295173
294913
  await addRpcRoutes(app);
295174
- addDataLakeRoutes$2(app);
295175
- addNodeRoutes$1(app);
294914
+ addDataLakeRoutes$1(app);
295176
294915
  }, "addRoutes");
295177
294916
 
295178
294917
  // src/server/app.ts
295179
- var getApp$3 = /* @__PURE__ */ __name$5(async (context) => {
295180
- addInstrumentation$3();
294918
+ var getApp$2 = /* @__PURE__ */ __name$5(async (context) => {
294919
+ addInstrumentation$2();
295181
294920
  const app = express2();
295182
294921
  app.set("etag", false);
295183
294922
  app.use(cors());
@@ -295191,164 +294930,36 @@ var getApp$3 = /* @__PURE__ */ __name$5(async (context) => {
295191
294930
  app.use(customPoweredByHeader);
295192
294931
  disableCaseSensitiveRouting(app);
295193
294932
  app.context = context;
295194
- await addRoutes$3(app);
294933
+ await addRoutes$2(app);
295195
294934
  app.use(standardErrors);
295196
294935
  return app;
295197
294936
  }, "getApp");
295198
- async function initApiParams(params) {
295199
- const { config, node: providedNode } = params;
295200
- const logger = assertEx(params.logger, () => "Logger is required to init server");
295201
- const statusReporter = initStatusReporter({
295202
- logger
295203
- });
295204
- await startupSpanAsync("initHealthEndpoints", () => initHealthEndpoints({
295205
- config,
295206
- logger,
295207
- statusReporter
295208
- }));
295209
- const telemetryConfig = buildTelemetryConfig(config, "xl1-api", "1.0.0", DefaultMetricsScrapePorts.api);
295210
- const { traceProvider, meterProvider } = await startupSpanAsync("initTelemetry", () => initTelemetry(telemetryConfig));
295211
- const initContext = {
295212
- _id: "init-context",
295213
- config,
295214
- logger,
295215
- statusReporter,
295216
- timeBudgetLimit: 1e3,
295217
- meterProvider,
295218
- traceProvider,
295219
- singletons: {},
295220
- caches: {}
295221
- };
295222
- const wallet = await initApiWallet(initContext);
295223
- const balancesSummaryMap = assertEx(await initBalanceSummaryMap(initContext), () => "Balance Summary Map not initialized");
295224
- const transfersSummaryMap = assertEx(await initTransferSummaryMap(initContext), () => "Transfer Summary Map not initialized");
295225
- const { node, writableChainArchivist, readonlyChainArchivist, pendingTransactionsArchivist, pendingBlocksArchivist } = await initServerNode({
295226
- ...initContext,
295227
- wallet,
295228
- node: providedNode,
295229
- transfersSummaryMap,
295230
- balancesSummaryMap
295231
- });
295232
- await writableChainArchivist.start();
295233
- await readonlyChainArchivist.start();
295234
- await pendingTransactionsArchivist.start();
295235
- await pendingBlocksArchivist.start();
295236
- const [head, chainId] = await initFinalizationArchivistIfNeeded(writableChainArchivist, config, wallet);
295237
- assertEx(head.chain === chainId, () => `Chain ID does not match head block chain ID [init] [${head.chain} !== ${chainId}]`);
295238
- const mods = await node.resolve("*");
295239
- await Promise.all(mods.map((mod) => {
295240
- return mod.start?.() ?? (() => true);
295241
- }));
295242
- const locator = buildLocalProviderLocator({
295243
- context: initContext,
295244
- finalizedArchivist: writableChainArchivist,
295245
- pendingTransactionsArchivist,
295246
- pendingBlocksArchivist,
295247
- balancesSummaryMap,
295248
- transfersSummaryMap,
295249
- node
295250
- });
295251
- await initEvmProvidersIfAvailable(locator);
295252
- locator.register(SimpleBlockValidationViewer.factory(SimpleBlockValidationViewer.dependencies, {
295253
- state: validateHydratedBlockState,
295254
- protocol: validateHydratedBlock
295255
- }));
295256
- locator.register(SimpleXyoConnection.factory(SimpleXyoConnection.dependencies, {}));
295257
- const apiContext = {
295258
- ...initContext,
295259
- ...locator.context,
295260
- _id: "api-context",
295261
- node
295262
- };
295263
- const blockViewer = await locator.getInstance(BlockViewerMoniker);
295264
- assertEx(await blockViewer.start(), () => "Failed to start BlockViewer");
295265
- const blk = await blockViewer.currentBlock();
295266
- assertEx(blk, () => "No blocks found after initialization");
295267
- const accountBalanceViewer = await locator.getInstance(AccountBalanceViewerMoniker);
295268
- assertEx(await accountBalanceViewer.start(), () => "Failed to start AccountBalanceViewer");
295269
- const xyoViewer = await locator.getInstance(XyoViewerMoniker);
295270
- assertEx(await xyoViewer.start(), () => "Failed to start XyoViewer");
295271
- const mempoolViewer = await locator.getInstance(MempoolViewerMoniker);
295272
- assertEx(await mempoolViewer.start(), () => "Failed to start MempoolViewer");
295273
- const mempoolRunner = await locator.getInstance(MempoolRunnerMoniker);
295274
- assertEx(await mempoolRunner.start(), () => "Failed to start MempoolRunner");
295275
- console.info(`[API] Current block after initialization: #${blk[0].block} (${blk[0]._hash})`);
295276
- const validatorActor = config.actors.mempool.enabled ? void 0 : await ValidatorActor.create({
295277
- id: "validator-mempool-server",
295278
- account: wallet,
295279
- context: locator.context,
295280
- finalizedArchivist: writableChainArchivist,
295281
- mempoolViewer,
295282
- blockViewer
295283
- });
295284
- await validatorActor?.start();
295285
- const mempoolActor = config.actors.mempool.enabled ? void 0 : await MempoolActor.create({
295286
- id: "mempool-mempool-server",
295287
- account: wallet,
295288
- context: locator.context,
295289
- mempoolRunner,
295290
- pendingBlocksArchivist,
295291
- pendingTransactionsArchivist
295292
- });
295293
- await mempoolActor?.start();
295294
- return {
295295
- id: "api-actor",
295296
- account: wallet,
295297
- context: apiContext,
295298
- transfersSummaryMap,
295299
- balancesSummaryMap
295300
- };
295301
- }
295302
- __name$5(initApiParams, "initApiParams");
295303
294937
 
295304
294938
  // src/server/server.ts
295305
- var hostname$3 = "::";
295306
- async function getServer$3(context) {
294939
+ var hostname$2 = "::";
294940
+ async function getServer$2(context) {
295307
294941
  const { logger } = context;
295308
294942
  const { port } = context.config.actors.api;
295309
- const app = await getApp$3(context);
295310
- const server = app.listen(port, hostname$3, () => logger?.log(`[API] Server listening at http://${hostname$3}:${port}`));
294943
+ const app = await getApp$2(context);
294944
+ const server = app.listen(port, hostname$2, () => logger?.info(`[API] Server listening at http://${hostname$2}:${port}`));
295311
294945
  server.setTimeout(2e4);
295312
294946
  return server;
295313
294947
  }
295314
- __name$5(getServer$3, "getServer");
294948
+ __name$5(getServer$2, "getServer");
295315
294949
 
295316
294950
  // src/ApiActor.ts
295317
- function _ts_decorate$1(decorators, target, key, desc) {
294951
+ function _ts_decorate$4(decorators, target, key, desc) {
295318
294952
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
295319
294953
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
295320
294954
  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;
295321
294955
  return c > 3 && r && Object.defineProperty(target, key, r), r;
295322
294956
  }
295323
- __name$5(_ts_decorate$1, "_ts_decorate");
295324
- var ApiActor = class extends Actor {
294957
+ __name$5(_ts_decorate$4, "_ts_decorate");
294958
+ var ApiActor = class extends ActorV3 {
295325
294959
  static {
295326
294960
  __name$5(this, "ApiActor");
295327
294961
  }
295328
294962
  server;
295329
- get context() {
295330
- return this.params.context;
295331
- }
295332
- static defaultFactories() {
295333
- return [
295334
- ...super.defaultFactories()
295335
- ];
295336
- }
295337
- static async paramsHandler(params) {
295338
- const logger = params?.context?.logger;
295339
- let account = params?.account;
295340
- if (account === void 0) {
295341
- const newAccount = await Account.random();
295342
- logger?.warn(`No account provided to ApiActor, generating random account ${newAccount.address}`);
295343
- account = newAccount;
295344
- }
295345
- logger?.info(`Running api for account ${account.address}`);
295346
- return {
295347
- ...await super.paramsHandler(params),
295348
- context: params.context,
295349
- account: assertEx(account, () => "ApiActor requires an account to run")
295350
- };
295351
- }
295352
294963
  async createHandler() {
295353
294964
  await super.createHandler();
295354
294965
  }
@@ -295362,25 +294973,26 @@ var ApiActor = class extends Actor {
295362
294973
  this.stopServer();
295363
294974
  }
295364
294975
  async startServer() {
295365
- this.server = await getServer$3(this.context);
294976
+ this.server = await getServer$2(this.context);
295366
294977
  }
295367
294978
  stopServer() {
295368
294979
  this.server?.close();
295369
294980
  this.server = void 0;
295370
294981
  }
295371
294982
  };
295372
- ApiActor = _ts_decorate$1([
294983
+ ApiActor = _ts_decorate$4([
295373
294984
  creatable()
295374
294985
  ], ApiActor);
295375
- var runApi = /* @__PURE__ */ __name$5(async ({ config, orchestrator, ...params }) => {
295376
- const logger = new IdLogger(params.logger ?? console, () => "API");
295377
- const account = await Account.random();
295378
- logger.info(`Running api for account ${account.address} [random]`);
295379
- const actorParams = await initApiParams({
294986
+ var runApi = /* @__PURE__ */ __name$5(async (config, orchestrator, locator) => {
294987
+ const account = await initApiWallet({
295380
294988
  config,
295381
- logger
294989
+ logger: locator.context.logger
294990
+ });
294991
+ const api = await ApiActor.create({
294992
+ account,
294993
+ config,
294994
+ locator
295382
294995
  });
295383
- const api = await ApiActor.create(actorParams);
295384
294996
  const actors = [
295385
294997
  api
295386
294998
  ].filter(exists$2);
@@ -295392,22 +295004,118 @@ var runApi = /* @__PURE__ */ __name$5(async ({ config, orchestrator, ...params }
295392
295004
 
295393
295005
  var __defProp$4 = Object.defineProperty;
295394
295006
  var __name$4 = (target, value) => __defProp$4(target, "name", { value, configurable: true });
295395
- function _ts_decorate(decorators, target, key, desc) {
295007
+ function _ts_decorate$3(decorators, target, key, desc) {
295396
295008
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
295397
295009
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
295398
295010
  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;
295399
295011
  return c > 3 && r && Object.defineProperty(target, key, r), r;
295400
295012
  }
295401
- __name$4(_ts_decorate, "_ts_decorate");
295013
+ __name$4(_ts_decorate$3, "_ts_decorate");
295014
+ var MempoolActor = class extends ActorV3 {
295015
+ static {
295016
+ __name$4(this, "MempoolActor");
295017
+ }
295018
+ _mempoolRunner;
295019
+ _blockTimerId = null;
295020
+ _blockTimerMutex = new Mutex$1();
295021
+ _transactionTimerId = null;
295022
+ _transactionTimerMutex = new Mutex$1();
295023
+ get mempoolRunner() {
295024
+ return this._mempoolRunner;
295025
+ }
295026
+ async createHandler() {
295027
+ await super.createHandler();
295028
+ this._mempoolRunner = await this.locator.getInstance(MempoolRunnerMoniker);
295029
+ }
295030
+ async startHandler() {
295031
+ await super.startHandler();
295032
+ this.restartTransactionTimer();
295033
+ this.restartBlockTimer();
295034
+ }
295035
+ async stopHandler() {
295036
+ await super.stopHandler();
295037
+ this.stopTransactionTimer();
295038
+ this.stopBlockTimer();
295039
+ }
295040
+ restartBlockTimer() {
295041
+ this.stopBlockTimer();
295042
+ this._blockTimerId = setInterval(() => {
295043
+ if (this._blockTimerMutex.isLocked()) {
295044
+ return;
295045
+ }
295046
+ void this._blockTimerMutex.runExclusive(async () => {
295047
+ await this.mempoolRunner.prunePendingBlocks({
295048
+ batchSize: 50
295049
+ });
295050
+ });
295051
+ }, 1e3);
295052
+ }
295053
+ restartTransactionTimer() {
295054
+ this.stopTransactionTimer();
295055
+ this._transactionTimerId = setInterval(() => {
295056
+ if (this._transactionTimerMutex.isLocked()) {
295057
+ return;
295058
+ }
295059
+ void this._transactionTimerMutex.runExclusive(async () => {
295060
+ await this.mempoolRunner.prunePendingTransactions({
295061
+ batchSize: 50
295062
+ });
295063
+ });
295064
+ }, 1e3);
295065
+ }
295066
+ stopBlockTimer() {
295067
+ if (this._blockTimerId !== null) {
295068
+ clearInterval(this._blockTimerId);
295069
+ }
295070
+ this._blockTimerId = null;
295071
+ }
295072
+ stopTransactionTimer() {
295073
+ if (this._transactionTimerId !== null) {
295074
+ clearInterval(this._transactionTimerId);
295075
+ }
295076
+ this._transactionTimerId = null;
295077
+ }
295078
+ };
295079
+ MempoolActor = _ts_decorate$3([
295080
+ creatable()
295081
+ ], MempoolActor);
295082
+ var runMempool = /* @__PURE__ */ __name$4(async (config, orchestrator, locator) => {
295083
+ const account = await initMempoolWallet({
295084
+ config,
295085
+ logger: locator.context.logger
295086
+ });
295087
+ const mempool = await MempoolActor.create({
295088
+ account,
295089
+ config,
295090
+ locator
295091
+ });
295092
+ const actors = [
295093
+ mempool
295094
+ ].filter(exists$2);
295095
+ for (const actor of actors) {
295096
+ await orchestrator.registerActor(actor);
295097
+ }
295098
+ await orchestrator.start();
295099
+ }, "runMempool");
295100
+
295101
+ var __defProp$3 = Object.defineProperty;
295102
+ var __name$3 = (target, value) => __defProp$3(target, "name", { value, configurable: true });
295103
+ function _ts_decorate$2(decorators, target, key, desc) {
295104
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
295105
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
295106
+ 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;
295107
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
295108
+ }
295109
+ __name$3(_ts_decorate$2, "_ts_decorate");
295402
295110
  var TEN_MINUTES = 10 * 60 * 1e3;
295403
- var toFormattedBlockReference = /* @__PURE__ */ __name$4((blockBoundWitness) => {
295111
+ var toFormattedBlockReference = /* @__PURE__ */ __name$3((blockBoundWitness) => {
295404
295112
  return `${blockBoundWitness.block} [${toHex(blockBoundWitness._hash, {
295405
295113
  prefix: true
295406
295114
  })}]`;
295407
295115
  }, "toFormattedBlockReference");
295408
295116
  var ProducerActor = class _ProducerActor extends ActorV3 {
295409
295117
  static {
295410
- __name$4(this, "ProducerActor");
295118
+ __name$3(this, "ProducerActor");
295411
295119
  }
295412
295120
  /**
295413
295121
  * The interval time (in MS) between block production attempts.
@@ -295438,7 +295146,6 @@ var ProducerActor = class _ProducerActor extends ActorV3 {
295438
295146
  _mempoolRunner;
295439
295147
  _mempoolViewer;
295440
295148
  _produceBlockMutex = new Mutex$1();
295441
- _rewardAddress;
295442
295149
  _stakeTotalsViewer;
295443
295150
  get logger() {
295444
295151
  return assertEx(super.logger, () => "Logger is required for ProducerActor");
@@ -295657,10 +295364,10 @@ var ProducerActor = class _ProducerActor extends ActorV3 {
295657
295364
  return true;
295658
295365
  }
295659
295366
  };
295660
- ProducerActor = _ts_decorate([
295367
+ ProducerActor = _ts_decorate$2([
295661
295368
  creatable()
295662
295369
  ], ProducerActor);
295663
- var runProducer = /* @__PURE__ */ __name$4(async (config, orchestrator, locator) => {
295370
+ var runProducer = /* @__PURE__ */ __name$3(async (config, orchestrator, locator) => {
295664
295371
  const account = await initProducerAccount({
295665
295372
  config,
295666
295373
  logger: locator.context.logger
@@ -342486,11 +342193,11 @@ var ClientType;
342486
342193
  ClientType["normal"] = "normal";
342487
342194
  })(ClientType || (ClientType = {}));
342488
342195
 
342489
- var __defProp$3 = Object.defineProperty;
342490
- var __name$3 = (target, value) => __defProp$3(target, "name", { value, configurable: true });
342196
+ var __defProp$2 = Object.defineProperty;
342197
+ var __name$2 = (target, value) => __defProp$2(target, "name", { value, configurable: true });
342491
342198
  var connection;
342492
342199
  var maxRetriesPerRequest = null;
342493
- var getConnection = /* @__PURE__ */ __name$3((config) => {
342200
+ var getConnection = /* @__PURE__ */ __name$2((config) => {
342494
342201
  if (isDefined(connection)) return connection;
342495
342202
  const { redisHost: host, redisPort: port } = config.actors.bridge;
342496
342203
  connection = new builtExports.Redis({
@@ -342501,7 +342208,7 @@ var getConnection = /* @__PURE__ */ __name$3((config) => {
342501
342208
  return connection;
342502
342209
  }, "getConnection");
342503
342210
  var flowProducer;
342504
- var getFlowProducer = /* @__PURE__ */ __name$3((connection2) => {
342211
+ var getFlowProducer = /* @__PURE__ */ __name$2((connection2) => {
342505
342212
  if (isDefined(flowProducer)) return flowProducer;
342506
342213
  flowProducer = new FlowProducer({
342507
342214
  connection: connection2
@@ -342510,7 +342217,7 @@ var getFlowProducer = /* @__PURE__ */ __name$3((connection2) => {
342510
342217
  }, "getFlowProducer");
342511
342218
 
342512
342219
  // src/queue/workers/createWorkers.ts
342513
- var createWorkers = /* @__PURE__ */ __name$3((connection2, services) => {
342220
+ var createWorkers = /* @__PURE__ */ __name$2((connection2, services) => {
342514
342221
  Xl1ToEthBridgeParent.createWorker(connection2);
342515
342222
  Xl1TransactionPreparation.createWorker(connection2, services);
342516
342223
  Xl1TransactionSubmission.createWorker(connection2, services);
@@ -342521,7 +342228,7 @@ var createWorkers = /* @__PURE__ */ __name$3((connection2, services) => {
342521
342228
  }, "createWorkers");
342522
342229
  var name = "Monitor Submitted ETH Transaction";
342523
342230
  var queueName = "eth-tx-monitor";
342524
- var createWorker = /* @__PURE__ */ __name$3((connection2, services) => {
342231
+ var createWorker = /* @__PURE__ */ __name$2((connection2, services) => {
342525
342232
  const provider = assertEx(services?.provider, () => "provider service not provided");
342526
342233
  const stateMap = assertEx(services?.ethTxStateMap, () => "ethTxStateMap service not provided");
342527
342234
  const worker = new Worker(queueName, async (job) => {
@@ -342555,7 +342262,7 @@ var EthTransactionMonitor = {
342555
342262
  };
342556
342263
  var name2 = "Prepare ETH Transaction";
342557
342264
  var queueName2 = "eth-tx-prepare";
342558
- var createWorker2 = /* @__PURE__ */ __name$3((connection2, services) => {
342265
+ var createWorker2 = /* @__PURE__ */ __name$2((connection2, services) => {
342559
342266
  const bridge = assertEx(services?.bridge, () => "bridge service not provided");
342560
342267
  const stateMap = assertEx(services?.ethTxStateMap, () => "ethTxStateMap service not provided");
342561
342268
  const worker = new Worker(queueName2, async (job) => {
@@ -342565,8 +342272,8 @@ var createWorker2 = /* @__PURE__ */ __name$3((connection2, services) => {
342565
342272
  await job.log(`[${hash}] building ETH transaction`);
342566
342273
  const bridgeIntent = assertEx(tx[1].find(isBridgeIntent), () => "No bridge intent found");
342567
342274
  const amount = hexToBigInt(bridgeIntent.destAmount);
342568
- const srcAddress = getAddress$2(bridgeIntent.srcAddress);
342569
- const destAddress = getAddress$2(bridgeIntent.destAddress);
342275
+ const srcAddress = getAddress(bridgeIntent.srcAddress);
342276
+ const destAddress = getAddress(bridgeIntent.destAddress);
342570
342277
  const nonce = hexToBigInt(await PayloadBuilder.hash(tx[0]));
342571
342278
  const preparedTx = await bridge.getFunction("bridgeFromRemote").populateTransaction(srcAddress, destAddress, amount, nonce);
342572
342279
  await job.log(`[${hash}] built ETH transaction`);
@@ -342592,7 +342299,7 @@ var EthTransactionPreparation = {
342592
342299
  name: name2,
342593
342300
  queueName: queueName2
342594
342301
  };
342595
- var submitEthTransaction = /* @__PURE__ */ __name$3(async (tx, bridgeableToken, bridge, wallet) => {
342302
+ var submitEthTransaction = /* @__PURE__ */ __name$2(async (tx, bridgeableToken, bridge, wallet) => {
342596
342303
  const xl1Transaction = assertEx(tx[0], () => "No corresponding XL1 transaction found");
342597
342304
  const bridgeIntent = assertEx(tx[1].find(isBridgeIntent), () => "No bridge intent found");
342598
342305
  const srcAddress = toEthAddress(bridgeIntent.srcAddress);
@@ -342603,17 +342310,19 @@ var submitEthTransaction = /* @__PURE__ */ __name$3(async (tx, bridgeableToken,
342603
342310
  const receipt = await bridgeTx.wait(1);
342604
342311
  return receipt?.hash;
342605
342312
  }, "submitEthTransaction");
342606
- var submitXl1Transaction = /* @__PURE__ */ __name$3(async (preparedTx, gateway) => {
342607
- const onChain = preparedTx[1].filter(isAllowedBlockPayload);
342608
- const offChainPayloads = preparedTx[1].filter((p) => !isAllowedBlockPayload(p));
342609
- const result = await gateway.addPayloadsToChain(onChain, offChainPayloads);
342610
- return result;
342313
+ var submitXl1Transaction = /* @__PURE__ */ __name$2(async (preparedTx, gateway) => {
342314
+ const runner = assertEx(gateway.connection.runner, () => "No runner available on gateway connection");
342315
+ const result = await runner.broadcastTransaction(preparedTx);
342316
+ return [
342317
+ result,
342318
+ preparedTx
342319
+ ];
342611
342320
  }, "submitXl1Transaction");
342612
342321
 
342613
342322
  // src/queue/workers/EthTransactionSubmission.ts
342614
342323
  var name3 = "Submit ETH Transaction";
342615
342324
  var queueName3 = "eth-tx-submit";
342616
- var createWorker3 = /* @__PURE__ */ __name$3((connection2, services) => {
342325
+ var createWorker3 = /* @__PURE__ */ __name$2((connection2, services) => {
342617
342326
  const bridge = assertEx(services?.bridge, () => "bridge service not provided");
342618
342327
  const bridgeableToken = assertEx(services?.bridgeableToken, () => "bridgeableToken service not provided");
342619
342328
  const wallet = assertEx(services?.wallet, () => "wallet service not provided");
@@ -342658,7 +342367,7 @@ var EthTransactionSubmission = {
342658
342367
  };
342659
342368
  var name4 = "Bridge XL1 to Ethereum";
342660
342369
  var queueName4 = "xl1-to-eth-bridge";
342661
- var createWorker4 = /* @__PURE__ */ __name$3((connection2) => {
342370
+ var createWorker4 = /* @__PURE__ */ __name$2((connection2) => {
342662
342371
  const worker = new Worker(queueName4, async (job) => {
342663
342372
  await job.log(`[${job.name}] start`);
342664
342373
  await job.log(`[${job.name}] done`);
@@ -342682,7 +342391,7 @@ var Xl1ToEthBridgeParent = {
342682
342391
  };
342683
342392
  var name5 = "Monitor Submitted XL1 Transaction";
342684
342393
  var queueName5 = "xl1-tx-monitor";
342685
- var createWorker5 = /* @__PURE__ */ __name$3((connection2, services) => {
342394
+ var createWorker5 = /* @__PURE__ */ __name$2((connection2, services) => {
342686
342395
  const gateway = assertEx(services?.gateway, () => "gateway service not provided");
342687
342396
  const stateMap = assertEx(services?.xl1TxStateMap, () => "xl1TxStateMap service not provided");
342688
342397
  const worker = new Worker(queueName5, async (job) => {
@@ -342723,7 +342432,7 @@ var Xl1TransactionMonitor = {
342723
342432
  };
342724
342433
  var name6 = "Prepare XL1 Transaction";
342725
342434
  var queueName6 = "xl1-tx-prepare";
342726
- var createWorker6 = /* @__PURE__ */ __name$3((connection2, services) => {
342435
+ var createWorker6 = /* @__PURE__ */ __name$2((connection2, services) => {
342727
342436
  const stateMap = assertEx(services?.xl1TxStateMap, () => "xl1TxStateMap service not provided");
342728
342437
  const worker = new Worker(queueName6, async (job) => {
342729
342438
  const { tx } = job.data;
@@ -342754,7 +342463,7 @@ var Xl1TransactionPreparation = {
342754
342463
  };
342755
342464
  var name7 = "Submit XL1 Transaction";
342756
342465
  var queueName7 = "xl1-tx-submit";
342757
- var createWorker7 = /* @__PURE__ */ __name$3((connection2, services) => {
342466
+ var createWorker7 = /* @__PURE__ */ __name$2((connection2, services) => {
342758
342467
  const gateway = assertEx(services?.gateway, () => "gateway service not provided");
342759
342468
  const stateMap = assertEx(services?.xl1TxStateMap, () => "xl1TxStateMap service not provided");
342760
342469
  const worker = new Worker(queueName7, async (job) => {
@@ -342796,7 +342505,7 @@ var Xl1TransactionSubmission = {
342796
342505
  };
342797
342506
 
342798
342507
  // src/queue/flows/createXl1ToEthBridgeJob.ts
342799
- var createXl1ToEthBridgeJob = /* @__PURE__ */ __name$3(async (flowProducer2, tx) => {
342508
+ var createXl1ToEthBridgeJob = /* @__PURE__ */ __name$2(async (flowProducer2, tx) => {
342800
342509
  const flow = await flowProducer2.add({
342801
342510
  name: Xl1ToEthBridgeParent.name,
342802
342511
  queueName: Xl1ToEthBridgeParent.queueName,
@@ -342882,13 +342591,13 @@ var createXl1ToEthBridgeJob = /* @__PURE__ */ __name$3(async (flowProducer2, tx)
342882
342591
  }, "createXl1ToEthBridgeJob");
342883
342592
 
342884
342593
  // src/server/addFlowProducer.ts
342885
- var addFlowProducer = /* @__PURE__ */ __name$3((app, config) => {
342594
+ var addFlowProducer = /* @__PURE__ */ __name$2((app, config) => {
342886
342595
  const connection2 = getConnection(config);
342887
342596
  const flowProducer2 = getFlowProducer(connection2);
342888
342597
  app.flowProducer = flowProducer2;
342889
342598
  return app;
342890
342599
  }, "addFlowProducer");
342891
- var addInstrumentation$2 = /* @__PURE__ */ __name$3(() => {
342600
+ var addInstrumentation$1 = /* @__PURE__ */ __name$2(() => {
342892
342601
  const instrumentations = [
342893
342602
  new HttpInstrumentation(),
342894
342603
  new ExpressInstrumentation()
@@ -342897,25 +342606,25 @@ var addInstrumentation$2 = /* @__PURE__ */ __name$3(() => {
342897
342606
  instrumentations
342898
342607
  });
342899
342608
  }, "addInstrumentation");
342900
- var asChainId = /* @__PURE__ */ __name$3((value) => {
342609
+ var asChainId = /* @__PURE__ */ __name$2((value) => {
342901
342610
  const chainId = asHex(value);
342902
342611
  return chainId;
342903
342612
  }, "asChainId");
342904
- var asToken = /* @__PURE__ */ __name$3((value) => {
342613
+ var asToken = /* @__PURE__ */ __name$2((value) => {
342905
342614
  const token = asAddress(value);
342906
342615
  return token;
342907
342616
  }, "asToken");
342908
- var tryGetBridgeEscrowAddress = /* @__PURE__ */ __name$3((config) => {
342617
+ var tryGetBridgeEscrowAddress = /* @__PURE__ */ __name$2((config) => {
342909
342618
  const address = asAddress(config.actors.bridge.escrowAddress);
342910
342619
  return address;
342911
342620
  }, "tryGetBridgeEscrowAddress");
342912
- var tryGetBridgeFeesAddress = /* @__PURE__ */ __name$3((config) => {
342621
+ var tryGetBridgeFeesAddress = /* @__PURE__ */ __name$2((config) => {
342913
342622
  const address = asAddress(config.actors.bridge.feesAddress);
342914
342623
  return address;
342915
342624
  }, "tryGetBridgeFeesAddress");
342916
342625
 
342917
342626
  // src/config/getFeeStructure.ts
342918
- var getFeeStructure = /* @__PURE__ */ __name$3((config) => {
342627
+ var getFeeStructure = /* @__PURE__ */ __name$2((config) => {
342919
342628
  const { feeFixed, feeRateBasisPoints } = config.actors.bridge;
342920
342629
  return {
342921
342630
  feeFixed,
@@ -342924,26 +342633,26 @@ var getFeeStructure = /* @__PURE__ */ __name$3((config) => {
342924
342633
  }, "getFeeStructure");
342925
342634
 
342926
342635
  // src/config/getMaxBridgeAmount.ts
342927
- var getMaxBridgeAmount = /* @__PURE__ */ __name$3((config) => {
342636
+ var getMaxBridgeAmount = /* @__PURE__ */ __name$2((config) => {
342928
342637
  const { maxBridgeAmount } = config.actors.bridge;
342929
342638
  return maxBridgeAmount;
342930
342639
  }, "getMaxBridgeAmount");
342931
342640
 
342932
342641
  // src/config/getMinBridgeAmount.ts
342933
- var getMinBridgeAmount = /* @__PURE__ */ __name$3((config) => {
342642
+ var getMinBridgeAmount = /* @__PURE__ */ __name$2((config) => {
342934
342643
  const { minBridgeAmount } = config.actors.bridge;
342935
342644
  return minBridgeAmount;
342936
342645
  }, "getMinBridgeAmount");
342937
- var getRemoteChainId = /* @__PURE__ */ __name$3((config) => {
342646
+ var getRemoteChainId = /* @__PURE__ */ __name$2((config) => {
342938
342647
  const remoteChainId = assertEx(asChainId(config.actors.bridge.remoteChainId), () => "Invalid remote chain ID in config");
342939
342648
  return remoteChainId;
342940
342649
  }, "getRemoteChainId");
342941
- var getRemoteTokenAddress = /* @__PURE__ */ __name$3((config) => {
342650
+ var getRemoteTokenAddress = /* @__PURE__ */ __name$2((config) => {
342942
342651
  const token = asToken(config.actors.bridge.remoteTokenAddress);
342943
342652
  return assertEx(token, () => "Remote token address is not defined in bridge configuration");
342944
342653
  }, "getRemoteTokenAddress");
342945
342654
  var accountServiceSingleton;
342946
- var getBridgeWalletAccount = /* @__PURE__ */ __name$3(async (config) => {
342655
+ var getBridgeWalletAccount = /* @__PURE__ */ __name$2(async (config) => {
342947
342656
  if (accountServiceSingleton) return accountServiceSingleton;
342948
342657
  let walletPhrase = config.actors.bridge.mnemonic;
342949
342658
  if (isUndefined$1(walletPhrase)) {
@@ -342963,7 +342672,7 @@ ${randomMnemonic}
342963
342672
  }, "getBridgeWalletAccount");
342964
342673
 
342965
342674
  // src/config/getTransferAddresses.ts
342966
- var getTransferAddresses = /* @__PURE__ */ __name$3(async (config) => {
342675
+ var getTransferAddresses = /* @__PURE__ */ __name$2(async (config) => {
342967
342676
  const escrowAddress = tryGetBridgeEscrowAddress(config) ?? (await getBridgeWalletAccount(config)).address;
342968
342677
  const feesAddress = tryGetBridgeFeesAddress(config) ?? (await getBridgeWalletAccount(config)).address;
342969
342678
  return {
@@ -342971,21 +342680,21 @@ var getTransferAddresses = /* @__PURE__ */ __name$3(async (config) => {
342971
342680
  feesAddress
342972
342681
  };
342973
342682
  }, "getTransferAddresses");
342974
- var getXl1ChainId = /* @__PURE__ */ __name$3((config) => {
342683
+ var getXl1ChainId = /* @__PURE__ */ __name$2((config) => {
342975
342684
  const xl1ChainId = config.actors.bridge.xl1ChainId;
342976
342685
  if (isDefined(xl1ChainId)) {
342977
342686
  return assertEx(asChainId(xl1ChainId), () => "Invalid xl1ChainId in bridge config");
342978
342687
  }
342979
342688
  return assertEx(asChainId(config.chain.id), () => "Invalid chain.id in config");
342980
342689
  }, "getXl1ChainId");
342981
- var getXl1TokenAddress = /* @__PURE__ */ __name$3((config) => {
342690
+ var getXl1TokenAddress = /* @__PURE__ */ __name$2((config) => {
342982
342691
  const token = asToken(config.actors.bridge.xl1TokenAddress);
342983
342692
  if (isDefined(token)) return token;
342984
342693
  return getXl1ChainId(config);
342985
342694
  }, "getXl1TokenAddress");
342986
342695
 
342987
342696
  // src/config/getBridgeSettings.ts
342988
- var getBridgeSettings = /* @__PURE__ */ __name$3(async (config) => {
342697
+ var getBridgeSettings = /* @__PURE__ */ __name$2(async (config) => {
342989
342698
  const { feeFixed, feeRateBasisPoints } = getFeeStructure(config);
342990
342699
  const { feesAddress, escrowAddress } = await getTransferAddresses(config);
342991
342700
  const maxBridgeAmount = getMaxBridgeAmount(config);
@@ -343007,27 +342716,13 @@ var getBridgeSettings = /* @__PURE__ */ __name$3(async (config) => {
343007
342716
  xl1ChainId
343008
342717
  };
343009
342718
  }, "getBridgeSettings");
343010
- var gatewayInstance;
343011
- var getGateway$1 = /* @__PURE__ */ __name$3(async (config) => {
343012
- if (isDefined(gatewayInstance)) return gatewayInstance;
343013
- const { mnemonic, chainRpcApiUrl: endpoint } = config.actors.bridge;
343014
- const walletPhrase = isDefined(mnemonic) ? mnemonic : HDWallet.generateMnemonic();
343015
- const wallet = await generateXyoBaseWalletFromPhrase(walletPhrase);
343016
- const signerAccount = await wallet.derivePath(ADDRESS_INDEX.XYO);
343017
- const transportFactory = /* @__PURE__ */ __name$3((schemas) => new HttpRpcTransport(endpoint, schemas), "transportFactory");
343018
- const locator = await buildJsonRpcProviderLocator({
343019
- transportFactory,
343020
- signerAccount
343021
- });
343022
- return await locator.getInstance(XyoGatewayRunnerMoniker);
343023
- }, "getGateway");
343024
342719
 
343025
342720
  // src/server/routes/bridge/routeDefinitions/routes/bridgeConfig.ts
343026
342721
  var BridgeConfigResponseZod = BridgeSettingsZod;
343027
342722
  var validateRequest$1 = requestHandlerValidator({
343028
342723
  response: BridgeConfigResponseZod
343029
342724
  });
343030
- var makeBridgeConfigRoute = /* @__PURE__ */ __name$3((config) => {
342725
+ var makeBridgeConfigRoute = /* @__PURE__ */ __name$2((config) => {
343031
342726
  return {
343032
342727
  method: "get",
343033
342728
  path: "/bridge/chains/:chainId/config",
@@ -343049,7 +342744,7 @@ var makeBridgeConfigRoute = /* @__PURE__ */ __name$3((config) => {
343049
342744
  })
343050
342745
  };
343051
342746
  }, "makeBridgeConfigRoute");
343052
- var getRemoteChainIdZod = /* @__PURE__ */ __name$3((config) => {
342747
+ var getRemoteChainIdZod = /* @__PURE__ */ __name$2((config) => {
343053
342748
  const remoteChainId = getRemoteChainId(config);
343054
342749
  return HexZod.superRefine((val, ctx) => {
343055
342750
  const chainId = asHex(val);
@@ -343064,7 +342759,7 @@ var getRemoteChainIdZod = /* @__PURE__ */ __name$3((config) => {
343064
342759
  }, "getRemoteChainIdZod");
343065
342760
 
343066
342761
  // src/server/routes/bridge/routeDefinitions/routes/bridgeFromRemoteStatus.ts
343067
- var makeBridgeFromRemoteStatusRoute = /* @__PURE__ */ __name$3((config) => {
342762
+ var makeBridgeFromRemoteStatusRoute = /* @__PURE__ */ __name$2((config) => {
343068
342763
  const params = object$4({
343069
342764
  chainId: getRemoteChainIdZod(config),
343070
342765
  nonce: string$2().nonempty()
@@ -343100,7 +342795,7 @@ var makeBridgeFromRemoteStatusRoute = /* @__PURE__ */ __name$3((config) => {
343100
342795
  })
343101
342796
  };
343102
342797
  }, "makeBridgeFromRemoteStatusRoute");
343103
- var calculateBridgeFees = /* @__PURE__ */ __name$3((srcAmount, feeStructure) => {
342798
+ var calculateBridgeFees = /* @__PURE__ */ __name$2((srcAmount, feeStructure) => {
343104
342799
  const { feeFixed, feeRateBasisPoints } = feeStructure;
343105
342800
  const srcAmountBigInt = hexToBigInt(srcAmount);
343106
342801
  const feeFixedBigInt = hexToBigInt(feeFixed);
@@ -343115,7 +342810,7 @@ var calculateBridgeFees = /* @__PURE__ */ __name$3((srcAmount, feeStructure) =>
343115
342810
  feeVariable
343116
342811
  };
343117
342812
  }, "calculateBridgeFees");
343118
- var generateBridgeEstimate = /* @__PURE__ */ __name$3(async (srcAddress, srcAmount, destAddress, config, nonceOverride) => {
342813
+ var generateBridgeEstimate = /* @__PURE__ */ __name$2(async (srcAddress, srcAmount, destAddress, config, nonceOverride) => {
343119
342814
  const { escrowAddress, feeFixed, feeRateBasisPoints, feesAddress, remoteChainId, remoteTokenAddress, xl1ChainId, xl1TokenAddress } = await getBridgeSettings(config);
343120
342815
  const sender = toAddress(srcAddress);
343121
342816
  const fees = calculateBridgeFees(srcAmount, {
@@ -343154,7 +342849,7 @@ var generateBridgeEstimate = /* @__PURE__ */ __name$3(async (srcAddress, srcAmou
343154
342849
  transfer
343155
342850
  ];
343156
342851
  }, "generateBridgeEstimate");
343157
- var validateBridgeEstimateExact = /* @__PURE__ */ __name$3(async (intent, transfer, config) => {
342852
+ var validateBridgeEstimateExact = /* @__PURE__ */ __name$2(async (intent, transfer, config) => {
343158
342853
  const { srcAddress, srcAmount, destAddress } = intent;
343159
342854
  const [calculatedIntent, calculatedTransfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config);
343160
342855
  if (isUndefined$1(calculatedIntent) || isUndefined$1(calculatedTransfer)) return false;
@@ -343166,7 +342861,7 @@ var validateBridgeEstimateExact = /* @__PURE__ */ __name$3(async (intent, transf
343166
342861
  if (await PayloadBuilder.dataHash(expectedTransferStatic) !== await PayloadBuilder.dataHash(actualTransferStatic)) return false;
343167
342862
  return true;
343168
342863
  }, "validateBridgeEstimateExact");
343169
- var validateBridgeTransaction = /* @__PURE__ */ __name$3(async (signedTxBw, intent, transfer, config) => {
342864
+ var validateBridgeTransaction = /* @__PURE__ */ __name$2(async (signedTxBw, intent, transfer, config) => {
343170
342865
  const { srcAddress } = intent;
343171
342866
  const chainId = getXl1ChainId(config);
343172
342867
  if (signedTxBw.chain !== chainId) return false;
@@ -343189,7 +342884,7 @@ var BridgeToRemoteBodyZod = tuple([
343189
342884
  TransferZod
343190
342885
  ]);
343191
342886
  var BridgeToRemoteResponseZod = PayloadZodStrictOfSchema(BridgeSourceObservationSchema).extend(BridgeSourceObservationFieldsZod.shape);
343192
- var makeBridgeToRemoteRoute = /* @__PURE__ */ __name$3((config) => {
342887
+ var makeBridgeToRemoteRoute = /* @__PURE__ */ __name$2((config) => {
343193
342888
  const params = object$4({
343194
342889
  chainId: getRemoteChainIdZod(config)
343195
342890
  });
@@ -343246,7 +342941,7 @@ var BridgeToRemoteEstimateResponseZod = tuple([
343246
342941
  PayloadZodStrictOfSchema(BridgeIntentSchema).extend(BridgeIntentFieldsZod.shape),
343247
342942
  TransferZod
343248
342943
  ]);
343249
- var makeBridgeToRemoteEstimateRoute = /* @__PURE__ */ __name$3((config) => {
342944
+ var makeBridgeToRemoteEstimateRoute = /* @__PURE__ */ __name$2((config, gateway) => {
343250
342945
  const params = object$4({
343251
342946
  chainId: getRemoteChainIdZod(config)
343252
342947
  });
@@ -343263,7 +342958,6 @@ var makeBridgeToRemoteEstimateRoute = /* @__PURE__ */ __name$3((config) => {
343263
342958
  const { srcAddress, srcAmount, destAddress } = req.body;
343264
342959
  const [bridgeIntent, transfer] = await generateBridgeEstimate(srcAddress, srcAmount, destAddress, config);
343265
342960
  const sender = toAddress(srcAddress);
343266
- const gateway = await getGateway$1(config);
343267
342961
  const viewer = assertEx(gateway.connection.viewer, () => new Error("Viewer not available on gateway connection"));
343268
342962
  const currentBlockNumber = await viewer.currentBlockNumber();
343269
342963
  const nbf = toXL1BlockNumber(currentBlockNumber, true);
@@ -343296,7 +342990,7 @@ var BridgeToRemoteStatusResponseZod = union$1([
343296
342990
  PayloadZodStrictOfSchema(BridgeDestinationObservationSchema).extend(BridgeDestinationObservationFieldsZod.shape)
343297
342991
  ])
343298
342992
  ]);
343299
- var makeBridgeToRemoteStatusRoute = /* @__PURE__ */ __name$3((config) => {
342993
+ var makeBridgeToRemoteStatusRoute = /* @__PURE__ */ __name$2((config) => {
343300
342994
  const params = object$4({
343301
342995
  chainId: getRemoteChainIdZod(config),
343302
342996
  nonce: string$2().nonempty()
@@ -343366,10 +343060,10 @@ var makeBridgeToRemoteStatusRoute = /* @__PURE__ */ __name$3((config) => {
343366
343060
  }, "makeBridgeToRemoteStatusRoute");
343367
343061
 
343368
343062
  // src/server/routes/bridge/routeDefinitions/getRouteDefinitions.ts
343369
- var getRouteDefinitions$1 = /* @__PURE__ */ __name$3((config) => {
343063
+ var getRouteDefinitions$1 = /* @__PURE__ */ __name$2((config, gateway) => {
343370
343064
  return [
343371
343065
  makeBridgeConfigRoute(config),
343372
- makeBridgeToRemoteEstimateRoute(config),
343066
+ makeBridgeToRemoteEstimateRoute(config, gateway),
343373
343067
  makeBridgeToRemoteRoute(config),
343374
343068
  makeBridgeToRemoteStatusRoute(config),
343375
343069
  makeBridgeFromRemoteStatusRoute(config)
@@ -343377,21 +343071,21 @@ var getRouteDefinitions$1 = /* @__PURE__ */ __name$3((config) => {
343377
343071
  }, "getRouteDefinitions");
343378
343072
 
343379
343073
  // src/server/routes/bridge/addBridgeRoutes.ts
343380
- var addBridgeRoutes = /* @__PURE__ */ __name$3((app, config) => {
343381
- const routeDefinitions = getRouteDefinitions$1(config);
343074
+ var addBridgeRoutes = /* @__PURE__ */ __name$2((app, config, gateway) => {
343075
+ const routeDefinitions = getRouteDefinitions$1(config, gateway);
343382
343076
  for (const definition of routeDefinitions) {
343383
343077
  app[definition.method](definition.path, definition.handlers);
343384
343078
  }
343385
343079
  }, "addBridgeRoutes");
343386
343080
 
343387
343081
  // src/server/routes/addRoutes.ts
343388
- var addRoutes$2 = /* @__PURE__ */ __name$3((app, config) => {
343389
- addBridgeRoutes(app, config);
343082
+ var addRoutes$1 = /* @__PURE__ */ __name$2((app, config, gateway) => {
343083
+ addBridgeRoutes(app, config, gateway);
343390
343084
  }, "addRoutes");
343391
343085
 
343392
343086
  // src/server/app.ts
343393
- var getApp$2 = /* @__PURE__ */ __name$3((node, config) => {
343394
- addInstrumentation$2();
343087
+ var getApp$1 = /* @__PURE__ */ __name$2((node, config, gateway) => {
343088
+ addInstrumentation$1();
343395
343089
  const app = express2();
343396
343090
  app.set("etag", false);
343397
343091
  app.use(cors());
@@ -343406,7 +343100,7 @@ var getApp$2 = /* @__PURE__ */ __name$3((node, config) => {
343406
343100
  disableCaseSensitiveRouting(app);
343407
343101
  app.node = node;
343408
343102
  addFlowProducer(app, config);
343409
- addRoutes$2(app, config);
343103
+ addRoutes$1(app, config, gateway);
343410
343104
  app.use(standardErrors);
343411
343105
  return app;
343412
343106
  }, "getApp");
@@ -343414,7 +343108,7 @@ var EVMLiquidityBridgeTransactionCompletionMonitorSentinelConfigSchema = asSchem
343414
343108
  var defaultJobCheckIntervalMs = 15e3;
343415
343109
  var EVMLiquidityBridgeTransactionCompletionMonitorSentinel = class extends AbstractSentinel {
343416
343110
  static {
343417
- __name$3(this, "EVMLiquidityBridgeTransactionCompletionMonitorSentinel");
343111
+ __name$2(this, "EVMLiquidityBridgeTransactionCompletionMonitorSentinel");
343418
343112
  }
343419
343113
  static configSchemas = [
343420
343114
  EVMLiquidityBridgeTransactionCompletionMonitorSentinelConfigSchema
@@ -343462,7 +343156,7 @@ var EVMLiquidityBridgeTransactionCompletionMonitorSentinel = class extends Abstr
343462
343156
  const { provider, bridgeAddress } = this.params;
343463
343157
  const key = assertEx(this.account?.private?.hex, () => new Error("Account private key is required"));
343464
343158
  this._wallet = new Wallet(key, provider);
343465
- this._bridge = LiquidityPoolBridge__factory.connect(getAddress$2(bridgeAddress), this._wallet);
343159
+ this._bridge = LiquidityPoolBridge__factory.connect(getAddress(bridgeAddress), this._wallet);
343466
343160
  const network = await provider.getNetwork();
343467
343161
  this._bridgeChainId = assertEx(hexFromBigInt(network.chainId), () => new Error("Failed to parse bridgeChainId"));
343468
343162
  const tokenAddress = await this.bridge.token();
@@ -343536,8 +343230,8 @@ var EVMLiquidityBridgeTransactionCompletionMonitorSentinel = class extends Abstr
343536
343230
  async relayBridgeIntentSync(bridgeIntent) {
343537
343231
  const amount = hexToBigInt(bridgeIntent.destAmount);
343538
343232
  const nonce = await this.wallet.getNonce();
343539
- const srcAddress = getAddress$2(bridgeIntent.srcAddress);
343540
- const destAddress = getAddress$2(bridgeIntent.destAddress);
343233
+ const srcAddress = getAddress(bridgeIntent.srcAddress);
343234
+ const destAddress = getAddress(bridgeIntent.destAddress);
343541
343235
  const tx = await this.bridge.bridgeFromRemote(srcAddress, destAddress, amount, nonce);
343542
343236
  const confirmation = await tx.wait();
343543
343237
  const transactionResponse = await confirmation?.getTransaction();
@@ -343556,7 +343250,7 @@ var XL1TransactionCompletionMonitorSentinelConfigSchema = asSchema("network.xyo.
343556
343250
  var defaultJobCheckIntervalMs2 = 15e3;
343557
343251
  var XL1TransactionCompletionMonitorSentinel = class extends AbstractSentinel {
343558
343252
  static {
343559
- __name$3(this, "XL1TransactionCompletionMonitorSentinel");
343253
+ __name$2(this, "XL1TransactionCompletionMonitorSentinel");
343560
343254
  }
343561
343255
  static configSchemas = [
343562
343256
  XL1TransactionCompletionMonitorSentinelConfigSchema
@@ -343663,7 +343357,7 @@ var XL1TransactionCompletionMonitorSentinel = class extends AbstractSentinel {
343663
343357
  };
343664
343358
 
343665
343359
  // src/manifest/getModuleLocator.ts
343666
- var getModuleLocator = /* @__PURE__ */ __name$3(async (context) => {
343360
+ var getModuleLocator = /* @__PURE__ */ __name$2(async (context) => {
343667
343361
  const { config, locator, logger } = context;
343668
343362
  const { otlpEndpoint } = config.telemetry?.otel ?? {};
343669
343363
  const { path: endpoint = "/metrics", port = 9468 } = config.telemetry?.metrics?.scrape ?? {};
@@ -343750,7 +343444,7 @@ var getModuleLocator = /* @__PURE__ */ __name$3(async (context) => {
343750
343444
  moduleLocator.register(EVMLiquidityBridgeTransactionCompletionMonitorSentinel.factory(evmLiquidityBridgeTransactionCompletionMonitorSentinelParams));
343751
343445
  return moduleLocator;
343752
343446
  }, "getModuleLocator");
343753
- var getIterableMap = /* @__PURE__ */ __name$3(async (config, collection) => {
343447
+ var getIterableMap = /* @__PURE__ */ __name$2(async (config, collection) => {
343754
343448
  const mongoConfig = config.storage?.mongo;
343755
343449
  if (hasMongoConfig(mongoConfig)) {
343756
343450
  const { connectionString: dbConnectionString, database: dbName, domain: dbDomain, password: dbPassword, username: dbUserName } = mongoConfig;
@@ -343801,10 +343495,10 @@ var node_default$1 = {
343801
343495
  var NodeManifest$1 = node_default$1;
343802
343496
 
343803
343497
  // src/manifest/getNode.ts
343804
- var getNode$1 = /* @__PURE__ */ __name$3(async (context) => {
343498
+ var getNode$1 = /* @__PURE__ */ __name$2(async (context) => {
343805
343499
  const { config, wallet } = context;
343806
343500
  const { chainRpcApiUrl: endpoint } = config.actors.bridge;
343807
- const transportFactory = /* @__PURE__ */ __name$3((schemas) => new HttpRpcTransport(endpoint, schemas), "transportFactory");
343501
+ const transportFactory = /* @__PURE__ */ __name$2((schemas) => new HttpRpcTransport(endpoint, schemas), "transportFactory");
343808
343502
  const signerAccount = await getBridgeWalletAccount(config);
343809
343503
  const locator = await buildJsonRpcProviderLocator({
343810
343504
  signerAccount,
@@ -343822,7 +343516,7 @@ var getNode$1 = /* @__PURE__ */ __name$3(async (context) => {
343822
343516
  }
343823
343517
  return node;
343824
343518
  }, "getNode");
343825
- var getIterableMap2 = /* @__PURE__ */ __name$3(async (config, collection) => {
343519
+ var getIterableMap2 = /* @__PURE__ */ __name$2(async (config, collection) => {
343826
343520
  const mongoConfig = config.storage?.mongo;
343827
343521
  if (hasMongoConfig(mongoConfig)) {
343828
343522
  const { connectionString: dbConnectionString, database: dbName, domain: dbDomain, password: dbPassword, username: dbUserName } = mongoConfig;
@@ -343851,9 +343545,8 @@ var getIterableMap2 = /* @__PURE__ */ __name$3(async (config, collection) => {
343851
343545
  }, "getIterableMap");
343852
343546
 
343853
343547
  // src/manifest/getServices.ts
343854
- var getServices = /* @__PURE__ */ __name$3(async (context) => {
343548
+ var getServices = /* @__PURE__ */ __name$2(async (context, gateway) => {
343855
343549
  const { config } = context;
343856
- const gateway = await getGateway$1(config);
343857
343550
  const ethTxStateMap = await getIterableMap2(config, "liquidity_bridge_xl1_to_eth_eth_tx_state");
343858
343551
  const xl1TxStateMap = await getIterableMap2(config, "liquidity_bridge_xl1_to_eth_xl1_tx_state");
343859
343552
  const provider = await initEvmProvider({
@@ -343862,8 +343555,8 @@ var getServices = /* @__PURE__ */ __name$3(async (context) => {
343862
343555
  const { remoteBridgeContractAddress, remoteChainWalletPrivateKey, remoteTokenAddress, mnemonic } = config.actors.bridge;
343863
343556
  const account = isDefined(mnemonic) ? await HDWallet.fromPhrase(mnemonic) : await HDWallet.random();
343864
343557
  const wallet = new Wallet(remoteChainWalletPrivateKey, provider);
343865
- const bridgeableToken = BridgeableToken__factory.connect(getAddress$2(remoteTokenAddress), wallet);
343866
- const bridge = LiquidityPoolBridge__factory.connect(getAddress$2(remoteBridgeContractAddress), wallet);
343558
+ const bridgeableToken = BridgeableToken__factory.connect(getAddress(remoteTokenAddress), wallet);
343559
+ const bridge = LiquidityPoolBridge__factory.connect(getAddress(remoteBridgeContractAddress), wallet);
343867
343560
  const bridgeOwner = await bridge.owner();
343868
343561
  assertEx(bridgeOwner.toLowerCase() === wallet.address.toLowerCase(), () => "Wallet is not the owner of the bridge contract");
343869
343562
  return {
@@ -343879,14 +343572,14 @@ var getServices = /* @__PURE__ */ __name$3(async (context) => {
343879
343572
  }, "getServices");
343880
343573
 
343881
343574
  // src/server/addWorkers.ts
343882
- var addWorkers = /* @__PURE__ */ __name$3((config, services) => {
343575
+ var addWorkers = /* @__PURE__ */ __name$2((config, services) => {
343883
343576
  const connection2 = getConnection(config);
343884
343577
  createWorkers(connection2, services);
343885
343578
  }, "addWorkers");
343886
343579
 
343887
343580
  // src/server/server.ts
343888
- var hostname$2 = "::";
343889
- var getSeedPhrase$1 = /* @__PURE__ */ __name$3(async (bios, config, logger) => {
343581
+ var hostname$1 = "::";
343582
+ var getSeedPhrase$1 = /* @__PURE__ */ __name$2(async (bios, config, logger) => {
343890
343583
  const storedSeedPhrase = await bios.seedPhraseStore.get("os");
343891
343584
  logger?.debug(`[Bridge] Stored mnemonic: ${storedSeedPhrase}`);
343892
343585
  const { mnemonic } = config.actors.api;
@@ -343906,7 +343599,7 @@ var getSeedPhrase$1 = /* @__PURE__ */ __name$3(async (bios, config, logger) => {
343906
343599
  }
343907
343600
  return assertEx(await bios.seedPhraseStore.get("os"), () => "Unable to acquire mnemonic from bios");
343908
343601
  }, "getSeedPhrase");
343909
- var getServer$2 = /* @__PURE__ */ __name$3(async (context) => {
343602
+ var getServer$1 = /* @__PURE__ */ __name$2(async (context, gateway) => {
343910
343603
  const { logger, config } = context;
343911
343604
  const { port, mnemonic } = config.actors.bridge;
343912
343605
  const bios = await boot();
@@ -343918,369 +343611,58 @@ var getServer$2 = /* @__PURE__ */ __name$3(async (context) => {
343918
343611
  config
343919
343612
  };
343920
343613
  const node = context.node ?? await getNode$1(nodeContext);
343921
- const app = getApp$2(node, config);
343614
+ const app = getApp$1(node, config, gateway);
343922
343615
  const services = await getServices({
343923
343616
  config,
343924
343617
  logger
343925
- });
343618
+ }, gateway);
343926
343619
  addWorkers(config, services);
343927
- const server = app.listen(port, hostname$2, () => logger?.log(`[Bridge] Server listening at http://${hostname$2}:${port}`));
343620
+ const server = app.listen(port, hostname$1, () => logger?.log(`[Bridge] Server listening at http://${hostname$1}:${port}`));
343928
343621
  server.setTimeout(2e4);
343929
343622
  return server;
343930
343623
  }, "getServer");
343931
343624
 
343932
- var __defProp$2 = Object.defineProperty;
343933
- var __name$2 = (target, value) => __defProp$2(target, "name", { value, configurable: true });
343934
- var addInstrumentation$1 = /* @__PURE__ */ __name$2(() => {
343935
- const instrumentations = [
343936
- new HttpInstrumentation(),
343937
- new ExpressInstrumentation()
343938
- ];
343939
- registerInstrumentations({
343940
- instrumentations
343941
- });
343942
- }, "addInstrumentation");
343943
- var handler = /* @__PURE__ */ __name$2(async (req, res, next) => {
343944
- const { address: moduleIdentifier } = req.params;
343945
- const { node } = req.app;
343946
- const address = asAddress(moduleIdentifier);
343947
- if (isDefined(address)) {
343948
- let mod = node.address === address ? node : await node.resolve(address, {
343949
- direction: "down"
343950
- });
343951
- if (mod) {
343952
- res.json(await mod.state());
343953
- return;
343954
- }
343625
+ // src/BridgeActor.ts
343626
+ function _ts_decorate$1(decorators, target, key, desc) {
343627
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
343628
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
343629
+ 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;
343630
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
343631
+ }
343632
+ __name$2(_ts_decorate$1, "_ts_decorate");
343633
+ var BridgeActor = class extends ActorV3 {
343634
+ static {
343635
+ __name$2(this, "BridgeActor");
343955
343636
  }
343956
- if (isModuleName(moduleIdentifier)) {
343957
- const mod = await node.resolve(moduleIdentifier, {
343958
- direction: "down"
343959
- });
343960
- if (mod) {
343961
- res.redirect(StatusCodes.MOVED_TEMPORARILY, `/${mod.address}`);
343962
- return;
343963
- }
343637
+ _gatewayRunner;
343638
+ server;
343639
+ get gatewayRunner() {
343640
+ return this._gatewayRunner;
343964
343641
  }
343965
- next("route");
343966
- }, "handler");
343967
- var getAddress = asyncHandler(handler);
343968
- var DEFAULT_DEPTH = 5;
343969
- var getQueryConfig = /* @__PURE__ */ __name$2((mod, req, bw, payloads) => {
343970
- const nestedBwAddresses = payloads?.flat(DEFAULT_DEPTH).filter((payload) => payload?.schema === BoundWitnessSchema).map((bw2) => bw2.addresses) ?? [];
343971
- const addresses = [
343972
- bw.addresses,
343973
- ...nestedBwAddresses
343974
- ].filter((address) => address.length > 0);
343975
- const allowed = addresses.length > 0 ? Object.fromEntries(mod.queries.map((schema) => [
343976
- schema,
343977
- addresses
343978
- ])) : {};
343979
- const security = {
343980
- allowed
343981
- };
343982
- return {
343983
- schema: ModuleConfigSchema,
343984
- security
343985
- };
343986
- }, "getQueryConfig");
343987
-
343988
- // src/server/routes/address/post/post.ts
343989
- var handler2 = /* @__PURE__ */ __name$2(async (req, res, next) => {
343990
- const returnError = /* @__PURE__ */ __name$2((code, message = "An error occurred", details) => {
343991
- const error = new ModuleErrorBuilder().message(message).details(details).build();
343992
- res.locals.rawResponse = false;
343993
- res.status(code).json(error);
343994
- next();
343995
- }, "returnError");
343996
- const { address } = req.params;
343997
- const { node } = req.app;
343998
- const [bw, payloads] = Array.isArray(req.body) ? req.body : [];
343999
- if (!isAddress(address)) {
344000
- return returnError(StatusCodes.BAD_REQUEST, "Missing address");
344001
- }
344002
- if (!bw) {
344003
- return returnError(StatusCodes.BAD_REQUEST, "Missing boundwitness");
344004
- }
344005
- if (!isQueryBoundWitness(bw)) {
344006
- return returnError(StatusCodes.BAD_REQUEST, "Invalid query boundwitness");
344007
- }
344008
- let modules = [];
344009
- const normalizedAddress = toAddress(address);
344010
- if (node.address === normalizedAddress) modules = [
344011
- node
344012
- ];
344013
- else {
344014
- const typedAddress = asAddress(address);
344015
- const byAddress = typedAddress === void 0 ? void 0 : await node.resolve(typedAddress, {
344016
- maxDepth: 10
344017
- });
344018
- if (byAddress) modules = [
344019
- byAddress
344020
- ];
344021
- else {
344022
- const byName = await node.resolve(address, {
344023
- direction: "down"
344024
- });
344025
- if (byName) {
344026
- const moduleAddress = assertEx(byName?.address, () => "Error redirecting to module by address");
344027
- res.redirect(StatusCodes.TEMPORARY_REDIRECT, `/${moduleAddress}`);
344028
- return;
344029
- } else {
344030
- return returnError(StatusCodes.NOT_FOUND, "Module not found", {
344031
- address
344032
- });
344033
- }
344034
- }
343642
+ async createHandler() {
343643
+ await super.createHandler();
343644
+ this._gatewayRunner = await this.locator.getInstance(XyoGatewayRunnerMoniker);
344035
343645
  }
344036
- if (modules.length > 0) {
344037
- const mod = modules[0];
344038
- const queryConfig = getQueryConfig(mod, req, bw, payloads);
344039
- try {
344040
- const queryResult = await mod.query(bw, payloads, queryConfig);
344041
- res.json(queryResult);
344042
- } catch (ex) {
344043
- return returnError(StatusCodes.INTERNAL_SERVER_ERROR, "Query Failed", {
344044
- message: ex?.message ?? "Unknown Error"
344045
- });
344046
- }
344047
- } else {
344048
- return returnError(StatusCodes.NOT_FOUND, "Module not found", {
344049
- address
344050
- });
343646
+ async startHandler() {
343647
+ await super.startHandler();
343648
+ this.stopServer();
343649
+ await this.startServer();
344051
343650
  }
344052
- }, "handler");
344053
- var postAddress = asyncHandler(handler2);
344054
-
344055
- // src/server/routes/address/addNodeRoutes.ts
344056
- var addNodeRoutes = /* @__PURE__ */ __name$2((app) => {
344057
- const defaultModule = app.node;
344058
- const address = defaultModule.address;
344059
- const defaultModuleEndpoint = `/${address}`;
344060
- app.get("/", (_req, res) => res.redirect(StatusCodes.MOVED_TEMPORARILY, defaultModuleEndpoint));
344061
- app.post("/", (_req, res) => res.redirect(StatusCodes.TEMPORARY_REDIRECT, defaultModuleEndpoint));
344062
- app.get("/:address", getAddress);
344063
- app.post("/:address", postAddress);
344064
- app.get("/:hash", (_req, res) => {
344065
- res.sendStatus(StatusCodes.NOT_FOUND);
344066
- });
344067
- app.post("/:hash", (_req, res) => {
344068
- res.sendStatus(StatusCodes.NOT_FOUND);
344069
- });
344070
- }, "addNodeRoutes");
344071
- var resolveArchivist$1 = /* @__PURE__ */ __name$2(async (node, archivistModuleIdentifier) => {
344072
- const mod = await node.resolve(archivistModuleIdentifier);
344073
- return asArchivistInstance(mod, {
344074
- required: true
344075
- });
344076
- }, "resolveArchivist");
344077
- var archivistInstance$1;
344078
- var getArchivist$1 = /* @__PURE__ */ __name$2(async (node, archivistModuleIdentifier) => {
344079
- if (isDefined(archivistInstance$1)) return archivistInstance$1;
344080
- archivistInstance$1 = await resolveArchivist$1(node, archivistModuleIdentifier);
344081
- return archivistInstance$1;
344082
- }, "getArchivist");
344083
- var archivistMiddleware$1 = /* @__PURE__ */ __name$2((options) => {
344084
- const { node, archivistModuleIdentifier } = options;
344085
- const router = express2.Router({
344086
- mergeParams: true
344087
- });
344088
- router.post("/insert", async (req, res) => {
344089
- setRawResponseFormat(res);
344090
- const body = Array.isArray(req.body) ? req.body : [
344091
- req.body
344092
- ];
344093
- const payloads = (await PayloadBuilder.hashPairs(body)).map((p) => p[0]);
344094
- const archivist = await getArchivist$1(node, archivistModuleIdentifier);
344095
- const result = await archivist.insert(payloads);
344096
- res.status(200).json(result);
344097
- });
344098
- router.get("/next", async (req, res) => {
344099
- setRawResponseFormat(res);
344100
- const cursor = isSequence(req.query.cursor) ? req.query.cursor : void 0;
344101
- const limit = isDefined(req.query.limit) ? Number(req.query.limit) : void 0;
344102
- const open = isDefined(req.query.open) ? Boolean(req.query.open) : void 0;
344103
- const order = req.query.order === "asc" ? "asc" : "desc";
344104
- const options2 = {
344105
- limit,
344106
- open,
344107
- order,
344108
- cursor
344109
- };
344110
- const archivist = await getArchivist$1(node, archivistModuleIdentifier);
344111
- const result = await archivist.next(options2);
344112
- res.status(200).json(result);
344113
- });
344114
- router.post("/next", async (req, res) => {
344115
- setRawResponseFormat(res);
344116
- const options2 = req.body;
344117
- const archivist = await getArchivist$1(node, archivistModuleIdentifier);
344118
- const result = await (isDefined(options2) ? archivist.next(options2) : archivist.next());
344119
- res.status(200).json(result);
344120
- });
344121
- router.get("/get/:hash", async (req, res) => {
344122
- setRawResponseFormat(res);
344123
- const { hash: rawHash } = req.params;
344124
- const hash = asHash(rawHash);
344125
- if (isDefined(hash)) {
344126
- const archivist = await getArchivist$1(node, archivistModuleIdentifier);
344127
- const [payload] = await archivist.get([
344128
- hash
344129
- ]);
344130
- if (isAnyPayload(payload)) {
344131
- res.json(payload);
344132
- return;
344133
- }
344134
- }
344135
- res.status(400).send();
344136
- });
344137
- return router;
344138
- }, "archivistMiddleware");
344139
-
344140
- // src/server/routes/dataLake/addDataLakeRoutes.ts
344141
- var addDataLakeRoutes$1 = /* @__PURE__ */ __name$2((app) => {
344142
- const { node } = app;
344143
- const archivistModuleIdentifier = "Chain:Finalized";
344144
- app.use("/chain", archivistMiddleware$1({
344145
- node,
344146
- archivistModuleIdentifier
344147
- }));
344148
- }, "addDataLakeRoutes");
344149
- var addHealthRoutes = /* @__PURE__ */ __name$2((app) => {
344150
- app.get("/healthz", (_req, res) => {
344151
- res.status(StatusCodes.OK).send();
344152
- });
344153
- app.get("/livez", (_req, res) => {
344154
- res.status(StatusCodes.OK).send();
344155
- });
344156
- app.get("/readyz", (_req, res) => {
344157
- res.status(StatusCodes.OK).send();
344158
- });
344159
- }, "addHealthRoutes");
344160
-
344161
- // src/server/routes/addRoutes.ts
344162
- var addRoutes$1 = /* @__PURE__ */ __name$2((app) => {
344163
- addHealthRoutes(app);
344164
- addDataLakeRoutes$1(app);
344165
- addNodeRoutes(app);
344166
- }, "addRoutes");
344167
-
344168
- // src/server/app.ts
344169
- var getApp$1 = /* @__PURE__ */ __name$2((context) => {
344170
- addInstrumentation$1();
344171
- const app = express2();
344172
- app.set("etag", false);
344173
- app.use(cors());
344174
- app.use(compression$1());
344175
- app.use(responseProfiler);
344176
- app.use(getJsonBodyParser(getJsonBodyParserOptions({
344177
- limit: "1mb"
344178
- })));
344179
- app.use(standardResponses);
344180
- disableExpressDefaultPoweredByHeader(app);
344181
- app.use(customPoweredByHeader);
344182
- disableCaseSensitiveRouting(app);
344183
- app.context = context;
344184
- app.node = context.node;
344185
- addRoutes$1(app);
344186
- app.use(standardErrors);
344187
- return app;
344188
- }, "getApp");
344189
- var hostname$1 = "::";
344190
- var getProviderFactoryLocator = /* @__PURE__ */ __name$2((context, finalizedArchivist, pendingTransactionsArchivist, pendingBlocksArchivist) => {
344191
- const locator = new ProviderFactoryLocator(context);
344192
- locator.register(SimpleBlockValidationViewer.factory(SimpleBlockValidationViewer.dependencies, {
344193
- state: validateHydratedBlockState,
344194
- protocol: validateHydratedBlock
344195
- }));
344196
- locator.register(SimpleMempoolViewer.factory(SimpleMempoolViewer.dependencies, {
344197
- pendingTransactionsArchivist,
344198
- pendingBlocksArchivist
344199
- }));
344200
- locator.register(SimpleMempoolRunner.factory(SimpleMempoolRunner.dependencies, {
344201
- pendingTransactionsArchivist,
344202
- pendingBlocksArchivist
344203
- }));
344204
- locator.register(SimpleBlockViewer.factory(SimpleBlockViewer.dependencies, {
344205
- finalizedArchivist
344206
- }));
344207
- locator.register(SimpleWindowedBlockViewer.factory(SimpleWindowedBlockViewer.dependencies, {
344208
- maxWindowSize: 1e4,
344209
- syncInterval: 1e4
344210
- }));
344211
- locator.register(SimpleStakeViewer.factory(SimpleStakeViewer.dependencies, {}));
344212
- locator.register(SimpleStakeEventsViewer.factory(SimpleStakeEventsViewer.dependencies, {}));
344213
- return locator;
344214
- }, "getProviderFactoryLocator");
344215
- var getServer$1 = /* @__PURE__ */ __name$2(async (context) => {
344216
- const { config, node: providedNode } = context;
344217
- const { port } = context.config.actors.api;
344218
- const logger = assertEx(context.logger, () => "Logger is required to init server");
344219
- const statusReporter = initStatusReporter({
344220
- logger
344221
- });
344222
- await startupSpanAsync("initHealthEndpoints", () => initHealthEndpoints({
344223
- config,
344224
- logger,
344225
- statusReporter
344226
- }));
344227
- const telemetryConfig = buildTelemetryConfig(config, "xl1-mempool", "1.0.0", DefaultMetricsScrapePorts.mempool);
344228
- const { traceProvider, meterProvider } = await startupSpanAsync("initTelemetry", () => initTelemetry(telemetryConfig));
344229
- const initContext = {
344230
- _id: "init-context",
344231
- config,
344232
- logger,
344233
- statusReporter,
344234
- meterProvider,
344235
- traceProvider,
344236
- singletons: {},
344237
- caches: {}
344238
- };
344239
- const wallet = await initMempoolWallet(initContext);
344240
- const balancesSummaryMap = assertEx(await initBalanceSummaryMap(initContext), () => "Balance Summary Map not initialized");
344241
- const transfersSummaryMap = assertEx(await initTransferSummaryMap(initContext), () => "Transfer Summary Map not initialized");
344242
- const { node, writableChainArchivist, readonlyChainArchivist, pendingTransactionsArchivist, pendingBlocksArchivist } = await initServerNode({
344243
- ...initContext,
344244
- wallet,
344245
- node: providedNode,
344246
- transfersSummaryMap,
344247
- balancesSummaryMap
344248
- });
344249
- assertEx(await findMostRecentBlock(readonlyChainArchivist), () => "No head found");
344250
- const mods = await node.resolve("*");
344251
- await Promise.all(mods.map((mod) => {
344252
- return mod.start?.() ?? (() => true);
344253
- }));
344254
- const locator = getProviderFactoryLocator(initContext, writableChainArchivist, pendingTransactionsArchivist, pendingBlocksArchivist);
344255
- const mempoolContext = {
344256
- ...initContext,
344257
- node,
344258
- transfersSummaryMap,
344259
- balancesSummaryMap,
344260
- ...locator.context,
344261
- _id: "mempool-context"
344262
- };
344263
- const blockViewer = await locator.getInstance(BlockViewerMoniker);
344264
- assertEx(await blockViewer.start(), () => "Failed to start BlockViewer");
344265
- const blk = await blockViewer.currentBlock();
344266
- assertEx(blk, () => "No blocks found after initialization");
344267
- const mempoolViewer = await locator.getInstance(MempoolViewerMoniker);
344268
- assertEx(await mempoolViewer.start(), () => "Failed to start MempoolViewer");
344269
- console.info(`[Mempool] Current block after initialization: #${blk[0].block} (${blk[0]._hash})`);
344270
- const actor = await ValidatorActor.create({
344271
- id: "validator-mempool-server",
344272
- account: wallet,
344273
- context: locator.context,
344274
- finalizedArchivist: writableChainArchivist,
344275
- blockViewer,
344276
- mempoolViewer
344277
- });
344278
- await actor.start();
344279
- const app = getApp$1(mempoolContext);
344280
- const server = app.listen(port, hostname$1, () => logger?.log(`[Mempool] Server listening at http://${hostname$1}:${port}`));
344281
- server.setTimeout(2e4);
344282
- return server;
344283
- }, "getServer");
343651
+ async stopHandler() {
343652
+ await super.stopHandler();
343653
+ this.stopServer();
343654
+ }
343655
+ async startServer() {
343656
+ this.server = await getServer$1(this.context, this._gatewayRunner);
343657
+ }
343658
+ stopServer() {
343659
+ this.server?.close();
343660
+ this.server = void 0;
343661
+ }
343662
+ };
343663
+ BridgeActor = _ts_decorate$1([
343664
+ creatable()
343665
+ ], BridgeActor);
344284
343666
 
344285
343667
  var __defProp$1 = Object.defineProperty;
344286
343668
  var __name$1 = (target, value) => __defProp$1(target, "name", { value, configurable: true });
@@ -344791,7 +344173,7 @@ var DerivedAddressWalletTransferSentinel = class extends AbstractSentinel {
344791
344173
  };
344792
344174
 
344793
344175
  // src/manifest/getLocator.ts
344794
- var getLocator = /* @__PURE__ */ __name$1(async (context) => {
344176
+ var getLocator = /* @__PURE__ */ __name$1(async (context, gateway) => {
344795
344177
  const { config, logger } = context;
344796
344178
  const { otlpEndpoint } = config.telemetry?.otel ?? {};
344797
344179
  const { path: endpoint = "/metrics", port = 9467 } = config.telemetry?.metrics?.scrape ?? {};
@@ -344842,7 +344224,6 @@ var getLocator = /* @__PURE__ */ __name$1(async (context) => {
344842
344224
  meterProvider,
344843
344225
  statusReporter
344844
344226
  }));
344845
- const gateway = await getGateway(config);
344846
344227
  const chainStepRewardsClaimSentinelParams = {
344847
344228
  gateway,
344848
344229
  traceProvider,
@@ -344859,22 +344240,6 @@ var getLocator = /* @__PURE__ */ __name$1(async (context) => {
344859
344240
  locator.register(DerivedAddressWalletTransferSentinel.factory(derivedAddressWalletTransferSentinelParams));
344860
344241
  return locator;
344861
344242
  }, "getLocator");
344862
- var getGateway = /* @__PURE__ */ __name$1(async (config) => {
344863
- const { mnemonic, chainRpcApiUrl } = config.actors.rewardRedemption;
344864
- const transportFactory = /* @__PURE__ */ __name$1((schemas) => new HttpRpcTransport(chainRpcApiUrl, schemas), "transportFactory");
344865
- const locator = await buildJsonRpcProviderLocator({
344866
- transportFactory
344867
- });
344868
- const phrase = mnemonic ?? HDWallet.generateMnemonic();
344869
- const wallet = await generateXyoBaseWalletFromPhrase(phrase);
344870
- const account = await wallet.derivePath(ADDRESS_INDEX.XYO);
344871
- locator.register(SimpleXyoSigner.factory(SimpleXyoSigner.dependencies, {
344872
- account
344873
- }));
344874
- locator.register(SimpleXyoGatewayRunner.factory(SimpleXyoGatewayRunner.dependencies, {}));
344875
- const gateway = await locator.getInstance(SimpleXyoGatewayRunner.defaultMoniker);
344876
- return gateway;
344877
- }, "getGateway");
344878
344243
 
344879
344244
  // src/manifest/node.json
344880
344245
  var node_default = {
@@ -344973,9 +344338,9 @@ var PrivateChildManifests = [];
344973
344338
  var PublicChildManifests = [];
344974
344339
 
344975
344340
  // src/manifest/getNode.ts
344976
- var getNode = /* @__PURE__ */ __name$1(async (context) => {
344341
+ var getNode = /* @__PURE__ */ __name$1(async (context, gateway) => {
344977
344342
  const { wallet } = context;
344978
- const locator = await getLocator(context);
344343
+ const locator = await getLocator(context, gateway);
344979
344344
  const wrapper = new ManifestWrapper(NodeManifest, wallet, locator, PublicChildManifests, PrivateChildManifests);
344980
344345
  const [node, ...childNodes] = await wrapper.loadNodes();
344981
344346
  if (childNodes?.length > 0) {
@@ -345007,7 +344372,7 @@ var getSeedPhrase = /* @__PURE__ */ __name$1(async (bios, config, logger) => {
345007
344372
  }
345008
344373
  return assertEx(await bios.seedPhraseStore.get("os"), () => "Unable to acquire mnemonic from bios");
345009
344374
  }, "getSeedPhrase");
345010
- var getServer = /* @__PURE__ */ __name$1(async (context) => {
344375
+ var getServer = /* @__PURE__ */ __name$1(async (context, gateway) => {
345011
344376
  const { logger, config } = context;
345012
344377
  const { port, mnemonic } = config.actors.rewardRedemption;
345013
344378
  const bios = await boot();
@@ -345018,13 +344383,55 @@ var getServer = /* @__PURE__ */ __name$1(async (context) => {
345018
344383
  logger,
345019
344384
  config
345020
344385
  };
345021
- const node = context.node ?? await getNode(nodeContext);
344386
+ const node = context.node ?? await getNode(nodeContext, gateway);
345022
344387
  const app = getApp(node, config);
345023
344388
  const server = app.listen(port, hostname, () => logger?.log(`[RewardsRedemption] Server listening at http://${hostname}:${port}`));
345024
344389
  server.setTimeout(12e4);
345025
344390
  return server;
345026
344391
  }, "getServer");
345027
344392
 
344393
+ // src/RewardRedemptionActor.ts
344394
+ function _ts_decorate(decorators, target, key, desc) {
344395
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
344396
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
344397
+ 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;
344398
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
344399
+ }
344400
+ __name$1(_ts_decorate, "_ts_decorate");
344401
+ var RewardRedemptionActor = class extends ActorV3 {
344402
+ static {
344403
+ __name$1(this, "RewardRedemptionActor");
344404
+ }
344405
+ _gatewayRunner;
344406
+ server;
344407
+ get gatewayRunner() {
344408
+ return this._gatewayRunner;
344409
+ }
344410
+ async createHandler() {
344411
+ await super.createHandler();
344412
+ this._gatewayRunner = await this.locator.getInstance(XyoGatewayRunnerMoniker);
344413
+ }
344414
+ async startHandler() {
344415
+ await super.startHandler();
344416
+ this.stopServer();
344417
+ await this.startServer();
344418
+ }
344419
+ async stopHandler() {
344420
+ await super.stopHandler();
344421
+ this.stopServer();
344422
+ }
344423
+ async startServer() {
344424
+ this.server = await getServer(this.context, this._gatewayRunner);
344425
+ }
344426
+ stopServer() {
344427
+ this.server?.close();
344428
+ this.server = void 0;
344429
+ }
344430
+ };
344431
+ RewardRedemptionActor = _ts_decorate([
344432
+ creatable()
344433
+ ], RewardRedemptionActor);
344434
+
345028
344435
  var dist = {};
345029
344436
 
345030
344437
  var defaults = {};
@@ -351881,16 +351288,41 @@ var mainExports = requireMain();
351881
351288
 
351882
351289
  var __defProp = Object.defineProperty;
351883
351290
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
351884
- function runBridge(context) {
351885
- void getServer$2(context);
351886
- }
351887
- __name(runBridge, "runBridge");
351888
- function runMempool(context) {
351889
- void getServer$1(context);
351890
- }
351891
- __name(runMempool, "runMempool");
351892
- function runRewardRedemptionApi(context) {
351893
- void getServer(context);
351291
+ var runBridge = /* @__PURE__ */ __name(async (config2, orchestrator, locator) => {
351292
+ const account = await initBridgeWallet({
351293
+ config: config2,
351294
+ logger: locator.context.logger
351295
+ });
351296
+ const api = await BridgeActor.create({
351297
+ account,
351298
+ config: config2,
351299
+ locator
351300
+ });
351301
+ const actors = [
351302
+ api
351303
+ ].filter(exists$2);
351304
+ for (const actor of actors) {
351305
+ await orchestrator.registerActor(actor);
351306
+ }
351307
+ await orchestrator.start();
351308
+ }, "runBridge");
351309
+ async function runRewardRedemptionApi(config2, orchestrator, locator) {
351310
+ const account = await initRewardsRedemptionApiWallet({
351311
+ config: config2,
351312
+ logger: locator.context.logger
351313
+ });
351314
+ const rewardRedemption = await RewardRedemptionActor.create({
351315
+ account,
351316
+ config: config2,
351317
+ locator
351318
+ });
351319
+ const actors = [
351320
+ rewardRedemption
351321
+ ].filter(exists$2);
351322
+ for (const actor of actors) {
351323
+ await orchestrator.registerActor(actor);
351324
+ }
351325
+ await orchestrator.start();
351894
351326
  }
351895
351327
  __name(runRewardRedemptionApi, "runRewardRedemptionApi");
351896
351328
 
@@ -352024,7 +351456,10 @@ async function localLocatorFromConfig(config2, context) {
352024
351456
  maxWindowSize: 1e4,
352025
351457
  syncInterval: 1e4
352026
351458
  }),
352027
- SimpleXyoViewer.factory(SimpleXyoViewer.dependencies, {})
351459
+ SimpleXyoConnectionViewer.factory(SimpleXyoConnectionViewer.dependencies, {}),
351460
+ SimpleXyoViewer.factory(SimpleXyoViewer.dependencies, {
351461
+ finalizedArchivist: readonlyChainArchivist
351462
+ })
352028
351463
  ]);
352029
351464
  locator.freeze();
352030
351465
  return locator;
@@ -352064,7 +351499,9 @@ async function remoteLocatorFromConfig(config2, context) {
352064
351499
  maxWindowSize: 1e4,
352065
351500
  syncInterval: 1e4
352066
351501
  }),
352067
- SimpleXyoViewer.factory(SimpleXyoViewer.dependencies, {})
351502
+ SimpleXyoViewer.factory(SimpleXyoViewer.dependencies, {
351503
+ finalizedArchivist: readonlyChainArchivist
351504
+ })
352068
351505
  ]);
352069
351506
  locator.freeze();
352070
351507
  return locator;
@@ -352081,6 +351518,27 @@ async function producerLocatorFromConfig(config2, context) {
352081
351518
  if (rewardAddress === account.address) {
352082
351519
  logger?.warn(`Using producer account address as reward address: ${account.address}`);
352083
351520
  }
351521
+ const remoteUrl = config2.remote.rpc?.url;
351522
+ if (isString$1(remoteUrl)) {
351523
+ const transportFactory = /* @__PURE__ */ __name((schemas) => new HttpRpcTransport(remoteUrl, schemas), "transportFactory");
351524
+ locator.registerMany([
351525
+ JsonRpcMempoolViewer.factory(JsonRpcMempoolViewer.dependencies, {
351526
+ transport: await transportFactory(MempoolViewerRpcSchemas)
351527
+ }),
351528
+ JsonRpcMempoolRunner.factory(JsonRpcMempoolRunner.dependencies, {
351529
+ transport: await transportFactory(MempoolRunnerRpcSchemas)
351530
+ }),
351531
+ JsonRpcAccountBalanceViewer.factory(JsonRpcAccountBalanceViewer.dependencies, {
351532
+ transport: await transportFactory(AccountBalanceViewerRpcSchemas)
351533
+ }),
351534
+ JsonRpcFinalizationViewer.factory(JsonRpcFinalizationViewer.dependencies, {
351535
+ transport: await transportFactory(FinalizationViewerRpcSchemas)
351536
+ }),
351537
+ JsonRpcBlockViewer.factory(JsonRpcBlockViewer.dependencies, {
351538
+ transport: await transportFactory(BlockViewerRpcSchemas)
351539
+ })
351540
+ ]);
351541
+ }
352084
351542
  locator.registerMany([
352085
351543
  SimpleBlockRewardViewer.factory(SimpleBlockRewardViewer.dependencies, {}),
352086
351544
  SimpleBlockRunner.factory(SimpleBlockRunner.dependencies, {
@@ -352092,6 +351550,68 @@ async function producerLocatorFromConfig(config2, context) {
352092
351550
  return locator;
352093
351551
  }
352094
351552
  __name(producerLocatorFromConfig, "producerLocatorFromConfig");
351553
+ function apiLocatorFromConfig(config2, context) {
351554
+ const locator = new ProviderFactoryLocator(context);
351555
+ locator.registerMany([]);
351556
+ locator.freeze();
351557
+ return locator;
351558
+ }
351559
+ __name(apiLocatorFromConfig, "apiLocatorFromConfig");
351560
+ function mempoolLocatorFromConfig(config2, context) {
351561
+ const locator = new ProviderFactoryLocator(context);
351562
+ locator.registerMany([]);
351563
+ locator.freeze();
351564
+ return locator;
351565
+ }
351566
+ __name(mempoolLocatorFromConfig, "mempoolLocatorFromConfig");
351567
+ async function bridgeLocatorFromConfig(config2, context) {
351568
+ const locator = new ProviderFactoryLocator(context);
351569
+ const { mnemonic } = config2.actors.bridge;
351570
+ const walletPhrase = isDefined(mnemonic) ? mnemonic : HDWallet.generateMnemonic();
351571
+ const wallet = await generateXyoBaseWalletFromPhrase(walletPhrase);
351572
+ const signerAccount = await wallet.derivePath(ADDRESS_INDEX.XYO);
351573
+ const remoteUrl = config2.actors.bridge.remote.rpc?.url;
351574
+ if (isString$1(remoteUrl)) {
351575
+ const transportFactory = /* @__PURE__ */ __name((schemas) => new HttpRpcTransport(remoteUrl, schemas), "transportFactory");
351576
+ locator.registerMany([
351577
+ JsonRpcMempoolViewer.factory(JsonRpcMempoolViewer.dependencies, {
351578
+ transport: await transportFactory(MempoolViewerRpcSchemas)
351579
+ }),
351580
+ JsonRpcMempoolRunner.factory(JsonRpcMempoolRunner.dependencies, {
351581
+ transport: await transportFactory(MempoolRunnerRpcSchemas)
351582
+ }),
351583
+ JsonRpcAccountBalanceViewer.factory(JsonRpcAccountBalanceViewer.dependencies, {
351584
+ transport: await transportFactory(AccountBalanceViewerRpcSchemas)
351585
+ }),
351586
+ JsonRpcFinalizationViewer.factory(JsonRpcFinalizationViewer.dependencies, {
351587
+ transport: await transportFactory(FinalizationViewerRpcSchemas)
351588
+ }),
351589
+ JsonRpcBlockViewer.factory(JsonRpcBlockViewer.dependencies, {
351590
+ transport: await transportFactory(BlockViewerRpcSchemas)
351591
+ })
351592
+ ]);
351593
+ }
351594
+ locator.registerMany([
351595
+ SimpleXyoSigner.factory(SimpleXyoSigner.dependencies, {
351596
+ account: signerAccount
351597
+ }),
351598
+ SimpleXyoRunner.factory(SimpleXyoRunner.dependencies, {}),
351599
+ SimpleXyoConnectionRunner.factory(SimpleXyoConnectionRunner.dependencies, {}),
351600
+ SimpleXyoGatewayRunner.factory(SimpleXyoGatewayRunner.dependencies, {})
351601
+ ]);
351602
+ locator.freeze();
351603
+ return locator;
351604
+ }
351605
+ __name(bridgeLocatorFromConfig, "bridgeLocatorFromConfig");
351606
+ function rewardRedemptionLocatorFromConfig(config2, context) {
351607
+ const locator = new ProviderFactoryLocator(context);
351608
+ locator.registerMany([
351609
+ SimpleXyoGatewayRunner.factory(SimpleXyoGatewayRunner.dependencies, {})
351610
+ ]);
351611
+ locator.freeze();
351612
+ return locator;
351613
+ }
351614
+ __name(rewardRedemptionLocatorFromConfig, "rewardRedemptionLocatorFromConfig");
352095
351615
  async function locatorsFromConfig(actors, config2, context) {
352096
351616
  const result = {
352097
351617
  _root: await rootLocatorFromConfig(config2, context)
@@ -352100,6 +351620,22 @@ async function locatorsFromConfig(actors, config2, context) {
352100
351620
  if (producer) {
352101
351621
  result.producer = producer;
352102
351622
  }
351623
+ const api = actors.includes("api") ? await apiLocatorFromConfig(config2, result._root.context) : void 0;
351624
+ if (api) {
351625
+ result.api = api;
351626
+ }
351627
+ const mempool = actors.includes("mempool") ? await mempoolLocatorFromConfig(config2, result._root.context) : void 0;
351628
+ if (mempool) {
351629
+ result.mempool = mempool;
351630
+ }
351631
+ const bridge = actors.includes("bridge") ? await bridgeLocatorFromConfig(config2, result._root.context) : void 0;
351632
+ if (bridge) {
351633
+ result.bridge = bridge;
351634
+ }
351635
+ const rewardRedemption = actors.includes("rewardRedemption") ? await rewardRedemptionLocatorFromConfig(config2, result._root.context) : void 0;
351636
+ if (rewardRedemption) {
351637
+ result.rewardRedemption = rewardRedemption;
351638
+ }
352103
351639
  return result;
352104
351640
  }
352105
351641
  __name(locatorsFromConfig, "locatorsFromConfig");
@@ -352150,7 +351686,7 @@ var waitForHostPort = /* @__PURE__ */ __name((host, port) => {
352150
351686
 
352151
351687
  // src/runCLI.ts
352152
351688
  var configuration;
352153
- var version = isDefined("1.19.7") ? "1.19.7" : "unknown";
351689
+ var version = isDefined("1.19.8") ? "1.19.8" : "unknown";
352154
351690
  function resolveConfig(config2) {
352155
351691
  const logger = console;
352156
351692
  const defaultChainId = toAddress("1");
@@ -352162,29 +351698,6 @@ function resolveConfig(config2) {
352162
351698
  return resolved;
352163
351699
  }
352164
351700
  __name(resolveConfig, "resolveConfig");
352165
- var getContextFromConfig = /* @__PURE__ */ __name(async (configuration2) => {
352166
- const logger = initLogger(configuration2);
352167
- const orchestrator = await Orchestrator.create({
352168
- logger
352169
- });
352170
- process.on("SIGINT", () => {
352171
- void (async () => {
352172
- try {
352173
- logger.log("\nSIGINT received. Attempting graceful shutdown...");
352174
- await orchestrator?.stop();
352175
- logger.log("Orchestrator stopped, exiting now.");
352176
- process.exit(0);
352177
- } catch (err) {
352178
- logger.error("Error stopping orchestrator:", err);
352179
- process.exit(1);
352180
- }
352181
- })();
352182
- });
352183
- return {
352184
- logger,
352185
- orchestrator
352186
- };
352187
- }, "getContextFromConfig");
352188
351701
  var getLocatorsFromConfig = /* @__PURE__ */ __name(async (actors, configuration2) => {
352189
351702
  const logger = initLogger(configuration2);
352190
351703
  const orchestrator = await Orchestrator.create({
@@ -352262,30 +351775,26 @@ $0 <command> [options]`).parserConfiguration({
352262
351775
  }).options(optionsFromGlobalZodRegistry()).wrap(y.terminalWidth()).command("api", "Run a XL1 API Node", (yargs2) => {
352263
351776
  return yargs2.command("$0", "Run a XL1 API Node", () => {
352264
351777
  }, async () => {
352265
- const context = await getContextFromConfig(configuration);
352266
- await runApi({
352267
- ...context,
352268
- config: configuration,
352269
- singletons: {}
352270
- });
351778
+ const { locators, orchestrator } = await getLocatorsFromConfig([
351779
+ "api"
351780
+ ], configuration);
351781
+ await runApi(configuration, orchestrator, locators["api"]);
352271
351782
  });
352272
351783
  }).command("bridge", "Run a XL1 Bridge Node", (yargs2) => {
352273
351784
  return yargs2.command("$0", "Run a XL1 Bridge Node", () => {
352274
351785
  }, async () => {
352275
- const context = await getContextFromConfig(configuration);
352276
- runBridge({
352277
- ...context,
352278
- config: configuration
352279
- });
351786
+ const { locators, orchestrator } = await getLocatorsFromConfig([
351787
+ "bridge"
351788
+ ], configuration);
351789
+ await runBridge(configuration, orchestrator, locators["bridge"]);
352280
351790
  });
352281
351791
  }).command("mempool", "Run a XL1 Mempool Node", (yargs2) => {
352282
351792
  return yargs2.command("$0", "Run a XL1 Mempool Node", () => {
352283
351793
  }, async () => {
352284
- const context = await getContextFromConfig(configuration);
352285
- runMempool({
352286
- ...context,
352287
- config: configuration
352288
- });
351794
+ const { locators, orchestrator } = await getLocatorsFromConfig([
351795
+ "mempool"
351796
+ ], configuration);
351797
+ await runMempool(configuration, orchestrator, locators["mempool"]);
352289
351798
  });
352290
351799
  }).command("producer", "Run a XL1 Producer Node", (yargs2) => {
352291
351800
  return yargs2.command("$0", "Run a XL1 Producer Node", () => {
@@ -352298,31 +351807,23 @@ $0 <command> [options]`).parserConfiguration({
352298
351807
  }).command("reward-redemption-api", "Run a XL1 Rewards Redemption API Node", (yargs2) => {
352299
351808
  return yargs2.command("$0", "Run a XL1 Rewards Redemption API Node", () => {
352300
351809
  }, async () => {
352301
- const context = await getContextFromConfig(configuration);
352302
- runRewardRedemptionApi({
352303
- ...context,
352304
- config: configuration
352305
- });
351810
+ const { locators, orchestrator } = await getLocatorsFromConfig([
351811
+ "rewardRedemption"
351812
+ ], configuration);
351813
+ await runRewardRedemptionApi(configuration, orchestrator, locators["rewardRedemption"]);
352306
351814
  });
352307
351815
  }).command("$0", "Run a full XL1 Node", () => {
352308
351816
  }, async () => {
352309
351817
  if (configuration.actors.mempool.enabled) ;
352310
- const context = await getContextFromConfig(configuration);
352311
351818
  const { locators, orchestrator } = await getLocatorsFromConfig([
351819
+ "api",
352312
351820
  "producer"
352313
351821
  ], configuration);
352314
351822
  if (configuration.actors.mempool.enabled) {
352315
- runMempool({
352316
- ...context,
352317
- config: configuration
352318
- });
351823
+ await runMempool(configuration, orchestrator, locators["mempool"]);
352319
351824
  await waitForHostPort(configuration.actors.mempool.host, configuration.actors.mempool.port);
352320
351825
  }
352321
- await runApi({
352322
- ...context,
352323
- config: configuration,
352324
- singletons: {}
352325
- });
351826
+ await runApi(configuration, orchestrator, locators["api"]);
352326
351827
  await waitForHostPort(configuration.actors.api.host, configuration.actors.api.port);
352327
351828
  await runProducer(configuration, orchestrator, locators["producer"]);
352328
351829
  }).options({
@@ -352349,3 +351850,4 @@ start().catch((err) => {
352349
351850
  // eslint-disable-next-line unicorn/no-process-exit
352350
351851
  process.exit(1);
352351
351852
  });
351853
+ //# sourceMappingURL=cli-min.mjs.map