'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');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
var dynamicEvents = require('../../../events/dynamicEvents.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
var errors = require('../../constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
var updatePrimaryWalletId = require('../../functions/updatePrimaryWalletId/updatePrimaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../store/state/authMode/authMode.cjs');
require('../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
var createEmbeddedWalletRequest = require('../../../views/Passkey/utils/createEmbeddedWalletRequest/createEmbeddedWalletRequest.cjs');
var findPasskeyEmailWalletConnector = require('../../../views/Passkey/utils/findPasskeyEmailWalletConnector/findPasskeyEmailWalletConnector.cjs');
var smartWallet = require('../useWalletConnectors/utils/smartWallet/smartWallet.cjs');
var findPrimaryEmbeddedChain = require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
var useEmbeddedWalletSessionKeys = require('../useEmbeddedWalletSessionKeys/useEmbeddedWalletSessionKeys.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
require('../../functions/compareChains/compareChains.cjs');
require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../context/LoadingContext/LoadingContext.cjs');
require('../../../context/WalletContext/WalletContext.cjs');
require('../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.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 getEmbeddedChain = (chainName) => {
    if (chainName === 'SOL')
        return sdkApiCore.EmbeddedWalletChainEnum.Sol;
    if (chainName === 'BTC')
        return sdkApiCore.EmbeddedWalletChainEnum.Btc;
    return sdkApiCore.EmbeddedWalletChainEnum.Evm;
};
// This hook needs to be async that's why it's not using useMutation
const useCreateDynamicEmbeddedWalletMutation = () => {
    var _a, _b;
    const { user, setShowAuthFlow, projectSettings, environmentId } = useInternalDynamicContext.useInternalDynamicContext();
    const [isLoading, setIsLoading] = React.useState(false);
    const [error, setError] = React.useState();
    const { getSessionPublicKey, shouldRegisterSessionKeysOnSignin } = useEmbeddedWalletSessionKeys.useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    const embeddedChainConfig = ((_b = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.embeddedWallets) === null || _b === void 0 ? void 0 : _b.chainConfigurations) || [];
    const primaryEmbeddedChain = findPrimaryEmbeddedChain.findPrimaryEmbeddedChain(projectSettings);
    const embeddedChains = embeddedChainConfig
        .filter((chain) => chain.enabled)
        .map((c) => getEmbeddedChain(c.name));
    const createDynamicEmbeddedWalletMutation = React.useCallback((_c) => _tslib.__awaiter(void 0, [_c], void 0, function* ({ environmentId, walletConnectorOptions, withAuthenticator, options, chains, }) {
        var _d, _e;
        setIsLoading(true);
        if (!user) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        }
        let sessionPublicKey;
        // get the session public key that was created in the login/signup flow
        if (shouldRegisterSessionKeysOnSignin()) {
            sessionPublicKey = getSessionPublicKey();
        }
        try {
            const { embeddedWalletVerifiedCredential, updatedUser, walletConnector, } = yield createEmbeddedWalletRequest.createEmbeddedWalletRequest({
                chains: chains !== null && chains !== void 0 ? chains : embeddedChains,
                environmentId,
                sessionPublicKey,
                user,
                walletConnector: findPasskeyEmailWalletConnector.findPasskeyEmailWalletConnector(walletConnectorOptions, primaryEmbeddedChain),
                webAuthnAttestation: options === null || options === void 0 ? void 0 : options.webAuthnAttestation,
                withAuthenticator,
            });
            const turnkeyVerifiedCredentials = (_d = updatedUser.verifiedCredentials) === null || _d === void 0 ? void 0 : _d.find(({ walletName }) => walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey'));
            /** It's not authenticated if it's a turnkey wallet that still hasn't created a passkey */
            const isAuthenticated = Boolean((_e = turnkeyVerifiedCredentials === null || turnkeyVerifiedCredentials === void 0 ? void 0 : turnkeyVerifiedCredentials.walletProperties) === null || _e === void 0 ? void 0 : _e.isAuthenticatorAttached);
            const embeddedWallet = walletConnector.createWallet({
                address: (yield walletConnector.getAddress()) || '',
                chain: walletConnector.connectedChain,
                connector: walletConnector,
                id: embeddedWalletVerifiedCredential.id,
                isAuthenticated,
                key: embeddedWalletVerifiedCredential.walletName || walletConnector.key,
            });
            const smartWallet$1 = smartWallet.findSmartWallet(embeddedWalletVerifiedCredential, updatedUser.verifiedCredentials);
            if (!smartWallet$1) {
                updatePrimaryWalletId.updatePrimaryWalletId(embeddedWalletVerifiedCredential.id);
            }
            else {
                yield smartWallet.initializeSmartWallet({
                    account: smartWallet$1,
                    primaryWalletId: smartWallet$1.id,
                    verifiedCredentials: updatedUser.verifiedCredentials,
                    walletConnectorOptions,
                });
                updatePrimaryWalletId.updatePrimaryWalletId(smartWallet$1.id);
            }
            dynamicEvents.dynamicEvents.emit('embeddedWalletCreated', embeddedWallet, turnkeyVerifiedCredentials, updatedUser);
            setShowAuthFlow(false, { performMultiWalletChecks: false });
        }
        catch (err) {
            logger.logger.error('Failed to create embedded wallet', err);
            setError(err);
            dynamicEvents.dynamicEvents.emit('embeddedWalletFailed', err);
        }
        finally {
            setIsLoading(false);
        }
    }), [
        embeddedChains,
        primaryEmbeddedChain,
        setShowAuthFlow,
        user,
        getSessionPublicKey,
        shouldRegisterSessionKeysOnSignin,
    ]);
    return {
        createDynamicEmbeddedWalletMutation,
        error,
        isLoading,
    };
};

exports.getEmbeddedChain = getEmbeddedChain;
exports.useCreateDynamicEmbeddedWalletMutation = useCreateDynamicEmbeddedWalletMutation;
