import { B as name, C as isCookieEnabled, D as instrumentFunction, F as getDefaultClient, L as ClientNotFoundError, N as DYNAMIC_SDK_API_VERSION, R as BaseError, S as __getSessionKeys_wrapped, T as ValueMustBeDefinedError, V as version, a as DYNAMIC_ICONIC_SPRITE_URL, c as CHAINS_INFO_MAP, f as __createDeviceSignatureHeadersMiddleware_wrapped, h as __getNonce_wrapped, j as randomString, m as __getDeviceSigner_wrapped, p as __getHeadersForNonceSignedByDeviceSigners_wrapped, s as __getChainFromVerifiedCredentialChain_wrapped, u as __createApiClient_wrapped, w as assertDefined, x as APIError, z as getCore } from "./InvalidParamError-B55FwITx.esm.js";
import { C as CrossTabBroadcastMessageSchema, E as FETCH_PROJECT_SETTINGS_TRACKER_KEY, H as __subscribeWithSelector_wrapped, I as __createStorageKeySchema_wrapped, L as __createStorage_wrapped, M as getBuffer, N as __logoutWithReason_wrapped, P as __generateSessionKeys_wrapped, R as InvalidStorageSet, S as __createCrossTabBroadcast_wrapped, T as __createDeferredPromise_wrapped, a as __updateWalletProviderKeysForVerifiedCredentials_wrapped, b as createKeychainService, c as __createSignInMessageStatement_wrapped, d as __createVisit_wrapped, f as hasExtension, h as __consumeCaptchaToken_wrapped, i as __getNetworksData_wrapped, l as formatSignInMessage, m as __setCaptchaToken_wrapped, n as __getNetworkProviders_wrapped, o as __verifyMessageSignatureOwnership_wrapped, p as __createRealtimeChannelSchema_wrapped, r as getNetworkProviderBuilderRegistry, s as __removeUnverifiedWalletAccount_wrapped, t as __getNetworkProviderFromNetworkId_wrapped, u as __setUnverifiedWalletAccounts_wrapped, v as NoNetworkProvidersError, w as CannotTrackError, x as __createLogger_wrapped, y as __createRealtimeService_wrapped, z as __createLocalStorageAdapter_wrapped } from "./getNetworkProviderFromNetworkId-DWSOEnSr.esm.js";
import { A as emitEvent, C as formatWalletAccountId, E as InvalidWalletProviderKeyError, S as normalizeWalletNameWithChain, T as splitWalletProviderKey, _ as getWalletProviderRegistry, g as WalletProviderPriority, h as __getWalletProviderFromWalletAccount_wrapped, n as getWalletProviderByKey, p as emitWalletAccountsChangedEvent, r as __updateAuthFromVerifyResponse_wrapped, t as __getVerifiedCredentialForWalletAccount_wrapped, u as __getWalletProviders_wrapped, v as __createRuntimeServiceAccessKey_wrapped, x as formatWalletProviderKey, y as NoWalletProviderFoundError } from "./getVerifiedCredentialForWalletAccount-Bx9dMVjF.esm.js";
import "./isMfaRequiredForAction-DVA7aeXI.esm.js";
import { n as __consumeMfaTokenIfRequiredForAction_wrapped, t as __getSignedSessionId_wrapped } from "./getSignedSessionId-GVIy9gR0.esm.js";
import { assertPackageVersion } from "@dynamic-labs-sdk/assert-package-version";
import * as z from "zod/mini";
import EventEmitter from "eventemitter3";

//#region src/errors/ClientsDoNotMatchError.ts
var ClientsDoNotMatchError = class extends BaseError {
	constructor() {
		super({
			cause: null,
			code: "clients_do_not_match_error",
			docsUrl: null,
			name: "ClientsDoNotMatchError",
			shortMessage: "Clients do not match"
		});
	}
};

//#endregion
//#region src/errors/MethodNotImplementedError.ts
var MethodNotImplementedError = class extends BaseError {
	constructor(methodName) {
		super({
			cause: null,
			code: "method_not_implemented_error",
			docsUrl: null,
			name: "MethodNotImplementedError",
			shortMessage: `This method is not implemented: ${methodName}`
		});
	}
};

//#endregion
//#region src/errors/MultipleClientsFoundError.ts
var MultipleClientsFoundError = class extends BaseError {
	constructor() {
		super({
			cause: null,
			code: "multiple_clients_found_error",
			docsUrl: null,
			name: "MultipleClientsFoundError",
			shortMessage: "Multiple Dynamic clients have been initialized. Please provide the intended client for this action explicitly"
		});
	}
};

//#endregion
//#region src/modules/extension/registerExtension/registerExtension.ts
/**
* Registers an extension to the client.
*
* Other extensions can be aware of which extensions are present,
* and allows creating dependencies between extensions.
*
* @param client - The client instance.
* @param extensionKey - The key of the extension to register.
* @returns The client instance.
* @instrumented
*/
const registerExtension = ({ extensionKey }, client) => {
	getCore(client).extensions.add(extensionKey);
};
const __registerExtension_impl = registerExtension;
const __registerExtension_wrapped = instrumentFunction({
	fn: __registerExtension_impl,
	functionName: "registerExtension",
	getCore: () => {
		try {
			return getCore(getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/modules/initializeClient/waitForProjectSettings/waitForProjectSettings.ts
/** @instrumented */
const waitForProjectSettings = async (client) => {
	const projectSettingsTracker = getCore(client).initTrack.getTracker(FETCH_PROJECT_SETTINGS_TRACKER_KEY);
	assertDefined(projectSettingsTracker, "Project settings tracker not found");
	await projectSettingsTracker.promise;
	assertDefined(client.projectSettings, "Project settings still not available after awaiting its tracker");
	return client.projectSettings;
};
const __waitForProjectSettings_impl = waitForProjectSettings;
const __waitForProjectSettings_wrapped = instrumentFunction({
	fn: __waitForProjectSettings_impl,
	functionName: "waitForProjectSettings",
	getCore: () => {
		try {
			return getCore(getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/modules/wallets/networks/createBaseNetworkProvider/createBaseNetworkProvider.ts
/** @instrumented */
const createBaseNetworkProvider = (chain, networkData) => ({
	blockExplorerUrls: networkData.blockExplorerUrls,
	chain,
	displayName: networkData.displayName,
	iconUrl: networkData.iconUrl,
	id: `${chain}-${networkData.networkId}`,
	name: networkData.name,
	nativeCurrency: networkData.nativeCurrency,
	networkId: networkData.networkId,
	rpcUrls: networkData.rpcUrls,
	testnet: networkData.testnet
});
const __createBaseNetworkProvider_impl = createBaseNetworkProvider;
const __createBaseNetworkProvider_wrapped = instrumentFunction({
	fn: __createBaseNetworkProvider_impl,
	functionName: "createBaseNetworkProvider",
	getCore: () => {
		try {
			return getCore(getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/modules/wallets/networks/getNetworkDataForNetworkId/getNetworkDataForNetworkId.ts
/** @instrumented */
const getNetworkDataForNetworkId = ({ networkId, chain }, client) => {
	return __getNetworksData_wrapped(client).find((networkData) => networkData.networkId === networkId && networkData.chain === chain);
};
const __getNetworkDataForNetworkId_impl = getNetworkDataForNetworkId;
const __getNetworkDataForNetworkId_wrapped = instrumentFunction({
	fn: __getNetworkDataForNetworkId_impl,
	functionName: "getNetworkDataForNetworkId",
	getCore: () => {
		try {
			return getCore(getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/modules/wallets/networks/lastKnownNetworkRegistry/createLastKnownNetworkRegistry/schema.ts
const networkRegistryStorageKeySchema = __createStorageKeySchema_wrapped({
	key: "lastKnownNetworkRegistry",
	schema: z.record(z.string(), z.string())
});

//#endregion
//#region src/modules/wallets/networks/lastKnownNetworkRegistry/createLastKnownNetworkRegistry/createLastKnownNetworkRegistry.ts
/**
* Creates the registry that keeps tabs on which wallet provider is
* connected to which network.
*
* Reminder that this will not be used for chains that have an internal way to
* switch networks (ex EVM).
* @not-instrumented
*/
const createLastKnownNetworkRegistry = (client) => {
	const core = getCore(client);
	const walletProviderKeyToNetworkId = /* @__PURE__ */ new Map();
	const getNetworkId = async ({ walletProviderKey }) => {
		if (walletProviderKeyToNetworkId.has(walletProviderKey)) return { networkId: walletProviderKeyToNetworkId.get(walletProviderKey) };
		const storageRecords = await core.storage.getItem(networkRegistryStorageKeySchema);
		if (storageRecords && storageRecords[walletProviderKey]) {
			const networkId = storageRecords[walletProviderKey];
			walletProviderKeyToNetworkId.set(walletProviderKey, networkId);
			return { networkId };
		}
		const walletProvider = getWalletProviderByKey({ walletProviderKey }, client);
		const networkProviders = __getNetworkProviders_wrapped(client);
		if (networkProviders.length === 0) throw new NoNetworkProvidersError();
		const defaultNetworkProvider = networkProviders.find((networkProvider) => networkProvider.chain === walletProvider.chain);
		assertDefined(defaultNetworkProvider, `No networks found for chain ${walletProvider.chain}`);
		walletProviderKeyToNetworkId.set(walletProviderKey, defaultNetworkProvider.networkId);
		return { networkId: defaultNetworkProvider.networkId };
	};
	const setNetworkId = async ({ networkId, walletProviderKey }) => {
		walletProviderKeyToNetworkId.set(walletProviderKey, networkId);
		await core.storage.setItem(networkRegistryStorageKeySchema, Object.fromEntries(walletProviderKeyToNetworkId.entries()));
	};
	return {
		getNetworkId,
		setNetworkId
	};
};

//#endregion
//#region src/modules/wallets/networks/lastKnownNetworkRegistry/getLastKnownNetworkRegistry/getLastKnownNetworkRegistry.ts
const getLastKnownNetworkRegistry = __createRuntimeServiceAccessKey_wrapped("last-known-network-registry", (client) => createLastKnownNetworkRegistry(client));

//#endregion
//#region src/modules/wallets/utils/formatWalletProviderGroupKey/formatWalletProviderGroupKey.ts
/** @not-instrumented */
const formatWalletProviderGroupKey = (walletName) => walletName.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();

//#endregion
//#region src/modules/wallets/utils/getAllProvidersFromWindow/getAllProvidersFromWindow.ts
/**
* Retrieves all providers from a window path.
*
* Unlike getInjectedProviderFromWindow which returns only the first provider,
* this function returns ALL providers found at the path, including those
* in a .providers array if present.
*
* This is particularly useful for detecting wallet providers in wallet app
* in-app browsers, where wallets inject their provider into the window object.
*
* @param path - Dot-separated path to traverse (e.g., "ethereum")
* @returns Array of all providers found, or empty array if none
* @not-instrumented
*/
const getAllProvidersFromWindow = (path) => {
	if (typeof window === "undefined") return [];
	const target = path.split(".").reduce((acc, key) => acc == null ? null : acc[key], window);
	if (typeof target !== "object" || target === null) return [];
	if (Array.isArray(target)) return target;
	const providers = [];
	const providersArray = target.providers;
	if (providersArray && Array.isArray(providersArray)) providers.push(...providersArray);
	providers.push(target);
	return providers;
};

//#endregion
//#region src/modules/wallets/utils/getInjectedProviderFromWindow/getInjectedProviderFromWindow.ts
/** @not-instrumented */
const getInjectedProviderFromWindow = (path) => {
	if (typeof window === "undefined") return null;
	const target = path.split(".").reduce((acc, key) => acc == null ? null : acc[key], window);
	if (typeof target !== "object" || target === null) return null;
	if (Array.isArray(target)) return target.length > 0 ? target[0] : null;
	const providersArray = target.providers;
	if (providersArray && Array.isArray(providersArray)) return providersArray.length > 0 ? providersArray[0] : null;
	return target;
};

//#endregion
//#region src/modules/wallets/walletProvider/defaultImplementations/getActiveNetworkIdFromLastKnownRegistry/getActiveNetworkIdFromLastKnownRegistry.ts
/** @instrumented */
const getActiveNetworkIdFromLastKnownRegistry = async ({ client, walletProviderKey }) => {
	return getLastKnownNetworkRegistry(client).getNetworkId({ walletProviderKey });
};

//#endregion
//#region src/modules/wallets/walletProvider/defaultImplementations/switchActiveNetworkInLastKnownRegistry/switchActiveNetworkInLastKnownRegistry.ts
/** @instrumented */
const switchActiveNetworkInLastKnownRegistry = async ({ client, networkId, walletProviderKey }) => {
	await getLastKnownNetworkRegistry(client).setNetworkId({
		networkId,
		walletProviderKey
	});
};

//#endregion
//#region src/modules/wallets/walletProvider/events/createWalletProviderEventEmitter/createWalletProviderEventEmitter.ts
/**
* Takes a callback that registers handlers for the external wallet provider.
* Returns both a getter of an eventEmitter that can be exposed via the wallet provider
* and a callback that will be used to destroy the listeners.
* @not-instrumented
*/
const createWalletProviderEventEmitter = ({ removeEventListeners, setupEventListeners, supportedEvents = [
	"accountsChanged",
	"disconnected",
	"networkChanged"
] }) => {
	let eventEmitter;
	/** Value returned by setupEventListeners */
	let setupReturnValue;
	const handleAccountsChanged = (params) => {
		assertDefined(eventEmitter, "Event emitter not defined");
		eventEmitter.emit("accountsChanged", params);
	};
	const handleDisconnected = () => {
		assertDefined(eventEmitter, "Event emitter not defined");
		eventEmitter.emit("disconnected");
	};
	const handleNetworkChanged = (params) => {
		assertDefined(eventEmitter, "Event emitter not defined");
		eventEmitter.emit("networkChanged", params);
	};
	const cleanupEventEmitter = () => {
		if (!eventEmitter) return;
		removeEventListeners({
			handleAccountsChanged,
			handleDisconnected,
			handleNetworkChanged,
			setupReturnValue
		});
		eventEmitter = void 0;
	};
	const getEventEmitter = () => {
		if (!eventEmitter) {
			eventEmitter = new EventEmitter();
			setupReturnValue = setupEventListeners({
				handleAccountsChanged,
				handleDisconnected,
				handleNetworkChanged
			});
		}
		return Object.assign(eventEmitter, { supportedEvents });
	};
	return {
		cleanupEventEmitter,
		getEventEmitter
	};
};
const __createWalletProviderEventEmitter_impl = createWalletProviderEventEmitter;
const __createWalletProviderEventEmitter_wrapped = instrumentFunction({
	fn: __createWalletProviderEventEmitter_impl,
	functionName: "createWalletProviderEventEmitter",
	getCore: () => {
		try {
			return getCore(getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/utils/bufferToBase64/bufferToBase64.ts
/** @not-instrumented */
const bufferToBase64 = (buf) => {
	const binstr = Array.prototype.map.call(buf, (ch) => String.fromCharCode(ch)).join("");
	return getBuffer().from(binstr, "binary").toString("base64");
};

//#endregion
//#region src/utils/filterDuplicates/filterDuplicates.ts
/**
* Filter duplicates from an array by equality.
* Uses a Set internally.
* @not-instrumented
*/
const filterDuplicates = (array) => Array.from(new Set(array));

//#endregion
//#region src/utils/parseAmountToSmallestUnit/parseAmountToSmallestUnit.ts
/**
* Converts a human-readable decimal amount string to the smallest unit
* representation as a bigint, using string-based arithmetic to avoid
* floating-point precision loss.
*
* @example
* parseAmountToSmallestUnit({ amount: '1.5', decimals: 9 })   // 1500000000n  (1.5 SOL in lamports)
* parseAmountToSmallestUnit({ amount: '1.5', decimals: 8 })   // 150000000n   (1.5 BTC in satoshis)
* parseAmountToSmallestUnit({ amount: '10.5', decimals: 6 })  // 10500000n    (10.5 USDC)
* parseAmountToSmallestUnit({ amount: '0.1', decimals: 9 })   // 100000000n   (no float error)
*
* @param params.amount - The amount as a decimal string (e.g. "1.5").
* @param params.decimals - The number of decimal places for the token.
* @returns The amount in smallest units as a bigint.
* @not-instrumented
*/
const parseAmountToSmallestUnit = ({ amount, decimals }) => {
	const [whole = "0", fraction = ""] = amount.split(".");
	const paddedFraction = fraction.padEnd(decimals, "0").slice(0, decimals);
	return BigInt(whole + paddedFraction);
};

//#endregion
//#region src/errors/ReactNativeOnlyError.ts
var ReactNativeOnlyError = class extends BaseError {
	constructor({ apiName }) {
		super({
			cause: null,
			code: "react_native_only_error",
			docsUrl: null,
			name: "ReactNativeOnlyError",
			shortMessage: `${apiName} is only available in React Native environments.`
		});
	}
};

//#endregion
//#region src/services/nativeManifest/getReactNativeManifest/getReactNativeManifest.ts
/**
* Returns the React Native manifest containing native SDK metadata.
*
* This function is only available in React Native environments.
* On web, it throws a `ReactNativeOnlyError`.
*
* @not-instrumented
*/
const getReactNativeManifest = () => {
	throw new ReactNativeOnlyError({ apiName: "getReactNativeManifest" });
};

//#endregion
//#region src/exports/core.ts
assertPackageVersion(name, version);

//#endregion
export { APIError, CHAINS_INFO_MAP, CannotTrackError, ClientNotFoundError, ClientsDoNotMatchError, CrossTabBroadcastMessageSchema, DYNAMIC_ICONIC_SPRITE_URL, DYNAMIC_SDK_API_VERSION, InvalidStorageSet, InvalidWalletProviderKeyError, MethodNotImplementedError, MultipleClientsFoundError, NoWalletProviderFoundError, ValueMustBeDefinedError, WalletProviderPriority, assertDefined, bufferToBase64, __consumeCaptchaToken_wrapped as consumeCaptchaToken, __consumeMfaTokenIfRequiredForAction_wrapped as consumeMfaTokenIfRequiredForAction, __createApiClient_wrapped as createApiClient, __createBaseNetworkProvider_wrapped as createBaseNetworkProvider, __createCrossTabBroadcast_wrapped as createCrossTabBroadcast, __createDeferredPromise_wrapped as createDeferredPromise, __createDeviceSignatureHeadersMiddleware_wrapped as createDeviceSignatureHeadersMiddleware, createKeychainService, __createLocalStorageAdapter_wrapped as createLocalStorageAdapter, __createLogger_wrapped as createLogger, __createRealtimeChannelSchema_wrapped as createRealtimeChannelSchema, __createRealtimeService_wrapped as createRealtimeService, __createRuntimeServiceAccessKey_wrapped as createRuntimeServiceAccessKey, __createSignInMessageStatement_wrapped as createSignInMessageStatement, __createStorage_wrapped as createStorage, __createStorageKeySchema_wrapped as createStorageKeySchema, __createVisit_wrapped as createVisit, __createWalletProviderEventEmitter_wrapped as createWalletProviderEventEmitter, emitEvent, emitWalletAccountsChangedEvent, filterDuplicates, formatSignInMessage, formatWalletAccountId, formatWalletProviderGroupKey, formatWalletProviderKey, __generateSessionKeys_wrapped as generateSessionKeys, getActiveNetworkIdFromLastKnownRegistry, getAllProvidersFromWindow, getBuffer, __getChainFromVerifiedCredentialChain_wrapped as getChainFromVerifiedCredentialChain, getCore, getDefaultClient, __getDeviceSigner_wrapped as getDeviceSigner, __getHeadersForNonceSignedByDeviceSigners_wrapped as getHeadersForNonceSignedByDeviceSigners, getInjectedProviderFromWindow, getLastKnownNetworkRegistry, __getNetworkDataForNetworkId_wrapped as getNetworkDataForNetworkId, getNetworkProviderBuilderRegistry, __getNetworkProviderFromNetworkId_wrapped as getNetworkProviderFromNetworkId, __getNetworkProviders_wrapped as getNetworkProviders, __getNonce_wrapped as getNonce, getReactNativeManifest, __getSessionKeys_wrapped as getSessionKeys, __getSignedSessionId_wrapped as getSignedSessionId, __getVerifiedCredentialForWalletAccount_wrapped as getVerifiedCredentialForWalletAccount, __getWalletProviderFromWalletAccount_wrapped as getWalletProviderFromWalletAccount, getWalletProviderRegistry, __getWalletProviders_wrapped as getWalletProviders, hasExtension, isCookieEnabled, __logoutWithReason_wrapped as logoutWithReason, normalizeWalletNameWithChain, parseAmountToSmallestUnit, randomString, __registerExtension_wrapped as registerExtension, __removeUnverifiedWalletAccount_wrapped as removeUnverifiedWalletAccount, __setCaptchaToken_wrapped as setCaptchaToken, __setUnverifiedWalletAccounts_wrapped as setUnverifiedWalletAccounts, splitWalletProviderKey, __subscribeWithSelector_wrapped as subscribeWithSelector, switchActiveNetworkInLastKnownRegistry, __updateAuthFromVerifyResponse_wrapped as updateAuthFromVerifyResponse, __updateWalletProviderKeysForVerifiedCredentials_wrapped as updateWalletProviderKeysForVerifiedCredentials, __verifyMessageSignatureOwnership_wrapped as verifyMessageSignatureOwnership, __waitForProjectSettings_wrapped as waitForProjectSettings };
//# sourceMappingURL=core.esm.js.map