import { createRequire as __createRequire } from 'module'; import { fileURLToPath as __fileURLToPath } from 'url'; import { dirname as __pathDirname } from 'path'; const require = __createRequire(import.meta.url); const __filename = __fileURLToPath(import.meta.url); const __dirname = __pathDirname(__filename);
import {
  Transaction,
  computeGasBudget,
  coreClientResolveTransactionPlugin,
  isCoinReservationDigest,
  isTransaction
} from "./chunk-N5MEZ42L.js";
import {
  BaseClient,
  CoreClient,
  formatMoveAbortMessage,
  parseTransactionBcs,
  parseTransactionEffectsBcs
} from "./chunk-VRFW55MF.js";
import {
  ObjectError,
  PACKAGE_VERSION,
  SUI_FRAMEWORK_ADDRESS,
  SUI_SYSTEM_ADDRESS,
  TransactionDataBuilder,
  TypeTagSerializer,
  chunk,
  deriveDynamicFieldID,
  hasMvrName,
  init_bcs,
  init_constants,
  init_dynamic_fields,
  init_type_tag_serializer,
  suiBcs
} from "./chunk-6ADWLA5A.js";
import {
  fromBase58,
  fromBase64,
  init_dist,
  init_move_registry,
  init_sui_types,
  init_suins,
  isValidNamedPackage,
  isValidSuiAddress,
  isValidSuiObjectId,
  isValidTransactionDigest,
  normalizeStructTag,
  normalizeSuiAddress,
  normalizeSuiNSName,
  normalizeSuiObjectId,
  toBase64,
  toHex
} from "./chunk-BLV67HXL.js";

// ../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/dist/jsonRpc/errors.mjs
var CODE_TO_ERROR_TYPE = {
  "-32700": "ParseError",
  "-32701": "OversizedRequest",
  "-32702": "OversizedResponse",
  "-32600": "InvalidRequest",
  "-32601": "MethodNotFound",
  "-32602": "InvalidParams",
  "-32603": "InternalError",
  "-32604": "ServerBusy",
  "-32000": "CallExecutionFailed",
  "-32001": "UnknownError",
  "-32003": "SubscriptionClosed",
  "-32004": "SubscriptionClosedWithError",
  "-32005": "BatchesNotSupported",
  "-32006": "TooManySubscriptions",
  "-32050": "TransientError",
  "-32002": "TransactionExecutionClientError"
};
var SuiHTTPTransportError = class extends Error {
};
var JsonRpcError = class extends SuiHTTPTransportError {
  constructor(message, code) {
    super(message);
    this.code = code;
    this.type = CODE_TO_ERROR_TYPE[code] ?? "ServerError";
  }
};
var SuiHTTPStatusError = class extends SuiHTTPTransportError {
  constructor(message, status, statusText) {
    super(message);
    this.status = status;
    this.statusText = statusText;
  }
};

// ../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/dist/jsonRpc/http-transport.mjs
var JsonRpcHTTPTransport = class {
  #requestId = 0;
  #options;
  constructor(options) {
    this.#options = options;
  }
  fetch(input, init) {
    const fetchFn = this.#options.fetch ?? fetch;
    if (!fetchFn) throw new Error("The current environment does not support fetch, you can provide a fetch implementation in the options for SuiHTTPTransport.");
    return fetchFn(input, init);
  }
  async request(input) {
    this.#requestId += 1;
    const res = await this.fetch(this.#options.rpc?.url ?? this.#options.url, {
      method: "POST",
      signal: input.signal,
      headers: {
        "Content-Type": "application/json",
        "Client-Sdk-Type": "typescript",
        "Client-Sdk-Version": PACKAGE_VERSION,
        "Client-Request-Method": input.method,
        ...this.#options.rpc?.headers
      },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: this.#requestId,
        method: input.method,
        params: input.params
      })
    });
    if (!res.ok) throw new SuiHTTPStatusError(`Unexpected status code: ${res.status}`, res.status, res.statusText);
    const data = await res.json();
    if ("error" in data && data.error != null) throw new JsonRpcError(data.error.message, data.error.code);
    return data.result;
  }
};

// ../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/dist/jsonRpc/client.mjs
init_suins();
init_move_registry();
init_sui_types();

// ../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/dist/jsonRpc/core.mjs
init_sui_types();
init_type_tag_serializer();
init_bcs();
init_dynamic_fields();
init_constants();
init_dist();
var MAX_GAS = 5e10;
function parseJsonRpcExecutionStatus(status, abortError) {
  if (status.status === "success") return {
    success: true,
    error: null
  };
  const rawMessage = status.error ?? "Unknown";
  if (abortError) {
    const commandMatch = rawMessage.match(/in command (\d+)/);
    const command = commandMatch ? parseInt(commandMatch[1], 10) : void 0;
    const instructionMatch = rawMessage.match(/instruction:\s*(\d+)/);
    const instruction = instructionMatch ? parseInt(instructionMatch[1], 10) : void 0;
    const moduleParts = abortError.module_id?.split("::") ?? [];
    const pkg = moduleParts[0] ? normalizeSuiAddress(moduleParts[0]) : void 0;
    const module = moduleParts[1];
    return {
      success: false,
      error: {
        $kind: "MoveAbort",
        message: formatMoveAbortMessage({
          command,
          location: pkg && module ? {
            package: pkg,
            module,
            functionName: abortError.function ?? void 0,
            instruction
          } : void 0,
          abortCode: String(abortError.error_code ?? 0),
          cleverError: abortError.line != null ? { lineNumber: abortError.line } : void 0
        }),
        command,
        MoveAbort: {
          abortCode: String(abortError.error_code ?? 0),
          location: abortError.module_id ? {
            package: normalizeSuiAddress(abortError.module_id.split("::")[0] ?? ""),
            module: abortError.module_id.split("::")[1] ?? "",
            functionName: abortError.function ?? void 0,
            instruction
          } : void 0
        }
      }
    };
  }
  return {
    success: false,
    error: {
      $kind: "Unknown",
      message: rawMessage,
      Unknown: null
    }
  };
}
var JSONRpcCoreClient = class extends CoreClient {
  #jsonRpcClient;
  constructor({ jsonRpcClient, mvr }) {
    super({
      network: jsonRpcClient.network,
      base: jsonRpcClient,
      mvr
    });
    this.#jsonRpcClient = jsonRpcClient;
  }
  async getObjects(options) {
    const batches = chunk(options.objectIds, 50);
    const results = [];
    for (const batch of batches) {
      const objects = await this.#jsonRpcClient.multiGetObjects({
        ids: batch,
        options: {
          showOwner: true,
          showType: true,
          showBcs: options.include?.content || options.include?.objectBcs ? true : false,
          showPreviousTransaction: options.include?.previousTransaction || options.include?.objectBcs ? true : false,
          showStorageRebate: options.include?.objectBcs ?? false,
          showContent: options.include?.json ?? false,
          showDisplay: options.include?.display ?? false
        },
        signal: options.signal
      });
      for (const [idx, object] of objects.entries()) if (object.error) results.push(ObjectError.fromResponse(object.error, batch[idx]));
      else results.push(parseObject(object.data, options.include));
    }
    return { objects: results };
  }
  async listOwnedObjects(options) {
    let filter = null;
    if (options.type) {
      const parts = options.type.split("::");
      if (parts.length === 1) filter = { Package: options.type };
      else if (parts.length === 2) filter = { MoveModule: {
        package: parts[0],
        module: parts[1]
      } };
      else filter = { StructType: options.type };
    }
    const objects = await this.#jsonRpcClient.getOwnedObjects({
      owner: options.owner,
      limit: options.limit,
      cursor: options.cursor,
      options: {
        showOwner: true,
        showType: true,
        showBcs: options.include?.content || options.include?.objectBcs ? true : false,
        showPreviousTransaction: options.include?.previousTransaction || options.include?.objectBcs ? true : false,
        showStorageRebate: options.include?.objectBcs ?? false,
        showContent: options.include?.json ?? false,
        showDisplay: options.include?.display ?? false
      },
      filter,
      signal: options.signal
    });
    return {
      objects: objects.data.map((result) => {
        if (result.error) throw ObjectError.fromResponse(result.error);
        return parseObject(result.data, options.include);
      }),
      hasNextPage: objects.hasNextPage,
      cursor: objects.nextCursor ?? null
    };
  }
  async listCoins(options) {
    const coins = await this.#jsonRpcClient.getCoins({
      owner: options.owner,
      coinType: options.coinType,
      limit: options.limit,
      cursor: options.cursor,
      signal: options.signal
    });
    return {
      objects: coins.data.map((coin) => ({
        objectId: coin.coinObjectId,
        version: coin.version,
        digest: coin.digest,
        balance: coin.balance,
        type: normalizeStructTag(`0x2::coin::Coin<${coin.coinType}>`),
        owner: {
          $kind: "AddressOwner",
          AddressOwner: options.owner
        }
      })),
      hasNextPage: coins.hasNextPage,
      cursor: coins.nextCursor ?? null
    };
  }
  async getBalance(options) {
    const balance = await this.#jsonRpcClient.getBalance({
      owner: options.owner,
      coinType: options.coinType,
      signal: options.signal
    });
    const addressBalance = balance.fundsInAddressBalance ?? "0";
    const coinBalance = String(BigInt(balance.totalBalance) - BigInt(addressBalance));
    return { balance: {
      coinType: normalizeStructTag(balance.coinType),
      balance: balance.totalBalance,
      coinBalance,
      addressBalance
    } };
  }
  async getCoinMetadata(options) {
    const coinType = (await this.mvr.resolveType({ type: options.coinType })).type;
    const result = await this.#jsonRpcClient.getCoinMetadata({
      coinType,
      signal: options.signal
    });
    if (!result) return { coinMetadata: null };
    return { coinMetadata: {
      id: result.id ?? null,
      decimals: result.decimals,
      name: result.name,
      symbol: result.symbol,
      description: result.description,
      iconUrl: result.iconUrl ?? null
    } };
  }
  async listBalances(options) {
    return {
      balances: (await this.#jsonRpcClient.getAllBalances({
        owner: options.owner,
        signal: options.signal
      })).map((balance) => {
        const addressBalance = balance.fundsInAddressBalance ?? "0";
        const coinBalance = String(BigInt(balance.totalBalance) - BigInt(addressBalance));
        return {
          coinType: normalizeStructTag(balance.coinType),
          balance: balance.totalBalance,
          coinBalance,
          addressBalance
        };
      }),
      hasNextPage: false,
      cursor: null
    };
  }
  async getTransaction(options) {
    return parseTransaction(await this.#jsonRpcClient.getTransactionBlock({
      digest: options.digest,
      options: {
        showRawInput: true,
        showEffects: true,
        showObjectChanges: options.include?.objectTypes ?? false,
        showRawEffects: options.include?.effects ?? false,
        showEvents: options.include?.events ?? false,
        showBalanceChanges: options.include?.balanceChanges ?? false
      },
      signal: options.signal
    }), options.include);
  }
  async executeTransaction(options) {
    return parseTransaction(await this.#jsonRpcClient.executeTransactionBlock({
      transactionBlock: options.transaction,
      signature: options.signatures,
      options: {
        showRawInput: true,
        showEffects: true,
        showRawEffects: options.include?.effects ?? false,
        showEvents: options.include?.events ?? false,
        showObjectChanges: options.include?.objectTypes ?? false,
        showBalanceChanges: options.include?.balanceChanges ?? false
      },
      signal: options.signal
    }), options.include);
  }
  async simulateTransaction(options) {
    if (!(options.transaction instanceof Uint8Array)) await options.transaction.build({
      client: this,
      onlyTransactionKind: true
    });
    const tx = Transaction.from(options.transaction);
    const data = options.transaction instanceof Uint8Array ? null : TransactionDataBuilder.restore(options.transaction.getData());
    const transactionBytes = data ? data.build({ overrides: { gasData: {
      budget: data.gasData.budget ?? String(MAX_GAS),
      price: data.gasData.price ?? String(await this.#jsonRpcClient.getReferenceGasPrice()),
      payment: data.gasData.payment ?? []
    } } }) : options.transaction;
    const sender = tx.getData().sender ?? normalizeSuiAddress("0x0");
    const checksDisabled = options.checksEnabled === false;
    let dryRunResult = null;
    try {
      dryRunResult = await this.#jsonRpcClient.dryRunTransactionBlock({
        transactionBlock: transactionBytes,
        signal: options.signal
      });
    } catch (e) {
      if (!checksDisabled) throw e;
    }
    let devInspectResult = null;
    if (options.include?.commandResults || checksDisabled) try {
      devInspectResult = await this.#jsonRpcClient.devInspectTransactionBlock({
        sender,
        transactionBlock: tx,
        signal: options.signal
      });
    } catch {
    }
    const dryRunFailed = !dryRunResult || dryRunResult.effects.status.status !== "success";
    const effectsSource = checksDisabled && dryRunFailed && devInspectResult ? devInspectResult : dryRunResult ?? devInspectResult;
    if (!effectsSource) throw new Error("simulateTransaction failed: no results from dryRun or devInspect");
    const { effects, objectTypes } = parseTransactionEffectsJson({
      effects: effectsSource.effects,
      objectChanges: (!dryRunFailed ? dryRunResult?.objectChanges : null) ?? []
    });
    let parsedTransaction;
    if (options.include?.transaction) {
      parsedTransaction = parseTransactionBcs(transactionBytes);
      if (data && !dryRunFailed && effects.gasUsed) {
        if (!data.gasData.budget) parsedTransaction.gasData.budget = computeGasBudget(effects.gasUsed);
      }
    }
    const transactionData = {
      digest: TransactionDataBuilder.getDigestFromBytes(transactionBytes),
      epoch: null,
      status: effects.status,
      effects: options.include?.effects ? effects : void 0,
      objectTypes: options.include?.objectTypes ? objectTypes : void 0,
      signatures: [],
      transaction: parsedTransaction ?? void 0,
      bcs: options.include?.bcs ? transactionBytes : void 0,
      balanceChanges: options.include?.balanceChanges && dryRunResult && !dryRunFailed ? dryRunResult.balanceChanges.map((change) => ({
        coinType: normalizeStructTag(change.coinType),
        address: parseOwnerAddress(change.owner),
        amount: change.amount
      })) : void 0,
      events: options.include?.events ? effectsSource.events?.map((event) => ({
        packageId: event.packageId,
        module: event.transactionModule,
        sender: event.sender,
        eventType: event.type,
        bcs: "bcs" in event ? fromBase64(event.bcs) : new Uint8Array(),
        json: event.parsedJson ?? null
      })) ?? [] : void 0
    };
    let commandResults;
    if (options.include?.commandResults && devInspectResult?.results) commandResults = devInspectResult.results.map((result) => ({
      returnValues: (result.returnValues ?? []).map(([bytes]) => ({ bcs: new Uint8Array(bytes) })),
      mutatedReferences: (result.mutableReferenceOutputs ?? []).map(([, bytes]) => ({ bcs: new Uint8Array(bytes) }))
    }));
    return effects.status.success ? {
      $kind: "Transaction",
      Transaction: transactionData,
      commandResults
    } : {
      $kind: "FailedTransaction",
      FailedTransaction: transactionData,
      commandResults
    };
  }
  async getReferenceGasPrice(options) {
    const referenceGasPrice = await this.#jsonRpcClient.getReferenceGasPrice({ signal: options?.signal });
    return { referenceGasPrice: String(referenceGasPrice) };
  }
  async getProtocolConfig(options) {
    const result = await this.#jsonRpcClient.getProtocolConfig({ signal: options?.signal });
    const attributes = {};
    for (const [key, value] of Object.entries(result.attributes)) if (value === null) attributes[key] = null;
    else if ("u16" in value) attributes[key] = value.u16;
    else if ("u32" in value) attributes[key] = value.u32;
    else if ("u64" in value) attributes[key] = value.u64;
    else if ("f64" in value) attributes[key] = value.f64;
    else if ("bool" in value) attributes[key] = value.bool;
    else {
      const entries = Object.entries(value);
      attributes[key] = entries.length === 1 ? String(entries[0][1]) : JSON.stringify(value);
    }
    return { protocolConfig: {
      protocolVersion: result.protocolVersion,
      featureFlags: { ...result.featureFlags },
      attributes
    } };
  }
  async getCurrentSystemState(options) {
    const systemState = await this.#jsonRpcClient.getLatestSuiSystemState({ signal: options?.signal });
    return { systemState: {
      systemStateVersion: systemState.systemStateVersion,
      epoch: systemState.epoch,
      protocolVersion: systemState.protocolVersion,
      referenceGasPrice: systemState.referenceGasPrice?.toString() ?? null,
      epochStartTimestampMs: systemState.epochStartTimestampMs,
      safeMode: systemState.safeMode,
      safeModeStorageRewards: systemState.safeModeStorageRewards,
      safeModeComputationRewards: systemState.safeModeComputationRewards,
      safeModeStorageRebates: systemState.safeModeStorageRebates,
      safeModeNonRefundableStorageFee: systemState.safeModeNonRefundableStorageFee,
      parameters: {
        epochDurationMs: systemState.epochDurationMs,
        stakeSubsidyStartEpoch: systemState.stakeSubsidyStartEpoch,
        maxValidatorCount: systemState.maxValidatorCount,
        minValidatorJoiningStake: systemState.minValidatorJoiningStake,
        validatorLowStakeThreshold: systemState.validatorLowStakeThreshold,
        validatorLowStakeGracePeriod: systemState.validatorLowStakeGracePeriod
      },
      storageFund: {
        totalObjectStorageRebates: systemState.storageFundTotalObjectStorageRebates,
        nonRefundableBalance: systemState.storageFundNonRefundableBalance
      },
      stakeSubsidy: {
        balance: systemState.stakeSubsidyBalance,
        distributionCounter: systemState.stakeSubsidyDistributionCounter,
        currentDistributionAmount: systemState.stakeSubsidyCurrentDistributionAmount,
        stakeSubsidyPeriodLength: systemState.stakeSubsidyPeriodLength,
        stakeSubsidyDecreaseRate: systemState.stakeSubsidyDecreaseRate
      }
    } };
  }
  async listDynamicFields(options) {
    const dynamicFields = await this.#jsonRpcClient.getDynamicFields({
      parentId: options.parentId,
      limit: options.limit,
      cursor: options.cursor
    });
    return {
      dynamicFields: dynamicFields.data.map((dynamicField) => {
        const isDynamicObject = dynamicField.type === "DynamicObject";
        const fullType = isDynamicObject ? `0x2::dynamic_field::Field<0x2::dynamic_object_field::Wrapper<${dynamicField.name.type}>, 0x2::object::ID>` : `0x2::dynamic_field::Field<${dynamicField.name.type}, ${dynamicField.objectType}>`;
        const bcsBytes = fromBase64(dynamicField.bcsName);
        const derivedNameType = isDynamicObject ? `0x2::dynamic_object_field::Wrapper<${dynamicField.name.type}>` : dynamicField.name.type;
        return {
          $kind: isDynamicObject ? "DynamicObject" : "DynamicField",
          fieldId: deriveDynamicFieldID(options.parentId, derivedNameType, bcsBytes),
          type: normalizeStructTag(fullType),
          name: {
            type: dynamicField.name.type,
            bcs: bcsBytes
          },
          valueType: dynamicField.objectType,
          childId: isDynamicObject ? dynamicField.objectId : void 0
        };
      }),
      hasNextPage: dynamicFields.hasNextPage,
      cursor: dynamicFields.nextCursor
    };
  }
  async verifyZkLoginSignature(options) {
    const result = await this.#jsonRpcClient.verifyZkLoginSignature({
      bytes: options.bytes,
      signature: options.signature,
      intentScope: options.intentScope,
      author: options.address
    });
    return {
      success: result.success,
      errors: result.errors
    };
  }
  async defaultNameServiceName(options) {
    return { data: { name: (await this.#jsonRpcClient.resolveNameServiceNames(options)).data[0] ?? null } };
  }
  resolveTransactionPlugin() {
    return coreClientResolveTransactionPlugin;
  }
  async getMoveFunction(options) {
    const resolvedPackageId = (await this.mvr.resolvePackage({ package: options.packageId })).package;
    const result = await this.#jsonRpcClient.getNormalizedMoveFunction({
      package: resolvedPackageId,
      module: options.moduleName,
      function: options.name
    });
    return { function: {
      packageId: normalizeSuiAddress(resolvedPackageId),
      moduleName: options.moduleName,
      name: options.name,
      visibility: parseVisibility(result.visibility),
      isEntry: result.isEntry,
      typeParameters: result.typeParameters.map((abilities) => ({
        isPhantom: false,
        constraints: parseAbilities(abilities)
      })),
      parameters: result.parameters.map((param) => parseNormalizedSuiMoveType(param)),
      returns: result.return.map((ret) => parseNormalizedSuiMoveType(ret))
    } };
  }
  async getChainIdentifier(_options) {
    return this.cache.read(["chainIdentifier"], async () => {
      return { chainIdentifier: (await this.#jsonRpcClient.getCheckpoint({ id: "0" })).digest };
    });
  }
};
function serializeObjectToBcs(object) {
  if (object.bcs?.dataType !== "moveObject") return;
  try {
    const typeStr = normalizeStructTag(object.bcs.type);
    let moveObjectType;
    const normalizedSuiFramework = normalizeSuiAddress(SUI_FRAMEWORK_ADDRESS);
    const gasCoinType = normalizeStructTag(`${SUI_FRAMEWORK_ADDRESS}::coin::Coin<${SUI_FRAMEWORK_ADDRESS}::sui::SUI>`);
    const stakedSuiType = normalizeStructTag(`${SUI_SYSTEM_ADDRESS}::staking_pool::StakedSui`);
    const coinPrefix = `${normalizedSuiFramework}::coin::Coin<`;
    if (typeStr === gasCoinType) moveObjectType = { GasCoin: null };
    else if (typeStr === stakedSuiType) moveObjectType = { StakedSui: null };
    else if (typeStr.startsWith(coinPrefix)) {
      const innerTypeMatch = typeStr.match(/* @__PURE__ */ new RegExp(`${normalizedSuiFramework.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}::coin::Coin<(.+)>$`));
      if (innerTypeMatch) moveObjectType = { Coin: TypeTagSerializer.parseFromStr(innerTypeMatch[1], true) };
      else throw new Error("Failed to parse Coin type");
    } else {
      const typeTag = TypeTagSerializer.parseFromStr(typeStr, true);
      if (typeof typeTag !== "object" || !("struct" in typeTag)) throw new Error("Expected struct type tag");
      moveObjectType = { Other: typeTag.struct };
    }
    const contents = fromBase64(object.bcs.bcsBytes);
    const owner = convertOwnerToBcs(object.owner);
    return suiBcs.Object.serialize({
      data: { Move: {
        type: moveObjectType,
        hasPublicTransfer: object.bcs.hasPublicTransfer,
        version: object.bcs.version,
        contents
      } },
      owner,
      previousTransaction: object.previousTransaction,
      storageRebate: object.storageRebate
    }).toBytes();
  } catch {
    return;
  }
}
function parseObject(object, include) {
  const bcsContent = object.bcs?.dataType === "moveObject" ? fromBase64(object.bcs.bcsBytes) : void 0;
  const objectBcs = include?.objectBcs ? serializeObjectToBcs(object) : void 0;
  const type = object.type && object.type.includes("::") ? normalizeStructTag(object.type) : object.type ?? "";
  const jsonContent = include?.json && object.content?.dataType === "moveObject" ? object.content.fields : include?.json ? null : void 0;
  const displayData = include?.display ? object.display?.data != null ? {
    output: object.display.data,
    errors: null
  } : null : void 0;
  return {
    objectId: object.objectId,
    version: object.version,
    digest: object.digest,
    type,
    content: include?.content ? bcsContent : void 0,
    owner: parseOwner(object.owner),
    previousTransaction: include?.previousTransaction ? object.previousTransaction ?? void 0 : void 0,
    objectBcs,
    json: jsonContent,
    display: displayData
  };
}
function parseOwner(owner) {
  if (owner === "Immutable") return {
    $kind: "Immutable",
    Immutable: true
  };
  if ("ConsensusAddressOwner" in owner) return {
    $kind: "ConsensusAddressOwner",
    ConsensusAddressOwner: {
      owner: owner.ConsensusAddressOwner.owner,
      startVersion: owner.ConsensusAddressOwner.start_version
    }
  };
  if ("AddressOwner" in owner) return {
    $kind: "AddressOwner",
    AddressOwner: owner.AddressOwner
  };
  if ("ObjectOwner" in owner) return {
    $kind: "ObjectOwner",
    ObjectOwner: owner.ObjectOwner
  };
  if ("Shared" in owner) return {
    $kind: "Shared",
    Shared: { initialSharedVersion: owner.Shared.initial_shared_version }
  };
  throw new Error(`Unknown owner type: ${JSON.stringify(owner)}`);
}
function convertOwnerToBcs(owner) {
  if (owner === "Immutable") return { Immutable: null };
  if ("AddressOwner" in owner) return { AddressOwner: owner.AddressOwner };
  if ("ObjectOwner" in owner) return { ObjectOwner: owner.ObjectOwner };
  if ("Shared" in owner) return { Shared: { initialSharedVersion: owner.Shared.initial_shared_version } };
  if (typeof owner === "object" && owner !== null && "ConsensusAddressOwner" in owner) return { ConsensusAddressOwner: {
    startVersion: owner.ConsensusAddressOwner.start_version,
    owner: owner.ConsensusAddressOwner.owner
  } };
  throw new Error(`Unknown owner type: ${JSON.stringify(owner)}`);
}
function parseOwnerAddress(owner) {
  if (owner === "Immutable") return null;
  if ("ConsensusAddressOwner" in owner) return owner.ConsensusAddressOwner.owner;
  if ("AddressOwner" in owner) return owner.AddressOwner;
  if ("ObjectOwner" in owner) return owner.ObjectOwner;
  if ("Shared" in owner) return null;
  throw new Error(`Unknown owner type: ${JSON.stringify(owner)}`);
}
function parseTransaction(transaction, include) {
  const objectTypes = {};
  if (include?.objectTypes) transaction.objectChanges?.forEach((change) => {
    if (change.type !== "published") objectTypes[change.objectId] = normalizeStructTag(change.objectType);
  });
  let transactionData;
  let signatures = [];
  let bcsBytes;
  if (transaction.rawTransaction) {
    const parsedTx = suiBcs.SenderSignedData.parse(fromBase64(transaction.rawTransaction))[0];
    signatures = parsedTx.txSignatures;
    if (include?.transaction || include?.bcs) {
      const bytes = suiBcs.TransactionData.serialize(parsedTx.intentMessage.value).toBytes();
      if (include?.bcs) bcsBytes = bytes;
      if (include?.transaction) transactionData = { ...TransactionDataBuilder.restore({
        version: 2,
        sender: parsedTx.intentMessage.value.V1.sender,
        expiration: parsedTx.intentMessage.value.V1.expiration,
        gasData: parsedTx.intentMessage.value.V1.gasData,
        inputs: parsedTx.intentMessage.value.V1.kind.ProgrammableTransaction.inputs,
        commands: parsedTx.intentMessage.value.V1.kind.ProgrammableTransaction.commands
      }) };
    }
  }
  const status = transaction.effects?.status ? parseJsonRpcExecutionStatus(transaction.effects.status, transaction.effects.abortError) : {
    success: false,
    error: {
      $kind: "Unknown",
      message: "Unknown",
      Unknown: null
    }
  };
  const effectsBytes = transaction.rawEffects ? new Uint8Array(transaction.rawEffects) : null;
  const result = {
    digest: transaction.digest,
    epoch: transaction.effects?.executedEpoch ?? null,
    status,
    effects: include?.effects && effectsBytes ? parseTransactionEffectsBcs(effectsBytes) : void 0,
    objectTypes: include?.objectTypes ? objectTypes : void 0,
    transaction: transactionData,
    bcs: bcsBytes,
    signatures,
    balanceChanges: include?.balanceChanges ? transaction.balanceChanges?.map((change) => ({
      coinType: normalizeStructTag(change.coinType),
      address: parseOwnerAddress(change.owner),
      amount: change.amount
    })) ?? [] : void 0,
    events: include?.events ? transaction.events?.map((event) => ({
      packageId: event.packageId,
      module: event.transactionModule,
      sender: event.sender,
      eventType: event.type,
      bcs: "bcs" in event ? fromBase64(event.bcs) : new Uint8Array(),
      json: event.parsedJson ?? null
    })) ?? [] : void 0
  };
  return status.success ? {
    $kind: "Transaction",
    Transaction: result
  } : {
    $kind: "FailedTransaction",
    FailedTransaction: result
  };
}
function parseTransactionEffectsJson({ bytes, effects, objectChanges }) {
  const changedObjects = [];
  const unchangedConsensusObjects = [];
  const objectTypes = {};
  objectChanges?.forEach((change) => {
    switch (change.type) {
      case "published":
        changedObjects.push({
          objectId: change.packageId,
          inputState: "DoesNotExist",
          inputVersion: null,
          inputDigest: null,
          inputOwner: null,
          outputState: "PackageWrite",
          outputVersion: change.version,
          outputDigest: change.digest,
          outputOwner: null,
          idOperation: "Created"
        });
        break;
      case "transferred":
        changedObjects.push({
          objectId: change.objectId,
          inputState: "Exists",
          inputVersion: change.version,
          inputDigest: change.digest,
          inputOwner: {
            $kind: "AddressOwner",
            AddressOwner: change.sender
          },
          outputState: "ObjectWrite",
          outputVersion: change.version,
          outputDigest: change.digest,
          outputOwner: parseOwner(change.recipient),
          idOperation: "None"
        });
        objectTypes[change.objectId] = normalizeStructTag(change.objectType);
        break;
      case "mutated":
        changedObjects.push({
          objectId: change.objectId,
          inputState: "Exists",
          inputVersion: change.previousVersion,
          inputDigest: null,
          inputOwner: parseOwner(change.owner),
          outputState: "ObjectWrite",
          outputVersion: change.version,
          outputDigest: change.digest,
          outputOwner: parseOwner(change.owner),
          idOperation: "None"
        });
        objectTypes[change.objectId] = normalizeStructTag(change.objectType);
        break;
      case "deleted":
        changedObjects.push({
          objectId: change.objectId,
          inputState: "Exists",
          inputVersion: change.version,
          inputDigest: effects.deleted?.find((d) => d.objectId === change.objectId)?.digest ?? null,
          inputOwner: null,
          outputState: "DoesNotExist",
          outputVersion: null,
          outputDigest: null,
          outputOwner: null,
          idOperation: "Deleted"
        });
        objectTypes[change.objectId] = normalizeStructTag(change.objectType);
        break;
      case "wrapped":
        changedObjects.push({
          objectId: change.objectId,
          inputState: "Exists",
          inputVersion: change.version,
          inputDigest: null,
          inputOwner: {
            $kind: "AddressOwner",
            AddressOwner: change.sender
          },
          outputState: "ObjectWrite",
          outputVersion: change.version,
          outputDigest: effects.wrapped?.find((w) => w.objectId === change.objectId)?.digest ?? null,
          outputOwner: {
            $kind: "ObjectOwner",
            ObjectOwner: change.sender
          },
          idOperation: "None"
        });
        objectTypes[change.objectId] = normalizeStructTag(change.objectType);
        break;
      case "created":
        changedObjects.push({
          objectId: change.objectId,
          inputState: "DoesNotExist",
          inputVersion: null,
          inputDigest: null,
          inputOwner: null,
          outputState: "ObjectWrite",
          outputVersion: change.version,
          outputDigest: change.digest,
          outputOwner: parseOwner(change.owner),
          idOperation: "Created"
        });
        objectTypes[change.objectId] = normalizeStructTag(change.objectType);
        break;
    }
  });
  return {
    objectTypes,
    effects: {
      bcs: bytes ?? null,
      version: 2,
      status: parseJsonRpcExecutionStatus(effects.status, effects.abortError),
      gasUsed: effects.gasUsed,
      transactionDigest: effects.transactionDigest,
      gasObject: {
        objectId: effects.gasObject?.reference.objectId,
        inputState: "Exists",
        inputVersion: null,
        inputDigest: null,
        inputOwner: null,
        outputState: "ObjectWrite",
        outputVersion: effects.gasObject.reference.version,
        outputDigest: effects.gasObject.reference.digest,
        outputOwner: parseOwner(effects.gasObject.owner),
        idOperation: "None"
      },
      eventsDigest: effects.eventsDigest ?? null,
      dependencies: effects.dependencies ?? [],
      lamportVersion: effects.gasObject.reference.version,
      changedObjects,
      unchangedConsensusObjects,
      auxiliaryDataDigest: null
    }
  };
}
function parseNormalizedSuiMoveType(type) {
  if (typeof type !== "string") {
    if ("Reference" in type) return {
      reference: "immutable",
      body: parseNormalizedSuiMoveTypeBody(type.Reference)
    };
    if ("MutableReference" in type) return {
      reference: "mutable",
      body: parseNormalizedSuiMoveTypeBody(type.MutableReference)
    };
  }
  return {
    reference: null,
    body: parseNormalizedSuiMoveTypeBody(type)
  };
}
function parseNormalizedSuiMoveTypeBody(type) {
  switch (type) {
    case "Address":
      return { $kind: "address" };
    case "Bool":
      return { $kind: "bool" };
    case "U8":
      return { $kind: "u8" };
    case "U16":
      return { $kind: "u16" };
    case "U32":
      return { $kind: "u32" };
    case "U64":
      return { $kind: "u64" };
    case "U128":
      return { $kind: "u128" };
    case "U256":
      return { $kind: "u256" };
  }
  if (typeof type === "string") throw new Error(`Unknown type: ${type}`);
  if ("Vector" in type) return {
    $kind: "vector",
    vector: parseNormalizedSuiMoveTypeBody(type.Vector)
  };
  if ("Struct" in type) return {
    $kind: "datatype",
    datatype: {
      typeName: `${normalizeSuiAddress(type.Struct.address)}::${type.Struct.module}::${type.Struct.name}`,
      typeParameters: type.Struct.typeArguments.map((t) => parseNormalizedSuiMoveTypeBody(t))
    }
  };
  if ("TypeParameter" in type) return {
    $kind: "typeParameter",
    index: type.TypeParameter
  };
  throw new Error(`Unknown type: ${JSON.stringify(type)}`);
}
function parseAbilities(abilitySet) {
  return abilitySet.abilities.map((ability) => {
    switch (ability) {
      case "Copy":
        return "copy";
      case "Drop":
        return "drop";
      case "Store":
        return "store";
      case "Key":
        return "key";
      default:
        return "unknown";
    }
  });
}
function parseVisibility(visibility) {
  switch (visibility) {
    case "Public":
      return "public";
    case "Private":
      return "private";
    case "Friend":
      return "friend";
    default:
      return "unknown";
  }
}

// ../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/dist/jsonRpc/client.mjs
init_dist();
var SUI_CLIENT_BRAND = /* @__PURE__ */ Symbol.for("@mysten/SuiJsonRpcClient");
function isSuiJsonRpcClient(client) {
  return typeof client === "object" && client !== null && client[SUI_CLIENT_BRAND] === true;
}
var SuiJsonRpcClient = class extends BaseClient {
  get [SUI_CLIENT_BRAND]() {
    return true;
  }
  /**
  * Establish a connection to a Sui RPC endpoint
  *
  * @param options configuration options for the API Client
  */
  constructor(options) {
    super({ network: options.network });
    this.jsonRpc = this;
    this.transport = options.transport ?? new JsonRpcHTTPTransport({ url: options.url });
    this.core = new JSONRpcCoreClient({
      jsonRpcClient: this,
      mvr: options.mvr
    });
  }
  async getRpcApiVersion({ signal } = {}) {
    return (await this.transport.request({
      method: "rpc.discover",
      params: [],
      signal
    })).info.version;
  }
  /**
  * Get all Coin<`coin_type`> objects owned by an address.
  */
  async getCoins({ coinType, owner, cursor, limit, signal }) {
    if (!owner || !isValidSuiAddress(normalizeSuiAddress(owner))) throw new Error("Invalid Sui address");
    if (coinType && hasMvrName(coinType)) coinType = (await this.core.mvr.resolveType({ type: coinType })).type;
    const result = await this.transport.request({
      method: "suix_getCoins",
      params: [
        owner,
        coinType,
        cursor,
        limit
      ],
      signal
    });
    return {
      ...result,
      data: result.data.filter((coin) => !isCoinReservationDigest(coin.digest))
    };
  }
  /**
  * Get all Coin objects owned by an address.
  */
  async getAllCoins(input) {
    if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) throw new Error("Invalid Sui address");
    const result = await this.transport.request({
      method: "suix_getAllCoins",
      params: [
        input.owner,
        input.cursor,
        input.limit
      ],
      signal: input.signal
    });
    return {
      ...result,
      data: result.data.filter((coin) => !isCoinReservationDigest(coin.digest))
    };
  }
  /**
  * Get the total coin balance for one coin type, owned by the address owner.
  */
  async getBalance({ owner, coinType, signal }) {
    if (!owner || !isValidSuiAddress(normalizeSuiAddress(owner))) throw new Error("Invalid Sui address");
    if (coinType && hasMvrName(coinType)) coinType = (await this.core.mvr.resolveType({ type: coinType })).type;
    return await this.transport.request({
      method: "suix_getBalance",
      params: [owner, coinType],
      signal
    });
  }
  /**
  * Get the total coin balance for all coin types, owned by the address owner.
  */
  async getAllBalances(input) {
    if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) throw new Error("Invalid Sui address");
    return await this.transport.request({
      method: "suix_getAllBalances",
      params: [input.owner],
      signal: input.signal
    });
  }
  /**
  * Fetch CoinMetadata for a given coin type
  */
  async getCoinMetadata({ coinType, signal }) {
    if (coinType && hasMvrName(coinType)) coinType = (await this.core.mvr.resolveType({ type: coinType })).type;
    return await this.transport.request({
      method: "suix_getCoinMetadata",
      params: [coinType],
      signal
    });
  }
  /**
  *  Fetch total supply for a coin
  */
  async getTotalSupply({ coinType, signal }) {
    if (coinType && hasMvrName(coinType)) coinType = (await this.core.mvr.resolveType({ type: coinType })).type;
    return await this.transport.request({
      method: "suix_getTotalSupply",
      params: [coinType],
      signal
    });
  }
  /**
  * Invoke any RPC method
  * @param method the method to be invoked
  * @param args the arguments to be passed to the RPC request
  */
  async call(method, params, { signal } = {}) {
    return await this.transport.request({
      method,
      params,
      signal
    });
  }
  /**
  * Get Move function argument types like read, write and full access
  */
  async getMoveFunctionArgTypes({ package: pkg, module, function: fn, signal }) {
    if (pkg && isValidNamedPackage(pkg)) pkg = (await this.core.mvr.resolvePackage({ package: pkg })).package;
    return await this.transport.request({
      method: "sui_getMoveFunctionArgTypes",
      params: [
        pkg,
        module,
        fn
      ],
      signal
    });
  }
  /**
  * Get a map from module name to
  * structured representations of Move modules
  */
  async getNormalizedMoveModulesByPackage({ package: pkg, signal }) {
    if (pkg && isValidNamedPackage(pkg)) pkg = (await this.core.mvr.resolvePackage({ package: pkg })).package;
    return await this.transport.request({
      method: "sui_getNormalizedMoveModulesByPackage",
      params: [pkg],
      signal
    });
  }
  /**
  * Get a structured representation of Move module
  */
  async getNormalizedMoveModule({ package: pkg, module, signal }) {
    if (pkg && isValidNamedPackage(pkg)) pkg = (await this.core.mvr.resolvePackage({ package: pkg })).package;
    return await this.transport.request({
      method: "sui_getNormalizedMoveModule",
      params: [pkg, module],
      signal
    });
  }
  /**
  * Get a structured representation of Move function
  */
  async getNormalizedMoveFunction({ package: pkg, module, function: fn, signal }) {
    if (pkg && isValidNamedPackage(pkg)) pkg = (await this.core.mvr.resolvePackage({ package: pkg })).package;
    return await this.transport.request({
      method: "sui_getNormalizedMoveFunction",
      params: [
        pkg,
        module,
        fn
      ],
      signal
    });
  }
  /**
  * Get a structured representation of Move struct
  */
  async getNormalizedMoveStruct({ package: pkg, module, struct, signal }) {
    if (pkg && isValidNamedPackage(pkg)) pkg = (await this.core.mvr.resolvePackage({ package: pkg })).package;
    return await this.transport.request({
      method: "sui_getNormalizedMoveStruct",
      params: [
        pkg,
        module,
        struct
      ],
      signal
    });
  }
  /**
  * Get all objects owned by an address
  */
  async getOwnedObjects(input) {
    if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) throw new Error("Invalid Sui address");
    const filter = input.filter ? { ...input.filter } : void 0;
    if (filter && "MoveModule" in filter && isValidNamedPackage(filter.MoveModule.package)) filter.MoveModule = {
      module: filter.MoveModule.module,
      package: (await this.core.mvr.resolvePackage({ package: filter.MoveModule.package })).package
    };
    else if (filter && "StructType" in filter && hasMvrName(filter.StructType)) filter.StructType = (await this.core.mvr.resolveType({ type: filter.StructType })).type;
    return await this.transport.request({
      method: "suix_getOwnedObjects",
      params: [
        input.owner,
        {
          filter,
          options: input.options
        },
        input.cursor,
        input.limit
      ],
      signal: input.signal
    });
  }
  /**
  * Get details about an object
  */
  async getObject(input) {
    if (!input.id || !isValidSuiObjectId(normalizeSuiObjectId(input.id))) throw new Error("Invalid Sui Object id");
    return await this.transport.request({
      method: "sui_getObject",
      params: [input.id, input.options],
      signal: input.signal
    });
  }
  async tryGetPastObject(input) {
    return await this.transport.request({
      method: "sui_tryGetPastObject",
      params: [
        input.id,
        input.version,
        input.options
      ],
      signal: input.signal
    });
  }
  /**
  * Batch get details about a list of objects. If any of the object ids are duplicates the call will fail
  */
  async multiGetObjects(input) {
    input.ids.forEach((id) => {
      if (!id || !isValidSuiObjectId(normalizeSuiObjectId(id))) throw new Error(`Invalid Sui Object id ${id}`);
    });
    if (input.ids.length !== new Set(input.ids).size) throw new Error(`Duplicate object ids in batch call ${input.ids}`);
    return await this.transport.request({
      method: "sui_multiGetObjects",
      params: [input.ids, input.options],
      signal: input.signal
    });
  }
  /**
  * Get transaction blocks for a given query criteria
  */
  async queryTransactionBlocks({ filter, options, cursor, limit, order, signal }) {
    if (filter && "MoveFunction" in filter && isValidNamedPackage(filter.MoveFunction.package)) filter = {
      ...filter,
      MoveFunction: { package: (await this.core.mvr.resolvePackage({ package: filter.MoveFunction.package })).package }
    };
    return await this.transport.request({
      method: "suix_queryTransactionBlocks",
      params: [
        {
          filter,
          options
        },
        cursor,
        limit,
        (order || "descending") === "descending"
      ],
      signal
    });
  }
  async getTransactionBlock(input) {
    if (!isValidTransactionDigest(input.digest)) throw new Error("Invalid Transaction digest");
    return await this.transport.request({
      method: "sui_getTransactionBlock",
      params: [input.digest, input.options],
      signal: input.signal
    });
  }
  async multiGetTransactionBlocks(input) {
    input.digests.forEach((d) => {
      if (!isValidTransactionDigest(d)) throw new Error(`Invalid Transaction digest ${d}`);
    });
    if (input.digests.length !== new Set(input.digests).size) throw new Error(`Duplicate digests in batch call ${input.digests}`);
    return await this.transport.request({
      method: "sui_multiGetTransactionBlocks",
      params: [input.digests, input.options],
      signal: input.signal
    });
  }
  async executeTransactionBlock({ transactionBlock, signature, options, signal }) {
    return await this.transport.request({
      method: "sui_executeTransactionBlock",
      params: [
        typeof transactionBlock === "string" ? transactionBlock : toBase64(transactionBlock),
        Array.isArray(signature) ? signature : [signature],
        options
      ],
      signal
    });
  }
  async signAndExecuteTransaction({ transaction, signer, ...input }) {
    let transactionBytes;
    if (transaction instanceof Uint8Array) transactionBytes = transaction;
    else {
      transaction.setSenderIfNotSet(signer.toSuiAddress());
      transactionBytes = await transaction.build({ client: this });
    }
    const { signature, bytes } = await signer.signTransaction(transactionBytes);
    return this.executeTransactionBlock({
      transactionBlock: bytes,
      signature,
      ...input
    });
  }
  /**
  * Get total number of transactions
  */
  async getTotalTransactionBlocks({ signal } = {}) {
    const resp = await this.transport.request({
      method: "sui_getTotalTransactionBlocks",
      params: [],
      signal
    });
    return BigInt(resp);
  }
  /**
  * Getting the reference gas price for the network
  */
  async getReferenceGasPrice({ signal } = {}) {
    const resp = await this.transport.request({
      method: "suix_getReferenceGasPrice",
      params: [],
      signal
    });
    return BigInt(resp);
  }
  /**
  * Return the delegated stakes for an address
  */
  async getStakes(input) {
    if (!input.owner || !isValidSuiAddress(normalizeSuiAddress(input.owner))) throw new Error("Invalid Sui address");
    return await this.transport.request({
      method: "suix_getStakes",
      params: [input.owner],
      signal: input.signal
    });
  }
  /**
  * Return the delegated stakes queried by id.
  */
  async getStakesByIds(input) {
    input.stakedSuiIds.forEach((id) => {
      if (!id || !isValidSuiObjectId(normalizeSuiObjectId(id))) throw new Error(`Invalid Sui Stake id ${id}`);
    });
    return await this.transport.request({
      method: "suix_getStakesByIds",
      params: [input.stakedSuiIds],
      signal: input.signal
    });
  }
  /**
  * Return the latest system state content.
  */
  async getLatestSuiSystemState({ signal } = {}) {
    return await this.transport.request({
      method: "suix_getLatestSuiSystemState",
      params: [],
      signal
    });
  }
  /**
  * Get events for a given query criteria
  */
  async queryEvents({ query, cursor, limit, order, signal }) {
    if (query && "MoveEventType" in query && hasMvrName(query.MoveEventType)) query = {
      ...query,
      MoveEventType: (await this.core.mvr.resolveType({ type: query.MoveEventType })).type
    };
    if (query && "MoveEventModule" in query && isValidNamedPackage(query.MoveEventModule.package)) query = {
      ...query,
      MoveEventModule: {
        module: query.MoveEventModule.module,
        package: (await this.core.mvr.resolvePackage({ package: query.MoveEventModule.package })).package
      }
    };
    if ("MoveModule" in query && isValidNamedPackage(query.MoveModule.package)) query = {
      ...query,
      MoveModule: {
        module: query.MoveModule.module,
        package: (await this.core.mvr.resolvePackage({ package: query.MoveModule.package })).package
      }
    };
    return await this.transport.request({
      method: "suix_queryEvents",
      params: [
        query,
        cursor,
        limit,
        (order || "descending") === "descending"
      ],
      signal
    });
  }
  /**
  * Runs the transaction block in dev-inspect mode. Which allows for nearly any
  * transaction (or Move call) with any arguments. Detailed results are
  * provided, including both the transaction effects and any return values.
  */
  async devInspectTransactionBlock(input) {
    let devInspectTxBytes;
    if (isTransaction(input.transactionBlock)) {
      input.transactionBlock.setSenderIfNotSet(input.sender);
      devInspectTxBytes = toBase64(await input.transactionBlock.build({
        client: this,
        onlyTransactionKind: true
      }));
    } else if (typeof input.transactionBlock === "string") devInspectTxBytes = input.transactionBlock;
    else if (input.transactionBlock instanceof Uint8Array) devInspectTxBytes = toBase64(input.transactionBlock);
    else throw new Error("Unknown transaction block format.");
    input.signal?.throwIfAborted();
    return await this.transport.request({
      method: "sui_devInspectTransactionBlock",
      params: [
        input.sender,
        devInspectTxBytes,
        input.gasPrice?.toString(),
        input.epoch
      ],
      signal: input.signal
    });
  }
  /**
  * Dry run a transaction block and return the result.
  */
  async dryRunTransactionBlock(input) {
    return await this.transport.request({
      method: "sui_dryRunTransactionBlock",
      params: [typeof input.transactionBlock === "string" ? input.transactionBlock : toBase64(input.transactionBlock)]
    });
  }
  /**
  * Return the list of dynamic field objects owned by an object
  */
  async getDynamicFields(input) {
    if (!input.parentId || !isValidSuiObjectId(normalizeSuiObjectId(input.parentId))) throw new Error("Invalid Sui Object id");
    return await this.transport.request({
      method: "suix_getDynamicFields",
      params: [
        input.parentId,
        input.cursor,
        input.limit
      ],
      signal: input.signal
    });
  }
  /**
  * Return the dynamic field object information for a specified object
  */
  async getDynamicFieldObject(input) {
    return await this.transport.request({
      method: "suix_getDynamicFieldObject",
      params: [input.parentId, input.name],
      signal: input.signal
    });
  }
  /**
  * Get the sequence number of the latest checkpoint that has been executed
  */
  async getLatestCheckpointSequenceNumber({ signal } = {}) {
    const resp = await this.transport.request({
      method: "sui_getLatestCheckpointSequenceNumber",
      params: [],
      signal
    });
    return String(resp);
  }
  /**
  * Returns information about a given checkpoint
  */
  async getCheckpoint(input) {
    return await this.transport.request({
      method: "sui_getCheckpoint",
      params: [input.id],
      signal: input.signal
    });
  }
  /**
  * Returns historical checkpoints paginated
  */
  async getCheckpoints(input) {
    return await this.transport.request({
      method: "sui_getCheckpoints",
      params: [
        input.cursor,
        input?.limit,
        input.descendingOrder
      ],
      signal: input.signal
    });
  }
  /**
  * Return the committee information for the asked epoch
  */
  async getCommitteeInfo(input) {
    return await this.transport.request({
      method: "suix_getCommitteeInfo",
      params: [input?.epoch],
      signal: input?.signal
    });
  }
  async getNetworkMetrics({ signal } = {}) {
    return await this.transport.request({
      method: "suix_getNetworkMetrics",
      params: [],
      signal
    });
  }
  async getAddressMetrics({ signal } = {}) {
    return await this.transport.request({
      method: "suix_getLatestAddressMetrics",
      params: [],
      signal
    });
  }
  async getEpochMetrics(input) {
    return await this.transport.request({
      method: "suix_getEpochMetrics",
      params: [
        input?.cursor,
        input?.limit,
        input?.descendingOrder
      ],
      signal: input?.signal
    });
  }
  async getAllEpochAddressMetrics(input) {
    return await this.transport.request({
      method: "suix_getAllEpochAddressMetrics",
      params: [input?.descendingOrder],
      signal: input?.signal
    });
  }
  /**
  * Return the committee information for the asked epoch
  */
  async getEpochs(input) {
    return await this.transport.request({
      method: "suix_getEpochs",
      params: [
        input?.cursor,
        input?.limit,
        input?.descendingOrder
      ],
      signal: input?.signal
    });
  }
  /**
  * Returns list of top move calls by usage
  */
  async getMoveCallMetrics({ signal } = {}) {
    return await this.transport.request({
      method: "suix_getMoveCallMetrics",
      params: [],
      signal
    });
  }
  /**
  * Return the committee information for the asked epoch
  */
  async getCurrentEpoch({ signal } = {}) {
    return await this.transport.request({
      method: "suix_getCurrentEpoch",
      params: [],
      signal
    });
  }
  /**
  * Return the Validators APYs
  */
  async getValidatorsApy({ signal } = {}) {
    return await this.transport.request({
      method: "suix_getValidatorsApy",
      params: [],
      signal
    });
  }
  async getChainIdentifier({ signal } = {}) {
    return toHex(fromBase58((await this.getCheckpoint({
      id: "0",
      signal
    })).digest).slice(0, 4));
  }
  async resolveNameServiceAddress(input) {
    return await this.transport.request({
      method: "suix_resolveNameServiceAddress",
      params: [input.name],
      signal: input.signal
    });
  }
  async resolveNameServiceNames({ format = "dot", ...input }) {
    const { nextCursor, hasNextPage, data } = await this.transport.request({
      method: "suix_resolveNameServiceNames",
      params: [
        input.address,
        input.cursor,
        input.limit
      ],
      signal: input.signal
    });
    return {
      hasNextPage,
      nextCursor,
      data: data.map((name) => normalizeSuiNSName(name, format))
    };
  }
  async getProtocolConfig(input) {
    return await this.transport.request({
      method: "sui_getProtocolConfig",
      params: [input?.version],
      signal: input?.signal
    });
  }
  async verifyZkLoginSignature(input) {
    return await this.transport.request({
      method: "sui_verifyZkLoginSignature",
      params: [
        input.bytes,
        input.signature,
        input.intentScope,
        input.author
      ],
      signal: input.signal
    });
  }
  /**
  * Wait for a transaction block result to be available over the API.
  * This can be used in conjunction with `executeTransactionBlock` to wait for the transaction to
  * be available via the API.
  * This currently polls the `getTransactionBlock` API to check for the transaction.
  */
  async waitForTransaction({ signal, timeout = 60 * 1e3, pollInterval = 2 * 1e3, ...input }) {
    const timeoutSignal = AbortSignal.timeout(timeout);
    const timeoutPromise = new Promise((_, reject) => {
      timeoutSignal.addEventListener("abort", () => reject(timeoutSignal.reason));
    });
    timeoutPromise.catch(() => {
    });
    while (!timeoutSignal.aborted) {
      signal?.throwIfAborted();
      try {
        return await this.getTransactionBlock(input);
      } catch {
        await Promise.race([new Promise((resolve) => setTimeout(resolve, pollInterval)), timeoutPromise]);
      }
    }
    timeoutSignal.throwIfAborted();
    throw new Error("Unexpected error while waiting for transaction block.");
  }
};

// ../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/dist/jsonRpc/network.mjs
function getJsonRpcFullnodeUrl(network) {
  switch (network) {
    case "mainnet":
      return "https://fullnode.mainnet.sui.io:443";
    case "testnet":
      return "https://fullnode.testnet.sui.io:443";
    case "devnet":
      return "https://fullnode.devnet.sui.io:443";
    case "localnet":
      return "http://127.0.0.1:9000";
    default:
      throw new Error(`Unknown network: ${network}`);
  }
}

export {
  SuiHTTPTransportError,
  JsonRpcError,
  SuiHTTPStatusError,
  JsonRpcHTTPTransport,
  isSuiJsonRpcClient,
  SuiJsonRpcClient,
  getJsonRpcFullnodeUrl
};
//# sourceMappingURL=chunk-UTCM4BKX.js.map