import { A as NoWalletProviderFoundError, E as getWalletProviderFromWalletAccount, F as CHAINS_INFO_MAP, St as getCore, d as DEFAULT_WAAS_BASE_MPC_RELAY_API_URL, f as DYNAMIC_WAAS_METADATA, ht as CLIENT_SDK_NAME, l as isWaasWalletProvider, lt as isCookieEnabled, p as getWalletProviders, t as NativeModuleNotLinkedError, u as DEFAULT_WAAS_BASE_API_URL, vt as getDefaultClient, xt as BaseError } from "./NativeModuleNotLinkedError-DsfdAti9.native.esm.js";
import { n as NotWaasWalletAccountError, r as __refreshAuth_wrapped } from "./isDynamicWaasEnabled-CsNM4kzO.native.esm.js";
import { ACCESSIBLE, getGenericPassword, resetGenericPassword, setGenericPassword } from "react-native-keychain";
import { NativeEventEmitter, TurboModuleRegistry } from "react-native";
import { DynamicWalletClient } from "@dynamic-labs-wallet/browser-wallet-client";

//#region src/errors/NotWaasWalletProviderError.ts
var NotWaasWalletProviderError = class extends BaseError {
	constructor({ walletProviderKey }) {
		super({
			cause: null,
			code: "not_waas_wallet_provider_error",
			docsUrl: null,
			name: "NotWaasWalletProviderError",
			shortMessage: `Wallet provider ${walletProviderKey} is not a Dynamic WaaS wallet provider`
		});
	}
};

//#endregion
//#region src/errors/CorruptedKeyShareError.ts
/**
* Thrown when a persisted client key share cannot be parsed back into its
* structured form (e.g. a partially-written or corrupted keychain entry).
*
* Surfaced as a typed error rather than swallowed so callers can distinguish
* "no key share stored" (empty result) from "key share exists but is
* unreadable" — the latter must never be silently treated as the former,
* which could trigger an unintended re-keygen that overwrites recoverable
* material.
*/
var CorruptedKeyShareError = class extends BaseError {
	constructor({ cause = null } = {}) {
		super({
			cause,
			code: "corrupted_key_share_error",
			details: "The stored client key share could not be parsed. The secure storage entry may be partially written or corrupted.",
			docsUrl: null,
			name: "CorruptedKeyShareError",
			shortMessage: "Stored client key share is corrupted and cannot be read."
		});
	}
};

//#endregion
//#region src/turboModules/NativeDynamicWebView.ts
var NativeDynamicWebView_default = TurboModuleRegistry.get("DynamicClientWebView");

//#endregion
//#region src/errors/WebViewLoadFailedError.ts
/**
* Thrown when `DynamicWebView.open()` (via the WaaS transport provider)
* fails to establish a usable load. Inspect `reason` to distinguish the
* failure mode; `statusCode` and `underlyingError` provide structured
* metadata for the cases that have it.
*/
var WebViewLoadFailedError = class extends BaseError {
	reason;
	statusCode;
	underlyingError;
	constructor({ reason, shortMessage, cause = null, statusCode, underlyingError }) {
		super({
			cause,
			code: "webview_load_failed_error",
			details: underlyingError,
			docsUrl: null,
			name: "WebViewLoadFailedError",
			shortMessage
		});
		this.reason = reason;
		this.statusCode = statusCode;
		this.underlyingError = underlyingError;
	}
};

//#endregion
//#region src/modules/waas/createWaasClient/translateNativeOpenError.ts
const REASON_BY_NATIVE_CODE = {
	webview_cancelled: "cancelled",
	webview_content_process_terminated: "content_process_terminated",
	webview_http_error: "http_error",
	webview_instance_busy: "instance_busy",
	webview_invalid_url: "invalid_url",
	webview_navigation_failed: "navigation_failed",
	webview_no_host_view: "no_host_view",
	webview_unsupported: "unsupported"
};
/**
* Translates a native `DynamicWebView.open()` rejection into a typed
* `WebViewLoadFailedError`. Maps the native RCT reject code to the JS-level
* `WebViewLoadFailureReason` discriminator (falling back to
* `navigation_failed` for unrecognized codes) and carries through the
* structured `statusCode` / `underlyingError` metadata.
*
* The `reason` it produces is the contract `createWaasSDKContainer` branches
* on — notably `emitError` swallows `cancelled` because that code is only ever
* produced by our own `close()` teardown (verified on both the iOS and Android
* native sides). Keep `REASON_BY_NATIVE_CODE` in sync with the native reject
* codes so that branching stays correct.
*
* @notInstrumented
*/
const translateNativeOpenError = (err) => {
	const rejection = err ?? {};
	const isNativeRejectionCode = (code) => code != void 0 && code in REASON_BY_NATIVE_CODE;
	const reason = isNativeRejectionCode(rejection.code) ? REASON_BY_NATIVE_CODE[rejection.code] : "navigation_failed";
	return new WebViewLoadFailedError({
		cause: err instanceof Error ? err : null,
		reason,
		shortMessage: rejection.message ?? `DynamicWebView open failed (${reason}).`,
		statusCode: rejection.userInfo?.DynamicWebViewStatusCode,
		underlyingError: rejection.userInfo?.DynamicWebViewUnderlying
	});
};

//#endregion
//#region src/modules/waas/createWaasClient/createNativeWaasSDKContainer.native.ts
const NATIVE_MODULE_NAME = "DynamicClientWebView";
const MESSAGE_EVENT_NAME = "dynamicBridgeMessage";
const generateInstanceId = () => `${Date.now().toString(36)}-${crypto.randomUUID()}`;
/**
* Creates a React Native `WaasSDKContainer` backed by a hidden, headless native
* WebView (WKWebView on iOS, `android.webkit.WebView` on Android) hosted by the
* `DynamicClientWebView` TurboModule. Each invocation returns an isolated
* container with its own instance ID, native WebView, and message routing.
*
* Used for MPC operations (signing, key-share management) where there is
* nothing for the user to see. The VISIBLE private-key export display is no
* longer a native overlay — it is rendered by the `ExportPrivateKey` component
* (`@dynamic-labs-sdk/react-native-embedded-wallet-export`) on top of
* `react-native-webview`, so it scrolls and positions like any RN view.
*
* @notInstrumented
*/
const createNativeWaasSDKContainer = () => {
	if (!NativeDynamicWebView_default) throw new NativeModuleNotLinkedError({ moduleName: NATIVE_MODULE_NAME });
	const nativeModule = NativeDynamicWebView_default;
	const instanceId = generateInstanceId();
	const emitter = new NativeEventEmitter(nativeModule);
	const messageHandlers = [];
	const errorHandlers = [];
	let subscription = null;
	let destroyed = false;
	const emitError = (err) => {
		if (destroyed) return;
		const translated = translateNativeOpenError(err);
		if (translated.reason === "cancelled") return;
		for (const handler of errorHandlers) handler(translated);
	};
	return {
		destroy() {
			if (destroyed) return;
			destroyed = true;
			subscription?.remove();
			subscription = null;
			messageHandlers.length = 0;
			errorHandlers.length = 0;
			nativeModule.close(instanceId);
		},
		isAlive: () => !destroyed,
		onError(handler) {
			errorHandlers.push(handler);
			return () => {
				const index = errorHandlers.indexOf(handler);
				if (index !== -1) errorHandlers.splice(index, 1);
			};
		},
		onMessage(handler) {
			messageHandlers.push(handler);
			subscription ??= emitter.addListener(MESSAGE_EVENT_NAME, (payload) => {
				if (payload.instanceId !== instanceId) return;
				for (const fn of messageHandlers) fn(payload.data);
			});
			return () => {
				const index = messageHandlers.indexOf(handler);
				if (index !== -1) messageHandlers.splice(index, 1);
				if (messageHandlers.length === 0) {
					subscription?.remove();
					subscription = null;
				}
			};
		},
		sendMessage(data) {
			nativeModule.sendMessage(instanceId, data);
		},
		async setUrl(url) {
			nativeModule.open(instanceId, url).catch(emitError);
		}
	};
};

//#endregion
//#region src/modules/waas/createWaasClient/createWaasSDKContainer.native.ts
/**
* Creates a React Native `WaasSDKContainer` backed by a hidden, headless native
* WebView (WKWebView on iOS, `android.webkit.WebView` on Android) hosted by the
* `DynamicClientWebView` TurboModule. Used for MPC operations (signing, key-share
* management) where there is nothing for the user to see.
*
* For the private-key export display — where the hosted page must render the
* key for the user — use the `ExportPrivateKey` component from
* `@dynamic-labs-sdk/react-native-embedded-wallet-export`, which renders the
* key inside a `react-native-webview` instead of a native overlay.
*
* @notInstrumented
*/
const createWaasSDKContainer = () => createNativeWaasSDKContainer();

//#endregion
//#region src/modules/waas/createWaasClient/createWaasClient.native.ts
/**
* Keychain security options for the client key share. The share is wallet
* key material that cannot be re-derived locally, so the options are pinned
* explicitly rather than inherited from `react-native-keychain` defaults
* (which vary across versions and platforms).
*
* `WHEN_UNLOCKED_THIS_DEVICE_ONLY` keeps the share readable only while the
* device is unlocked, excludes it from iCloud Keychain sync, and prevents it
* migrating to a new device on encrypted-backup restore. It deliberately does
* NOT set `accessControl` (e.g. biometry) — reads must not surface a Face ID /
* passcode prompt, since the share is read on routine wallet operations.
*/
const KEY_SHARE_KEYCHAIN_OPTIONS = { accessible: ACCESSIBLE.WHEN_UNLOCKED_THIS_DEVICE_ONLY };
/** @notInstrumented */
const createWaasClient = ({ chainName }, client) => {
	const core = getCore(client);
	const additionalTrustedOrigins = core.waas?.additionalTrustedOrigins;
	const getKeyShareService = (accountAddress) => `${core.environmentId}:${accountAddress}`;
	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,
		environmentId: core.environmentId,
		hostOrigin: core.metadata?.universalLink,
		sdkVersion: `${CLIENT_SDK_NAME}/${core.version}`,
		...additionalTrustedOrigins == void 0 ? {} : { additionalTrustedOrigins },
		...core.waas?.loadTimeoutMs == void 0 ? {} : { iframeLoadTimeout: core.waas.loadTimeoutMs },
		...core.waas?.maxLoadRetries == void 0 ? {} : { maxRetryAttempts: core.waas.maxLoadRetries }
	}, {
		createWaasSDKContainer,
		secureStorage: {
			getClientKeyShare: async (accountAddress) => {
				const result = await getGenericPassword({ service: getKeyShareService(accountAddress) });
				if (!result) return [];
				try {
					return JSON.parse(result.password);
				} catch (cause) {
					throw new CorruptedKeyShareError({ cause: cause instanceof Error ? cause : null });
				}
			},
			removeClientKeyShare: async (accountAddress) => {
				await resetGenericPassword({ service: getKeyShareService(accountAddress) });
			},
			setClientKeyShare: async (accountAddress, shares) => {
				await setGenericPassword(accountAddress, JSON.stringify(shares), {
					...KEY_SHARE_KEYCHAIN_OPTIONS,
					service: getKeyShareService(accountAddress)
				});
			}
		}
	});
};

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

//#endregion
//#region src/modules/waas/getWaasWalletProviderFromWalletAccount/getWaasWalletProviderFromWalletAccount.ts
/** @notInstrumented */
const getWaasWalletProviderFromWalletAccount = ({ walletAccount }, client) => {
	const walletProvider = getWalletProviderFromWalletAccount({ walletAccount }, client);
	if (!isWaasWalletProvider(walletProvider)) throw new NotWaasWalletAccountError({ walletAddress: walletAccount.address });
	return walletProvider;
};

//#endregion
//#region src/modules/waas/migrateFromFireblocks/migrateFromFireblocks.ts
/**
* Migrates an existing Fireblocks NCW wallet into Dynamic's WaaS infrastructure.
*
* Migration is a single cross-chain operation: one call takes over the Fireblocks
* key material and provisions Dynamic WaaS wallet accounts for every supported
* chain. Because it is not per-chain, this resolves a single WaaS wallet provider
* (any registered chain) and delegates the takeover to it.
*
* @param params.deviceId - The Fireblocks NCW device id being migrated.
* @param params.jwt - The Fireblocks-issued JWT authorizing the takeover.
* @param params.storage - The serialized Fireblocks NCW device storage.
* @param params.password - The password that encrypted the legacy device storage.
* @param params.expectedAddresses - Required per-chain expected address; its keys are the chains migration runs on, and each imported address is verified against it.
* @param [params.coinTypes] - Optional SLIP-0044 coin types per chain name.
* @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
* @returns A promise resolving to the per-chain migration results.
* @notInstrumented
*/
const migrateFromFireblocks = async ({ coinTypes, deviceId, expectedAddresses, jwt, password, storage }, client = getDefaultClient()) => {
	const providers = getWalletProviders(client);
	if (providers.length === 0) throw new NoWalletProviderFoundError({ walletProviderKey: DYNAMIC_WAAS_METADATA.displayName });
	const waasProvider = providers.find(isWaasWalletProvider);
	if (!waasProvider) throw new NotWaasWalletProviderError({ walletProviderKey: providers[0].key });
	const result = await waasProvider.migrateFromFireblocks({
		coinTypes,
		deviceId,
		expectedAddresses,
		jwt,
		password,
		storage
	});
	await __refreshAuth_wrapped(client);
	return result;
};

//#endregion
export { NotWaasWalletProviderError as a, createWaasClient as i, getWaasWalletProviderFromWalletAccount as n, getWaasChainNameFromChain as r, migrateFromFireblocks as t };
//# sourceMappingURL=migrateFromFireblocks-hfh_j7wm.native.esm.js.map