'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../../../_virtual/_tslib.cjs');
var React = require('react');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var utils = require('@dynamic-labs/utils');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('../../../../context/DynamicContext/DynamicContext.cjs');
require('../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('react/jsx-runtime');
require('../../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
var localStorage = require('../../../constants/localStorage.cjs');
require('../../../constants/colors.cjs');
require('../../../constants/values.cjs');
require('../../../../shared/consts/index.cjs');
require('../../../../events/dynamicEvents.cjs');
require('../../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../../context/ErrorContext/ErrorContext.cjs');
var findEmbeddedWalletFromVerifiedCredentials = require('../../../functions/findEmbeddedWalletFromVerifiedCredentials/findEmbeddedWalletFromVerifiedCredentials.cjs');
var findTurnkeyWallet = require('../../../functions/findTurnkeyWallet/findTurnkeyWallet.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
var getUserWalletsFromVerifiedCredentials = require('../../../functions/getUserWalletsFromVerifiedCredentials/getUserWalletsFromVerifiedCredentials.cjs');
require('../../../../store/state/nonce/nonce.cjs');
var addPasskeyIdentifierToWalletConnector = require('../../../functions/addPasskeyIdentifierToWalletConnector/addPasskeyIdentifierToWalletConnector.cjs');
var getUserVerifiedCredentialType = require('../../../functions/getUserVerifiedCredentialType/getUserVerifiedCredentialType.cjs');
var hasEmbeddedWallet = require('../../../functions/hasEmbeddedWallet/hasEmbeddedWallet.cjs');
var getEmbeddedWalletAuthHandler = require('../../../functions/getEmbeddedWalletAuthHandler/getEmbeddedWalletAuthHandler.cjs');
var getEmbeddedWalletSessionExpiration = require('../../../functions/getEmbeddedWalletSessionExpiration/getEmbeddedWalletSessionExpiration.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../../config/ApiEndpoint.cjs');
var embeddedWallets = require('../../../../data/api/embeddedWallets/embeddedWallets.cjs');
require('@dynamic-labs/locale');
var user = require('../../../../data/api/user/user.cjs');
require('../../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
var turnkeyExport = require('../../../../views/EmbeddedReveal/utils/turnkeyExport/turnkeyExport.cjs');
var errors = require('../../../constants/errors.cjs');
require('../../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../../context/AccountExistsContext/AccountExistsContext.cjs');
var UserWalletsContext = require('../../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../../store/state/authMode/authMode.cjs');
require('../../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
var useElementById = require('../../useElementById/useElementById.cjs');
require('../../../functions/compareChains/compareChains.cjs');
var findPrimaryEmbeddedChain = require('../../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
var getTurnkeyWalletId = require('../../../functions/getTurnkeyWalletId/getTurnkeyWalletId.cjs');
require('../../../../context/ThemeContext/ThemeContext.cjs');
var useSmartWallets = require('../../useSmartWallets/useSmartWallets.cjs');
require('../../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
var usePasskeyRecovery = require('../../usePasskeyRecovery/usePasskeyRecovery.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../../context/LoadingContext/LoadingContext.cjs');
var WalletContext = require('../../../../context/WalletContext/WalletContext.cjs');
var useIsTurnkeyWallet = require('../../useIsTurnkeyWallet/useIsTurnkeyWallet.cjs');
var passkeyRecovery = require('../../../../views/Passkey/utils/passkeyRecovery/passkeyRecovery.cjs');
var getNewVerifiedCredentialsFromDiff = require('../../../functions/getNewVerifiedCredentialsFromDiff/getNewVerifiedCredentialsFromDiff.cjs');
var validateTurnkeyProviderEnabled = require('../../../validations/validateTurnkeyProviderEnabled/validateTurnkeyProviderEnabled.cjs');
var constants = require('./constants.cjs');
var useTurnkey = require('./useTurnkey/useTurnkey.cjs');
require('yup');
require('../../../../context/MockContext/MockContext.cjs');
require('../../../../views/CollectUserDataView/useFields.cjs');
require('../../../../context/FieldsStateContext/FieldsStateContext.cjs');
require('../../../../context/UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
require('../../../../store/state/walletOptions/walletOptions.cjs');
require('react-i18next');
require('../../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../../components/Alert/Alert.cjs');
require('../../../../components/ShadowDOM/ShadowDOM.cjs');
require('../../../../components/IconButton/IconButton.cjs');
require('../../../../components/InlineWidget/InlineWidget.cjs');
require('../../../../components/Input/Input.cjs');
require('../../../../components/IsBrowser/IsBrowser.cjs');
require('../../../../components/MenuList/Dropdown/Dropdown.cjs');
require('../../../../components/OverlayCard/OverlayCard.cjs');
require('../../../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../../../components/Popper/Popper/Popper.cjs');
require('../../../../components/Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../../useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../../context/FooterAnimationContext/index.cjs');
require('../../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../../../context/PasskeyContext/PasskeyContext.cjs');
require('../../../../context/OnrampContext/OnrampContext.cjs');
require('../../../../store/state/sendBalances.cjs');
require('../../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../../index.cjs');
require('../../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../../store/state/tokenBalances.cjs');
require('../../../../store/state/multichainBalances.cjs');
require('../../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useInternalDynamicContext = require('../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');

const isConnectorSessionKeyActive = (connector) => {
    var _a;
    if (!connector || !walletConnectorCore.isSessionKeyCompatibleWalletConnector(connector))
        return false;
    return Boolean((_a = connector.sessionKeys) === null || _a === void 0 ? void 0 : _a.publicKey);
};
// Hook exposed to customers
/**
 *
 * @returns {
 * createEmbeddedWallet, - creates Secure enclave embedded wallet according to the settings
 * createOrRestoreSession, - creates or restores a embedded wallet session
 * createPasskey, - creates a new passkey both for an existing wallet or a wallet to be created
 * getPasskeys, - gets all passkeys for the user
 * isLoadingEmbeddedWallet, - loading state of the embedded wallet
 * isSessionActive, - checks if the embedded wallet session is active
 * revealEmbeddedWalletKey - export the recovery phrase or private key of the embedded wallet
 * sendOneTimeCode, - sends a one-time code to the user so they can create a session or add a new passkey
 * userHasEmbeddedWallet, - checks if the user has an embedded wallet
 * }
 */
const useSecureEnclaveEmbeddedWallet = () => {
    var _a, _b, _c, _d, _e;
    const { projectSettings, primaryWallet, user: user$1, environmentId, walletConnectorOptions, } = useInternalDynamicContext.useInternalDynamicContext();
    const { addedWalletsIds } = UserWalletsContext.useInternalUserWallets();
    const { createTurnkeyWallet } = useTurnkey.useTurnkey();
    const { hasRecoveryEmail } = useIsTurnkeyWallet.useIsTurnkeyWallet();
    const { createRootElement } = useElementById.useElementById();
    const { isLoadingEmbeddedWallet, setIsLoadingEmbeddedWallet } = WalletContext.useWalletContext();
    const { getEOAWallet } = useSmartWallets.useSmartWallets();
    const wallet = (_a = (primaryWallet && getEOAWallet(primaryWallet))) !== null && _a !== void 0 ? _a : primaryWallet;
    const userHasEmbeddedWallet = React.useCallback(() => hasEmbeddedWallet.hasEmbeddedWallet(user$1, 'turnkey'), [user$1]);
    const getWalletVersion = React.useCallback(() => {
        if (walletConnectorCore.isSessionKeyCompatibleWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
            return constants.EmbeddedWalletVersion.V2;
        }
        return constants.EmbeddedWalletVersion.V1;
    }, [wallet === null || wallet === void 0 ? void 0 : wallet.connector]);
    const { shouldInitRecovery, initPasskeyRecoveryProcess } = usePasskeyRecovery.usePasskeyRecovery();
    /**
     * Creates a new secure enclave embedded wallet according to the settings from the dashboard
     * @param chain - optional chain parameter to create the wallet for
     * @param options - optional parameter contained more settings for the wallet creation
     * @returns Promise<Wallet | undefined>
     */
    const createEmbeddedWallet = React.useCallback((chains, options) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _f;
        if (!user$1) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        }
        const userWalletsCredentials = getUserWalletsFromVerifiedCredentials.getUserWalletsFromVerifiedCredentials(user$1);
        const primaryChain = findPrimaryEmbeddedChain.findPrimaryEmbeddedChain(projectSettings);
        const embeddedWalletVerifiedCredential = findEmbeddedWalletFromVerifiedCredentials.findEmbeddedWalletFromVerifiedCredentials(user$1, chains !== null && chains !== void 0 ? chains : [primaryChain]);
        const isManualMode = ((_f = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _f === void 0 ? void 0 : _f.automaticEmbeddedWalletCreation) === false;
        // if user has a wallet and it's not embedded,
        // throw error to follow another flow and set up the right wallet
        // However, if the user is in manual mode continue.
        if ((userWalletsCredentials === null || userWalletsCredentials === void 0 ? void 0 : userWalletsCredentials.length) &&
            !embeddedWalletVerifiedCredential &&
            !isManualMode) {
            throw new utils.EmbeddedWalletException('User already has a linked branded wallet, and manual mode creation is not enabled.');
        }
        validateTurnkeyProviderEnabled.validateTurnkeyProviderEnabled(projectSettings);
        // TEMP: immediately disable loading state
        setIsLoadingEmbeddedWallet(false);
        return createTurnkeyWallet(chains, options);
    }), [createTurnkeyWallet, projectSettings, setIsLoadingEmbeddedWallet, user$1]);
    /**
     * Creates a new secure enclave embedded wallet account
     * @param chain - chain parameter to create the wallet for
     * @returns Promise<UserProfile | undefined>
     */
    const createEmbeddedWalletAccount = React.useCallback((_g) => _tslib.__awaiter(void 0, [_g], void 0, function* ({ chain }) {
        var _h, _j, _k;
        if (!user$1) {
            throw new Error(errors.USER_NOT_LOGGED_IN);
        }
        validateTurnkeyProviderEnabled.validateTurnkeyProviderEnabled(projectSettings);
        const primaryChain = findPrimaryEmbeddedChain.findPrimaryEmbeddedChain(projectSettings);
        const embeddedWalletVerifiedCredential = findEmbeddedWalletFromVerifiedCredentials.findEmbeddedWalletFromVerifiedCredentials(user$1, [primaryChain]);
        const turnkeyWalletId = (_h = embeddedWalletVerifiedCredential === null || embeddedWalletVerifiedCredential === void 0 ? void 0 : embeddedWalletVerifiedCredential.walletProperties) === null || _h === void 0 ? void 0 : _h.turnkeyHDWalletId;
        if (!turnkeyWalletId) {
            throw new utils.DynamicError('No HD wallet was found for this user to derive a wallet account. Use createEmbeddedWallet first', 'NoHdWalletFound');
        }
        const requestToStamp = yield embeddedWallets.getCreateEmbeddedWalletAccountRequest({
            chain,
            environmentId,
        });
        if (walletConnectorCore.isSessionKeyCompatibleWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
            yield ((_j = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _j === void 0 ? void 0 : _j.createOrRestoreSession({
                ignoreRestore: true,
            }));
        }
        else if (yield shouldInitRecovery()) {
            yield initPasskeyRecoveryProcess('email');
        }
        const signedRequest = yield ((_k = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _k === void 0 ? void 0 : _k.stampCreateWalletAccountRequest({
            request: requestToStamp,
        }));
        const verifiedUser = yield embeddedWallets.createEmbeddedWalletAccount({
            createEmbeddedWalletAccountRequest: signedRequest,
            environmentId,
        });
        const newWalletIds = getNewVerifiedCredentialsFromDiff.getNewVerifiedCredentialsFromDiff(user$1.verifiedCredentials, verifiedUser.user.verifiedCredentials)
            .filter(({ format }) => format === sdkApiCore.JwtVerifiedCredentialFormatEnum.Blockchain)
            .map(({ id }) => id);
        addedWalletsIds.current = addedWalletsIds.current.concat(newWalletIds);
        return user.refreshUserJwt({ environmentId });
    }), [
        environmentId,
        wallet === null || wallet === void 0 ? void 0 : wallet.connector,
        initPasskeyRecoveryProcess,
        projectSettings,
        shouldInitRecovery,
        user$1,
        addedWalletsIds,
    ]);
    /**
     * Creates or restores a secure enclave embedded wallet session
     * If it detects that the session is possible to be restored, it will restore it
     * @param oneTimeCode - optional one-time code parameter. If not informed it tries to restore a session
     * @returns Promise<'session_created' | 'session_restored'> - returns a string indicating the status of the session
     */
    const createOrRestoreSession = React.useCallback((options) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _l, _m, _o, _p, _q, _r, _s;
        if (!user$1) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        }
        const primaryConnector = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector;
        if (primaryConnector &&
            walletConnectorCore.isSessionKeyCompatibleWalletConnector(primaryConnector)) {
            return primaryConnector.createOrRestoreSession();
        }
        const eoaConnector = wallet === null || wallet === void 0 ? void 0 : wallet.connector;
        if (eoaConnector && walletConnectorCore.isSessionKeyCompatibleWalletConnector(eoaConnector)) {
            return eoaConnector.createOrRestoreSession();
        }
        const turnkeyRecoveryHandler = getEmbeddedWalletAuthHandler.getEmbeddedWalletAuthHandler(wallet === null || wallet === void 0 ? void 0 : wallet.connector);
        if (turnkeyRecoveryHandler.isSessionActive()) {
            return errors.ACTIVE_SESSION;
        }
        const turnkeyAuthIframeContainerRef = createRootElement(constants.iframeContainerId);
        // try to restore session if possible
        if (passkeyRecovery.canRestoreEmbeddedWalletSession((_l = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _l === void 0 ? void 0 : _l.sessionKeyDuration)) {
            try {
                const sessionRestored = yield passkeyRecovery.restoreEmbeddedWalletSession({
                    iframeContainer: turnkeyAuthIframeContainerRef.current,
                    iframeElementId: constants.iframeElementId,
                    sessionExpiration: getEmbeddedWalletSessionExpiration.getEmbeddedWalletSessionExpiration((_o = (_m = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _m === void 0 ? void 0 : _m.embeddedWallets) === null || _o === void 0 ? void 0 : _o.sessionKeyDuration),
                    user: user$1,
                    wallet: primaryWallet,
                });
                if (sessionRestored)
                    return errors.SESSION_RESTORED;
            }
            catch (err) {
                logger.logger.error('Failed to restore embedded wallet', err);
            }
        }
        if (!(options === null || options === void 0 ? void 0 : options.oneTimeCode)) {
            throw new utils.DynamicError('One-time code is required to create a session.', errors.INVALID_REQUEST);
        }
        // tries to create a new session with the informed one-time code
        // verify user has a turnkey wallet and email VC
        if (!userHasEmbeddedWallet() || !hasRecoveryEmail) {
            throw new utils.DynamicError('User does not have a secure enclave wallet or a verified email', errors.INVALID_WALLET_DATA);
        }
        if (!primaryWallet) {
            throw new utils.DynamicError('No primary wallet found');
        }
        const primaryTurnkeyWalletId = getTurnkeyWalletId.getTurnkeyWalletId(primaryWallet.id, (user$1 === null || user$1 === void 0 ? void 0 : user$1.verifiedCredentials) || []);
        const organizationId = (_s = (_r = (_q = (_p = user$1 === null || user$1 === void 0 ? void 0 : user$1.verifiedCredentials) === null || _p === void 0 ? void 0 : _p.find(({ walletName, id }) => (walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey')) && id === primaryTurnkeyWalletId)) === null || _q === void 0 ? void 0 : _q.walletProperties) === null || _r === void 0 ? void 0 : _r.turnkeySubOrganizationId) !== null && _s !== void 0 ? _s : undefined;
        yield turnkeyRecoveryHandler.verifyRecoveryCode(options.oneTimeCode, organizationId);
        const sessionSettings = {
            createdAt: new Date().getTime(),
            emailCode: options.oneTimeCode,
            userId: turnkeyRecoveryHandler.recoveryUserId,
        };
        utils.StorageService.setItem(localStorage.EMBEDDED_WALLET_SESSION_SETTINGS, sessionSettings);
        return errors.SESSION_CREATED;
    }), [
        createRootElement,
        user$1,
        hasRecoveryEmail,
        primaryWallet,
        (_c = (_b = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _b === void 0 ? void 0 : _b.embeddedWallets) === null || _c === void 0 ? void 0 : _c.sessionKeyDuration,
        userHasEmbeddedWallet,
        wallet === null || wallet === void 0 ? void 0 : wallet.connector,
    ]);
    /**
     * Creates a new passkey both for an existing wallet or a wallet to be created
     * @param options - optional parameter to inform a one-time code to create a session,
     * @returns Promise<WebAuthnAttestation>
     */
    const createPasskey = React.useCallback((options) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _t, _u;
        if (!user$1) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        }
        validateTurnkeyProviderEnabled.validateTurnkeyProviderEnabled(projectSettings);
        const turnkeyWallet = findTurnkeyWallet.findTurnkeyWalletByPrimaryChain(walletConnectorOptions, (_t = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _t === void 0 ? void 0 : _t.chainConfigurations, user$1.verifiedCredentials);
        if (!(turnkeyWallet === null || turnkeyWallet === void 0 ? void 0 : turnkeyWallet.walletConnector)) {
            throw new utils.DynamicError('Wallet connector not found', errors.INVALID_WALLET_DATA);
        }
        const walletConnector = turnkeyWallet.walletConnector;
        walletConnector.setEmail(user$1 === null || user$1 === void 0 ? void 0 : user$1.email);
        if (user$1 && !(user$1 === null || user$1 === void 0 ? void 0 : user$1.email)) {
            addPasskeyIdentifierToWalletConnector.addPasskeyIdentifierToWalletConnector(walletConnector, user$1);
        }
        const hasEmailVC = getUserVerifiedCredentialType.getUserVerifiedCredentialType(user$1, sdkApiCore.JwtVerifiedCredentialFormatEnum.Email);
        // return a new passkey if the user doesn't have a wallet yet or
        // none of the requirements to add a passkey to an existing wallet are met
        if (!('id' in turnkeyWallet) || !hasEmailVC) {
            return walletConnector.getWebAuthnAttestation();
        }
        const turnkeySubOrganizationId = (_u = turnkeyWallet === null || turnkeyWallet === void 0 ? void 0 : turnkeyWallet.walletProperties) === null || _u === void 0 ? void 0 : _u.turnkeySubOrganizationId;
        if (!turnkeySubOrganizationId) {
            throw new utils.DynamicError('No sub organization id found for the wallet', errors.INVALID_WALLET_DATA);
        }
        const turnkAuthenticatorHandler = getEmbeddedWalletAuthHandler.getEmbeddedWalletAuthHandler(walletConnector);
        // add new passkey to the wallet through an active session
        yield createOrRestoreSession(options);
        const { attestation, challenge, displayName } = yield walletConnector.getWebAuthnAttestation();
        yield turnkAuthenticatorHandler.addPasskeyAuthenticator({
            attestation,
            challenge,
            turnkeySubOrganizationId,
        });
        const updatedUser = yield embeddedWallets.completePasskeyRecovery({
            attestation: attestation,
            challenge,
            environmentId,
            walletId: turnkeyWallet === null || turnkeyWallet === void 0 ? void 0 : turnkeyWallet.id,
        });
        if (!updatedUser) {
            throw new utils.DynamicError('Error completing passkey recovery');
        }
        return { attestation, challenge, displayName };
    }), [
        createOrRestoreSession,
        environmentId,
        projectSettings,
        user$1,
        walletConnectorOptions,
    ]);
    /**
     * Gets all passkeys for the user
     * @returns Promise<Passkey[]>
     */
    const getPasskeys = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!user$1) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        }
        const data = yield embeddedWallets.getUserPasskeys({
            environmentId: environmentId,
        });
        return data.passkeys;
    }), [user$1, environmentId]);
    const isEmailAuthSessionActive = React.useMemo(() => {
        var _a;
        const eoaConnector = wallet === null || wallet === void 0 ? void 0 : wallet.connector;
        if (!eoaConnector || !('getAuthenticatorHandler' in eoaConnector))
            return false;
        return (_a = getEmbeddedWalletAuthHandler.getEmbeddedWalletAuthHandler(eoaConnector)) === null || _a === void 0 ? void 0 : _a.isSessionActive();
    }, [wallet === null || wallet === void 0 ? void 0 : wallet.connector]);
    const isSessionKeySessionAAActive = React.useMemo(() => isConnectorSessionKeyActive(wallet === null || wallet === void 0 ? void 0 : wallet.connector), [wallet === null || wallet === void 0 ? void 0 : wallet.connector]);
    const isSessionKeySessionActive = React.useMemo(() => isConnectorSessionKeyActive(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector), [primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector]);
    /**
     * Checks if the embedded wallet session is active
     */
    const isSessionActive = isEmailAuthSessionActive ||
        isSessionKeySessionActive ||
        isSessionKeySessionAAActive;
    /**
     * export the recovery phrase or private key of the embedded wallet
     * @param options - optional parameter object containing the type of key to reveal 'recoveryPhrase' | 'privateKey'
     * and the html container id to render the iframe into
     * @returns Promise<string> - returns the embedded wallet recovery phrase or private key
     */
    const revealEmbeddedWalletKey = React.useCallback((_v) => _tslib.__awaiter(void 0, [_v], void 0, function* ({ type, htmlContainerId, }) {
        var _w, _x, _y, _z, _0, _1;
        if (!user$1) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        }
        yield turnkeyExport.cleanupExport({
            wallet: wallet,
        });
        const turnkeyWallet = findTurnkeyWallet.findTurnkeyWalletByPrimaryChain(walletConnectorOptions, (_w = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _w === void 0 ? void 0 : _w.chainConfigurations, user$1 === null || user$1 === void 0 ? void 0 : user$1.verifiedCredentials);
        const turnkeyHDWalletId = (_x = turnkeyWallet === null || turnkeyWallet === void 0 ? void 0 : turnkeyWallet.walletProperties) === null || _x === void 0 ? void 0 : _x.turnkeyHDWalletId;
        if (type === 'recoveryPhrase' && !turnkeyHDWalletId) {
            type = 'privateKey';
        }
        const iframeContainerElement = createRootElement(constants.revealIframeElementId, htmlContainerId || constants.revealIframeContainerId);
        // hide the iframe container until the export is done
        // since it will show unrelated turnkey content
        iframeContainerElement.current.style.display = 'none';
        if (walletConnectorCore.isSessionKeyCompatibleWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
            yield ((_y = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _y === void 0 ? void 0 : _y.createOrRestoreSession());
        }
        yield turnkeyExport.initExport({
            iframeContainer: iframeContainerElement.current,
            iframeElementId: constants.revealIframeElementId,
            wallet: wallet,
        });
        try {
            yield turnkeyExport.exportCredential({
                address: type === 'privateKey' ? wallet === null || wallet === void 0 ? void 0 : wallet.address : undefined,
                environmentId,
                user: user$1,
                wallet: wallet,
            });
        }
        catch (err) {
            if (walletConnectorCore.isSessionKeyCompatibleWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector) &&
                ((_z = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _z === void 0 ? void 0 : _z.removeSessionKeys)) {
                yield ((_0 = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _0 === void 0 ? void 0 : _0.removeSessionKeys());
                yield ((_1 = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _1 === void 0 ? void 0 : _1.createOrRestoreSession({
                    ignoreRestore: true,
                }));
                logger.logger.error('[TK - removeSessionKeys] failed to perform revealEmbeddedWalletKey activity', {
                    address: wallet === null || wallet === void 0 ? void 0 : wallet.address,
                    err,
                    userId: user$1 === null || user$1 === void 0 ? void 0 : user$1.userId,
                });
            }
            yield turnkeyExport.exportCredential({
                address: type === 'privateKey' ? wallet === null || wallet === void 0 ? void 0 : wallet.address : undefined,
                environmentId,
                user: user$1,
                wallet: wallet,
            });
        }
        // show the iframe container after the export is done
        // to show the exported content only
        iframeContainerElement.current.style.display = 'block';
        return true;
    }), [
        createRootElement,
        environmentId,
        wallet,
        (_e = (_d = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _d === void 0 ? void 0 : _d.embeddedWallets) === null || _e === void 0 ? void 0 : _e.chainConfigurations,
        user$1,
        walletConnectorOptions,
    ]);
    /**
     * Sends a one-time code to the user so they can create a session or add a new passkey
     * @returns Promise<'code_sent'>
     */
    const sendOneTimeCode = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _2, _3;
        if (!user$1) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        }
        const targetTurnkeyWallet = findTurnkeyWallet.findTurnkeyWalletByPrimaryChain(walletConnectorOptions, (_2 = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _2 === void 0 ? void 0 : _2.chainConfigurations, user$1.verifiedCredentials);
        if (!targetTurnkeyWallet || !('id' in targetTurnkeyWallet)) {
            throw new utils.DynamicError('User does not have a valid secure enclave wallet', errors.INVALID_WALLET_DATA);
        }
        const turnkeyAuthenticatorHandler = getEmbeddedWalletAuthHandler.getEmbeddedWalletAuthHandler(targetTurnkeyWallet === null || targetTurnkeyWallet === void 0 ? void 0 : targetTurnkeyWallet.walletConnector);
        const targetTurnkeyWalletId = targetTurnkeyWallet.id;
        const isSessionActive = turnkeyAuthenticatorHandler.isSessionActive();
        if (isSessionActive) {
            throw new utils.DynamicError('Session is active. No need to create a new one', errors.ACTIVE_SESSION);
        }
        const turnkeyAuthIframeContainerRef = createRootElement(constants.iframeContainerId);
        const publicKey = yield turnkeyAuthenticatorHandler.initRecovery('email', turnkeyAuthIframeContainerRef.current, constants.iframeElementId, getEmbeddedWalletSessionExpiration.getEmbeddedWalletSessionExpiration((_3 = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _3 === void 0 ? void 0 : _3.sessionKeyDuration));
        if (!publicKey) {
            throw new utils.DynamicError(errors.ERROR_SENDING_CODE);
        }
        const response = yield embeddedWallets.initEmbeddedWalletSession({
            authenticatorType: 'email',
            environmentId,
            publicKey,
            walletId: targetTurnkeyWalletId,
        });
        turnkeyAuthenticatorHandler.recoveryUserId = response.turnkeyUserId;
        return errors.CODE_SENT;
    }), [
        createRootElement,
        user$1,
        environmentId,
        projectSettings,
        walletConnectorOptions,
    ]);
    return React.useMemo(() => ({
        createEmbeddedWallet,
        createEmbeddedWalletAccount,
        createOrRestoreSession,
        createPasskey,
        getPasskeys,
        getWalletVersion,
        isLoadingEmbeddedWallet,
        isSessionActive,
        revealEmbeddedWalletKey,
        sendOneTimeCode,
        userHasEmbeddedWallet,
    }), [
        createEmbeddedWallet,
        createEmbeddedWalletAccount,
        createOrRestoreSession,
        createPasskey,
        getPasskeys,
        getWalletVersion,
        isLoadingEmbeddedWallet,
        isSessionActive,
        revealEmbeddedWalletKey,
        sendOneTimeCode,
        userHasEmbeddedWallet,
    ]);
};

exports.isConnectorSessionKeyActive = isConnectorSessionKeyActive;
exports.useSecureEnclaveEmbeddedWallet = useSecureEnclaveEmbeddedWallet;
