'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var utils = require('@dynamic-labs/utils');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('react');
var dynamicEvents = require('../../../events/dynamicEvents.cjs');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('react/jsx-runtime');
var ViewContext = 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('@dynamic-labs/sdk-api-core');
require('../../../shared/consts/index.cjs');
var authMode = require('../../../store/state/authMode/authMode.cjs');
var useInternalDynamicContext = require('../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
var ErrorContext = require('../../../context/ErrorContext/ErrorContext.cjs');
var errors = require('../../constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
var getVerifyArgs = require('../../functions/getVerifyArgs/getVerifyArgs.cjs');
var updatePrimaryWalletId = require('../../functions/updatePrimaryWalletId/updatePrimaryWalletId.cjs');
var connectedWalletsInfo = 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');
var wallets = require('../../../data/api/wallets/wallets.cjs');
var AccessDeniedContext = require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
var AccountExistsContext = require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
var UserWalletsContext = require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
var getSiweStatement = require('../../functions/getSiweStatement/getSiweStatement.cjs');
require('../../../context/VerificationContext/VerificationContext.cjs');
require('../../../store/state/nonce/nonce.cjs');
require('react-dom');
require('../../functions/compareChains/compareChains.cjs');
require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
var useEmbeddedWalletSessionKeys = require('../useEmbeddedWalletSessionKeys/useEmbeddedWalletSessionKeys.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
var useUserAuth = require('../useUserAuth/useUserAuth.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('../../../context/WalletContext/WalletContext.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('../../../context/LoadingContext/LoadingContext.cjs');
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('../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.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');

// This logic is used to both verify or link a wallet
// Since we are re-using the different screens to authenticate or link the wallet.
// This logic is the best place to determine whether we should verify or verify and link.
const useVerifyWallet = ({ displaySiweStatement, environmentId, projectSettings, setIsSingleWalletAccount, }) => {
    const { setExistentAccountData } = AccountExistsContext.useAccountExistsContext();
    const { setDeniedAddress, setDeniedOauthProvider } = AccessDeniedContext.useAccessDeniedContext();
    const { pushView, clearStackAndPushInitialView } = ViewContext.useViewContext();
    const { setErrorMessage, setError } = ErrorContext.useErrorContext();
    const { multiWalletWidgetState, debugError, multiWallet: multiWalletEnabled, appName, primaryWalletId, setShowAuthFlow, siweStatement, connectedWallets, user, events, primaryWallet, enableConnectOnlyFallback, selectedWalletConnector, } = useInternalDynamicContext.useInternalDynamicContext();
    const { addedWalletsIds } = UserWalletsContext.useInternalUserWallets();
    const { initAuth } = useUserAuth.useUserAuth({ authMethod: 'wallet' });
    const { generateSessionKey, shouldRegisterSessionKeysOnSignin } = useEmbeddedWalletSessionKeys.useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    // If the user is not already logged it means that we only need to verify
    // We need this boolean to distinguish between logic for verify or linking.
    const verifyOnly = !user;
    const shouldFallbackToConnectOnly = enableConnectOnlyFallback && (verifyOnly || !multiWalletEnabled);
    const generateJWT = (walletConnector, walletProvider, getAddressOpts, publicWalletAddress, captchaToken, oauth, signedMessageOverride, messageToSignOverride) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const verifyArgs = yield getVerifyArgs.getVerifyArgs({
            displaySiweStatement,
            environmentId,
            getAddressOpts,
            messageToSignOverride,
            publicWalletAddress,
            signedMessageOverride,
            siweStatement: getSiweStatement.getSiweStatement({ appName, siweStatement }),
            walletConnector,
            walletProvider,
        });
        if (shouldRegisterSessionKeysOnSignin() && verifyOnly) {
            const keypair = yield generateSessionKey();
            verifyArgs.sessionPublicKey = keypair.publicKey;
        }
        let verifyResponse;
        if (!user) {
            verifyResponse = wallets.verifyWallet(environmentId, Object.assign(Object.assign({}, verifyArgs), { captchaToken,
                oauth }));
        }
        else {
            verifyResponse = wallets.linkWallet(environmentId, verifyArgs);
        }
        return { verifyArgs, verifyFunction: () => verifyResponse };
    });
    // Overrides the stored primary wallet id when the
    // user logs in for the first time.
    // Or when the user is linking an additional
    // account on the same wallet as the primary wallet.
    const updatePrimaryWallet = ({ walletConnector, verifiedCredentials, lastVerifiedCredentialId, }) => {
        const newSelectedCredentialWallet = verifiedCredentials.find((cred) => cred.id === lastVerifiedCredentialId && cred.format === 'blockchain');
        if (newSelectedCredentialWallet) {
            const currentPrimaryWallet = verifiedCredentials.find((a) => a.id === primaryWalletId);
            if (verifyOnly ||
                !primaryWallet ||
                (multiWalletWidgetState === 'awaiting_signature' &&
                    newSelectedCredentialWallet.walletName ===
                        (currentPrimaryWallet === null || currentPrimaryWallet === void 0 ? void 0 : currentPrimaryWallet.walletName)) ||
                ((currentPrimaryWallet === null || currentPrimaryWallet === void 0 ? void 0 : currentPrimaryWallet.chain) === 'flow' &&
                    walletConnector.connectedChain === 'FLOW')) {
                updatePrimaryWalletId.updatePrimaryWalletId(newSelectedCredentialWallet.id);
            }
        }
    };
    const handleWalletUsedError = (e) => {
        var _a;
        // This is a special case where the user is trying to link a wallet
        // and the wallet is already linked and we don't want to kill the session.
        setShowAuthFlow(true);
        pushView('wallet-used');
        setIsSingleWalletAccount(false);
        if (e.code === 'reassign_wallet_error') {
            if ((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.preventOrphanedAccounts) {
                pushView('wallet-cannot-be-transferred');
            }
            setIsSingleWalletAccount(true);
        }
    };
    const handleDisconnectWallet = ({ walletConnector, endSession = true, }) => {
        connectedWalletsInfo.resetConnectedWalletsInfo();
        if (endSession)
            walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.endSession();
    };
    const handleError = (e, walletConnector, address, oauth) => {
        var _a;
        // see: PhantomRedirect#signMessage
        if (e.message === 'ignore') {
            return;
        }
        // Emit failure if this wallet connector was currently selected for auth
        if (selectedWalletConnector &&
            selectedWalletConnector.key === walletConnector.key)
            dynamicEvents.dynamicEvents.emit('authFailure', {
                address,
                connectorName: walletConnector.name,
                option: walletConnector.name,
                type: 'wallet',
            }, { error: e });
        if (e instanceof utils.EmbeddedWalletExistsError) {
            pushView('embedded-wallet-exists');
            setShowAuthFlow(true);
            return;
        }
        if (e instanceof utils.WalletUsedError) {
            handleDisconnectWallet({ endSession: false, walletConnector });
            return handleWalletUsedError(e);
        }
        if (e instanceof utils.MergeAccountsConfirmationError) {
            pushView('merge-user-accounts', Object.assign({}, e));
            setShowAuthFlow(true);
            return;
        }
        if (e instanceof utils.ChainalysisError) {
            handleDisconnectWallet({ walletConnector });
            setDeniedAddress(address);
            pushView('chainalysis-blocked-wallet');
            return;
        }
        if (e instanceof utils.GateBlockedError) {
            handleDisconnectWallet({ walletConnector });
            setDeniedAddress(address);
            pushView('gate-blocked-wallet');
            return;
        }
        if (e instanceof utils.SandboxMaximumThresholdReachedError) {
            pushView('sandbox-maximum-threshold-reached');
            return;
        }
        if (e instanceof utils.NoAccessError) {
            handleDisconnectWallet({ walletConnector });
            setDeniedAddress(address);
            // we need to set this value if it's magic in order to set proper icon
            if (walletConnectorCore.isSocialWalletConnector(walletConnector)) {
                setDeniedOauthProvider(oauth === null || oauth === void 0 ? void 0 : oauth.provider);
            }
            pushView('no-access');
            return;
        }
        if (e instanceof utils.AccountExistsError) {
            handleDisconnectWallet({ walletConnector });
            setExistentAccountData(e.errorPayload);
            pushView('account-exists');
            return;
        }
        const authMode$1 = authMode.getAuthMode();
        if (connectedWallets.length && authMode$1 === 'connect-only') {
            throw new utils.DynamicError(e.message);
        }
        const userRejectedRequestError = (_a = e === null || e === void 0 ? void 0 : e.message) === null || _a === void 0 ? void 0 : _a.includes('User rejected the request');
        const fallbackToConnectOnly = shouldFallbackToConnectOnly && !userRejectedRequestError;
        if (fallbackToConnectOnly) {
            logger.logger.warn('Verification failed, changing to connect-only');
            // verification failed for unknown reason, set authmode to connect-only and show wallet list
            authMode.setAuthMode('connect-only');
            pushView('wallet-list');
            return;
        }
        else {
            handleDisconnectWallet({ walletConnector });
            clearStackAndPushInitialView();
        }
        logger.logger.error(e);
        if (debugError) {
            setError(`${e.message}\n ${e.stack}`);
        }
        else {
            setErrorMessage(e.code);
        }
    };
    return (_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ walletConnector, getAddressOpts, publicWalletAddress, captchaToken, oauth, signedMessageOverride, messageToSignOverride, }) {
        const walletProvider = walletConnectorCore.getWalletProvider(walletConnector);
        dynamicEvents.dynamicEvents.emit('authInit', {
            address: publicWalletAddress,
            connectorName: walletConnector.name,
            option: walletConnector.name,
            type: 'wallet',
        });
        try {
            const { verifyFunction, verifyArgs } = yield generateJWT(walletConnector, walletProvider, getAddressOpts, publicWalletAddress, captchaToken, oauth, signedMessageOverride, messageToSignOverride);
            yield initAuth({
                isSignIn: verifyOnly,
                onError: (e) => {
                    handleError(e, walletConnector, publicWalletAddress, oauth);
                },
                onVerifySuccess: (user) => {
                    var _a;
                    if (!user) {
                        throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
                    }
                    try {
                        (_a = events === null || events === void 0 ? void 0 : events.onSignedMessage) === null || _a === void 0 ? void 0 : _a.call(events, {
                            messageToSign: verifyArgs.messageToSign,
                            signedMessage: verifyArgs.signedMessage,
                        });
                    }
                    catch (_b) {
                        logger.logger.warn('Error calling onSignedMessage callback');
                    }
                    utils.StorageService.setItem(localStorage.LAST_USED_WALLET, walletConnector.key);
                    authMode.setAuthMode('connect-and-sign');
                    updatePrimaryWallet({
                        lastVerifiedCredentialId: user.lastVerifiedCredentialId,
                        verifiedCredentials: user.verifiedCredentials,
                        walletConnector,
                    });
                    const walletId = user.lastVerifiedCredentialId;
                    if (walletId) {
                        addedWalletsIds.current.push(walletId);
                    }
                },
                options: {
                    address: publicWalletAddress,
                    connectorName: walletConnector.name,
                },
                skipDefaultErrorHandling: true,
                verifyFunction,
            });
        }
        catch (e) {
            handleError(e, walletConnector, publicWalletAddress, oauth);
        }
    });
};

exports.useVerifyWallet = useVerifyWallet;
