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 {
  ExecutionStatus,
  MvrClient,
  TransactionDataBuilder,
  TypeTagSerializer,
  init_bcs,
  init_effects,
  init_type_tag_serializer,
  suiBcs
} from "./chunk-UY3WLP52.js";
import {
  SUI_ADDRESS_LENGTH,
  blake2b,
  init_blake2,
  init_dist,
  init_dist2,
  init_sui_types,
  normalizeStructTag,
  parseStructTag,
  toBase64,
  toHex
} from "./chunk-3XUF7GM3.js";
import {
  __esm
} from "./chunk-YPWSCLE3.js";

// ../../node_modules/.pnpm/@mysten+sui@2.11.0_typescript@5.9.3/node_modules/@mysten/sui/dist/utils/dynamic-fields.mjs
function deriveDynamicFieldID(parentId, typeTag, key) {
  const address = suiBcs.Address.serialize(parentId).toBytes();
  const tag = suiBcs.TypeTag.serialize(typeTag).toBytes();
  const keyLength = suiBcs.u64().serialize(key.length).toBytes();
  const hash = blake2b.create({ dkLen: 32 });
  hash.update(new Uint8Array([240]));
  hash.update(address);
  hash.update(keyLength);
  hash.update(key);
  hash.update(tag);
  return `0x${toHex(hash.digest().slice(0, 32))}`;
}
var init_dynamic_fields = __esm({
  "../../node_modules/.pnpm/@mysten+sui@2.11.0_typescript@5.9.3/node_modules/@mysten/sui/dist/utils/dynamic-fields.mjs"() {
    "use strict";
    init_bcs();
    init_dist2();
    init_blake2();
  }
});

// ../../node_modules/.pnpm/@mysten+sui@2.11.0_typescript@5.9.3/node_modules/@mysten/sui/dist/client/cache.mjs
var ClientCache = class ClientCache2 {
  #prefix;
  #cache;
  constructor({ prefix, cache } = {}) {
    this.#prefix = prefix ?? [];
    this.#cache = cache ?? /* @__PURE__ */ new Map();
  }
  read(key, load) {
    const cacheKey = [this.#prefix, ...key].join(":");
    if (this.#cache.has(cacheKey)) return this.#cache.get(cacheKey);
    const result = load();
    this.#cache.set(cacheKey, result);
    if (typeof result === "object" && result !== null && "then" in result) return Promise.resolve(result).then((v) => {
      this.#cache.set(cacheKey, v);
      return v;
    }).catch((err) => {
      this.#cache.delete(cacheKey);
      throw err;
    });
    return result;
  }
  readSync(key, load) {
    const cacheKey = [this.#prefix, ...key].join(":");
    if (this.#cache.has(cacheKey)) return this.#cache.get(cacheKey);
    const result = load();
    this.#cache.set(cacheKey, result);
    return result;
  }
  clear(prefix) {
    const prefixKey = [...this.#prefix, ...prefix ?? []].join(":");
    if (!prefixKey) {
      this.#cache.clear();
      return;
    }
    for (const key of this.#cache.keys()) if (key.startsWith(prefixKey)) this.#cache.delete(key);
  }
  scope(prefix) {
    return new ClientCache2({
      prefix: [...this.#prefix, ...Array.isArray(prefix) ? prefix : [prefix]],
      cache: this.#cache
    });
  }
};

// ../../node_modules/.pnpm/@mysten+sui@2.11.0_typescript@5.9.3/node_modules/@mysten/sui/dist/client/client.mjs
var BaseClient = class {
  constructor({ network, base, cache = base?.cache ?? new ClientCache() }) {
    this.network = network;
    this.base = base ?? this;
    this.cache = cache;
  }
  $extend(...registrations) {
    const extensions = Object.fromEntries(registrations.map((registration) => {
      return [registration.name, registration.register(this)];
    }));
    const methodCache = /* @__PURE__ */ new Map();
    return new Proxy(this, { get(target, prop, receiver) {
      if (typeof prop === "string" && prop in extensions) return extensions[prop];
      const value = Reflect.get(target, prop, receiver);
      if (typeof value === "function") {
        if (prop === "$extend") return value.bind(receiver);
        if (!methodCache.has(prop)) methodCache.set(prop, value.bind(target));
        return methodCache.get(prop);
      }
      return value;
    } });
  }
};

// ../../node_modules/.pnpm/@mysten+sui@2.11.0_typescript@5.9.3/node_modules/@mysten/sui/dist/client/core.mjs
init_sui_types();
init_type_tag_serializer();
init_bcs();
init_dynamic_fields();
var DEFAULT_MVR_URLS = {
  mainnet: "https://mainnet.mvr.mystenlabs.com",
  testnet: "https://testnet.mvr.mystenlabs.com"
};
var CoreClient = class extends BaseClient {
  constructor(options) {
    super(options);
    this.core = this;
    this.mvr = new MvrClient({
      cache: this.cache.scope("core.mvr"),
      url: options.mvr?.url ?? DEFAULT_MVR_URLS[this.network],
      pageSize: options.mvr?.pageSize,
      overrides: options.mvr?.overrides
    });
  }
  async getObject(options) {
    const { objectId } = options;
    const { objects: [result] } = await this.getObjects({
      objectIds: [objectId],
      signal: options.signal,
      include: options.include
    });
    if (result instanceof Error) throw result;
    return { object: result };
  }
  async getDynamicField(options) {
    const normalizedNameType = TypeTagSerializer.parseFromStr((await this.core.mvr.resolveType({ type: options.name.type })).type);
    const fieldId = deriveDynamicFieldID(options.parentId, normalizedNameType, options.name.bcs);
    const { objects: [fieldObject] } = await this.getObjects({
      objectIds: [fieldId],
      signal: options.signal,
      include: {
        previousTransaction: true,
        content: true
      }
    });
    if (fieldObject instanceof Error) throw fieldObject;
    const fieldType = parseStructTag(fieldObject.type);
    const content = await fieldObject.content;
    const nameTypeParam = fieldType.typeParams[0];
    const isDynamicObject = typeof nameTypeParam !== "string" && nameTypeParam.module === "dynamic_object_field" && nameTypeParam.name === "Wrapper";
    const valueBcs = content.slice(SUI_ADDRESS_LENGTH + options.name.bcs.length);
    const valueType = typeof fieldType.typeParams[1] === "string" ? fieldType.typeParams[1] : normalizeStructTag(fieldType.typeParams[1]);
    return { dynamicField: {
      $kind: isDynamicObject ? "DynamicObject" : "DynamicField",
      fieldId: fieldObject.objectId,
      digest: fieldObject.digest,
      version: fieldObject.version,
      type: fieldObject.type,
      previousTransaction: fieldObject.previousTransaction,
      name: {
        type: typeof nameTypeParam === "string" ? nameTypeParam : normalizeStructTag(nameTypeParam),
        bcs: options.name.bcs
      },
      value: {
        type: valueType,
        bcs: valueBcs
      },
      childId: isDynamicObject ? suiBcs.Address.parse(valueBcs) : void 0
    } };
  }
  async getDynamicObjectField(options) {
    const wrappedType = `0x2::dynamic_object_field::Wrapper<${(await this.core.mvr.resolveType({ type: options.name.type })).type}>`;
    const { dynamicField } = await this.getDynamicField({
      parentId: options.parentId,
      name: {
        type: wrappedType,
        bcs: options.name.bcs
      },
      signal: options.signal
    });
    const { object } = await this.getObject({
      objectId: dynamicField.childId,
      signal: options.signal,
      include: options.include
    });
    return { object };
  }
  async waitForTransaction(options) {
    const { signal, timeout = 60 * 1e3, pollSchedule, include } = options;
    const digest = "result" in options && options.result ? (options.result.Transaction ?? options.result.FailedTransaction).digest : options.digest;
    const abortSignal = signal ? AbortSignal.any([AbortSignal.timeout(timeout), signal]) : AbortSignal.timeout(timeout);
    const abortPromise = new Promise((_, reject) => {
      abortSignal.addEventListener("abort", () => reject(abortSignal.reason));
    });
    abortPromise.catch(() => {
    });
    const schedule = pollSchedule ?? [
      0,
      300,
      600,
      1500,
      3500
    ];
    const t0 = Date.now();
    let scheduleIndex = 0;
    const lastInterval = schedule.length > 0 ? schedule[schedule.length - 1] - (schedule[schedule.length - 2] ?? 0) : 2e3;
    while (true) {
      if (scheduleIndex < schedule.length) {
        const remaining = t0 + schedule[scheduleIndex] - Date.now();
        scheduleIndex++;
        if (remaining > 0) await Promise.race([new Promise((resolve) => setTimeout(resolve, remaining)), abortPromise]);
      } else await Promise.race([new Promise((resolve) => setTimeout(resolve, lastInterval)), abortPromise]);
      abortSignal.throwIfAborted();
      try {
        return await this.getTransaction({
          digest,
          include,
          signal: abortSignal
        });
      } catch {
      }
    }
  }
  async signAndExecuteTransaction({ transaction, signer, additionalSignatures = [], ...input }) {
    let transactionBytes;
    if (transaction instanceof Uint8Array) transactionBytes = transaction;
    else {
      transaction.setSenderIfNotSet(signer.toSuiAddress());
      transactionBytes = await transaction.build({ client: this });
    }
    const { signature } = await signer.signTransaction(transactionBytes);
    return this.executeTransaction({
      transaction: transactionBytes,
      signatures: [signature, ...additionalSignatures],
      ...input
    });
  }
};

// ../../node_modules/.pnpm/@mysten+sui@2.11.0_typescript@5.9.3/node_modules/@mysten/sui/dist/client/utils.mjs
init_effects();
init_bcs();
init_dist();
var ordinalRules = new Intl.PluralRules("en-US", { type: "ordinal" });
var ordinalSuffixes = /* @__PURE__ */ new Map([
  ["one", "st"],
  ["two", "nd"],
  ["few", "rd"],
  ["other", "th"]
]);
function formatOrdinal(n) {
  return `${n}${ordinalSuffixes.get(ordinalRules.select(n))}`;
}
function formatMoveAbortMessage(options) {
  const { command, location, abortCode, cleverError } = options;
  const parts = [];
  if (command != null) parts.push(`MoveAbort in ${formatOrdinal(command + 1)} command`);
  else parts.push("MoveAbort");
  if (cleverError?.constantName) {
    const errorStr = cleverError.value ? `'${cleverError.constantName}': ${cleverError.value}` : `'${cleverError.constantName}'`;
    parts.push(errorStr);
  } else parts.push(`abort code: ${abortCode}`);
  if (location?.package && location?.module) {
    const locationStr = [`in '${[
      location.package.startsWith("0x") ? location.package : `0x${location.package}`,
      location.module,
      location.functionName
    ].filter(Boolean).join("::")}'`];
    if (cleverError?.lineNumber != null) locationStr.push(`(line ${cleverError.lineNumber})`);
    else if (location.instruction != null) locationStr.push(`(instruction ${location.instruction})`);
    parts.push(locationStr.join(" "));
  }
  return parts.join(", ");
}
var MinimalEffectsWithError = suiBcs.struct("MinimalEffectsWithError", { status: ExecutionStatus });
var MinimalTransactionEffectsWithError = suiBcs.enum("MinimalTransactionEffectsWithError", {
  V1: MinimalEffectsWithError,
  V2: MinimalEffectsWithError
});
var MinimalExecutionStatusNoError = suiBcs.enum("MinimalExecutionStatusNoError", {
  Success: null,
  Failed: null
});
var MinimalEffectsNoError = suiBcs.struct("MinimalEffectsNoError", { status: MinimalExecutionStatusNoError });
var MinimalTransactionEffectsNoError = suiBcs.enum("MinimalTransactionEffectsNoError", {
  V1: MinimalEffectsNoError,
  V2: MinimalEffectsNoError
});
function formatErrorMessage($kind, data) {
  if (data !== null && data !== void 0 && typeof data !== "boolean") return `${$kind}(${JSON.stringify(data, (_key, value) => typeof value === "bigint" ? value.toString() : value)})`;
  return $kind;
}
function parseBcsExecutionError(failure) {
  const error = failure.error;
  const command = failure.command != null ? Number(failure.command) : void 0;
  switch (error.$kind) {
    case "MoveAbort": {
      const [location, abortCode] = error.MoveAbort;
      const moveLocation = {
        package: location.module.address,
        module: location.module.name,
        function: location.function,
        functionName: location.functionName ?? void 0,
        instruction: location.instruction
      };
      return {
        $kind: "MoveAbort",
        message: formatMoveAbortMessage({
          command,
          location: moveLocation,
          abortCode: String(abortCode)
        }),
        command,
        MoveAbort: {
          abortCode: String(abortCode),
          location: moveLocation
        }
      };
    }
    case "MoveObjectTooBig":
      return {
        $kind: "SizeError",
        message: formatErrorMessage("MoveObjectTooBig", error.MoveObjectTooBig),
        command,
        SizeError: {
          name: "ObjectTooBig",
          size: Number(error.MoveObjectTooBig.objectSize),
          maxSize: Number(error.MoveObjectTooBig.maxObjectSize)
        }
      };
    case "MovePackageTooBig":
      return {
        $kind: "SizeError",
        message: formatErrorMessage("MovePackageTooBig", error.MovePackageTooBig),
        command,
        SizeError: {
          name: "PackageTooBig",
          size: Number(error.MovePackageTooBig.objectSize),
          maxSize: Number(error.MovePackageTooBig.maxObjectSize)
        }
      };
    case "EffectsTooLarge":
      return {
        $kind: "SizeError",
        message: formatErrorMessage("EffectsTooLarge", error.EffectsTooLarge),
        command,
        SizeError: {
          name: "EffectsTooLarge",
          size: Number(error.EffectsTooLarge.currentSize),
          maxSize: Number(error.EffectsTooLarge.maxSize)
        }
      };
    case "WrittenObjectsTooLarge":
      return {
        $kind: "SizeError",
        message: formatErrorMessage("WrittenObjectsTooLarge", error.WrittenObjectsTooLarge),
        command,
        SizeError: {
          name: "WrittenObjectsTooLarge",
          size: Number(error.WrittenObjectsTooLarge.currentSize),
          maxSize: Number(error.WrittenObjectsTooLarge.maxSize)
        }
      };
    case "MoveVectorElemTooBig":
      return {
        $kind: "SizeError",
        message: formatErrorMessage("MoveVectorElemTooBig", error.MoveVectorElemTooBig),
        command,
        SizeError: {
          name: "MoveVectorElemTooBig",
          size: Number(error.MoveVectorElemTooBig.valueSize),
          maxSize: Number(error.MoveVectorElemTooBig.maxScaledSize)
        }
      };
    case "MoveRawValueTooBig":
      return {
        $kind: "SizeError",
        message: formatErrorMessage("MoveRawValueTooBig", error.MoveRawValueTooBig),
        command,
        SizeError: {
          name: "MoveRawValueTooBig",
          size: Number(error.MoveRawValueTooBig.valueSize),
          maxSize: Number(error.MoveRawValueTooBig.maxScaledSize)
        }
      };
    case "CommandArgumentError":
      return {
        $kind: "CommandArgumentError",
        message: formatErrorMessage("CommandArgumentError", error.CommandArgumentError),
        command,
        CommandArgumentError: {
          argument: error.CommandArgumentError.argIdx,
          name: error.CommandArgumentError.kind.$kind
        }
      };
    case "TypeArgumentError":
      return {
        $kind: "TypeArgumentError",
        message: formatErrorMessage("TypeArgumentError", error.TypeArgumentError),
        command,
        TypeArgumentError: {
          typeArgument: error.TypeArgumentError.argumentIdx,
          name: error.TypeArgumentError.kind.$kind
        }
      };
    case "PackageUpgradeError": {
      const upgradeError = error.PackageUpgradeError.upgradeError;
      return {
        $kind: "PackageUpgradeError",
        message: formatErrorMessage("PackageUpgradeError", error.PackageUpgradeError),
        command,
        PackageUpgradeError: {
          name: upgradeError.$kind,
          packageId: upgradeError.$kind === "UnableToFetchPackage" ? upgradeError.UnableToFetchPackage.packageId : void 0,
          digest: upgradeError.$kind === "DigestDoesNotMatch" ? toBase64(upgradeError.DigestDoesNotMatch.digest) : void 0
        }
      };
    }
    case "ExecutionCancelledDueToSharedObjectCongestion":
      return {
        $kind: "CongestedObjects",
        message: formatErrorMessage("ExecutionCancelledDueToSharedObjectCongestion", error.ExecutionCancelledDueToSharedObjectCongestion),
        command,
        CongestedObjects: {
          name: "ExecutionCanceledDueToConsensusObjectCongestion",
          objects: error.ExecutionCancelledDueToSharedObjectCongestion.congested_objects
        }
      };
    case "AddressDeniedForCoin":
      return {
        $kind: "CoinDenyListError",
        message: formatErrorMessage("AddressDeniedForCoin", error.AddressDeniedForCoin),
        command,
        CoinDenyListError: {
          name: "AddressDeniedForCoin",
          address: error.AddressDeniedForCoin.address,
          coinType: error.AddressDeniedForCoin.coinType
        }
      };
    case "CoinTypeGlobalPause":
      return {
        $kind: "CoinDenyListError",
        message: formatErrorMessage("CoinTypeGlobalPause", error.CoinTypeGlobalPause),
        command,
        CoinDenyListError: {
          name: "CoinTypeGlobalPause",
          coinType: error.CoinTypeGlobalPause.coinType
        }
      };
    case "CircularObjectOwnership":
      return {
        $kind: "ObjectIdError",
        message: formatErrorMessage("CircularObjectOwnership", error.CircularObjectOwnership),
        command,
        ObjectIdError: {
          name: "CircularObjectOwnership",
          objectId: error.CircularObjectOwnership.object
        }
      };
    case "InvalidGasObject":
      return {
        $kind: "ObjectIdError",
        message: "InvalidGasObject",
        command,
        ObjectIdError: {
          name: "InvalidGasObject",
          objectId: ""
        }
      };
    case "InputObjectDeleted":
      return {
        $kind: "ObjectIdError",
        message: "InputObjectDeleted",
        command,
        ObjectIdError: {
          name: "InputObjectDeleted",
          objectId: ""
        }
      };
    case "InvalidTransferObject":
      return {
        $kind: "ObjectIdError",
        message: "InvalidTransferObject",
        command,
        ObjectIdError: {
          name: "InvalidTransferObject",
          objectId: ""
        }
      };
    case "NonExclusiveWriteInputObjectModified":
      return {
        $kind: "Unknown",
        message: formatErrorMessage("NonExclusiveWriteInputObjectModified", error.NonExclusiveWriteInputObjectModified),
        command,
        Unknown: null
      };
    case "InsufficientGas":
    case "InvariantViolation":
    case "FeatureNotYetSupported":
    case "InsufficientCoinBalance":
    case "CoinBalanceOverflow":
    case "PublishErrorNonZeroAddress":
    case "SuiMoveVerificationError":
    case "MovePrimitiveRuntimeError":
    case "VMVerificationOrDeserializationError":
    case "VMInvariantViolation":
    case "FunctionNotFound":
    case "ArityMismatch":
    case "TypeArityMismatch":
    case "NonEntryFunctionInvoked":
    case "UnusedValueWithoutDrop":
    case "InvalidPublicFunctionReturnType":
    case "PublishUpgradeMissingDependency":
    case "PublishUpgradeDependencyDowngrade":
    case "CertificateDenied":
    case "SuiMoveVerificationTimedout":
    case "SharedObjectOperationNotAllowed":
    case "ExecutionCancelledDueToRandomnessUnavailable":
    case "InvalidLinkage":
    case "InsufficientBalanceForWithdraw":
      return {
        $kind: "Unknown",
        message: error.$kind,
        command,
        Unknown: null
      };
    default:
      return {
        $kind: "Unknown",
        message: "Unknown error",
        command,
        Unknown: null
      };
  }
}
function parseTransactionBcs(bytes, onlyTransactionKind = false) {
  return (onlyTransactionKind ? TransactionDataBuilder.fromKindBytes(bytes) : TransactionDataBuilder.fromBytes(bytes)).snapshot();
}
function parseTransactionEffectsBcs(effects) {
  const parsed = suiBcs.TransactionEffects.parse(effects);
  switch (parsed.$kind) {
    case "V1":
      return parseTransactionEffectsV1({
        bytes: effects,
        effects: parsed.V1
      });
    case "V2":
      return parseTransactionEffectsV2({
        bytes: effects,
        effects: parsed.V2
      });
    default:
      throw new Error(`Unknown transaction effects version: ${parsed.$kind}`);
  }
}
function parseTransactionEffectsV1(_) {
  throw new Error("V1 effects are not supported yet");
}
function parseTransactionEffectsV2({ bytes, effects }) {
  const changedObjects = effects.changedObjects.map(([id, change]) => {
    return {
      objectId: id,
      inputState: change.inputState.$kind === "Exist" ? "Exists" : "DoesNotExist",
      inputVersion: change.inputState.Exist?.[0][0] ?? null,
      inputDigest: change.inputState.Exist?.[0][1] ?? null,
      inputOwner: change.inputState.Exist?.[1] ?? null,
      outputState: change.outputState.$kind === "NotExist" ? "DoesNotExist" : change.outputState.$kind,
      outputVersion: change.outputState.$kind === "PackageWrite" ? change.outputState.PackageWrite?.[0] : change.outputState.$kind === "ObjectWrite" ? effects.lamportVersion : null,
      outputDigest: change.outputState.$kind === "PackageWrite" ? change.outputState.PackageWrite?.[1] : change.outputState.$kind === "ObjectWrite" ? change.outputState.ObjectWrite?.[0] ?? null : null,
      outputOwner: change.outputState.$kind === "ObjectWrite" ? change.outputState.ObjectWrite[1] : null,
      idOperation: change.idOperation.$kind
    };
  });
  return {
    bcs: bytes,
    version: 2,
    status: effects.status.$kind === "Success" ? {
      success: true,
      error: null
    } : {
      success: false,
      error: parseBcsExecutionError(effects.status.Failure)
    },
    gasUsed: effects.gasUsed,
    transactionDigest: effects.transactionDigest,
    gasObject: effects.gasObjectIndex === null ? null : changedObjects[effects.gasObjectIndex] ?? null,
    eventsDigest: effects.eventsDigest,
    dependencies: effects.dependencies,
    lamportVersion: effects.lamportVersion,
    changedObjects,
    unchangedConsensusObjects: effects.unchangedConsensusObjects.map(([objectId, object]) => {
      return {
        kind: object.$kind,
        objectId,
        version: object.$kind === "ReadOnlyRoot" ? object.ReadOnlyRoot[0] : object[object.$kind],
        digest: object.$kind === "ReadOnlyRoot" ? object.ReadOnlyRoot[1] : null
      };
    }),
    auxiliaryDataDigest: effects.auxDataDigest
  };
}

export {
  deriveDynamicFieldID,
  init_dynamic_fields,
  BaseClient,
  CoreClient,
  formatMoveAbortMessage,
  parseTransactionBcs,
  parseTransactionEffectsBcs
};
//# sourceMappingURL=chunk-U5RNEK6Q.js.map