var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
    if (decorator = decorators[i])
      result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp(target, key, result);
  return result;
};
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);

// src/modules/gateway/dataLakes/PageProvider.ts
import {
  DataLakeRunnerMoniker,
  DataLakeViewerMoniker
} from "@xyo-network/xl1-protocol/protocol-lib";
import { DataLakesGetMethod, DataLakesInsertMethod } from "#rpc";
var AbstractDataLakePageProvider = class {
  id;
  transport;
  /** Creates an instance with the supplied configuration. */
  constructor(transport, id) {
    this.transport = transport;
    this.id = id;
  }
  /** Returns get. */
  async get(hashes) {
    return await this.transport.sendRequest(DataLakesGetMethod, [{ id: this.id, hashes }]);
  }
  /** Returns the next result exposed by this provider. */
  next(_options) {
    throw new Error("Method [next] not implemented.");
  }
};
var DataLakePageViewer = class extends AbstractDataLakePageProvider {
  /** Moniker implemented by this provider instance. */
  moniker = DataLakeViewerMoniker;
};
var DataLakePageRunner = class extends AbstractDataLakePageProvider {
  /** Moniker implemented by this provider instance. */
  moniker = DataLakeRunnerMoniker;
  /** Removes data through the clear operation. */
  clear() {
    throw new Error("Method [clear] not implemented.");
  }
  /** Removes data through the delete operation. */
  delete(_hashes) {
    throw new Error("Method [delete] not implemented.");
  }
  /** Submits the insert operation to its backing provider. */
  async insert(items) {
    return await this.transport.sendRequest(DataLakesInsertMethod, [{ id: this.id, payloads: items }]);
  }
};

// src/modules/gateway/examples/getAccountBalance.ts
import { assertEx } from "@ariestools/sdk";
async function getAccountBalance(gateway, address) {
  const viewer = assertEx(
    gateway.connection.viewer,
    () => "Gateway has no connection.viewer \u2014 cannot read balances"
  );
  return await viewer.account.balance.accountBalance(address);
}

// src/modules/gateway/examples/transferXl1.ts
async function transferXl1(runner, to, amount, options) {
  return await runner.send(to, amount, options);
}

// src/modules/gateway/GatewayBuilder.ts
import { isDefined } from "@ariestools/sdk";
import { XyoGatewayMoniker, XyoGatewayRunnerMoniker } from "@xyo-network/xl1-protocol/protocol-lib";
import { basicRemoteRunnerLocator, basicRemoteViewerLocator } from "#providers";

// src/modules/gateway/XyoSignerWrapper.ts
import { XyoSignerMoniker } from "@xyo-network/xl1-protocol/protocol-lib";
import {
  AbstractCreatableProvider,
  creatableProvider
} from "#protocol-sdk";
var XyoSignerWrapper = class extends AbstractCreatableProvider {
  /** Moniker implemented by this provider instance. */
  moniker = XyoSignerWrapper.defaultMoniker;
  /** Submits the address operation to its backing provider. */
  address() {
    return this.params.signer.address();
  }
  /** Returns the sign result exposed by this provider. */
  sign(bw) {
    return this.params.signer.sign(bw);
  }
  /** Returns the sign transaction result exposed by this provider. */
  signTransaction(tx) {
    return this.params.signer.signTransaction(tx);
  }
};
/** Connection kinds supported by this provider. */
__publicField(XyoSignerWrapper, "connectionTypes", ["none"]);
/** Primary moniker used to resolve this provider. */
__publicField(XyoSignerWrapper, "defaultMoniker", XyoSignerMoniker);
/** Provider monikers that must resolve before this provider can be created. */
__publicField(XyoSignerWrapper, "dependencies", []);
/** Provider monikers implemented by this provider class. */
__publicField(XyoSignerWrapper, "monikers", [XyoSignerMoniker]);
XyoSignerWrapper = __decorateClass([
  creatableProvider()
], XyoSignerWrapper);

// src/modules/gateway/GatewayBuilder.ts
var GatewayBuilder = class {
  _additionalProviders = [];
  _additionalRunnerProviders = [];
  _dataLakeEndpoint;
  _logger;
  _name = "gateway-client";
  _rpc;
  _validators;
  /** Replaces the supplemental read/provider factories registered with the gateway locator. */
  additionalProviders(factories) {
    this._additionalProviders = factories;
    return this;
  }
  /** Replaces the supplemental mutation-provider factories registered with the gateway locator. */
  additionalRunnerProviders(factories) {
    this._additionalRunnerProviders = factories;
    return this;
  }
  /** Builds a read-only gateway, or a mutation-capable gateway when a signer is supplied. */
  async build(signer) {
    if (!isDefined(this._rpc)) {
      throw new Error("GatewayBuilder: rpcUrl() or postMessage() must be set before build()");
    }
    const rpcConnection = this._rpc;
    if (signer === void 0) {
      const locator2 = await basicRemoteViewerLocator(this._name, rpcConnection, this._dataLakeEndpoint, {
        validators: this._validators,
        additionalProviders: this._additionalProviders,
        logger: this._logger
      });
      return await locator2.getInstance(XyoGatewayMoniker);
    }
    const signerFactory = XyoSignerWrapper.factory(XyoSignerWrapper.dependencies, { signer });
    const locator = await basicRemoteRunnerLocator(this._name, rpcConnection, void 0, this._dataLakeEndpoint, {
      validators: this._validators,
      additionalProviders: this._additionalProviders,
      additionalRunnerProviders: this._additionalRunnerProviders,
      logger: this._logger,
      signerFactory
    });
    return await locator.getInstance(XyoGatewayRunnerMoniker);
  }
  /** Configures the endpoint used to retrieve data-lake content. */
  dataLakeEndpoint(endpoint) {
    this._dataLakeEndpoint = endpoint;
    return this;
  }
  /** Sets the logger shared by every provider created for this gateway. */
  logger(logger) {
    this._logger = logger;
    return this;
  }
  /** Sets the diagnostic name used by the gateway and its provider locator. */
  name(name) {
    this._name = name;
    return this;
  }
  /** Configures post-message RPC for the target network and wallet session. */
  postMessage(networkId, sessionId) {
    this._rpc = {
      protocol: "postMessage",
      networkId,
      sessionId
    };
    return this;
  }
  /** Configures HTTP JSON-RPC as the gateway transport. */
  rpcUrl(url) {
    this._rpc = { protocol: "http", url };
    return this;
  }
  /** Configures validators applied to blocks returned by the gateway. */
  validators(validators) {
    this._validators = validators;
    return this;
  }
};

// src/modules/gateway/getRestGateway.ts
import { XyoGatewayMoniker as XyoGatewayMoniker2 } from "@xyo-network/xl1-protocol/protocol-lib";
import { restConnectionFromS3Bucket } from "#protocol-sdk";
import { basicRestViewerLocator, resolveFinalizedAlias } from "#providers";
var STANDARD_ENDPOINT_SUBDOMAINS = {
  chainState: "state",
  finalized: "blocks",
  index: "indexes"
};
function restGatewayConfigFromEndpoint(endpoint) {
  const url = new URL(endpoint);
  const bucketOrigin = (subdomain) => `${url.protocol}//${subdomain}.${url.host}`;
  const finalized = { readUrl: bucketOrigin(STANDARD_ENDPOINT_SUBDOMAINS.finalized) };
  return {
    blocks: finalized,
    chainState: { readUrl: bucketOrigin(STANDARD_ENDPOINT_SUBDOMAINS.chainState) },
    finalized,
    index: { readUrl: bucketOrigin(STANDARD_ENDPOINT_SUBDOMAINS.index) }
  };
}
async function getRestGateway(config) {
  const resolved = typeof config === "string" ? restGatewayConfigFromEndpoint(config) : config;
  const {
    dataLakeEndpoint,
    fetchFn,
    logger,
    name,
    primeCaches,
    initRewardsCache
  } = typeof config === "string" ? {} : config;
  const restConfig = {
    finalized: restConnectionFromS3Bucket(resolveFinalizedAlias(resolved, "getRestGateway", logger)),
    chainState: resolved.chainState ? restConnectionFromS3Bucket(resolved.chainState) : void 0,
    index: resolved.index ? restConnectionFromS3Bucket(resolved.index) : void 0
  };
  const locator = await basicRestViewerLocator(name ?? "rest-gateway-client", restConfig, dataLakeEndpoint, {
    fetchFn,
    initRewardsCache,
    logger,
    primeCaches
  });
  return await locator.getInstance(XyoGatewayMoniker2);
}

// src/modules/gateway/getRestGatewayRunner.ts
import { isDefined as isDefined2 } from "@ariestools/sdk";
import { XyoGatewayRunnerMoniker as XyoGatewayRunnerMoniker2 } from "@xyo-network/xl1-protocol/protocol-lib";
import { restConnectionFromS3Bucket as restConnectionFromS3Bucket2 } from "#protocol-sdk";
import { basicRestRunnerLocator, resolveFinalizedAlias as resolveFinalizedAlias2 } from "#providers";
async function getRestGatewayRunner(config) {
  const buckets = "endpoint" in config ? restGatewayConfigFromEndpoint(config.endpoint) : config;
  const {
    dataLakeEndpoint,
    fetchFn,
    logger,
    name,
    primeCaches,
    rpcUrl,
    signer,
    signerFactory: providedSignerFactory,
    signerTransport,
    initRewardsCache
  } = config;
  const restConfig = {
    finalized: restConnectionFromS3Bucket2(resolveFinalizedAlias2(buckets, "getRestGatewayRunner", logger)),
    chainState: buckets.chainState ? restConnectionFromS3Bucket2(buckets.chainState) : void 0,
    index: buckets.index ? restConnectionFromS3Bucket2(buckets.index) : void 0
  };
  const signerFactory = isDefined2(signer) ? XyoSignerWrapper.factory(XyoSignerWrapper.dependencies, { signer }) : providedSignerFactory;
  const locator = await basicRestRunnerLocator(
    name ?? "rest-gateway-runner-client",
    restConfig,
    dataLakeEndpoint,
    {
      fetchFn,
      initRewardsCache,
      logger,
      primeCaches,
      rpcUrl,
      signerFactory,
      signerTransport
    }
  );
  return await locator.getInstance(XyoGatewayRunnerMoniker2);
}

// src/modules/gateway/witnessPreviousStep.ts
import { asHash, assertEx as assertEx2 } from "@ariestools/sdk";
import { PayloadBuilder } from "@xyo-network/sdk";
import {
  stepSize,
  StepWitnessSchema,
  XyoGatewayRunnerMoniker as XyoGatewayRunnerMoniker3
} from "@xyo-network/xl1-protocol/protocol-lib";
async function witnessPreviousStep(gateway, options) {
  const {
    addToChain = false,
    step = 2,
    transactionOptions,
    witness: witnessOption
  } = options ?? {};
  const size = stepSize(step);
  const runner = gateway.moniker === XyoGatewayRunnerMoniker3 ? gateway : void 0;
  const viewer = assertEx2(
    gateway.connection.viewer,
    () => "witnessPreviousStep: gateway has no connection.viewer \u2014 cannot read blocks"
  );
  const [currentBw] = await viewer.currentBlock();
  const stepHash = asHash(
    currentBw.step_hashes?.at(step),
    () => `witnessPreviousStep: step hash not found for step ${step} in block ${currentBw.block}`
  );
  const witnessAddress = assertEx2(
    witnessOption ?? await runner?.signer.address(),
    () => "witnessPreviousStep: no observer address \u2014 pass options.witness or supply a runner with a signer"
  );
  const payload = new PayloadBuilder({ schema: StepWitnessSchema }).fields({
    blockHash: currentBw._hash,
    blockNumber: currentBw.block,
    stepHash,
    stepSize: size,
    witness: witnessAddress
  }).build();
  const witness = await PayloadBuilder.addHashMeta(payload);
  if (addToChain) {
    const chainRunner = assertEx2(
      runner,
      () => "witnessPreviousStep: addToChain requires a XyoGatewayRunner \u2014 a read-only gateway cannot submit transactions"
    );
    const [txHash, transaction] = await chainRunner.addPayloadsToChain([], [payload], transactionOptions);
    return {
      transaction,
      txHash,
      witness
    };
  }
  return { witness };
}
export {
  AbstractDataLakePageProvider,
  DataLakePageRunner,
  DataLakePageViewer,
  GatewayBuilder,
  XyoSignerWrapper,
  getAccountBalance,
  getRestGateway,
  getRestGatewayRunner,
  restGatewayConfigFromEndpoint,
  transferXl1,
  witnessPreviousStep
};
//# sourceMappingURL=gateway.mjs.map
