import { J as getDefaultClient, N as isCookieEnabled, P as assertDefined, Q as getCore, Z as BaseError, a as DYNAMIC_WAAS_METADATA, f as NoWalletProviderFoundError, h as emitEvent, n as isWaasWalletProvider, p as getChainFromVerifiedCredentialChain, t as InvalidParamError, u as getWalletProviderRegistry } from "./InvalidParamError-BxBgwLQB.native.esm.js";
import { JwtVerifiedCredentialFormatEnum, WalletProviderEnum } from "@dynamic-labs/sdk-api-core";

//#region src/utils/setCookie/setCookie.ts
/**
* Sefelly sets the cookie in the browser.
* @not-instrumented
*/
const setCookie = (cookie) => {
	document.cookie = cookie;
};

//#endregion
//#region src/errors/InvalidWalletProviderKeyError.ts
var InvalidWalletProviderKeyError = class extends BaseError {
	constructor(value) {
		super({
			cause: null,
			code: "invalid_wallet_provider_key",
			docsUrl: null,
			name: "InvalidWalletProviderKeyError",
			shortMessage: `Invalid wallet provider key: ${value}. Key must be in the format of <normalizedWalletNameWithChain>:<walletProviderType>[:<suffix>]`
		});
	}
};

//#endregion
//#region src/modules/wallets/walletProvider/splitWalletProviderKey/splitWalletProviderKey.ts
/** @not-instrumented */
const splitWalletProviderKey = (walletProviderKey) => {
	const [normalizedWalletNameWithChain, walletProviderType, suffix, ...rest] = walletProviderKey.split(":");
	if (!normalizedWalletNameWithChain || !Object.values(WalletProviderEnum).includes(walletProviderType) || rest.length > 0) throw new InvalidWalletProviderKeyError(walletProviderKey);
	return {
		normalizedWalletNameWithChain,
		suffix,
		walletProviderType
	};
};

//#endregion
//#region src/modules/wallets/utils/normalizeAddress/normalizeAddress.ts
/** @not-instrumented */
const normalizeAddress = ({ address, chain }) => {
	let normalizedAddress = address;
	if (normalizedAddress?.startsWith("0x")) normalizedAddress = normalizedAddress.slice(2);
	normalizedAddress = ["EVM", "FLOW"].includes(chain) ? normalizedAddress?.toLowerCase() : normalizedAddress;
	return normalizedAddress;
};

//#endregion
//#region src/modules/wallets/utils/formatWalletAccountId/formatWalletAccountId.ts
/** @not-instrumented */
const formatWalletAccountId = ({ address, chain, walletProviderKey }) => {
	const { normalizedWalletNameWithChain } = splitWalletProviderKey(walletProviderKey);
	return `${normalizedWalletNameWithChain}:${normalizeAddress({
		address,
		chain
	})}`;
};

//#endregion
//#region src/modules/wallets/utils/convertUnverifiedWalletAccountToWalletAccount/convertUnverifiedWalletAccountToWalletAccount.ts
/** @not-instrumented */
const convertUnverifiedWalletAccountToWalletAccount = ({ unverifiedWalletAccount }) => ({
	address: unverifiedWalletAccount.address,
	addressesWithTypes: unverifiedWalletAccount.addressesWithTypes,
	chain: unverifiedWalletAccount.chain,
	id: formatWalletAccountId({
		address: unverifiedWalletAccount.address,
		chain: unverifiedWalletAccount.chain,
		walletProviderKey: unverifiedWalletAccount.walletProviderKey
	}),
	lastSelectedAt: unverifiedWalletAccount.lastSelectedAt,
	verifiedCredentialId: null,
	walletProviderKey: unverifiedWalletAccount.walletProviderKey
});

//#endregion
//#region src/modules/wallets/utils/normalizeWalletNameWithChain/normalizeWalletNameWithChain.ts
/**
* Format the raw wallet name and chain to get the value we can use for
* verified credentials' `walletName` field.
* @not-instrumented
*/
const normalizeWalletNameWithChain = ({ displayName, chain }) => {
	const sanitizedWalletName = displayName.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
	const chainLowered = chain.toLocaleLowerCase();
	if (sanitizedWalletName.endsWith(chainLowered)) return sanitizedWalletName;
	return `${sanitizedWalletName}${chainLowered}`;
};

//#endregion
//#region src/modules/wallets/utils/formatWalletProviderKey/formatWalletProviderKey.ts
/**
* Assembles the wallet provider key from the wallet name, chain, and wallet provider type.
*
* The suffix is optional and can be used to add a uniquely identifying string to the key, which
* might be necessary for some wallet providers (like Wallet Connect).
*
* IMPORTANT: Do NOT add a suffix unless absolutely necessary, as it will cause the wallet account
* to not be able to find its wallet provider when connecting to a new device (it won't be possible
* to determine the full key just from the Verified Credential data).
* @not-instrumented
*/
const formatWalletProviderKey = ({ suffix, chain, displayName, walletProviderType }) => {
	return `${normalizeWalletNameWithChain({
		chain,
		displayName
	})}:${walletProviderType}${suffix ? `:${suffix}` : ""}`;
};

//#endregion
//#region src/modules/wallets/walletProvider/walletProviderKeyMap/getWalletProviderKeyFromVerifiedCredential/getWalletProviderKeyFromVerifiedCredential.ts
/** @not-instrumented */
const getWalletProviderKeyFromVerifiedCredential = ({ verifiedCredential }, client) => {
	const { walletProviderKeyMap } = getCore(client).state.get();
	const storedWalletProviderKey = walletProviderKeyMap[verifiedCredential.id];
	if (storedWalletProviderKey) return { walletProviderKey: storedWalletProviderKey };
	/**
	* We fallback to comprising the wallet provider key from walletName and walletProvider.
	*
	* Some wallet provider types (like Wallet Connect) also use a special suffix for their wallet provider
	* keys, so this won't be enough for them.
	* Therefore, for those specific wallet providers, the wallet account will remain without a wallet provider
	* and will require reconnection.
	* Read walletProvider.types.ts for more info.
	*/
	assertDefined(verifiedCredential.walletName, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing walletName`);
	assertDefined(verifiedCredential.walletProvider, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing walletProvider`);
	assertDefined(verifiedCredential.chain, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing chain`);
	return { walletProviderKey: formatWalletProviderKey({
		chain: getChainFromVerifiedCredentialChain(verifiedCredential.chain),
		displayName: verifiedCredential.walletName,
		walletProviderType: verifiedCredential.walletProvider
	}) };
};

//#endregion
//#region src/modules/wallets/utils/convertVerifiedCredentialToWalletAccount/convertVerifiedCredentialToWalletAccount.ts
/** @not-instrumented */
const convertVerifiedCredentialToWalletAccount = ({ verifiedCredential }, client) => {
	assertDefined(verifiedCredential.address, "Missing address in verified credential");
	assertDefined(verifiedCredential.chain, "Missing chain in verified credential");
	const chain = getChainFromVerifiedCredentialChain(verifiedCredential.chain);
	const { walletProviderKey } = getWalletProviderKeyFromVerifiedCredential({ verifiedCredential }, client);
	const walletAccountId = formatWalletAccountId({
		address: verifiedCredential.address,
		chain,
		walletProviderKey
	});
	return {
		address: verifiedCredential.address,
		addressesWithTypes: verifiedCredential.walletAdditionalAddresses,
		chain,
		hardwareWalletVendor: verifiedCredential.walletProperties?.hardwareWallet,
		id: walletAccountId,
		lastSelectedAt: verifiedCredential.lastSelectedAt ?? null,
		verifiedCredentialId: verifiedCredential.id,
		walletProviderKey
	};
};

//#endregion
//#region src/modules/wallets/getWalletAccounts/getWalletAccountsFromState/getWalletAccountsFromState.ts
/** @not-instrumented */
const getWalletAccountsFromState = ({ unverifiedWalletAccounts, user }, client) => {
	const walletAccountsMap = /* @__PURE__ */ new Map();
	/**
	* Handle the unverified wallet accounts before the user verified credentials
	* so the later verified wallet accounts can override the unverified wallet accounts
	*/
	unverifiedWalletAccounts.forEach((unverifiedWalletAccount) => {
		const walletAccount = convertUnverifiedWalletAccountToWalletAccount({ unverifiedWalletAccount });
		walletAccountsMap.set(walletAccount.id, walletAccount);
	});
	(user?.verifiedCredentials ?? []).filter((verified) => verified.format === JwtVerifiedCredentialFormatEnum.Blockchain).forEach((verifiedWalletAccount) => {
		const walletAccount = convertVerifiedCredentialToWalletAccount({ verifiedCredential: verifiedWalletAccount }, client);
		walletAccountsMap.set(walletAccount.id, walletAccount);
	});
	return Array.from(walletAccountsMap.values());
};

//#endregion
//#region src/modules/wallets/getWalletAccounts/getWalletAccounts.ts
/**
* Retrieves all wallet accounts associated with the current session.
*
* This function returns both verified and unverified wallet accounts,
* combining data from user credentials and local unverified accounts.
* You can differentiate between verified and unverified wallet accounts by
* checking the `verifiedCredentialId` property.
*
* @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
* @returns An array of wallet accounts associated with the session.
* @not-instrumented
*/
const getWalletAccounts = (client = getDefaultClient()) => {
	const { unverifiedWalletAccounts, user } = getCore(client).state.get();
	return getWalletAccountsFromState({
		unverifiedWalletAccounts,
		user
	}, client);
};

//#endregion
//#region src/modules/auth/consts.ts
const DYNAMIC_AUTH_COOKIE_NAME = "DYNAMIC_JWT_TOKEN";

//#endregion
//#region src/modules/wallets/emitWalletAccountsChangedEvent/emitWalletAccountsChangedEvent.ts
/**
* Emits the `walletAccountsChanged` event.
* @not-instrumented
*/
const emitWalletAccountsChangedEvent = (client) => {
	emitEvent({
		args: { walletAccounts: getWalletAccounts(client) },
		event: "walletAccountsChanged"
	}, client);
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/checkAndRaiseWalletAccountsChangedEvent/checkAndRaiseWalletAccountsChangedEvent.ts
/** @not-instrumented */
const checkAndRaiseWalletAccountsChangedEvent = ({ previousState }, client) => {
	const core = getCore(client);
	if (getWalletAccountsHash(previousState, client) !== getWalletAccountsHash(core.state.get(), client)) emitWalletAccountsChangedEvent(client);
};
const getWalletAccountsHash = (state, client) => getWalletAccountsFromState(state, client).map((walletAccount) => JSON.stringify(walletAccount)).sort().join("-");

//#endregion
//#region src/modules/mfa/isUserMissingMfaAuth/isUserMissingMfaAuth.ts
/**
* Checks if the user requires additional MFA authentication.
*
* This function determines if the current user session requires
* additional multi-factor authentication to access certain features.
*
* @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
* @returns True if the user needs additional MFA authentication, false otherwise.
* @not-instrumented
*/
const isUserMissingMfaAuth = (client = getDefaultClient()) => {
	const user = client.user;
	assertDefined(user, "User not logged in");
	return Boolean(user.scope?.includes("requiresAdditionalAuth"));
};

//#endregion
//#region src/modules/wallets/getWalletProviders/getWalletProviders.ts
/**
* Get all available wallet providers to interact with internally.
* @not-instrumented
*/
const getWalletProviders = (client) => {
	return getWalletProviderRegistry(client).listProviders();
};

//#endregion
//#region src/modules/waas/findWaasWalletProviderByChain/findWaasWalletProviderByChain.ts
/** @not-instrumented */
const findWaasWalletProviderByChain = ({ chain }, client) => {
	const providers = getWalletProviders(client);
	const waasProviderKey = formatWalletProviderKey({
		chain,
		displayName: DYNAMIC_WAAS_METADATA.displayName,
		walletProviderType: WalletProviderEnum.EmbeddedWallet
	});
	const waasProvider = providers.find((provider) => provider.key === waasProviderKey && provider.chain === chain);
	if (!waasProvider || !isWaasWalletProvider(waasProvider)) return null;
	return waasProvider;
};

//#endregion
//#region src/modules/waas/isWaasWalletAccount/isWaasWalletAccount.ts
/**
* This function determines whether the provided wallet account is a Dynamic
* WaaS wallet account.
*
* @param params.walletAccount - The wallet account to check.
* @returns True if the wallet account is a WaaS wallet account, false otherwise.
* @not-instrumented
*/
const isWaasWalletAccount = ({ walletAccount }) => {
	return walletAccount.walletProviderKey.includes(DYNAMIC_WAAS_METADATA.normalizedWalletName);
};

//#endregion
//#region src/modules/waas/restoreUserSharesForAllWalletAccounts/restoreUserSharesForAllWalletAccounts.ts
/** @not-instrumented */
const restoreUserSharesForAllWalletAccounts = async (client) => {
	/**
	* Restoring the user shares will fails if the user is missing the MFA auth.
	* This early return prevents the attempt to restore the user shares to fail
	* when we know it will fails and just add noise to the logs.
	*/
	if (isUserMissingMfaAuth(client)) return;
	const waasWalletAccounts = getWalletAccounts(client).filter((walletAccount) => isWaasWalletAccount({ walletAccount }));
	await Promise.all(waasWalletAccounts.map(async (walletAccount) => {
		const provider = findWaasWalletProviderByChain({ chain: walletAccount.chain }, client);
		/**
		* The environment might not have the embedded wallet extensions installed.
		* In that case there is no provider for the chain and we can skip restoring the user share.
		*/
		if (!provider) return;
		return provider.restoreUserShareForWalletAccount({ walletAccount });
	}));
};

//#endregion
//#region src/modules/auth/decodeJwt/decodeJwt.ts
/**
* Decodes a JWT token and returns the full payload.
*
* This function extracts and returns the complete JWT payload including scopes,
* expiration time, and other claims.
*
* @param jwt - The JWT token string.
* @returns The decoded JWT payload object.
* @throws InvalidParamError if the token is invalid or cannot be decoded.
*
* @example
* ```typescript
* const payload = decodeJwt(jwt);
* // Returns: { scopes: ['wallet:export'], exp: 1234567890, ... }
* ```
* @not-instrumented
*/
const decodeJwt = (jwt) => {
	try {
		const parts = jwt.split(".");
		if (parts.length !== 3) throw new InvalidParamError("Invalid JWT format");
		const base64Payload = parts[1].replaceAll("-", "+").replaceAll("_", "/");
		const paddedPayload = base64Payload + "=".repeat((4 - base64Payload.length % 4) % 4);
		const decodedPayload = atob(paddedPayload);
		return JSON.parse(decodedPayload);
	} catch (error) {
		if (error instanceof InvalidParamError) throw error;
		throw new InvalidParamError(`Failed to decode JWT: ${error instanceof Error ? error.message : String(error)}`);
	}
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/normalizeScopes/normalizeScopes.ts
/**
* Normalizes scopes by deduplicating and sorting them.
* This creates a canonical representation for comparison.
*
* @param scopes - Array of scope strings (may contain duplicates)
* @returns Normalized, sorted array of unique scopes
* @not-instrumented
*/
const normalizeScopes = (scopes) => {
	return [...new Set(scopes)].sort((a, b) => a.localeCompare(b));
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/parseElevatedAccessToken/parseElevatedAccessToken.ts
/**
* Validates and parses an elevated access token from a JWT string.
* Extracts scopes, expiration, and validates the token structure.
*
* Policy decisions:
* - Tokens without scopes are rejected (returns null)
* - Tokens with empty scopes array are rejected (returns null)
* - Tokens without exp field are rejected (returns null)
* - Expired tokens are rejected (returns null)
*
* @returns Parsed token data or null if token is invalid/expired
* @not-instrumented
*/
const parseElevatedAccessToken = ({ token }) => {
	const payload = decodeJwt(token);
	const filteredScopes = ((payload?.scope)?.split(" ") ?? []).filter((s) => s.length > 0);
	const singleUse = payload.singleUse ?? false;
	if (!filteredScopes || filteredScopes.length === 0) return null;
	if (!payload.exp) return null;
	const expiresAt = /* @__PURE__ */ new Date(payload.exp * 1e3);
	if (expiresAt <= /* @__PURE__ */ new Date()) return null;
	return {
		expiresAt,
		normalizedScopes: normalizeScopes(filteredScopes),
		scopes: filteredScopes,
		singleUse,
		token
	};
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/upsertElevatedAccessToken/upsertElevatedAccessToken.ts
/**
* Upserts an elevated access token into the current tokens array.
*
* Policy: Only one token per normalized scope-set is allowed.
* If a token with the same normalized scopes exists, it is replaced.
* This ensures we don't accumulate multiple tokens for the same scope combination.
*
* @param currentTokens - Current array of elevated access tokens
* @param newToken - New token to upsert
* @returns Updated array of tokens with the new token upserted
* @not-instrumented
*/
const upsertElevatedAccessToken = ({ currentTokens, newToken }) => {
	const newScopeKey = normalizeScopes(newToken.scopes).join(" ");
	return [...currentTokens.filter((existingToken) => {
		return normalizeScopes(existingToken.scopes).join(" ") !== newScopeKey;
	}), {
		expiresAt: newToken.expiresAt,
		scopes: newToken.scopes,
		singleUse: newToken.singleUse,
		token: newToken.token
	}];
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/updateAuthFromVerifyResponse.ts
/** @not-instrumented */
const updateAuthFromVerifyResponse = ({ response }, client) => {
	const core = getCore(client);
	const previousState = { ...core.state.get() };
	const { user, minifiedJwt, jwt, expiresAt, mfaToken, elevatedAccessToken } = response;
	const sessionExpiresAt = /* @__PURE__ */ new Date(expiresAt * 1e3);
	const newState = {
		legacyToken: jwt ?? null,
		sessionExpiresAt,
		token: minifiedJwt ?? null,
		user
	};
	if (mfaToken) newState.mfaToken = mfaToken;
	const currentTokens = core.state.get().elevatedAccessTokens || [];
	newState.elevatedAccessTokens = currentTokens;
	if (elevatedAccessToken) {
		const parsedToken = parseElevatedAccessToken({ token: elevatedAccessToken });
		if (parsedToken) newState.elevatedAccessTokens = upsertElevatedAccessToken({
			currentTokens,
			newToken: parsedToken
		});
	}
	core.state.set(newState);
	/**
	* For customers using a sandbox environment with cookies enabled, we need to set the cookie
	* programmatically because Redcoast won't set the cookie via headers. We set the cookie programmatically
	* so customers can access the cookie from document.cookie consistently between sandbox and live environments.
	*/
	if (minifiedJwt && isCookieEnabled(client)) setCookie(`${DYNAMIC_AUTH_COOKIE_NAME}=${minifiedJwt}; expires=${sessionExpiresAt.toUTCString()}; path=/; SameSite=Lax`);
	checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);
	if (!previousState.user && Boolean(newState.user)) restoreUserSharesForAllWalletAccounts(client);
};

//#endregion
//#region src/modules/wallets/utils/getVerifiedCredentialForWalletAccount/getVerifiedCredentialForWalletAccount.ts
/** @not-instrumented */
const getVerifiedCredentialForWalletAccount = ({ walletAccount }, client) => {
	return client.user?.verifiedCredentials.find((vc) => vc.id === walletAccount.verifiedCredentialId);
};

//#endregion
//#region src/modules/wallets/getWalletProviderByKey/getWalletProviderByKey.ts
/** @not-instrumented */
const getWalletProviderByKey = ({ walletProviderKey }, client) => {
	const walletProvider = getWalletProviders(client).find((walletProvider$1) => walletProvider$1.key === walletProviderKey);
	if (!walletProvider) throw new NoWalletProviderFoundError({ walletProviderKey });
	return walletProvider;
};

//#endregion
export { formatWalletAccountId as _, parseElevatedAccessToken as a, InvalidWalletProviderKeyError as b, findWaasWalletProviderByChain as c, checkAndRaiseWalletAccountsChangedEvent as d, emitWalletAccountsChangedEvent as f, normalizeWalletNameWithChain as g, formatWalletProviderKey as h, upsertElevatedAccessToken as i, getWalletProviders as l, getWalletAccounts as m, getVerifiedCredentialForWalletAccount as n, restoreUserSharesForAllWalletAccounts as o, DYNAMIC_AUTH_COOKIE_NAME as p, updateAuthFromVerifyResponse as r, isWaasWalletAccount as s, getWalletProviderByKey as t, isUserMissingMfaAuth as u, normalizeAddress as v, setCookie as x, splitWalletProviderKey as y };
//# sourceMappingURL=getWalletProviderByKey-C5w8qJ0f.native.esm.js.map