const require_isMfaRequiredForAction = require('./isMfaRequiredForAction-Btejc5g3.cjs');
const require_updateAuthFromVerifyResponse = require('./updateAuthFromVerifyResponse-CElYpi97.cjs');
require('./isDynamicWaasEnabled-BwP1oowd.cjs');
const require_isUserOnboardingComplete = require('./isUserOnboardingComplete-C86NDY7I.cjs');
const require_getSignedSessionId = require('./getSignedSessionId-cMGkmojJ.cjs');
const require_migrateFromFireblocks = require('./migrateFromFireblocks-B_q8Oawb.cjs');
let _dynamic_labs_sdk_assert_package_version = require("@dynamic-labs-sdk/assert-package-version");
let _dynamic_labs_sdk_api_core = require("@dynamic-labs/sdk-api-core");
let _dynamic_labs_wallet_browser_wallet_client = require("@dynamic-labs-wallet/browser-wallet-client");

//#region src/modules/waas/createWaasClient/createWaasClient.ts
/** @notInstrumented */
const createWaasClient = ({ chainName }, client) => {
	const core = require_updateAuthFromVerifyResponse.getCore(client);
	const additionalTrustedOrigins = core.waas?.additionalTrustedOrigins;
	const baseClientKeysharesRelayApiUrl = client.projectSettings?.sdk.waas?.customKeyshareRelayBaseUrl;
	return new _dynamic_labs_wallet_browser_wallet_client.DynamicWalletClient({
		authMode: require_updateAuthFromVerifyResponse.isCookieEnabled(client) ? "cookie" : "header",
		authToken: client.token || "",
		baseApiUrl: (core.apiBaseUrl || require_updateAuthFromVerifyResponse.DEFAULT_WAAS_BASE_API_URL).replace("/api/v0", ""),
		baseMPCRelayApiUrl: client.projectSettings?.sdk.waas?.relayUrl || require_updateAuthFromVerifyResponse.DEFAULT_WAAS_BASE_MPC_RELAY_API_URL,
		chainName,
		eagerlyRecoverKeyShares: true,
		environmentId: core.environmentId,
		sdkVersion: `${require_updateAuthFromVerifyResponse.CLIENT_SDK_NAME}/${core.version}`,
		...additionalTrustedOrigins == void 0 ? {} : { additionalTrustedOrigins },
		...baseClientKeysharesRelayApiUrl == void 0 ? {} : { baseClientKeysharesRelayApiUrl }
	}, {
		getSignedSessionId: () => require_getSignedSessionId.getSignedSessionId(client).then(({ signature }) => signature),
		onUnauthorized: () => {
			require_isMfaRequiredForAction.__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 require_updateAuthFromVerifyResponse.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 = require_updateAuthFromVerifyResponse.getCore(sdkClient).logger;
	let _waasClient;
	let _waasClientSessionId;
	const getWaasClient = async () => {
		const currentSessionId = require_updateAuthFromVerifyResponse.getCore(sdkClient).state.get().user?.sessionId;
		if (_waasClient && currentSessionId !== _waasClientSessionId) _waasClient = void 0;
		if (!_waasClient) {
			if (!require_isUserOnboardingComplete.isUserOnboardingComplete(sdkClient)) throw new require_isUserOnboardingComplete.WaasOnboardingIncompleteError();
			_waasClient = createWaasClient({ chainName: getWaasChainNameFromChain(chain) }, sdkClient);
			_waasClientSessionId = currentSessionId;
			await _waasClient.initialize();
		}
		return _waasClient;
	};
	const backupKeySharesToGoogleDrive = async ({ googleDriveAccessToken, password, walletAccount }) => {
		const { signature: signedSessionId } = await require_getSignedSessionId.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 require_getSignedSessionId.getSignedSessionId(sdkClient);
		return await (await getWaasClient()).createWalletAccount({
			authToken: sdkClient.token ?? void 0,
			bitcoinConfig: args.bitcoinConfig,
			password: args.password,
			signedSessionId,
			thresholdSignatureScheme: args.thresholdSignatureScheme ?? _dynamic_labs_wallet_browser_wallet_client.ThresholdSignatureScheme.TWO_OF_TWO
		});
	};
	const delegateKeyShares = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await require_getSignedSessionId.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 require_getSignedSessionId.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 require_getSignedSessionId.getSignedSessionId(sdkClient);
		const waasClient = await getWaasClient();
		const mfaToken = await require_getSignedSessionId.consumeMfaTokenIfRequiredForAction({ mfaAction: _dynamic_labs_sdk_api_core.MFAAction.WalletWaasExport }, sdkClient);
		const elevatedAccessToken = require_updateAuthFromVerifyResponse.getElevatedAccessToken({ scope: _dynamic_labs_sdk_api_core.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 require_getSignedSessionId.getSignedSessionId(sdkClient);
		await (await getWaasClient()).getWallet({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			signedSessionId,
			walletOperation: _dynamic_labs_wallet_browser_wallet_client.WalletOperation.SIGN_MESSAGE
		});
	};
	const importPrivateKey = async ({ privateKey, thresholdSignatureScheme = _dynamic_labs_wallet_browser_wallet_client.ThresholdSignatureScheme.TWO_OF_TWO }) => {
		const { signature: signedSessionId } = await require_getSignedSessionId.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 require_getSignedSessionId.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 require_getSignedSessionId.getSignedSessionId(sdkClient);
		const walletClient = await getWaasClient();
		const mfaToken = await require_getSignedSessionId.consumeMfaTokenIfRequiredForAction({ mfaAction: _dynamic_labs_sdk_api_core.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 require_getSignedSessionId.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 require_getSignedSessionId.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 require_updateAuthFromVerifyResponse.InvalidParamError(`Message must be ${RAW_MESSAGE_MESSAGE_REQUIRED_LENGTH} characters long`);
		const { signature: signedSessionId } = await require_getSignedSessionId.getSignedSessionId(sdkClient);
		const mfaToken = await require_getSignedSessionId.consumeMfaTokenIfRequiredForAction({ mfaAction: _dynamic_labs_sdk_api_core.MFAAction.WalletWaasSign }, sdkClient);
		const elevatedAccessToken = require_updateAuthFromVerifyResponse.getElevatedAccessToken({ scope: _dynamic_labs_sdk_api_core.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 require_getSignedSessionId.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 require_getSignedSessionId.getSignedSessionId(sdkClient);
		const mfaToken = await require_getSignedSessionId.consumeMfaTokenIfRequiredForAction({ mfaAction: _dynamic_labs_sdk_api_core.MFAAction.WalletWaasSign }, sdkClient);
		const elevatedAccessToken = require_updateAuthFromVerifyResponse.getElevatedAccessToken({ scope: _dynamic_labs_sdk_api_core.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 require_getSignedSessionId.getSignedSessionId(sdkClient);
		const mfaToken = await require_getSignedSessionId.consumeMfaTokenIfRequiredForAction({ mfaAction: _dynamic_labs_sdk_api_core.MFAAction.WalletWaasSign }, sdkClient);
		const elevatedAccessToken = require_updateAuthFromVerifyResponse.getElevatedAccessToken({ scope: _dynamic_labs_sdk_api_core.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 require_getSignedSessionId.getSignedSessionId(sdkClient);
		return (await getWaasClient()).getWalletRecoveryState({
			accountAddress: walletAccount.address,
			authToken: sdkClient.token ?? void 0,
			signedSessionId
		});
	};
	const unlockWallet = async ({ password, walletAccount }) => {
		const { signature: signedSessionId } = await require_getSignedSessionId.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 require_migrateFromFireblocks.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 === _dynamic_labs_sdk_api_core.WalletProviderEnum.EmbeddedWallet && credential.walletName?.toLowerCase().startsWith(require_updateAuthFromVerifyResponse.DYNAMIC_WAAS_METADATA.normalizedWalletName) && credential.address && credential.chain && require_updateAuthFromVerifyResponse.getChainFromVerifiedCredentialChain(credential.chain) === chain) ?? []).map((credential) => credential.address);
};

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

//#endregion
exports.DYNAMIC_WAAS_METADATA = require_updateAuthFromVerifyResponse.DYNAMIC_WAAS_METADATA;
exports.createWaasClient = createWaasClient;
exports.createWaasProvider = createWaasProvider;
exports.exportWaasPrivateKeyToContainer = exportWaasPrivateKeyToContainer;
exports.getAllUserWaasAddressesForChain = getAllUserWaasAddressesForChain;
exports.getWaasChainNameFromChain = getWaasChainNameFromChain;
exports.migrateFromFireblocks = require_migrateFromFireblocks.migrateFromFireblocks;
exports.preconnectWaasIframe = require_isUserOnboardingComplete.preconnectWaasIframe;
//# sourceMappingURL=waasCore.cjs.map