// ../../node_modules/.pnpm/@metamask+json-rpc-engine@10.5.0_typescript@6.0.3/node_modules/@metamask/json-rpc-engine/dist/v2/utils.mjs
import { hasProperty, isObject } from "@metamask/utils";
var _a;
var isRequest = (message) => hasProperty(message, "id");
var isNotification = (message) => !isRequest(message);
function stringify(value) {
  return JSON.stringify(value, null, 2);
}
var isInstance = (value, symbol) => isObject(value) && symbol in value && value[symbol] === true;
var JsonRpcEngineErrorSymbol = /* @__PURE__ */ Symbol.for("json-rpc-engine#JsonRpcEngineError");
var JsonRpcEngineError = class extends Error {
  constructor(message) {
    super(message);
    this[_a] = true;
    this.name = "JsonRpcEngineError";
  }
  /**
   * Check if a value is a {@link JsonRpcEngineError} instance.
   * Works across different package versions in the same realm.
   *
   * @param value - The value to check.
   * @returns Whether the value is a {@link JsonRpcEngineError} instance.
   */
  static isInstance(value) {
    return isInstance(value, JsonRpcEngineErrorSymbol);
  }
};
_a = JsonRpcEngineErrorSymbol;

// ../../node_modules/.pnpm/@metamask+json-rpc-engine@10.5.0_typescript@6.0.3/node_modules/@metamask/json-rpc-engine/dist/v2/compatibility-utils.mjs
import { getMessageFromCode, JsonRpcError } from "@metamask/rpc-errors";
import { hasProperty as hasProperty2, isObject as isObject2, isValidJson } from "@metamask/utils";
import { klona } from "klona";

// ../../node_modules/.pnpm/@metamask+json-rpc-engine@10.5.0_typescript@6.0.3/node_modules/@metamask/json-rpc-engine/dist/v2/MiddlewareContext.mjs
var _a2;
var MiddlewareContextSymbol = /* @__PURE__ */ Symbol.for("json-rpc-engine#MiddlewareContext");
var MiddlewareContext = class extends Map {
  /**
   * Check if a value is a {@link MiddlewareContext} instance.
   * Works across different package versions in the same realm.
   *
   * @param value - The value to check.
   * @returns Whether the value is a {@link MiddlewareContext} instance.
   */
  static isInstance(value) {
    return isInstance(value, MiddlewareContextSymbol);
  }
  constructor(entries) {
    super(entries && isIterable(entries) ? entries : entriesFromKeyValues(entries ?? {}));
    this[_a2] = true;
    Object.freeze(this);
  }
  get(key) {
    return super.get(key);
  }
  /**
   * Get a value from the context. Throws if the key is not found.
   *
   * @param key - The key to get the value for.
   * @returns The value.
   */
  assertGet(key) {
    if (!super.has(key)) {
      throw new Error(`Context key "${String(key)}" not found`);
    }
    return super.get(key);
  }
  /**
   * Set a value in the context. Throws if the key already exists.
   * {@link delete} an existing key before setting it to a new value.
   *
   * @throws If the key already exists.
   * @param key - The key to set the value for.
   * @param value - The value to set.
   * @returns The context.
   */
  set(key, value) {
    if (super.has(key)) {
      throw new Error(`MiddlewareContext key "${String(key)}" already exists`);
    }
    super.set(key, value);
    return this;
  }
};
_a2 = MiddlewareContextSymbol;
function isIterable(value) {
  return Symbol.iterator in value;
}
function entriesFromKeyValues(keyValues) {
  return Reflect.ownKeys(keyValues).map((key) => [
    key,
    keyValues[key]
  ]);
}

// ../../node_modules/.pnpm/@metamask+json-rpc-engine@10.5.0_typescript@6.0.3/node_modules/@metamask/json-rpc-engine/dist/v2/compatibility-utils.mjs
var deepClone = (value) => klona(value);

// ../../node_modules/.pnpm/@metamask+json-rpc-engine@10.5.0_typescript@6.0.3/node_modules/@metamask/json-rpc-engine/dist/getUniqueId.mjs
var MAX = 4294967295;
var idCounter = Math.floor(Math.random() * MAX);
function getUniqueId() {
  idCounter = (idCounter + 1) % MAX;
  return idCounter;
}

// ../../node_modules/.pnpm/@metamask+json-rpc-engine@10.5.0_typescript@6.0.3/node_modules/@metamask/json-rpc-engine/dist/v2/JsonRpcEngineV2.mjs
import { hasProperty as hasProperty3 } from "@metamask/utils";
import $deepFreeze from "deep-freeze-strict";
var __classPrivateFieldSet = function(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet = function(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _JsonRpcEngineV2_instances;
var _JsonRpcEngineV2_middleware;
var _JsonRpcEngineV2_isDestroyed;
var _JsonRpcEngineV2_handle;
var _JsonRpcEngineV2_makeNextFactory;
var _JsonRpcEngineV2_makeMiddlewareIterator;
var _JsonRpcEngineV2_updateResult;
var _JsonRpcEngineV2_assertValidNextRequest;
var _JsonRpcEngineV2_assertIsNotDestroyed;
function $importDefault(module) {
  if (module?.__esModule) {
    return module.default;
  }
  return module;
}
var deepFreeze = $importDefault($deepFreeze);
var JsonRpcEngineV2 = class _JsonRpcEngineV2 {
  // See .create() for why this is private.
  // eslint-disable-next-line no-restricted-syntax
  constructor({ middleware }) {
    _JsonRpcEngineV2_instances.add(this);
    _JsonRpcEngineV2_middleware.set(this, void 0);
    _JsonRpcEngineV2_isDestroyed.set(this, false);
    __classPrivateFieldSet(this, _JsonRpcEngineV2_middleware, [...middleware], "f");
  }
  // We use a static factory method in order to construct a supertype of all middleware contexts,
  // which enables us to instantiate an engine despite different middleware expecting different
  // context types.
  /**
   * Create a new JSON-RPC engine.
   *
   * @throws If the middleware array is empty.
   * @param options - The options for the engine.
   * @param options.middleware - The middleware to use.
   * @returns The JSON-RPC engine.
   */
  static create({ middleware }) {
    if (middleware.length === 0) {
      throw new JsonRpcEngineError("Middleware array cannot be empty");
    }
    const mw = middleware;
    return new _JsonRpcEngineV2({
      middleware: mw
    });
  }
  async handle(request, { context } = {}) {
    const isReq = isRequest(request);
    const { result } = await __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_handle).call(this, request, context);
    if (isReq && result === void 0) {
      throw new JsonRpcEngineError(`Nothing ended request: ${stringify(request)}`);
    }
    return deepClone(result);
  }
  /**
   * Convert the engine into a JSON-RPC middleware.
   *
   * @returns The JSON-RPC middleware.
   */
  asMiddleware() {
    __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_assertIsNotDestroyed).call(this);
    return async ({ request, context, next }) => {
      const { result, request: finalRequest } = await __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_handle).call(this, request, context);
      return result === void 0 ? await next(finalRequest) : result;
    };
  }
  /**
   * Destroy the engine. Calls the `destroy()` method of any middleware that has
   * one. Attempting to use the engine after destroying it will throw an error.
   */
  async destroy() {
    if (__classPrivateFieldGet(this, _JsonRpcEngineV2_isDestroyed, "f")) {
      return;
    }
    __classPrivateFieldSet(this, _JsonRpcEngineV2_isDestroyed, true, "f");
    const destructionPromise = Promise.all(__classPrivateFieldGet(this, _JsonRpcEngineV2_middleware, "f").map(async (middleware) => {
      if (
        // Intentionally using `in` to walk the prototype chain.
        "destroy" in middleware && typeof middleware.destroy === "function"
      ) {
        return middleware.destroy();
      }
      return void 0;
    }));
    __classPrivateFieldSet(this, _JsonRpcEngineV2_middleware, [], "f");
    await destructionPromise;
  }
};
_JsonRpcEngineV2_middleware = /* @__PURE__ */ new WeakMap(), _JsonRpcEngineV2_isDestroyed = /* @__PURE__ */ new WeakMap(), _JsonRpcEngineV2_instances = /* @__PURE__ */ new WeakSet(), _JsonRpcEngineV2_handle = /**
 * Handle a JSON-RPC request. Throws if a middleware performs an invalid
 * operation. Permits returning an `undefined` result.
 *
 * @param originalRequest - The JSON-RPC request to handle.
 * @param rawContext - The context to pass to the middleware.
 * @returns The result from the middleware.
 */
async function _JsonRpcEngineV2_handle2(originalRequest, rawContext = new MiddlewareContext()) {
  __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_assertIsNotDestroyed).call(this);
  deepFreeze(originalRequest);
  const state = {
    request: originalRequest,
    result: void 0
  };
  const middlewareIterator = __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_makeMiddlewareIterator).call(this);
  const firstMiddleware = middlewareIterator.next().value;
  const context = MiddlewareContext.isInstance(rawContext) ? rawContext : new MiddlewareContext(rawContext);
  const makeNext = __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_makeNextFactory).call(this, middlewareIterator, state, context);
  const result = await firstMiddleware({
    request: originalRequest,
    context,
    next: makeNext()
  });
  __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_updateResult).call(this, result, state);
  return state;
}, _JsonRpcEngineV2_makeNextFactory = function _JsonRpcEngineV2_makeNextFactory2(middlewareIterator, state, context) {
  const makeNext = () => {
    let wasCalled = false;
    const next = async (request = state.request) => {
      if (wasCalled) {
        throw new JsonRpcEngineError(`Middleware attempted to call next() multiple times for request: ${stringify(request)}`);
      }
      wasCalled = true;
      if (request !== state.request) {
        __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_assertValidNextRequest).call(this, state.request, request);
        state.request = deepFreeze(request);
      }
      const { value: nextMiddleware, done } = middlewareIterator.next();
      if (done) {
        return void 0;
      }
      const result = await nextMiddleware({
        request,
        context,
        next: makeNext()
      });
      __classPrivateFieldGet(this, _JsonRpcEngineV2_instances, "m", _JsonRpcEngineV2_updateResult).call(this, result, state);
      return state.result;
    };
    return next;
  };
  return makeNext;
}, _JsonRpcEngineV2_makeMiddlewareIterator = function _JsonRpcEngineV2_makeMiddlewareIterator2() {
  return __classPrivateFieldGet(this, _JsonRpcEngineV2_middleware, "f")[Symbol.iterator]();
}, _JsonRpcEngineV2_updateResult = function _JsonRpcEngineV2_updateResult2(result, state) {
  if (isNotification(state.request) && result !== void 0) {
    throw new JsonRpcEngineError(`Result returned for notification: ${stringify(state.request)}`);
  }
  if (result !== void 0 && result !== state.result) {
    if (typeof result === "object" && result !== null) {
      deepFreeze(result);
    }
    state.result = result;
  }
}, _JsonRpcEngineV2_assertValidNextRequest = function _JsonRpcEngineV2_assertValidNextRequest2(currentRequest, nextRequest) {
  if (nextRequest.jsonrpc !== currentRequest.jsonrpc) {
    throw new JsonRpcEngineError(`Middleware attempted to modify readonly property "jsonrpc" for request: ${stringify(currentRequest)}`);
  }
  if (hasProperty3(nextRequest, "id") !== hasProperty3(currentRequest, "id") || // @ts-expect-error - "id" does not exist on notifications, but we can still
  // check the value of the property at runtime.
  nextRequest.id !== currentRequest.id) {
    throw new JsonRpcEngineError(`Middleware attempted to modify readonly property "id" for request: ${stringify(currentRequest)}`);
  }
}, _JsonRpcEngineV2_assertIsNotDestroyed = function _JsonRpcEngineV2_assertIsNotDestroyed2() {
  if (__classPrivateFieldGet(this, _JsonRpcEngineV2_isDestroyed, "f")) {
    throw new JsonRpcEngineError("Engine is destroyed");
  }
};

// ../../node_modules/.pnpm/@metamask+json-rpc-engine@10.5.0_typescript@6.0.3/node_modules/@metamask/json-rpc-engine/dist/v2/createScaffoldMiddleware.mjs
function createScaffoldMiddleware(handlers) {
  return ({ request, context, next }) => {
    const handlerOrResult = handlers[request.method];
    if (handlerOrResult === void 0) {
      return next();
    }
    return typeof handlerOrResult === "function" ? handlerOrResult({ request, context, next }) : handlerOrResult;
  };
}

// ../../node_modules/.pnpm/@metamask+json-rpc-engine@10.5.0_typescript@6.0.3/node_modules/@metamask/json-rpc-engine/dist/v2/JsonRpcServer.mjs
import { rpcErrors, serializeError } from "@metamask/rpc-errors";
import { hasProperty as hasProperty4, isObject as isObject3 } from "@metamask/utils";
var __classPrivateFieldSet2 = function(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet2 = function(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _a3;
var _JsonRpcServer_engine;
var _JsonRpcServer_onError;
var _JsonRpcServer_coerceRequest;
var jsonrpc = "2.0";
var JsonRpcServer = class {
  /**
   * Construct a new JSON-RPC server.
   *
   * @param options - The options for the server.
   * @param options.onError - The callback to handle errors thrown by the
   * engine. Errors always result in a failed response object, containing a
   * JSON-RPC 2.0 serialized version of the original error. If you need to
   * access the original error, use the `onError` callback. If the `onError`
   * callback itself throws or rejects, the error is silently ignored.
   * @param options.engine - The engine to use. Mutually exclusive with
   * `middleware`.
   * @param options.middleware - The middleware to use. Mutually exclusive with
   * `engine`.
   */
  constructor(options) {
    _JsonRpcServer_engine.set(this, void 0);
    _JsonRpcServer_onError.set(this, void 0);
    __classPrivateFieldSet2(this, _JsonRpcServer_onError, options.onError, "f");
    if (hasProperty4(options, "engine")) {
      __classPrivateFieldSet2(this, _JsonRpcServer_engine, options.engine, "f");
    } else {
      __classPrivateFieldSet2(this, _JsonRpcServer_engine, JsonRpcEngineV2.create({ middleware: options.middleware }), "f");
    }
  }
  async handle(rawRequest, options) {
    const [originalId, isRequest2] = getOriginalId(rawRequest);
    try {
      const request = __classPrivateFieldGet2(_a3, _a3, "m", _JsonRpcServer_coerceRequest).call(_a3, rawRequest, isRequest2);
      const result = await __classPrivateFieldGet2(this, _JsonRpcServer_engine, "f").handle(request, options);
      if (result !== void 0) {
        return {
          jsonrpc,
          // @ts-expect-error - Reassign the original id, regardless of its type.
          id: originalId,
          result
        };
      }
    } catch (error) {
      try {
        const maybePromise = __classPrivateFieldGet2(this, _JsonRpcServer_onError, "f")?.call(this, error);
        if (maybePromise instanceof Promise) {
          maybePromise.catch(() => {
          });
        }
      } catch {
      }
      if (isRequest2) {
        return {
          jsonrpc,
          // @ts-expect-error - Reassign the original id, regardless of its type.
          id: originalId,
          error: serializeError(error, {
            shouldIncludeStack: false,
            shouldPreserveMessage: true
          })
        };
      }
    }
    return void 0;
  }
};
_a3 = JsonRpcServer, _JsonRpcServer_engine = /* @__PURE__ */ new WeakMap(), _JsonRpcServer_onError = /* @__PURE__ */ new WeakMap(), _JsonRpcServer_coerceRequest = function _JsonRpcServer_coerceRequest2(rawRequest, isRequest2) {
  if (!isMinimalRequest(rawRequest)) {
    throw rpcErrors.invalidRequest({
      data: {
        request: rawRequest
      }
    });
  }
  const request = {
    jsonrpc,
    method: rawRequest.method
  };
  if (hasProperty4(rawRequest, "params")) {
    request.params = rawRequest.params;
  }
  if (isRequest2) {
    request.id = getUniqueId();
  }
  return request;
};
function isMinimalRequest(rawRequest) {
  return isObject3(rawRequest) && hasProperty4(rawRequest, "method") && typeof rawRequest.method === "string" && hasValidParams(rawRequest);
}
function hasValidParams(rawRequest) {
  if (hasProperty4(rawRequest, "params")) {
    return Array.isArray(rawRequest.params) || isObject3(rawRequest.params);
  }
  return true;
}
function getOriginalId(rawRequest) {
  if (isObject3(rawRequest) && hasProperty4(rawRequest, "id")) {
    return [rawRequest.id, true];
  }
  return [void 0, false];
}

// src/modules/rpc/engine-node/composedRpcEngineFromConnection.ts
import { isXyoJwtSignerMethods as isXyoJwtSignerMethods2, XyoGatewayRunnerMoniker } from "@xyo-network/xl1-protocol/protocol-lib";

// src/modules/rpc/engine/requestSchemas.ts
var requestSchemas = {};

// src/modules/rpc/engine/rpcMethodHandlersFromAccountBalanceViewer.ts
var rpcMethodHandlersFromAccountBalanceViewer = (viewer) => {
  return {
    accountBalanceViewer_qualifiedAccountBalances: (params) => viewer.qualifiedAccountBalances(...params ?? []),
    accountBalanceViewer_qualifiedAccountBalanceHistories: (params) => viewer.qualifiedAccountBalanceHistories(...params ?? [])
  };
};

// src/modules/rpc/engine/rpcMethodHandlersFromBlockViewer.ts
var rpcMethodHandlersFromBlockViewer = (viewer) => {
  return {
    blockViewer_blocksByHash: (params) => viewer.blocksByHash(...params ?? []),
    blockViewer_blocksByNumber: (params) => viewer.blocksByNumber(...params ?? []),
    blockViewer_blocksByStep: (params) => viewer.blocksByStep(...params ?? []),
    blockViewer_currentBlock: (params) => viewer.currentBlock(...params ?? []),
    blockViewer_payloadsByHash: (params) => viewer.payloadsByHash(...params ?? [])
  };
};

// src/modules/rpc/engine/rpcMethodHandlersFromFinalizationViewer.ts
var rpcMethodHandlersFromFinalizationViewer = (viewer) => {
  return { finalizationViewer_head: (params) => viewer.head(...params ?? []) };
};

// src/modules/rpc/engine/rpcMethodHandlersFromMempoolRunner.ts
var rpcMethodHandlersFromMempoolRunner = (runner) => {
  return {
    mempoolRunner_submitBlocks: (params) => runner.submitBlocks(...params ?? []),
    mempoolRunner_submitTransactions: (params) => runner.submitTransactions(...params ?? [])
  };
};

// src/modules/rpc/engine/rpcMethodHandlersFromMempoolViewer.ts
var rpcMethodHandlersFromMempoolViewer = (viewer) => {
  return {
    mempoolViewer_pendingBlocks: (params) => viewer.pendingBlocks(...params ?? []),
    mempoolViewer_pendingTransactions: (params) => viewer.pendingTransactions(...params ?? [])
  };
};

// src/modules/rpc/engine/rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer.ts
var rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer = (viewer) => {
  return {
    networkStakingStepRewardsByPositionViewer_bonus: (params) => viewer.bonus(...params ?? []),
    networkStakingStepRewardsByPositionViewer_claimed: (params) => viewer.claimed(...params ?? []),
    networkStakingStepRewardsByPositionViewer_earned: (params) => viewer.earned(...params ?? []),
    networkStakingStepRewardsByPositionViewer_total: (params) => viewer.total(...params ?? []),
    networkStakingStepRewardsByPositionViewer_totalForPosition: (params) => viewer.totalForPosition(...params),
    networkStakingStepRewardsByPositionViewer_totalForStep: (params) => viewer.totalForStep(...params),
    networkStakingStepRewardsByPositionViewer_totalForStepForPosition: (params) => viewer.totalForStepForPosition(...params),
    networkStakingStepRewardsByPositionViewer_unclaimed: (params) => viewer.unclaimed(...params ?? [])
  };
};

// src/modules/rpc/engine/rpcMethodHandlersFromRunner.ts
var rpcMethodHandlersFromRunner = (runner) => {
  return { xyoRunner_broadcastTransaction: (params) => runner.broadcastTransaction(...params ?? []) };
};

// src/modules/rpc/engine/rpcMethodHandlersFromStakeTotalsViewer.ts
var rpcMethodHandlersFromStakeTotalsViewer = (viewer) => {
  return {
    stakeTotalsViewer_active: (params) => viewer.active(...params ?? []),
    stakeTotalsViewer_activeByStaked: (params) => viewer.activeByStaked(...params ?? []),
    stakeTotalsViewer_activeByStaker: (params) => viewer.activeByStaker(...params ?? []),
    stakeTotalsViewer_pending: (params) => viewer.pending(...params ?? []),
    stakeTotalsViewer_pendingByStaker: (params) => viewer.pendingByStaker(...params ?? []),
    stakeTotalsViewer_withdrawn: (params) => viewer.withdrawn(...params ?? []),
    stakeTotalsViewer_withdrawnByStaker: (params) => viewer.withdrawnByStaker(...params ?? [])
  };
};

// src/modules/rpc/engine/rpcMethodHandlersFromTimeSyncViewer.ts
var rpcMethodHandlersFromTimeSyncViewer = (viewer) => {
  return {
    timeSyncViewer_convertTime: (params) => viewer.convertTime(...params ?? []),
    timeSyncViewer_currentTime: (params) => viewer.currentTime(...params ?? []),
    timeSyncViewer_currentTimeAndHash: (params) => viewer.currentTimeAndHash(...params ?? []),
    timeSyncViewer_currentTimePayload: (params) => viewer.currentTimePayload(...params ?? [])
  };
};

// src/modules/rpc/engine/rpcMethodHandlersFromTransactionViewer.ts
var rpcMethodHandlersFromTransactionViewer = (viewer) => {
  return { transactionViewer_byHash: (params) => viewer.byHash(...params ?? []) };
};

// src/modules/rpc/engine/rpcMethodHandlersFromViewer.ts
var rpcMethodHandlersFromViewer = (viewer) => {
  return {
    xyoViewer_networkStakeStepRewardClaimedByAddress: (params) => viewer.networkStakeStepRewardClaimedByAddress(...params ?? []),
    xyoViewer_networkStakeStepRewardAddressReward: (params) => viewer.networkStakeStepRewardAddressReward(...params ?? []),
    xyoViewer_networkStakeStepRewardAddressHistory: (params) => viewer.networkStakeStepRewardAddressHistory(...params ?? []),
    xyoViewer_networkStakeStepRewardAddressShare: (params) => viewer.networkStakeStepRewardAddressShare(...params ?? []),
    xyoViewer_networkStakeStepRewardWeightForAddress: (params) => viewer.networkStakeStepRewardWeightForAddress?.(...params ?? []),
    xyoViewer_networkStakeStepRewardUnclaimedByAddress: (params) => viewer.networkStakeStepRewardUnclaimedByAddress(...params ?? []),
    xyoViewer_networkStakeStepRewardPoolShares: (params) => viewer.networkStakeStepRewardPoolShares(...params ?? []),
    xyoViewer_networkStakeStepRewardPoolRewards: (params) => viewer.networkStakeStepRewardPoolRewards(...params ?? []),
    xyoViewer_networkStakeStepRewardPositionWeight: (params) => viewer.networkStakeStepRewardPositionWeight?.(...params ?? []),
    xyoViewer_networkStakeStepRewardPotentialPositionLoss: (params) => viewer.networkStakeStepRewardPotentialPositionLoss?.(...params ?? []),
    xyoViewer_networkStakeStepRewardForStep: (params) => viewer.networkStakeStepRewardForStep?.(...params ?? []),
    xyoViewer_networkStakeStepRewardRandomizer: (params) => viewer.networkStakeStepRewardRandomizer?.(...params ?? []),
    xyoViewer_networkStakeStepRewardStakerCount: (params) => viewer.networkStakeStepRewardStakerCount?.(...params ?? []),
    xyoViewer_networkStakeStepRewardForStepForPosition: (params) => viewer.networkStakeStepRewardForStepForPosition?.(...params ?? []),
    xyoViewer_networkStakeStepRewardForPosition: (params) => viewer.networkStakeStepRewardForPosition?.(...params ?? []),
    xyoViewer_networkStakeStepRewardsForPosition: (params) => viewer.networkStakeStepRewardsForPosition?.(...params ?? []),
    xyoViewer_networkStakeStepRewardsForRange: (params) => viewer.networkStakeStepRewardsForRange?.(...params ?? []),
    xyoViewer_networkStakeStepRewardsForStepLevel: (params) => viewer.networkStakeStepRewardsForStepLevel?.(...params ?? []),
    xyoViewer_blocksByNumber: (params) => viewer.blocksByNumber(...params ?? []),
    xyoViewer_blocksByHash: (params) => viewer.blocksByHash(...params ?? []),
    xyoViewer_blocksByStep: (params) => viewer.blocksByStep(...params ?? []),
    xyoViewer_currentBlock: (params) => viewer.currentBlock(...params ?? []),
    xyoViewer_forkHistory: (params) => viewer.forkHistory(...params ?? []),
    xyoViewer_stakeById: (params) => viewer.stakeById(...params ?? []),
    xyoViewer_stakeByStaker: (params) => viewer.stakeByStaker(...params ?? []),
    xyoViewer_stakesByStaked: (params) => viewer.stakesByStaked(...params ?? []),
    xyoViewer_stakesByStaker: (params) => viewer.stakesByStaker(...params ?? []),
    xyoViewer_transactionByBlockHashAndIndex: (params) => viewer.transaction.byBlockHashAndIndex(...params ?? []),
    xyoViewer_transactionByBlockNumberAndIndex: (params) => viewer.transaction.byBlockNumberAndIndex(...params ?? []),
    xyoViewer_transactionByHash: (params) => viewer.transaction.byHash(...params ?? []),
    xyoViewer_payloadsByHash: (params) => viewer.payloadsByHash(...params ?? [])
  };
};

// src/modules/rpc/engine/rpcMethodHandlersFromConnection.ts
var rpcMethodHandlersFromConnection = (connection) => {
  const { runner, viewer } = connection;
  let result = {};
  if (runner) result = { ...result, ...rpcMethodHandlersFromRunner(runner) };
  if (viewer) result = { ...result, ...rpcMethodHandlersFromViewer(viewer) };
  const accountBalanceViewer = viewer?.account?.balance;
  if (accountBalanceViewer) {
    result = {
      ...result,
      ...rpcMethodHandlersFromAccountBalanceViewer(accountBalanceViewer)
    };
  }
  const blockViewer = viewer?.block;
  if (blockViewer) {
    result = {
      ...result,
      ...rpcMethodHandlersFromBlockViewer(blockViewer)
    };
  }
  const finalizationViewer = viewer?.finalization;
  if (finalizationViewer) {
    result = {
      ...result,
      ...rpcMethodHandlersFromFinalizationViewer(finalizationViewer)
    };
  }
  const mempoolViewer = viewer?.mempool;
  if (mempoolViewer) {
    result = {
      ...result,
      ...rpcMethodHandlersFromMempoolViewer(mempoolViewer)
    };
  }
  const timeSyncViewer = viewer?.time;
  if (timeSyncViewer) {
    result = {
      ...result,
      ...rpcMethodHandlersFromTimeSyncViewer(timeSyncViewer)
    };
  }
  const transactionViewer = viewer?.transaction;
  if (transactionViewer) {
    result = {
      ...result,
      ...rpcMethodHandlersFromTransactionViewer(transactionViewer)
    };
  }
  const stakeTotalsViewer = viewer?.stakeTotals;
  if (stakeTotalsViewer) {
    result = {
      ...result,
      ...rpcMethodHandlersFromStakeTotalsViewer(stakeTotalsViewer)
    };
  }
  const mempoolRunner = runner?.mempool;
  if (mempoolRunner) {
    result = {
      ...result,
      ...rpcMethodHandlersFromMempoolRunner(mempoolRunner)
    };
  }
  const networkStakeViewer = viewer?.networkStake;
  if (networkStakeViewer?.stepRewards?.position) {
    result = {
      ...result,
      ...rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer(networkStakeViewer.stepRewards.position)
    };
  }
  return result;
};

// src/modules/rpc/engine/rpcMethodHandlersFromSigner.ts
import { isXyoJwtSignerMethods } from "@xyo-network/xl1-protocol/protocol-lib";
function rpcMethodHandlersFromSigner(signer) {
  const baseHandlers = {
    xyoSigner_address: (params) => signer.address(...params ?? []),
    xyoSigner_sign: (params) => signer.sign(...params ?? [])
  };
  if (!isXyoJwtSignerMethods(signer)) return baseHandlers;
  return {
    ...baseHandlers,
    xyoSigner_signJwt: (params) => signer.signJwt(...params ?? [])
  };
}

// src/modules/rpc/types/ErrorCodes.ts
var JsonRpcErrorCodes = {
  InternalError: { code: -32603, message: "Internal JSON-RPC error (unexpected exception)." },
  InvalidParams: { code: -32602, message: "Invalid method parameter(s)." },
  InvalidRequest: { code: -32600, message: "The JSON sent is not a valid Request object." },
  MethodNotFound: { code: -32601, message: "The method does not exist or is not available." },
  UserRejected: { code: 4001, message: "User rejected the request." }
};

// src/modules/rpc/types/JsonRpc.ts
var jsonrpc2 = "2.0";

// src/modules/rpc/types/schema/AccountBalanceViewerRpcSchemas.ts
import { BigIntToJsonZod, JsonToBigIntZod } from "@ariestools/sdk";
import { XyoAddressZod } from "@xyo-network/sdk";
import {
  AccountBalanceHistoryItemZod,
  ChainQualifiedConfigZod,
  ChainQualifiedZod
} from "@xyo-network/xl1-protocol/protocol-lib";
import { z } from "zod";
var AccountBalanceViewerRpcSchemas = {
  accountBalanceViewer_qualifiedAccountBalances: {
    params: {
      to: z.tuple([z.array(XyoAddressZod), ChainQualifiedConfigZod]),
      from: z.tuple([z.array(XyoAddressZod), ChainQualifiedConfigZod])
    },
    result: {
      to: ChainQualifiedZod(z.record(XyoAddressZod, BigIntToJsonZod)),
      from: ChainQualifiedZod(z.record(XyoAddressZod, JsonToBigIntZod))
    }
  },
  accountBalanceViewer_qualifiedAccountBalanceHistories: {
    params: {
      to: z.tuple([z.array(XyoAddressZod), ChainQualifiedConfigZod]),
      from: z.tuple([z.array(XyoAddressZod), ChainQualifiedConfigZod])
    },
    result: {
      to: ChainQualifiedZod(z.record(XyoAddressZod, z.array(AccountBalanceHistoryItemZod))),
      from: ChainQualifiedZod(z.record(XyoAddressZod, z.array(AccountBalanceHistoryItemZod)))
    }
  }
};

// src/modules/rpc/types/schema/BlockViewerRpcSchemas.ts
import { HashZod } from "@ariestools/sdk";
import { HashMetaZod, PayloadZodLoose } from "@xyo-network/sdk";
import { SignedHydratedBlockWithHashMetaZod, XL1BlockNumberZod } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z2 } from "zod/mini";
var WithHashMetaPayloadZodLoose = z2.extend(PayloadZodLoose, HashMetaZod.shape);
var BlockViewerRpcSchemas = {
  blockViewer_blocksByNumber: {
    params: {
      to: z2.tuple([XL1BlockNumberZod, z2.optional(z2.number())]),
      from: z2.tuple([XL1BlockNumberZod, z2.optional(z2.number())])
    },
    result: {
      to: z2.array(SignedHydratedBlockWithHashMetaZod),
      from: z2.array(SignedHydratedBlockWithHashMetaZod)
    }
  },
  blockViewer_blocksByHash: {
    params: {
      to: z2.tuple([HashZod, z2.optional(z2.number())]),
      from: z2.tuple([HashZod, z2.optional(z2.number())])
    },
    result: {
      to: z2.array(SignedHydratedBlockWithHashMetaZod),
      from: z2.array(SignedHydratedBlockWithHashMetaZod)
    }
  },
  blockViewer_blocksByStep: {
    params: {
      to: z2.tuple([z2.number(), z2.number()]),
      from: z2.tuple([z2.number(), z2.number()])
    },
    result: {
      to: z2.array(SignedHydratedBlockWithHashMetaZod),
      from: z2.array(SignedHydratedBlockWithHashMetaZod)
    }
  },
  blockViewer_currentBlock: {
    params: {
      to: z2._default(z2.tuple([]), []),
      from: z2._default(z2.tuple([]), [])
    },
    result: {
      to: SignedHydratedBlockWithHashMetaZod,
      from: SignedHydratedBlockWithHashMetaZod
    }
  },
  blockViewer_payloadsByHash: {
    params: {
      to: z2.tuple([z2.array(HashZod)]),
      from: z2.tuple([z2.array(HashZod)])
    },
    result: {
      to: z2.array(WithHashMetaPayloadZodLoose),
      from: z2.array(WithHashMetaPayloadZodLoose)
    }
  }
};

// src/modules/rpc/types/schema/DataLakeViewerRpcSchema.ts
import { HashZod as HashZod2 } from "@ariestools/sdk";
import { PayloadZod } from "@xyo-network/sdk";
import { ArrayBufferToJsonZod, JsonToArrayBufferZod } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z3 } from "zod/mini";
var DataLakeViewerRpcSchemas = {
  dataLakeViewer_get: {
    params: {
      to: z3.tuple([z3.array(HashZod2)]),
      from: z3.tuple([z3.array(HashZod2)])
    },
    result: {
      to: z3.array(z3.union([z3.looseObject(PayloadZod.shape), ArrayBufferToJsonZod])),
      from: z3.array(z3.union([z3.looseObject(PayloadZod.shape), JsonToArrayBufferZod]))
    }
  },
  dataLakeViewer_next: {
    params: {
      to: z3.tuple([z3.looseObject({})]),
      from: z3.tuple([z3.looseObject({})])
    },
    result: {
      to: z3.array(z3.union([z3.looseObject(PayloadZod.shape), ArrayBufferToJsonZod])),
      from: z3.array(z3.union([z3.looseObject(PayloadZod.shape), JsonToArrayBufferZod]))
    }
  }
};

// src/modules/rpc/types/schema/FinalizationViewerRpcSchemas.ts
import { SignedHydratedBlockWithHashMetaZod as SignedHydratedBlockWithHashMetaZod2 } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z4 } from "zod";
var FinalizationViewerRpcSchemas = {
  finalizationViewer_head: {
    params: {
      to: z4.tuple([]).default([]),
      from: z4.tuple([]).default([])
    },
    result: {
      to: SignedHydratedBlockWithHashMetaZod2,
      from: SignedHydratedBlockWithHashMetaZod2
    }
  }
};

// src/modules/rpc/types/schema/MempoolRunnerRpcSchemas.ts
import { HashZod as HashZod3 } from "@ariestools/sdk";
import { SignedHydratedBlockZod, SignedHydratedTransactionZod } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z5 } from "zod";
var MempoolRunnerRpcSchemas = {
  mempoolRunner_submitBlocks: {
    params: {
      to: z5.tuple([z5.array(SignedHydratedBlockZod)]),
      from: z5.tuple([z5.array(SignedHydratedBlockZod)])
    },
    result: {
      to: z5.array(HashZod3),
      from: z5.array(HashZod3)
    }
  },
  mempoolRunner_submitTransactions: {
    params: {
      to: z5.tuple([z5.array(SignedHydratedTransactionZod)]),
      from: z5.tuple([z5.array(SignedHydratedTransactionZod)])
    },
    result: {
      to: z5.array(HashZod3),
      from: z5.array(HashZod3)
    }
  }
};

// src/modules/rpc/types/schema/MempoolViewerRpcSchemas.ts
import {
  PendingBlocksOptionsZod,
  PendingTransactionsOptionsZod,
  SignedHydratedBlockWithHashMetaZod as SignedHydratedBlockWithHashMetaZod3,
  SignedHydratedTransactionWithHashMetaZod
} from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z6 } from "zod/mini";
var MempoolViewerRpcSchemas = {
  mempoolViewer_pendingBlocks: {
    params: {
      to: z6.tuple([z6.optional(PendingBlocksOptionsZod)]),
      from: z6.tuple([z6.optional(PendingBlocksOptionsZod)])
    },
    result: {
      to: z6.array(SignedHydratedBlockWithHashMetaZod3),
      from: z6.array(SignedHydratedBlockWithHashMetaZod3)
    }
  },
  mempoolViewer_pendingTransactions: {
    params: {
      to: z6.tuple([z6.optional(PendingTransactionsOptionsZod)]),
      from: z6.tuple([z6.optional(PendingTransactionsOptionsZod)])
    },
    result: {
      to: z6.array(SignedHydratedTransactionWithHashMetaZod),
      from: z6.array(SignedHydratedTransactionWithHashMetaZod)
    }
  }
};

// src/modules/rpc/types/schema/NetworkStakeViewerRpcSchemas.ts
import { BigIntToJsonZod as BigIntToJsonZod2, JsonToBigIntZod as JsonToBigIntZod2 } from "@ariestools/sdk";
import { BlockNumberZod } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z7 } from "zod";
var NetworkStakeViewerRpcSchemas = {
  networkStakeViewer_active: {
    params: {
      to: z7.tuple([BlockNumberZod.optional()]),
      from: z7.tuple([BlockNumberZod.optional()])
    },
    result: {
      to: z7.tuple([BigIntToJsonZod2, z7.number()]),
      from: z7.tuple([JsonToBigIntZod2, z7.number()])
    }
  }
};

// src/modules/rpc/types/schema/RewardsByPositionViewerRpcSchemas.ts
import { BigIntToJsonZod as BigIntToJsonZod3, JsonToBigIntZod as JsonToBigIntZod3 } from "@ariestools/sdk";
import {
  asAttoXL1,
  asXL1BlockRange,
  RewardsRangeOptionsZod,
  StepIdentityZod
} from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z8 } from "zod/mini";
var NetworkStakingStepRewardsByPositionViewerRpcSchemas = {
  networkStakingStepRewardsByPositionViewer_bonus: {
    params: {
      to: z8.tuple([z8.optional(RewardsRangeOptionsZod)]),
      from: z8.tuple([z8.optional(RewardsRangeOptionsZod)])
    },
    result: {
      to: z8.record(z8.number(), BigIntToJsonZod3),
      from: z8.record(z8.number(), z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val))))
    }
  },
  networkStakingStepRewardsByPositionViewer_claimed: {
    params: {
      to: z8.tuple([z8.optional(RewardsRangeOptionsZod)]),
      from: z8.tuple([z8.optional(RewardsRangeOptionsZod)])
    },
    result: {
      to: z8.record(z8.number(), BigIntToJsonZod3),
      from: z8.record(z8.number(), z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val))))
    }
  },
  networkStakingStepRewardsByPositionViewer_earned: {
    params: {
      to: z8.tuple([z8.optional(RewardsRangeOptionsZod)]),
      from: z8.tuple([z8.optional(RewardsRangeOptionsZod)])
    },
    result: {
      to: z8.record(z8.number(), BigIntToJsonZod3),
      from: z8.record(z8.number(), z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val))))
    }
  },
  networkStakingStepRewardsByPositionViewer_total: {
    params: {
      to: z8.tuple([z8.optional(RewardsRangeOptionsZod)]),
      from: z8.tuple([z8.optional(RewardsRangeOptionsZod)])
    },
    result: {
      to: z8.record(z8.number(), BigIntToJsonZod3),
      from: z8.record(z8.number(), z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val))))
    }
  },
  networkStakingStepRewardsByPositionViewer_totalForPosition: {
    params: {
      to: z8.tuple([z8.number(), z8.tuple([z8.number(), z8.number()])]),
      from: z8.tuple([
        z8.number(),
        z8.pipe(
          z8.tuple([z8.number(), z8.number()]),
          z8.transform((value) => asXL1BlockRange([value[0], value[1]], { name: "totalForPosition" }))
        )
      ])
    },
    result: {
      to: z8.tuple([BigIntToJsonZod3, BigIntToJsonZod3]),
      from: z8.tuple([z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val))), z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val)))])
    }
  },
  networkStakingStepRewardsByPositionViewer_totalForStep: {
    params: {
      to: z8.tuple([StepIdentityZod]),
      from: z8.tuple([StepIdentityZod])
    },
    result: {
      to: BigIntToJsonZod3,
      from: z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val)))
    }
  },
  networkStakingStepRewardsByPositionViewer_totalForStepForPosition: {
    params: {
      to: z8.tuple([StepIdentityZod, z8.number()]),
      from: z8.tuple([StepIdentityZod, z8.number()])
    },
    result: {
      to: z8.tuple([BigIntToJsonZod3, BigIntToJsonZod3]),
      from: z8.tuple([z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val))), z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val)))])
    }
  },
  networkStakingStepRewardsByPositionViewer_unclaimed: {
    params: {
      to: z8.tuple([z8.optional(RewardsRangeOptionsZod)]),
      from: z8.tuple([z8.optional(RewardsRangeOptionsZod)])
    },
    result: {
      to: z8.record(z8.number(), BigIntToJsonZod3),
      from: z8.record(z8.number(), z8.pipe(JsonToBigIntZod3, z8.transform((val) => asAttoXL1(val))))
    }
  }
};

// src/modules/rpc/types/schema/RewardsByStakerViewerRpcSchemas.ts
import { BigIntToJsonZod as BigIntToJsonZod4, JsonToBigIntZod as JsonToBigIntZod4 } from "@ariestools/sdk";
import { XyoAddressZod as XyoAddressZod2 } from "@xyo-network/sdk";
import { asAttoXL1 as asAttoXL12, RewardsRangeOptionsZod as RewardsRangeOptionsZod2 } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z9 } from "zod/mini";
var NetworkStakingStepRewardsByStakerViewerRpcSchemas = {
  networkStakingStepRewardsByStakerViewer_bonus: {
    params: {
      to: z9.tuple([z9.optional(RewardsRangeOptionsZod2)]),
      from: z9.tuple([z9.optional(RewardsRangeOptionsZod2)])
    },
    result: {
      to: z9.record(XyoAddressZod2, BigIntToJsonZod4),
      from: z9.record(XyoAddressZod2, z9.pipe(JsonToBigIntZod4, z9.transform((val) => asAttoXL12(val))))
    }
  },
  networkStakingStepRewardsByStakerViewer_claimed: {
    params: {
      to: z9.tuple([z9.optional(RewardsRangeOptionsZod2)]),
      from: z9.tuple([z9.optional(RewardsRangeOptionsZod2)])
    },
    result: {
      to: z9.record(XyoAddressZod2, BigIntToJsonZod4),
      from: z9.record(XyoAddressZod2, z9.pipe(JsonToBigIntZod4, z9.transform((val) => asAttoXL12(val))))
    }
  },
  networkStakingStepRewardsByStakerViewer_earned: {
    params: {
      to: z9.tuple([z9.optional(RewardsRangeOptionsZod2)]),
      from: z9.tuple([z9.optional(RewardsRangeOptionsZod2)])
    },
    result: {
      to: z9.record(XyoAddressZod2, BigIntToJsonZod4),
      from: z9.record(XyoAddressZod2, z9.pipe(JsonToBigIntZod4, z9.transform((val) => asAttoXL12(val))))
    }
  },
  networkStakingStepRewardsByStakerViewer_total: {
    params: {
      to: z9.tuple([z9.optional(RewardsRangeOptionsZod2)]),
      from: z9.tuple([z9.optional(RewardsRangeOptionsZod2)])
    },
    result: {
      to: z9.record(XyoAddressZod2, BigIntToJsonZod4),
      from: z9.record(XyoAddressZod2, z9.pipe(JsonToBigIntZod4, z9.transform((val) => asAttoXL12(val))))
    }
  },
  networkStakingStepRewardsByStakerViewer_unclaimed: {
    params: {
      to: z9.tuple([z9.optional(RewardsRangeOptionsZod2)]),
      from: z9.tuple([z9.optional(RewardsRangeOptionsZod2)])
    },
    result: {
      to: z9.record(XyoAddressZod2, BigIntToJsonZod4),
      from: z9.record(XyoAddressZod2, z9.pipe(JsonToBigIntZod4, z9.transform((val) => asAttoXL12(val))))
    }
  }
};

// src/modules/rpc/types/schema/RewardsByStepViewerRpcSchemas.ts
import { BigIntToJsonZod as BigIntToJsonZod5, JsonToBigIntZod as JsonToBigIntZod5 } from "@ariestools/sdk";
import { XyoAddressZod as XyoAddressZod3 } from "@xyo-network/sdk";
import { asAttoXL1 as asAttoXL13, RewardsRangeOptionsZod as RewardsRangeOptionsZod3 } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z10 } from "zod/mini";
var NetworkStakingStepRewardsByStepViewerRpcSchemas = {
  networkStakingStepRewardsByStepViewer_bonus: {
    params: {
      to: z10.tuple([z10.optional(RewardsRangeOptionsZod3)]),
      from: z10.tuple([z10.optional(RewardsRangeOptionsZod3)])
    },
    result: {
      to: z10.record(XyoAddressZod3, BigIntToJsonZod5),
      from: z10.record(XyoAddressZod3, z10.pipe(JsonToBigIntZod5, z10.transform((val) => asAttoXL13(val))))
    }
  },
  networkStakingStepRewardsByStepViewer_claimed: {
    params: {
      to: z10.tuple([z10.optional(RewardsRangeOptionsZod3)]),
      from: z10.tuple([z10.optional(RewardsRangeOptionsZod3)])
    },
    result: {
      to: z10.record(XyoAddressZod3, BigIntToJsonZod5),
      from: z10.record(XyoAddressZod3, z10.pipe(JsonToBigIntZod5, z10.transform((val) => asAttoXL13(val))))
    }
  },
  networkStakingStepRewardsByStepViewer_earned: {
    params: {
      to: z10.tuple([z10.optional(RewardsRangeOptionsZod3)]),
      from: z10.tuple([z10.optional(RewardsRangeOptionsZod3)])
    },
    result: {
      to: z10.record(XyoAddressZod3, BigIntToJsonZod5),
      from: z10.record(XyoAddressZod3, z10.pipe(JsonToBigIntZod5, z10.transform((val) => asAttoXL13(val))))
    }
  },
  networkStakingStepRewardsByStepViewer_total: {
    params: {
      to: z10.tuple([z10.optional(RewardsRangeOptionsZod3)]),
      from: z10.tuple([z10.optional(RewardsRangeOptionsZod3)])
    },
    result: {
      to: z10.record(XyoAddressZod3, BigIntToJsonZod5),
      from: z10.record(XyoAddressZod3, z10.pipe(JsonToBigIntZod5, z10.transform((val) => asAttoXL13(val))))
    }
  },
  networkStakingStepRewardsByStepViewer_unclaimed: {
    params: {
      to: z10.tuple([z10.optional(RewardsRangeOptionsZod3)]),
      from: z10.tuple([z10.optional(RewardsRangeOptionsZod3)])
    },
    result: {
      to: z10.record(XyoAddressZod3, BigIntToJsonZod5),
      from: z10.record(XyoAddressZod3, z10.pipe(JsonToBigIntZod5, z10.transform((val) => asAttoXL13(val))))
    }
  }
};

// src/modules/rpc/types/schema/RewardsTotalViewerRpcSchemas.ts
import { BigIntToJsonZod as BigIntToJsonZod6, JsonToBigIntZod as JsonToBigIntZod6 } from "@ariestools/sdk";
import { asAttoXL1 as asAttoXL14, RewardsRangeOptionsZod as RewardsRangeOptionsZod4 } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z11 } from "zod/mini";
var NetworkStakingStepRewardsTotalViewerRpcSchemas = {
  networkStakingStepRewardsTotalViewer_bonus: {
    params: {
      to: z11.tuple([z11.optional(RewardsRangeOptionsZod4)]),
      from: z11.tuple([z11.optional(RewardsRangeOptionsZod4)])
    },
    result: {
      to: BigIntToJsonZod6,
      from: z11.pipe(JsonToBigIntZod6, z11.transform((val) => asAttoXL14(val)))
    }
  },
  networkStakingStepRewardsTotalViewer_claimed: {
    params: {
      to: z11.tuple([z11.optional(RewardsRangeOptionsZod4)]),
      from: z11.tuple([z11.optional(RewardsRangeOptionsZod4)])
    },
    result: {
      to: BigIntToJsonZod6,
      from: z11.pipe(JsonToBigIntZod6, z11.transform((val) => asAttoXL14(val)))
    }
  },
  networkStakingStepRewardsTotalViewer_earned: {
    params: {
      to: z11.tuple([z11.optional(RewardsRangeOptionsZod4)]),
      from: z11.tuple([z11.optional(RewardsRangeOptionsZod4)])
    },
    result: {
      to: BigIntToJsonZod6,
      from: z11.pipe(JsonToBigIntZod6, z11.transform((val) => asAttoXL14(val)))
    }
  },
  networkStakingStepRewardsTotalViewer_total: {
    params: {
      to: z11.tuple([z11.optional(RewardsRangeOptionsZod4)]),
      from: z11.tuple([z11.optional(RewardsRangeOptionsZod4)])
    },
    result: {
      to: BigIntToJsonZod6,
      from: z11.pipe(JsonToBigIntZod6, z11.transform((val) => asAttoXL14(val)))
    }
  },
  networkStakingStepRewardsTotalViewer_unclaimed: {
    params: {
      to: z11.tuple([z11.optional(RewardsRangeOptionsZod4)]),
      from: z11.tuple([z11.optional(RewardsRangeOptionsZod4)])
    },
    result: {
      to: BigIntToJsonZod6,
      from: z11.pipe(JsonToBigIntZod6, z11.transform((val) => asAttoXL14(val)))
    }
  }
};

// src/modules/rpc/types/schema/StakeTotalsViewerRpcSchemas.ts
import { BigIntToJsonZod as BigIntToJsonZod7, JsonToBigIntZod as JsonToBigIntZod7 } from "@ariestools/sdk";
import { XyoAddressZod as XyoAddressZod4 } from "@xyo-network/sdk";
import { asAttoXL1 as asAttoXL15 } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z12 } from "zod/mini";
var StakeTotalsViewerRpcSchemas = {
  stakeTotalsViewer_active: {
    params: {
      to: z12.tuple([z12.optional(z12.number())]),
      from: z12.tuple([z12.optional(z12.number())])
    },
    result: {
      to: BigIntToJsonZod7,
      from: z12.pipe(JsonToBigIntZod7, z12.transform((val) => asAttoXL15(val)))
    }
  },
  stakeTotalsViewer_activeByStaked: {
    params: {
      to: z12.tuple([XyoAddressZod4, z12.optional(z12.number())]),
      from: z12.tuple([XyoAddressZod4, z12.optional(z12.number())])
    },
    result: {
      to: BigIntToJsonZod7,
      from: z12.pipe(JsonToBigIntZod7, z12.transform((val) => asAttoXL15(val)))
    }
  },
  stakeTotalsViewer_activeByStaker: {
    params: {
      to: z12.tuple([XyoAddressZod4, z12.optional(z12.number())]),
      from: z12.tuple([XyoAddressZod4, z12.optional(z12.number())])
    },
    result: {
      to: BigIntToJsonZod7,
      from: z12.pipe(JsonToBigIntZod7, z12.transform((val) => asAttoXL15(val)))
    }
  },
  stakeTotalsViewer_pending: {
    params: {
      to: z12.tuple([z12.optional(z12.number())]),
      from: z12.tuple([z12.optional(z12.number())])
    },
    result: {
      to: BigIntToJsonZod7,
      from: z12.pipe(JsonToBigIntZod7, z12.transform((val) => asAttoXL15(val)))
    }
  },
  stakeTotalsViewer_pendingByStaker: {
    params: {
      to: z12.tuple([XyoAddressZod4, z12.optional(z12.number())]),
      from: z12.tuple([XyoAddressZod4, z12.optional(z12.number())])
    },
    result: {
      to: BigIntToJsonZod7,
      from: z12.pipe(JsonToBigIntZod7, z12.transform((val) => asAttoXL15(val)))
    }
  },
  stakeTotalsViewer_withdrawn: {
    params: {
      to: z12.tuple([z12.optional(z12.number())]),
      from: z12.tuple([z12.optional(z12.number())])
    },
    result: {
      to: BigIntToJsonZod7,
      from: z12.pipe(JsonToBigIntZod7, z12.transform((val) => asAttoXL15(val)))
    }
  },
  stakeTotalsViewer_withdrawnByStaker: {
    params: {
      to: z12.tuple([XyoAddressZod4, z12.optional(z12.number())]),
      from: z12.tuple([XyoAddressZod4, z12.optional(z12.number())])
    },
    result: {
      to: BigIntToJsonZod7,
      from: z12.pipe(JsonToBigIntZod7, z12.transform((val) => asAttoXL15(val)))
    }
  }
};

// src/modules/rpc/types/schema/StakeViewerRpcSchemas.ts
import { XyoAddressZod as XyoAddressZod5 } from "@xyo-network/sdk";
import { JsonToStakeZod, StakeToJsonZod } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z14 } from "zod";

// src/modules/rpc/types/schema/NoArgsZod.ts
import { z as z13 } from "zod";
var NoArgsZod = z13.tuple([]).default([]);

// src/modules/rpc/types/schema/StakeViewerRpcSchemas.ts
var StakeViewerRpcSchemas = {
  stakeViewer_minWithdrawalBlocks: {
    params: {
      to: NoArgsZod,
      from: NoArgsZod
    },
    result: {
      to: z14.number(),
      from: z14.number()
    }
  },
  stakeViewer_rewardsContract: {
    params: {
      to: NoArgsZod,
      from: NoArgsZod
    },
    result: {
      to: XyoAddressZod5,
      from: XyoAddressZod5
    }
  },
  stakeViewer_stakeById: {
    params: {
      to: z14.tuple([z14.number()]),
      from: z14.tuple([z14.number()])
    },
    result: {
      to: StakeToJsonZod,
      from: JsonToStakeZod
    }
  },
  stakeViewer_stakeByStaker: {
    params: {
      to: z14.tuple([XyoAddressZod5, z14.number()]),
      from: z14.tuple([XyoAddressZod5, z14.number()])
    },
    result: {
      to: StakeToJsonZod,
      from: JsonToStakeZod
    }
  },
  stakeViewer_stakesByStaker: {
    params: {
      to: z14.tuple([XyoAddressZod5]),
      from: z14.tuple([XyoAddressZod5])
    },
    result: {
      to: z14.array(StakeToJsonZod),
      from: z14.array(JsonToStakeZod)
    }
  },
  stakeViewer_stakesByStaked: {
    params: {
      to: z14.tuple([XyoAddressZod5]),
      from: z14.tuple([XyoAddressZod5])
    },
    result: {
      to: z14.array(StakeToJsonZod),
      from: z14.array(JsonToStakeZod)
    }
  },
  stakeViewer_stakingTokenAddress: {
    params: {
      to: NoArgsZod,
      from: NoArgsZod
    },
    result: {
      to: XyoAddressZod5,
      from: XyoAddressZod5
    }
  }
};

// src/modules/rpc/types/schema/StepRewardsViewerRpcSchemas.ts
var NetworkStakingStepRewardsViewerRpcSchemas = {};

// src/modules/rpc/types/schema/StepViewerRpcSchemas.ts
import { BigIntToJsonZod as BigIntToJsonZod8, JsonToBigIntZod as JsonToBigIntZod8 } from "@ariestools/sdk";
import {
  JsonToStakeZod as JsonToStakeZod2,
  StakeToJsonZod as StakeToJsonZod2,
  StepIdentityZod as StepIdentityZod2
} from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z15 } from "zod";
var StepViewerRpcSchemas = {
  randomizer: {
    params: {
      to: z15.tuple([StepIdentityZod2]),
      from: z15.tuple([StepIdentityZod2])
    },
    result: {
      to: BigIntToJsonZod8,
      from: JsonToBigIntZod8
    }
  },
  stake: {
    params: {
      to: z15.tuple([StepIdentityZod2]),
      from: z15.tuple([StepIdentityZod2])
    },
    result: {
      to: BigIntToJsonZod8,
      from: JsonToBigIntZod8
    }
  },
  stakers: {
    params: {
      to: z15.tuple([StepIdentityZod2]),
      from: z15.tuple([StepIdentityZod2])
    },
    result: {
      to: BigIntToJsonZod8,
      from: JsonToBigIntZod8
    }
  },
  weight: {
    params: {
      to: z15.tuple([StepIdentityZod2]),
      from: z15.tuple([StepIdentityZod2])
    },
    result: {
      to: BigIntToJsonZod8,
      from: JsonToBigIntZod8
    }
  },
  positionCount: {
    params: {
      to: z15.tuple([StepIdentityZod2]),
      from: z15.tuple([StepIdentityZod2])
    },
    result: {
      to: z15.number(),
      from: z15.number()
    }
  },
  positions: {
    params: {
      to: z15.tuple([StepIdentityZod2]),
      from: z15.tuple([StepIdentityZod2])
    },
    result: {
      to: z15.array(StakeToJsonZod2),
      from: z15.array(JsonToStakeZod2)
    }
  },
  stakerCount: {
    params: {
      to: z15.tuple([StepIdentityZod2]),
      from: z15.tuple([StepIdentityZod2])
    },
    result: {
      to: z15.number(),
      from: z15.number()
    }
  }
};

// src/modules/rpc/types/schema/TimeSyncViewerRpcSchema.ts
import { TimeDomainZod, TimePayloadZod } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z16 } from "zod";
var TimeSyncViewerRpcSchemas = {
  timeSyncViewer_convertTime: {
    params: {
      from: z16.tuple([TimeDomainZod, TimeDomainZod, z16.number()]),
      to: z16.tuple([TimeDomainZod, TimeDomainZod, z16.number()])
    },
    result: {
      from: z16.number(),
      to: z16.number()
    }
  },
  timeSyncViewer_currentTime: {
    params: {
      from: z16.tuple([TimeDomainZod]),
      to: z16.tuple([TimeDomainZod])
    },
    result: {
      from: z16.tuple([TimeDomainZod, z16.number()]),
      to: z16.tuple([TimeDomainZod, z16.number()])
    }
  },
  timeSyncViewer_currentTimeAndHash: {
    params: {
      from: z16.tuple([TimeDomainZod]),
      to: z16.tuple([TimeDomainZod])
    },
    result: {
      from: z16.tuple([z16.number(), z16.nullable(z16.string())]),
      to: z16.tuple([z16.number(), z16.nullable(z16.string())])
    }
  },
  timeSyncViewer_currentTimePayload: {
    params: {
      from: z16.tuple([]).default([]),
      to: z16.tuple([]).default([])
    },
    result: {
      from: TimePayloadZod,
      to: TimePayloadZod
    }
  }
};

// src/modules/rpc/types/schema/TransactionViewerRpcSchema.ts
import { HashZod as HashZod4 } from "@ariestools/sdk";
import { SignedHydratedTransactionWithHashMetaZod as SignedHydratedTransactionWithHashMetaZod2 } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z17 } from "zod/mini";
var TransactionViewerRpcSchemas = {
  transactionViewer_byHash: {
    params: {
      to: z17.tuple([HashZod4]),
      from: z17.tuple([HashZod4])
    },
    result: {
      to: z17.nullable(SignedHydratedTransactionWithHashMetaZod2),
      from: z17.nullable(SignedHydratedTransactionWithHashMetaZod2)
    }
  }
};

// src/modules/rpc/types/schema/XyoPermissionsRpcSchemas.ts
import {
  InvokerPermissionZod,
  PermissionRequestZod,
  RequestedPermissionZod
} from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z18 } from "zod";
var XyoPermissionsRpcSchemas = {
  xyoPermissions_getPermissions: {
    params: {
      to: z18.tuple([]).default([]),
      from: z18.tuple([]).default([])
    },
    result: {
      to: z18.array(InvokerPermissionZod),
      from: z18.array(InvokerPermissionZod)
    }
  },
  xyoPermissions_requestPermissions: {
    params: {
      to: z18.tuple([z18.array(PermissionRequestZod)]),
      from: z18.tuple([z18.array(PermissionRequestZod)])
    },
    result: {
      to: z18.array(RequestedPermissionZod),
      from: z18.array(RequestedPermissionZod)
    }
  },
  xyoPermissions_revokePermissions: {
    params: {
      to: z18.tuple([z18.array(PermissionRequestZod)]),
      from: z18.tuple([z18.array(PermissionRequestZod)])
    },
    result: {
      to: z18.array(RequestedPermissionZod),
      from: z18.array(RequestedPermissionZod)
    }
  }
};

// src/modules/rpc/types/schema/XyoRunnerRpcSchemas.ts
import { HashToJsonZod, JsonToHashZod } from "@ariestools/sdk";
import { SignedHydratedTransactionZod as SignedHydratedTransactionZod2 } from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z19 } from "zod";
var XyoRunnerRpcSchemas = {
  xyoRunner_broadcastTransaction: {
    params: {
      to: z19.tuple([SignedHydratedTransactionZod2]),
      from: z19.tuple([SignedHydratedTransactionZod2])
    },
    result: {
      to: HashToJsonZod,
      from: JsonToHashZod
    }
  }
};

// src/modules/rpc/types/schema/XyoSignerRpcSchemas.ts
import {
  AnyUnsignedBoundWitnessZod,
  PayloadZodLoose as PayloadZodLoose2,
  SignedBoundWitnessZod,
  WithHashMetaPayloadZodLoose as WithHashMetaPayloadZodLoose2,
  WithHashMetaZod,
  XyoAddressZod as XyoAddressZod6
} from "@xyo-network/sdk";
import { z as z20 } from "zod/mini";
var XyoSignerJwtRpcLimits = {
  audienceLength: 2048,
  claimCount: 32,
  claimDepth: 8,
  claimKeyLength: 128,
  claimsBytes: 8192,
  schemaLength: 256
};
function hasAllowedClaimDepth(value) {
  const pending = [{ depth: 0, value }];
  while (pending.length > 0) {
    const current = pending.pop();
    if (current === void 0) break;
    if (current.depth > XyoSignerJwtRpcLimits.claimDepth) return false;
    if (typeof current.value !== "object" || current.value === null) continue;
    const children = Array.isArray(current.value) ? current.value : Object.values(current.value);
    pending.push(...children.map((child) => ({ depth: current.depth + 1, value: child })));
  }
  return true;
}
var JsonValueZod = z20.json();
var NonemptyAudienceZod = z20.string().check(
  z20.minLength(1),
  z20.maxLength(XyoSignerJwtRpcLimits.audienceLength),
  z20.refine((value) => value.trim().length > 0, { message: "audience must contain a non-whitespace character" })
);
var NonemptySchemaZod = z20.string().check(
  z20.minLength(1),
  z20.maxLength(XyoSignerJwtRpcLimits.schemaLength),
  z20.refine((value) => value.trim().length > 0, { message: "schema must contain a non-whitespace character" })
);
var PositiveIntegerTimeZod = z20.int().check(z20.positive());
var ClaimsWireZod = z20.record(
  z20.string().check(z20.minLength(1), z20.maxLength(XyoSignerJwtRpcLimits.claimKeyLength)),
  JsonValueZod
).check(
  z20.refine(
    (claims) => Object.keys(claims).length <= XyoSignerJwtRpcLimits.claimCount,
    { message: `claims may contain at most ${XyoSignerJwtRpcLimits.claimCount} top-level entries` }
  ),
  z20.refine(hasAllowedClaimDepth, { message: `claims may be at most ${XyoSignerJwtRpcLimits.claimDepth} levels deep` }),
  z20.refine(
    (claims) => new TextEncoder().encode(JSON.stringify(claims)).byteLength <= XyoSignerJwtRpcLimits.claimsBytes,
    { message: `claims may encode to at most ${XyoSignerJwtRpcLimits.claimsBytes} bytes` }
  ),
  z20.refine(
    (claims) => claims.nbf === void 0 || Number.isSafeInteger(claims.nbf),
    { message: "claims.nbf must be an integer when supplied" }
  )
);
var SignJwtOptionsWireZod = z20.strictObject({
  audience: NonemptyAudienceZod,
  claims: z20.optional(ClaimsWireZod),
  exp: z20.optional(PositiveIntegerTimeZod),
  schema: z20.optional(NonemptySchemaZod),
  ttl: z20.optional(PositiveIntegerTimeZod)
}).check(z20.refine(
  (options) => options.ttl === void 0 || options.exp === void 0,
  { message: "ttl and exp are mutually exclusive" }
));
var SignJwtOptionsZod = SignJwtOptionsWireZod;
var JwtHeaderWireZod = z20.strictObject({
  alg: z20.literal("ES256K"),
  kid: XyoAddressZod6,
  pub: z20.string().check(z20.minLength(1)),
  typ: z20.literal("JWT")
});
var JwtPayloadWireZod = z20.looseObject({
  aud: NonemptyAudienceZod,
  exp: PositiveIntegerTimeZod,
  iat: z20.int(),
  iss: XyoAddressZod6,
  schema: NonemptySchemaZod
}).check(
  z20.refine((payload) => payload.exp > payload.iat, { message: "JWT expiration must be after issuance" }),
  z20.refine((payload) => JsonValueZod.safeParse(payload).success, { message: "JWT payload must be JSON-safe" })
);
var SignJwtResultWireZod = z20.strictObject({
  header: JwtHeaderWireZod,
  payload: JwtPayloadWireZod,
  token: z20.string().check(z20.minLength(1))
}).check(z20.refine(
  (result) => result.header.kid === result.payload.iss,
  { message: "JWT header kid must equal payload issuer" }
));
var SignJwtResultZod = SignJwtResultWireZod;
var UnsignedHydratedBoundWitnessLooseZod = z20.tuple([
  AnyUnsignedBoundWitnessZod,
  z20.array(PayloadZodLoose2)
]);
var WithHashMetaSignedBoundWitnessZod = WithHashMetaZod(SignedBoundWitnessZod);
var WithHashMetaSignedBoundWitnessZodLoose = z20.looseObject(WithHashMetaSignedBoundWitnessZod.shape);
var SignedHydratedBoundWitnessWithHashMetaLooseZod = z20.tuple([
  WithHashMetaSignedBoundWitnessZodLoose,
  z20.array(WithHashMetaPayloadZodLoose2)
]);
var XyoSignerBaseRpcSchemas = {
  xyoSigner_address: {
    params: {
      to: NoArgsZod,
      from: NoArgsZod
    },
    result: {
      to: XyoAddressZod6,
      from: XyoAddressZod6
    }
  },
  xyoSigner_sign: {
    params: {
      to: z20.tuple([UnsignedHydratedBoundWitnessLooseZod]),
      from: z20.tuple([UnsignedHydratedBoundWitnessLooseZod])
    },
    result: {
      to: SignedHydratedBoundWitnessWithHashMetaLooseZod,
      from: SignedHydratedBoundWitnessWithHashMetaLooseZod
    }
  }
};
var XyoSignerRpcSchemas = {
  ...XyoSignerBaseRpcSchemas,
  xyoSigner_signJwt: {
    params: {
      to: z20.tuple([SignJwtOptionsZod]),
      from: z20.tuple([SignJwtOptionsZod])
    },
    result: {
      to: SignJwtResultZod,
      from: SignJwtResultZod
    }
  }
};

// src/modules/rpc/types/schema/XyoViewerRpcSchemas.ts
import {
  BigIntToJsonZod as BigIntToJsonZod9,
  HashZod as HashZod5,
  HexZod,
  JsonToBigIntZod as JsonToBigIntZod9
} from "@ariestools/sdk";
import { PayloadZodLoose as PayloadZodLoose3, XyoAddressZod as XyoAddressZod7 } from "@xyo-network/sdk";
import {
  asAttoXL1 as asAttoXL16,
  JsonToStakeZod as JsonToStakeZod3,
  SignedHydratedBlockWithHashMetaZod as SignedHydratedBlockWithHashMetaZod4,
  SignedHydratedTransactionZod as SignedHydratedTransactionZod3,
  StakeToJsonZod as StakeToJsonZod3,
  StepIdentityZod as StepIdentityZod3,
  XL1BlockNumberZod as XL1BlockNumberZod2
} from "@xyo-network/xl1-protocol/protocol-lib";
import { z as z21 } from "zod/mini";
var XyoViewerRpcSchemas = {
  xyoViewer_networkStakeStepRewardClaimedByAddress: {
    params: {
      to: z21.tuple([XyoAddressZod7]),
      from: z21.tuple([XyoAddressZod7])
    },
    result: {
      to: BigIntToJsonZod9,
      from: z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))
    }
  },
  xyoViewer_networkStakeStepRewardAddressReward: {
    params: {
      to: z21.tuple([StepIdentityZod3, XyoAddressZod7]),
      from: z21.tuple([StepIdentityZod3, XyoAddressZod7])
    },
    result: {
      to: z21.record(XyoAddressZod7, BigIntToJsonZod9),
      from: z21.record(XyoAddressZod7, z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val))))
    }
  },
  xyoViewer_networkStakeStepRewardAddressHistory: {
    params: {
      to: z21.tuple([XyoAddressZod7]),
      from: z21.tuple([XyoAddressZod7])
    },
    result: {
      to: z21.record(XyoAddressZod7, BigIntToJsonZod9),
      from: z21.record(XyoAddressZod7, z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val))))
    }
  },
  xyoViewer_networkStakeStepRewardAddressShare: {
    params: {
      to: z21.tuple([StepIdentityZod3, XyoAddressZod7]),
      from: z21.tuple([StepIdentityZod3, XyoAddressZod7])
    },
    result: {
      to: z21.tuple([BigIntToJsonZod9, BigIntToJsonZod9]),
      from: z21.tuple([JsonToBigIntZod9, JsonToBigIntZod9])
    }
  },
  xyoViewer_networkStakeStepRewardWeightForAddress: {
    params: {
      to: z21.tuple([StepIdentityZod3, XyoAddressZod7]),
      from: z21.tuple([StepIdentityZod3, XyoAddressZod7])
    },
    result: {
      to: BigIntToJsonZod9,
      from: JsonToBigIntZod9
    }
  },
  xyoViewer_networkStakeStepRewardUnclaimedByAddress: {
    params: {
      to: z21.tuple([XyoAddressZod7]),
      from: z21.tuple([XyoAddressZod7])
    },
    result: {
      to: BigIntToJsonZod9,
      from: z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))
    }
  },
  xyoViewer_networkStakeStepRewardPoolRewards: {
    params: {
      to: z21.tuple([StepIdentityZod3]),
      from: z21.tuple([StepIdentityZod3])
    },
    result: {
      to: z21.record(XyoAddressZod7, BigIntToJsonZod9),
      from: z21.record(XyoAddressZod7, z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val))))
    }
  },
  xyoViewer_networkStakeStepRewardPositionWeight: {
    params: {
      to: z21.tuple([StepIdentityZod3, z21.number()]),
      from: z21.tuple([StepIdentityZod3, z21.number()])
    },
    result: {
      to: BigIntToJsonZod9,
      from: JsonToBigIntZod9
    }
  },
  xyoViewer_networkStakeStepRewardPotentialPositionLoss: {
    params: {
      to: z21.tuple([StepIdentityZod3, z21.number()]),
      from: z21.tuple([StepIdentityZod3, z21.number()])
    },
    result: {
      to: BigIntToJsonZod9,
      from: z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))
    }
  },
  xyoViewer_networkStakeStepRewardForStep: {
    params: {
      to: z21.tuple([StepIdentityZod3]),
      from: z21.tuple([StepIdentityZod3])
    },
    result: {
      to: BigIntToJsonZod9,
      from: z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))
    }
  },
  xyoViewer_networkStakeStepRewardRandomizer: {
    params: {
      to: z21.tuple([StepIdentityZod3]),
      from: z21.tuple([StepIdentityZod3])
    },
    result: {
      to: BigIntToJsonZod9,
      from: z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))
    }
  },
  xyoViewer_networkStakeStepRewardStakerCount: {
    params: {
      to: z21.tuple([StepIdentityZod3]),
      from: z21.tuple([StepIdentityZod3])
    },
    result: {
      to: z21.number(),
      from: z21.number()
    }
  },
  xyoViewer_networkStakeStepRewardPoolShares: {
    params: {
      to: z21.tuple([StepIdentityZod3]),
      from: z21.tuple([StepIdentityZod3])
    },
    result: {
      to: z21.record(XyoAddressZod7, BigIntToJsonZod9),
      from: z21.record(XyoAddressZod7, JsonToBigIntZod9)
    }
  },
  xyoViewer_networkStakeStepRewardForStepForPosition: {
    params: {
      to: z21.tuple([StepIdentityZod3, z21.number()]),
      from: z21.tuple([StepIdentityZod3, z21.number()])
    },
    result: {
      to: z21.tuple([BigIntToJsonZod9, BigIntToJsonZod9]),
      from: z21.tuple([z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val))), z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))])
    }
  },
  xyoViewer_networkStakeStepRewardForPosition: {
    params: {
      to: z21.tuple([z21.number(), z21.tuple([z21.number(), z21.number()])]),
      from: z21.tuple([z21.number(), z21.tuple([z21.number(), z21.number()])])
    },
    result: {
      to: z21.tuple([BigIntToJsonZod9, BigIntToJsonZod9]),
      from: z21.tuple([z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val))), z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))])
    }
  },
  xyoViewer_networkStakeStepRewardsForRange: {
    params: {
      to: z21.tuple([z21.tuple([z21.number(), z21.number()])]),
      from: z21.tuple([z21.tuple([z21.number(), z21.number()])])
    },
    result: {
      to: BigIntToJsonZod9,
      from: z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))
    }
  },
  xyoViewer_networkStakeStepRewardsForStepLevel: {
    params: {
      to: z21.tuple([z21.number(), z21.tuple([z21.number(), z21.number()])]),
      from: z21.tuple([z21.number(), z21.tuple([z21.number(), z21.number()])])
    },
    result: {
      to: BigIntToJsonZod9,
      from: z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))
    }
  },
  xyoViewer_networkStakeStepRewardsForPosition: {
    params: {
      to: z21.tuple([z21.number(), z21.tuple([z21.number(), z21.number()])]),
      from: z21.tuple([z21.number(), z21.tuple([z21.number(), z21.number()])])
    },
    result: {
      to: z21.record(z21.string(), z21.tuple([BigIntToJsonZod9, BigIntToJsonZod9])),
      from: z21.record(z21.string(), z21.tuple([z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val))), z21.pipe(JsonToBigIntZod9, z21.transform((val) => asAttoXL16(val)))]))
    }
  },
  xyoViewer_blocksByNumber: {
    params: {
      to: z21.tuple([XL1BlockNumberZod2, z21.optional(z21.number())]),
      from: z21.tuple([XL1BlockNumberZod2, z21.optional(z21.number())])
    },
    result: {
      to: z21.array(SignedHydratedBlockWithHashMetaZod4),
      from: z21.array(SignedHydratedBlockWithHashMetaZod4)
    }
  },
  xyoViewer_blocksByHash: {
    params: {
      to: z21.tuple([HashZod5, z21.optional(z21.number())]),
      from: z21.tuple([HashZod5, z21.optional(z21.number())])
    },
    result: {
      to: z21.array(SignedHydratedBlockWithHashMetaZod4),
      from: z21.array(SignedHydratedBlockWithHashMetaZod4)
    }
  },
  xyoViewer_blocksByStep: {
    params: {
      to: z21.tuple([z21.number(), z21.number()]),
      from: z21.tuple([z21.number(), z21.number()])
    },
    result: {
      to: z21.array(SignedHydratedBlockWithHashMetaZod4),
      from: z21.array(SignedHydratedBlockWithHashMetaZod4)
    }
  },
  xyoViewer_currentBlock: {
    params: {
      to: z21._default(z21.tuple([]), []),
      from: z21._default(z21.tuple([]), [])
    },
    result: {
      to: SignedHydratedBlockWithHashMetaZod4,
      from: SignedHydratedBlockWithHashMetaZod4
    }
  },
  xyoViewer_forkHistory: {
    params: {
      to: z21._default(z21.tuple([]), []),
      from: z21._default(z21.tuple([]), [])
    },
    result: {
      to: z21.record(z21.number(), HexZod),
      from: z21.record(z21.number(), HexZod)
    }
  },
  xyoViewer_stakeByStaker: {
    params: {
      to: z21.tuple([XyoAddressZod7, z21.number()]),
      from: z21.tuple([XyoAddressZod7, z21.number()])
    },
    result: {
      to: StakeToJsonZod3,
      from: JsonToStakeZod3
    }
  },
  xyoViewer_stakeById: {
    params: {
      to: z21.tuple([z21.number()]),
      from: z21.tuple([z21.number()])
    },
    result: {
      to: StakeToJsonZod3,
      from: JsonToStakeZod3
    }
  },
  xyoViewer_stakesByStaker: {
    params: {
      to: z21.tuple([XyoAddressZod7]),
      from: z21.tuple([XyoAddressZod7])
    },
    result: {
      to: z21.array(StakeToJsonZod3),
      from: z21.array(JsonToStakeZod3)
    }
  },
  xyoViewer_stakesByStaked: {
    params: {
      to: z21.tuple([XyoAddressZod7]),
      from: z21.tuple([XyoAddressZod7])
    },
    result: {
      to: z21.array(StakeToJsonZod3),
      from: z21.array(JsonToStakeZod3)
    }
  },
  xyoViewer_transactionByBlockHashAndIndex: {
    params: {
      to: z21.tuple([HashZod5, z21.number()]),
      from: z21.tuple([HashZod5, z21.number()])
    },
    result: {
      to: z21.nullable(SignedHydratedTransactionZod3),
      from: z21.nullable(SignedHydratedTransactionZod3)
    }
  },
  xyoViewer_transactionByBlockNumberAndIndex: {
    params: {
      to: z21.tuple([z21.number(), z21.number()]),
      from: z21.tuple([z21.number(), z21.number()])
    },
    result: {
      to: z21.nullable(SignedHydratedTransactionZod3),
      from: z21.nullable(SignedHydratedTransactionZod3)
    }
  },
  xyoViewer_transactionByHash: {
    params: {
      to: z21.tuple([HashZod5]),
      from: z21.tuple([HashZod5])
    },
    result: {
      to: z21.nullable(SignedHydratedTransactionZod3),
      from: z21.nullable(SignedHydratedTransactionZod3)
    }
  },
  xyoViewer_payloadsByHash: {
    params: {
      to: z21.tuple([z21.array(HashZod5)]),
      from: z21.tuple([z21.array(HashZod5)])
    },
    result: {
      to: z21.array(PayloadZodLoose3),
      from: z21.array(PayloadZodLoose3)
    }
  }
};

// src/modules/rpc/types/schema/AllRpcSchemas.ts
var AllRpcSchemas = {
  ...AccountBalanceViewerRpcSchemas,
  ...XyoRunnerRpcSchemas,
  ...XyoSignerRpcSchemas,
  ...XyoViewerRpcSchemas,
  ...XyoPermissionsRpcSchemas,
  ...NetworkStakeViewerRpcSchemas,
  ...BlockViewerRpcSchemas,
  ...MempoolViewerRpcSchemas,
  ...MempoolRunnerRpcSchemas,
  ...TimeSyncViewerRpcSchemas,
  ...StepViewerRpcSchemas,
  ...DataLakeViewerRpcSchemas,
  ...StakeTotalsViewerRpcSchemas,
  ...StakeViewerRpcSchemas,
  ...NetworkStakingStepRewardsViewerRpcSchemas,
  ...NetworkStakingStepRewardsTotalViewerRpcSchemas,
  ...NetworkStakingStepRewardsByStepViewerRpcSchemas,
  ...NetworkStakingStepRewardsByStakerViewerRpcSchemas,
  ...NetworkStakingStepRewardsByPositionViewerRpcSchemas,
  ...TransactionViewerRpcSchemas,
  ...FinalizationViewerRpcSchemas
};

// src/modules/rpc/types/schema/createRequestSchema.ts
import { z as z22 } from "zod/mini";
var createRequestSchema = (methodName, paramsSchema = z22.undefined()) => z22.object({
  id: z22.union([z22.string(), z22.number()]),
  jsonrpc: z22.literal(jsonrpc2),
  method: z22.literal(methodName),
  params: paramsSchema
});

// src/modules/rpc/engine-node/middleware/createHandlerMiddleware.ts
var buildHandlerScaffold = (handlers) => {
  const scaffold = {};
  for (const [method, handler] of Object.entries(handlers)) {
    if (handler === void 0) continue;
    scaffold[method] = async ({ context }) => {
      const schema = context.assertGet("schema");
      const params = context.assertGet("params");
      const result = await handler(params);
      return schema.result.to.parse(result);
    };
  }
  return createScaffoldMiddleware(scaffold);
};
var createTypedHandlerMiddleware = (_schemas, handlers) => buildHandlerScaffold(handlers);

// src/modules/rpc/engine-node/middleware/createLoggingMiddleware.ts
var createLoggingMiddleware = (logger) => async ({ request, next }) => {
  try {
    return await next();
  } catch (error) {
    logger?.error(`RPC ${request.method} failed`, error);
    throw error;
  }
};

// src/modules/rpc/engine-node/middleware/createMethodNotFoundMiddleware.ts
var createMethodNotFoundMiddleware = () => ({ request }) => {
  throw new Error(`${JsonRpcErrorCodes.MethodNotFound.message} (${request.method})`);
};

// src/modules/rpc/engine-node/middleware/createValidationMiddleware.ts
var createValidationMiddleware = (schemas) => ({
  request,
  context,
  next
}) => {
  const schema = schemas[request.method];
  if (schema === void 0) return next();
  let requestSchema = requestSchemas[request.method];
  if (requestSchema === void 0) {
    requestSchema = createRequestSchema(request.method, schema.params.from);
    requestSchemas[request.method] = requestSchema;
  }
  const parsed = requestSchema.safeParse(request);
  if (!parsed.success) {
    throw new Error(parsed.error.message);
  }
  context.set("schema", schema);
  context.set("params", parsed.data.params);
  return next();
};

// src/modules/rpc/engine-node/composedRpcEngineFromConnection.ts
var buildTypedSubEngine = (schemas, handlers) => JsonRpcEngineV2.create({
  middleware: [
    createValidationMiddleware(schemas),
    createTypedHandlerMiddleware(schemas, handlers)
  ]
});
var composedRpcEngineFromConnection = (connection, logger) => {
  const { runner, viewer } = connection;
  const subEngines = [];
  if (runner) {
    subEngines.push(buildTypedSubEngine(XyoRunnerRpcSchemas, rpcMethodHandlersFromRunner(runner)));
  }
  if (viewer) {
    subEngines.push(buildTypedSubEngine(XyoViewerRpcSchemas, rpcMethodHandlersFromViewer(viewer)));
  }
  const accountBalanceViewer = viewer?.account?.balance;
  if (accountBalanceViewer) {
    subEngines.push(buildTypedSubEngine(
      AccountBalanceViewerRpcSchemas,
      rpcMethodHandlersFromAccountBalanceViewer(accountBalanceViewer)
    ));
  }
  const blockViewer = viewer?.block;
  if (blockViewer) {
    subEngines.push(buildTypedSubEngine(
      BlockViewerRpcSchemas,
      rpcMethodHandlersFromBlockViewer(blockViewer)
    ));
  }
  const finalizationViewer = viewer?.finalization;
  if (finalizationViewer) {
    subEngines.push(buildTypedSubEngine(
      FinalizationViewerRpcSchemas,
      rpcMethodHandlersFromFinalizationViewer(finalizationViewer)
    ));
  }
  const mempoolViewer = viewer?.mempool;
  if (mempoolViewer) {
    subEngines.push(buildTypedSubEngine(
      MempoolViewerRpcSchemas,
      rpcMethodHandlersFromMempoolViewer(mempoolViewer)
    ));
  }
  const timeSyncViewer = viewer?.time;
  if (timeSyncViewer) {
    subEngines.push(buildTypedSubEngine(
      TimeSyncViewerRpcSchemas,
      rpcMethodHandlersFromTimeSyncViewer(timeSyncViewer)
    ));
  }
  const transactionViewer = viewer?.transaction;
  if (transactionViewer) {
    subEngines.push(buildTypedSubEngine(
      TransactionViewerRpcSchemas,
      rpcMethodHandlersFromTransactionViewer(transactionViewer)
    ));
  }
  const stakeTotalsViewer = viewer?.stakeTotals;
  if (stakeTotalsViewer) {
    subEngines.push(buildTypedSubEngine(
      StakeTotalsViewerRpcSchemas,
      rpcMethodHandlersFromStakeTotalsViewer(stakeTotalsViewer)
    ));
  }
  const mempoolRunner = runner?.mempool;
  if (mempoolRunner) {
    subEngines.push(buildTypedSubEngine(
      MempoolRunnerRpcSchemas,
      rpcMethodHandlersFromMempoolRunner(mempoolRunner)
    ));
  }
  const networkStakeViewer = viewer?.networkStake;
  if (networkStakeViewer?.stepRewards?.position) {
    subEngines.push(buildTypedSubEngine(
      NetworkStakingStepRewardsByPositionViewerRpcSchemas,
      rpcMethodHandlersFromNetworkStakingStepRewardsByPositionViewer(networkStakeViewer.stepRewards.position)
    ));
  }
  const middleware = [
    createLoggingMiddleware(logger),
    ...subEngines.map((engine) => engine.asMiddleware()),
    createMethodNotFoundMiddleware()
  ];
  return JsonRpcEngineV2.create({ middleware });
};
var composedRpcServerFromConnection = (connection, logger) => {
  const engine = composedRpcEngineFromConnection(connection, logger);
  return new JsonRpcServer({ engine });
};
var composedRpcEngineFromGateway = (gateway, logger) => {
  const runner = gateway.moniker === XyoGatewayRunnerMoniker ? gateway : void 0;
  const middleware = [createLoggingMiddleware(logger)];
  if (runner) {
    const { signer } = runner;
    const signerSubEngine = isXyoJwtSignerMethods2(signer) ? buildTypedSubEngine(XyoSignerRpcSchemas, rpcMethodHandlersFromSigner(signer)) : buildTypedSubEngine(XyoSignerBaseRpcSchemas, rpcMethodHandlersFromSigner(signer));
    middleware.push(signerSubEngine.asMiddleware());
  }
  middleware.push(composedRpcEngineFromConnection(gateway.connection).asMiddleware());
  return JsonRpcEngineV2.create({ middleware });
};
var composedRpcServerFromGateway = (gateway, logger) => {
  const engine = composedRpcEngineFromGateway(gateway, logger);
  return new JsonRpcServer({ engine });
};

// src/modules/rpc/engine-node/createRpcDispatchMiddleware.ts
var createRpcDispatchMiddleware = (schemas, handlers, options) => async ({ request }) => {
  const method = request.method;
  const handler = handlers[method];
  const schema = schemas[method];
  if (schema === void 0 || handler === void 0) {
    const createError = options?.methodNotFound ?? (() => new Error(JsonRpcErrorCodes.MethodNotFound.message));
    throw createError(method);
  }
  let requestSchema = requestSchemas[method];
  if (requestSchema == void 0) {
    requestSchema = createRequestSchema(method, schema.params.from);
    requestSchemas[method] = requestSchema;
  }
  const parsed = requestSchema.safeParse(request);
  if (!parsed.success) {
    options?.logger?.error("RPC Request Validation Error", parsed.error);
    throw new Error(parsed.error.message);
  }
  const { params } = parsed.data;
  try {
    const result = await handler(params);
    return schema.result.to.parse(result);
  } catch (error) {
    options?.logger?.error("RPC Response Handler Error", error);
    throw error;
  }
};

// src/modules/rpc/engine-node/rpcEngineFromConnection.ts
var rpcEngineFromConnection = (connection, logger) => {
  const handlers = rpcMethodHandlersFromConnection(connection);
  const middleware = createRpcDispatchMiddleware(AllRpcSchemas, handlers, { logger });
  return JsonRpcEngineV2.create({ middleware: [middleware] });
};
function rpcServerFromConnection(connection, logger) {
  const engine = rpcEngineFromConnection(connection, logger);
  return new JsonRpcServer({ engine });
}
export {
  composedRpcEngineFromConnection,
  composedRpcEngineFromGateway,
  composedRpcServerFromConnection,
  composedRpcServerFromGateway,
  createLoggingMiddleware,
  createMethodNotFoundMiddleware,
  createRpcDispatchMiddleware,
  createTypedHandlerMiddleware,
  createValidationMiddleware,
  rpcEngineFromConnection,
  rpcServerFromConnection
};
//# sourceMappingURL=rpc.server.mjs.map
