import { Ct as name, I as getChainFromVerifiedCredentialChain, St as getCore, d as DYNAMIC_WAAS_METADATA, ft as getElevatedAccessToken, i as InvalidParamError, wt as version } from "./updateAuthFromVerifyResponse-BEoc7f0m.esm.js";
import "./isDynamicWaasEnabled-DwY38pjA.esm.js";
import { a as WaasOnboardingIncompleteError, i as preconnectWaasIframe, o as WaasLoadFailedError, t as isUserOnboardingComplete } from "./isUserOnboardingComplete-CUZO4avc.esm.js";
import "./isMfaRequiredForAction-C_a46AcW.esm.js";
import { t as consumeMfaTokenIfRequiredForAction } from "./consumeMfaTokenIfRequiredForAction-CblIF3QS.esm.js";
import { t as getSignedSessionId } from "./getSignedSessionId-C4igTuKk.esm.js";
import { i as createWaasClient, n as getWaasWalletProviderFromWalletAccount, r as getWaasChainNameFromChain, t as migrateFromFireblocks } from "./migrateFromFireblocks-Vic3tb61.esm.js";
import { assertPackageVersion } from "@dynamic-labs-sdk/assert-package-version";
import { MFAAction, TokenScope, WalletProviderEnum } from "@dynamic-labs/sdk-api-core";
import { ThresholdSignatureScheme, WalletOperation } from "@dynamic-labs-wallet/browser-wallet-client";

//#region src/utils/createTranslateRejection/createTranslateRejection.ts
/**
* Builds a reusable decorator, bound once to a `match`/`mapTo` pair, that wraps
* any async function so a matching rejection is rethrown as `mapTo(error)`
* while every other rejection — and every resolved value — passes through
* untouched. Unmatched errors are rethrown by reference, so the decorator can
* never swallow or reshape an error it was not asked to translate.
*
* Binding `match`/`mapTo` up front keeps the generic wrapping machinery here
* instead of at the call site: consumers get a plain `(fn) => wrappedFn`
* decorator they can apply to many functions of differing signatures, each of
* which keeps its own argument and return types.
*
* @notInstrumented
*/
const createTranslateRejection = ({ match, mapTo }) => (fn) => async (...args) => {
	try {
		return await fn(...args);
	} catch (error) {
		if (match(error)) throw mapTo(error);
		throw error;
	}
};

//#endregion
//#region src/modules/waas/createWaasProvider/isWaasLoadExhaustionError.ts
/**
* Exact message prefix of the rejection thrown by
* `@dynamic-labs-wallet/browser-wallet-client` when the secure container load
* exhausts all retry attempts. The upstream library throws a plain `Error`
* with no code, so message matching is the only detection mechanism available;
* the dependency is pinned to an exact version and the spec pins this string
* so drift is caught at upgrade time.
*/
const UPSTREAM_LOAD_EXHAUSTION_MESSAGE_PREFIX = "Failed to load iframe after all retry attempts";
/**
* True when `error` is the upstream "load retry attempts exhausted" rejection
* from the embedded (WaaS) wallet's secure container load. Narrows to `Error`
* so the matched value can be forwarded as a typed error cause without a cast,
* and guards `instanceof Error` before reading `.message` so a non-`Error`
* rejection never throws during detection.
*
* @notInstrumented
*/
const isWaasLoadExhaustionError = (error) => error instanceof Error && error.message.startsWith(UPSTREAM_LOAD_EXHAUSTION_MESSAGE_PREFIX);

//#endregion
//#region src/modules/waas/createWaasProvider/createWaasProvider.ts
const RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH = 64;
/** @notInstrumented */
const createWaasProvider = ({ sdkClient, chain }) => {
	const logger = getCore(sdkClient).logger;
	let _waasClient;
	let _waasClientSessionId;
	const resetClientIfCurrent = (client) => {
		if (_waasClient === client) {
			_waasClient = void 0;
			_waasClientSessionId = void 0;
		}
	};
	const getWaasClient = async () => {
		const currentSessionId = getCore(sdkClient).state.get().user?.sessionId;
		if (_waasClient && currentSessionId !== _waasClientSessionId) _waasClient = void 0;
		if (!_waasClient) {
			if (!isUserOnboardingComplete(sdkClient)) throw new WaasOnboardingIncompleteError();
			const builtClient = createWaasClient({ chainName: getWaasChainNameFromChain(chain) }, sdkClient);
			_waasClient = builtClient;
			_waasClientSessionId = currentSessionId;
			try {
				await builtClient.initialize();
			} catch (error) {
				resetClientIfCurrent(builtClient);
				throw error;
			}
		}
		return _waasClient;
	};
	const discardClientOnLoadFailure = async ({ waasClient, operation }) => {
		try {
			return await operation();
		} catch (error) {
			if (isWaasLoadExhaustionError(error)) resetClientIfCurrent(waasClient);
			throw error;
		}
	};
	const backupKeySharesToGoogleDrive = async ({ googleDriveAccessToken, password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		return discardClientOnLoadFailure({
			operation: () => waasClient.backupKeySharesToGoogleDrive({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				googleDriveAccessToken,
				password,
				signedSessionId
			}),
			waasClient
		});
	};
	const createWalletAccount = async (args = {}) => {
		logger.debug("[createWaasProvider] createWalletAccount", {
			bitcoinConfig: args.bitcoinConfig,
			thresholdSignatureScheme: args.thresholdSignatureScheme
		});
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		return await discardClientOnLoadFailure({
			operation: () => waasClient.createWalletAccount({
				authToken: sdkClient.token ?? void 0,
				bitcoinConfig: args.bitcoinConfig,
				businessAccountId: args.businessAccountId,
				password: args.password,
				signedSessionId,
				thresholdSignatureScheme: args.thresholdSignatureScheme ?? ThresholdSignatureScheme.TWO_OF_TWO
			}),
			waasClient
		});
	};
	const delegateKeyShares = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		return discardClientOnLoadFailure({
			operation: () => waasClient.delegateKeyShares({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				password,
				signedSessionId
			}),
			waasClient
		});
	};
	const exportClientKeyshares = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		await discardClientOnLoadFailure({
			operation: () => waasClient.exportClientKeyshares({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				password,
				signedSessionId
			}),
			waasClient
		});
	};
	const exportPrivateKey = async ({ container, displayContainer, walletAccount, password }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		const mfaToken = await consumeMfaTokenIfRequiredForAction({ mfaAction: MFAAction.WalletWaasExport }, sdkClient);
		const elevatedAccessToken = getElevatedAccessToken({ scope: TokenScope.Walletexport }, sdkClient);
		await discardClientOnLoadFailure({
			operation: () => waasClient.exportPrivateKey({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				container,
				displayContainer,
				elevatedAccessToken,
				mfaToken,
				password,
				signedSessionId
			}),
			waasClient
		});
	};
	const restoreUserShareForWalletAccount = async ({ walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		await discardClientOnLoadFailure({
			operation: () => waasClient.getWallet({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				signedSessionId,
				walletOperation: WalletOperation.SIGN_MESSAGE
			}),
			waasClient
		});
	};
	const importPrivateKey = async ({ privateKey, thresholdSignatureScheme = ThresholdSignatureScheme.TWO_OF_TWO }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const walletClient = await getWaasClient();
		await discardClientOnLoadFailure({
			operation: () => walletClient.importPrivateKey({
				authToken: sdkClient.token ?? void 0,
				privateKey,
				signedSessionId,
				thresholdSignatureScheme
			}),
			waasClient: walletClient
		});
	};
	const migrateFromFireblocks$1 = async ({ coinTypes, deviceId, expectedAddresses, jwt, password, storage }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const walletClient = await getWaasClient();
		return discardClientOnLoadFailure({
			operation: () => walletClient.migrateFromFireblocks({
				authToken: sdkClient.token ?? void 0,
				fireblocks: {
					deviceId,
					expectedAddresses,
					jwt,
					ncwStorage: storage,
					walletPassword: password,
					...coinTypes ? { coinTypes } : {}
				},
				signedSessionId
			}),
			waasClient: walletClient
		});
	};
	const refreshWalletAccountShares = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const walletClient = await getWaasClient();
		const mfaToken = await consumeMfaTokenIfRequiredForAction({ mfaAction: MFAAction.WalletWaasRefresh }, sdkClient);
		return discardClientOnLoadFailure({
			operation: () => walletClient.refreshWalletAccountShares({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				mfaToken,
				password,
				signedSessionId
			}),
			waasClient: walletClient
		});
	};
	const reshareToNewSignerShareSet = async ({ businessAccountId, password, signerType, targetSignerIdentity, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		return discardClientOnLoadFailure({
			operation: () => waasClient.reshareToNewSignerShareSet({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				businessAccountId,
				password,
				signedSessionId,
				signerType,
				targetSignerIdentity
			}),
			waasClient
		});
	};
	const revokeDelegation = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		return discardClientOnLoadFailure({
			operation: () => waasClient.revokeDelegation({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				password,
				signedSessionId
			}),
			waasClient
		});
	};
	const setWaasWalletAccountPassword = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		return discardClientOnLoadFailure({
			operation: () => waasClient.setPassword({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				newPassword: password,
				signedSessionId
			}),
			waasClient
		});
	};
	const signRawMessage = async ({ message, password, walletAccount }) => {
		if (message.length !== RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH) throw new InvalidParamError(`Message must be ${RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH} characters long`);
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const mfaToken = await consumeMfaTokenIfRequiredForAction({ mfaAction: MFAAction.WalletWaasSign }, sdkClient);
		const elevatedAccessToken = getElevatedAccessToken({ scope: TokenScope.Walletsign }, sdkClient);
		const walletClient = await getWaasClient();
		return { signature: await discardClientOnLoadFailure({
			operation: () => walletClient.signRawMessage({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				elevatedAccessToken,
				message,
				mfaToken,
				password,
				signedSessionId
			}),
			waasClient: walletClient
		}) };
	};
	const destroy = async (args) => {
		if (!_waasClient) return;
		const waasClient = await getWaasClient();
		if (args?.reason !== "token-expired") await waasClient.cleanup();
		_waasClient = void 0;
	};
	const updatePassword = async ({ walletAccount, currentPassword, newPassword }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		return discardClientOnLoadFailure({
			operation: () => waasClient.updatePassword({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				existingPassword: currentPassword,
				newPassword,
				signedSessionId
			}),
			waasClient
		});
	};
	const signMessage = async ({ message, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const mfaToken = await consumeMfaTokenIfRequiredForAction({ mfaAction: MFAAction.WalletWaasSign }, sdkClient);
		const elevatedAccessToken = getElevatedAccessToken({ scope: TokenScope.Walletsign }, sdkClient);
		const waasClient = await getWaasClient();
		return { signature: await discardClientOnLoadFailure({
			operation: () => waasClient.signMessage({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				elevatedAccessToken,
				message,
				mfaToken,
				signedSessionId
			}),
			waasClient
		}) };
	};
	const signSerializedTransaction = async ({ chainId, serializedTransaction, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const mfaToken = await consumeMfaTokenIfRequiredForAction({ mfaAction: MFAAction.WalletWaasSign }, sdkClient);
		const elevatedAccessToken = getElevatedAccessToken({ scope: TokenScope.Walletsign }, sdkClient);
		const waasClient = await getWaasClient();
		return { signature: await discardClientOnLoadFailure({
			operation: () => waasClient.signTransaction({
				authToken: sdkClient.token ?? void 0,
				chainId,
				elevatedAccessToken,
				mfaToken,
				senderAddress: walletAccount.address,
				signedSessionId,
				transaction: serializedTransaction
			}),
			waasClient
		}) };
	};
	const getWalletRecoveryState = async ({ walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		return discardClientOnLoadFailure({
			operation: () => waasClient.getWalletRecoveryState({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				signedSessionId
			}),
			waasClient
		});
	};
	const unlockWallet = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		return discardClientOnLoadFailure({
			operation: () => waasClient.unlockWallet({
				accountAddress: walletAccount.address,
				authToken: sdkClient.token ?? void 0,
				password,
				signedSessionId
			}),
			waasClient
		});
	};
	const translateLoadFailure = createTranslateRejection({
		mapTo: (error) => new WaasLoadFailedError({ cause: error }),
		match: isWaasLoadExhaustionError
	});
	return {
		backupKeySharesToGoogleDrive: translateLoadFailure(backupKeySharesToGoogleDrive),
		createWalletAccount: translateLoadFailure(createWalletAccount),
		delegateKeyShares: translateLoadFailure(delegateKeyShares),
		destroy: translateLoadFailure(destroy),
		exportClientKeyshares: translateLoadFailure(exportClientKeyshares),
		exportPrivateKey: translateLoadFailure(exportPrivateKey),
		getWaasClient: translateLoadFailure(getWaasClient),
		getWalletRecoveryState: translateLoadFailure(getWalletRecoveryState),
		importPrivateKey: translateLoadFailure(importPrivateKey),
		migrateFromFireblocks: translateLoadFailure(migrateFromFireblocks$1),
		refreshWalletAccountShares: translateLoadFailure(refreshWalletAccountShares),
		reshareToNewSignerShareSet: translateLoadFailure(reshareToNewSignerShareSet),
		restoreUserShareForWalletAccount: translateLoadFailure(restoreUserShareForWalletAccount),
		revokeDelegation: translateLoadFailure(revokeDelegation),
		setWaasWalletAccountPassword: translateLoadFailure(setWaasWalletAccountPassword),
		signMessage: translateLoadFailure(signMessage),
		signRawMessage: translateLoadFailure(signRawMessage),
		signSerializedTransaction: translateLoadFailure(signSerializedTransaction),
		unlockWallet: translateLoadFailure(unlockWallet),
		updatePassword: translateLoadFailure(updatePassword)
	};
};

//#endregion
//#region src/modules/waas/exportWaasPrivateKeyToContainer/exportWaasPrivateKeyToContainer.ts
/**
* Exports the private key for a WaaS wallet account into a caller-provided
* {@link WaasSDKContainer} (e.g. a visible React Native WebView) instead of a
* DOM element.
*
* This is the container-based counterpart to `exportWaasPrivateKey` (which
* injects an iframe into a DOM `displayContainer` on web). The export ceremony
* runs — and the private key is rendered — entirely inside the container's own
* sandboxed document; the key is never exposed to the host JS layer. The caller
* owns the container's lifecycle and must call `container.destroy()` when the
* display is dismissed.
*
* @param params.walletAccount - The WaaS wallet account to export the private key from.
* @param params.container - The container that hosts the secure key display.
* @param [params.password] - Optional password to decrypt the private key.
* @param client - The Dynamic client instance. This is an internal API (exposed
*   only via `@dynamic-labs-sdk/client/waas/core`), so the client is passed
*   explicitly rather than defaulted — callers resolve it (e.g. via
*   `getDefaultClient()`) and thread it in.
* @returns A promise that resolves when the private key export is complete.
* @notInstrumented
*/
const exportWaasPrivateKeyToContainer = async ({ container, password, walletAccount }, client) => {
	return getWaasWalletProviderFromWalletAccount({ walletAccount }, client).exportPrivateKey({
		container,
		password,
		walletAccount
	});
};

//#endregion
//#region src/modules/waas/getAllUserWaasAddressesForChain/getAllUserWaasAddressesForChain.ts
/** @notInstrumented */
const getAllUserWaasAddressesForChain = ({ chain }, client) => {
	if (!client.user) return [];
	return (client.user.verifiedCredentials.filter((credential) => credential.walletProvider === WalletProviderEnum.EmbeddedWallet && credential.walletName?.toLowerCase().startsWith(DYNAMIC_WAAS_METADATA.normalizedWalletName) && credential.address && credential.chain && getChainFromVerifiedCredentialChain(credential.chain) === chain) ?? []).map((credential) => credential.address);
};

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

//#endregion
export { DYNAMIC_WAAS_METADATA, createWaasClient, createWaasProvider, exportWaasPrivateKeyToContainer, getAllUserWaasAddressesForChain, getWaasChainNameFromChain, migrateFromFireblocks, preconnectWaasIframe };
//# sourceMappingURL=waasCore.esm.js.map