import { F as CHAINS_INFO_MAP, P as getChainFromVerifiedCredentialChain, _t as getCore, at as isCookieEnabled, ct as getElevatedAccessToken, d as DYNAMIC_WAAS_METADATA, i as InvalidParamError, l as DEFAULT_WAAS_BASE_API_URL, u as DEFAULT_WAAS_BASE_MPC_RELAY_API_URL, ut as CLIENT_SDK_NAME, vt as name, yt as version } from "./updateAuthFromVerifyResponse-azIi_3FB.esm.js";
import { i as __logoutWithReason_wrapped } from "./isMfaRequiredForAction-CqEcCTIe.esm.js";
import "./isDynamicWaasEnabled-BYaqAOml.esm.js";
import { a as WaasOnboardingIncompleteError, i as preconnectWaasIframe, t as isUserOnboardingComplete } from "./isUserOnboardingComplete-CBrAH0ZF.esm.js";
import { n as consumeMfaTokenIfRequiredForAction, t as getSignedSessionId } from "./getSignedSessionId-CUw7LJ35.esm.js";
import { n as getWaasWalletProviderFromWalletAccount, t as migrateFromFireblocks } from "./migrateFromFireblocks-Bbx2wHZD.esm.js";
import { assertPackageVersion } from "@dynamic-labs-sdk/assert-package-version";
import { MFAAction, TokenScope, WalletProviderEnum } from "@dynamic-labs/sdk-api-core";
import { DynamicWalletClient, ThresholdSignatureScheme, WalletOperation } from "@dynamic-labs-wallet/browser-wallet-client";

//#region src/modules/waas/createWaasClient/createWaasClient.ts
/** @notInstrumented */
const createWaasClient = ({ chainName }, client) => {
	const core = getCore(client);
	const additionalTrustedOrigins = core.waas?.additionalTrustedOrigins;
	const baseClientKeysharesRelayApiUrl = client.projectSettings?.sdk.waas?.customKeyshareRelayBaseUrl;
	return new DynamicWalletClient({
		authMode: isCookieEnabled(client) ? "cookie" : "header",
		authToken: client.token || "",
		baseApiUrl: (core.apiBaseUrl || DEFAULT_WAAS_BASE_API_URL).replace("/api/v0", ""),
		baseMPCRelayApiUrl: client.projectSettings?.sdk.waas?.relayUrl || DEFAULT_WAAS_BASE_MPC_RELAY_API_URL,
		chainName,
		eagerlyRecoverKeyShares: true,
		environmentId: core.environmentId,
		sdkVersion: `${CLIENT_SDK_NAME}/${core.version}`,
		...additionalTrustedOrigins == void 0 ? {} : { additionalTrustedOrigins },
		...baseClientKeysharesRelayApiUrl == void 0 ? {} : { baseClientKeysharesRelayApiUrl }
	}, {
		getSignedSessionId: () => getSignedSessionId(client).then(({ signature }) => signature),
		onUnauthorized: () => {
			__logoutWithReason_wrapped({ reason: "session-refresh-unauthorized" }, client).catch((error) => {
				core.logger.error("Failed to log out after WaaS unauthorized response", error);
			});
		}
	});
};

//#endregion
//#region src/modules/waas/getWaasChainNameFromChain/getWaasChainNameFromChain.ts
/** @notInstrumented */
const getWaasChainNameFromChain = (chain) => {
	return CHAINS_INFO_MAP[chain].waasChainNameOverride || chain;
};

//#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 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();
			_waasClient = createWaasClient({ chainName: getWaasChainNameFromChain(chain) }, sdkClient);
			_waasClientSessionId = currentSessionId;
			await _waasClient.initialize();
		}
		return _waasClient;
	};
	const backupKeySharesToGoogleDrive = async ({ googleDriveAccessToken, password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		return (await getWaasClient()).backupKeySharesToGoogleDrive({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			googleDriveAccessToken,
			password,
			signedSessionId
		});
	};
	const createWalletAccount = async (args = {}) => {
		logger.debug("[createWaasProvider] createWalletAccount", {
			bitcoinConfig: args.bitcoinConfig,
			thresholdSignatureScheme: args.thresholdSignatureScheme
		});
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		return await (await getWaasClient()).createWalletAccount({
			authToken: sdkClient.token ?? void 0,
			bitcoinConfig: args.bitcoinConfig,
			password: args.password,
			signedSessionId,
			thresholdSignatureScheme: args.thresholdSignatureScheme ?? ThresholdSignatureScheme.TWO_OF_TWO
		});
	};
	const delegateKeyShares = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		return (await getWaasClient()).delegateKeyShares({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			password,
			signedSessionId
		});
	};
	const exportClientKeyshares = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		await (await getWaasClient()).exportClientKeyshares({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			password,
			signedSessionId
		});
	};
	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 waasClient.exportPrivateKey({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			container,
			displayContainer,
			elevatedAccessToken,
			mfaToken,
			password,
			signedSessionId
		});
	};
	const restoreUserShareForWalletAccount = async ({ walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		await (await getWaasClient()).getWallet({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			signedSessionId,
			walletOperation: WalletOperation.SIGN_MESSAGE
		});
	};
	const importPrivateKey = async ({ privateKey, thresholdSignatureScheme = ThresholdSignatureScheme.TWO_OF_TWO }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		await (await getWaasClient()).importPrivateKey({
			authToken: sdkClient.token ?? void 0,
			privateKey,
			signedSessionId,
			thresholdSignatureScheme
		});
	};
	const migrateFromFireblocks$1 = async ({ coinTypes, deviceId, expectedAddresses, jwt, password, storage }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		return (await getWaasClient()).migrateFromFireblocks({
			authToken: sdkClient.token ?? void 0,
			fireblocks: {
				deviceId,
				expectedAddresses,
				jwt,
				ncwStorage: storage,
				walletPassword: password,
				...coinTypes ? { coinTypes } : {}
			},
			signedSessionId
		});
	};
	const refreshWalletAccountShares = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		const walletClient = await getWaasClient();
		const mfaToken = await consumeMfaTokenIfRequiredForAction({ mfaAction: MFAAction.WalletWaasRefresh }, sdkClient);
		return walletClient.refreshWalletAccountShares({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			mfaToken,
			password,
			signedSessionId
		});
	};
	const revokeDelegation = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		return (await getWaasClient()).revokeDelegation({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			password,
			signedSessionId
		});
	};
	const setWaasWalletAccountPassword = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		return (await getWaasClient()).setPassword({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			newPassword: password,
			signedSessionId
		});
	};
	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);
		return { signature: await (await getWaasClient()).signRawMessage({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			elevatedAccessToken,
			message,
			mfaToken,
			password,
			signedSessionId
		}) };
	};
	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);
		return (await getWaasClient()).updatePassword({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			existingPassword: currentPassword,
			newPassword,
			signedSessionId
		});
	};
	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);
		return { signature: await (await getWaasClient()).signMessage({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			elevatedAccessToken,
			message,
			mfaToken,
			signedSessionId
		}) };
	};
	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);
		return { signature: await (await getWaasClient()).signTransaction({
			authToken: sdkClient.token ?? void 0,
			chainId,
			elevatedAccessToken,
			mfaToken,
			senderAddress: walletAccount.address,
			signedSessionId,
			transaction: serializedTransaction
		}) };
	};
	const getWalletRecoveryState = async ({ walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		return (await getWaasClient()).getWalletRecoveryState({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			signedSessionId
		});
	};
	const unlockWallet = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await getSignedSessionId(sdkClient);
		return (await getWaasClient()).unlockWallet({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			password,
			signedSessionId
		});
	};
	return {
		backupKeySharesToGoogleDrive,
		createWalletAccount,
		delegateKeyShares,
		destroy,
		exportClientKeyshares,
		exportPrivateKey,
		getWaasClient,
		getWalletRecoveryState,
		importPrivateKey,
		migrateFromFireblocks: migrateFromFireblocks$1,
		refreshWalletAccountShares,
		restoreUserShareForWalletAccount,
		revokeDelegation,
		setWaasWalletAccountPassword,
		signMessage,
		signRawMessage,
		signSerializedTransaction,
		unlockWallet,
		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