'use client'
'use strict';

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

var _tslib = require('../../../../_virtual/_tslib.cjs');
var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var reactI18next = require('react-i18next');
var bs58 = require('bs58');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
var utils = require('@dynamic-labs/utils');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
require('../../context/DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('../../context/ViewContext/ViewContext.cjs');
var logger = require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
require('../../shared/consts/index.cjs');
require('../../events/dynamicEvents.cjs');
require('../../context/CaptchaContext/CaptchaContext.cjs');
require('../../context/ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../store/state/nonce/nonce.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 blockaid = require('../../data/api/transactions/blockaid.cjs');
require('../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
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');
require('../../utils/functions/compareChains/compareChains.cjs');
require('../Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../context/ThemeContext/ThemeContext.cjs');
var useForceUpdate = require('../../utils/hooks/useForceUpdate/useForceUpdate.cjs');
var useInterval = require('../../utils/hooks/useInterval/useInterval.cjs');
require('../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
var useMutation = require('../../utils/hooks/useMutation/useMutation.cjs');
var usePromise = require('../../utils/hooks/usePromise/usePromise.cjs');
require('@dynamic-labs/types');
require('../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../context/LoadingContext/LoadingContext.cjs');
require('../../context/WalletContext/WalletContext.cjs');
require('../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../../context/MockContext/MockContext.cjs');
require('../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('../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
var Alert = require('../../components/Alert/Alert.cjs');
var Typography = require('../../components/Typography/Typography.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');
var useFetchCurrency = require('../../widgets/DynamicWidget/hooks/useFetchCurrency/useFetchCurrency.cjs');
require('formik');
require('../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
var useEffectOnce = require('../../utils/hooks/useEffectOnce/useEffectOnce.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('../ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../context/FooterAnimationContext/index.cjs');
require('../MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../context/PasskeyContext/PasskeyContext.cjs');
require('../../context/OnrampContext/OnrampContext.cjs');
require('../../store/state/sendBalances.cjs');
var TransactionConfirmationPageLayout = require('../../components/TransactionConfirmationPageLayout/TransactionConfirmationPageLayout.cjs');
require('../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.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');
var useTransactionTotal = require('./hooks/useTransactionTotal/useTransactionTotal.cjs');
var transactionErrorMessage = require('./helpers/transactionErrorMessage.cjs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var bs58__default = /*#__PURE__*/_interopDefaultLegacy(bs58);

const FEE_REFRESH_INTERVAL = 20000;
var SimulationStatus;
(function (SimulationStatus) {
    SimulationStatus["LOADING"] = "loading";
    SimulationStatus["FAILED"] = "failed";
    SimulationStatus["SKIPPED"] = "skipped";
    SimulationStatus["SUCCESS"] = "success";
})(SimulationStatus || (SimulationStatus = {}));
const TransactionConfirmationView = ({ transaction, onError, onSuccess, mutation, onClickBack, walletConnector, onClickClose, title, displayPoweredByDynamicFooter = false, copykey, hideModal, currentToken, isNativeToken, transactionValue, isModal, sendBalanceTransaction, }) => {
    const { primaryWallet, environmentId } = useInternalDynamicContext.useInternalDynamicContext();
    const [isGasSponsored, setIsGasSponsored] = React.useState(false);
    const [isGasSponsoredLoading, setIsGasSponsoredLoading] = React.useState(false);
    const update = useForceUpdate.useForceUpdate();
    const { t } = reactI18next.useTranslation();
    const { currency } = useFetchCurrency.useFetchCurrency(walletConnector);
    // Update the chainId access to handle undefined case
    const chainId = React.useMemo(() => {
        if (!(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector)) {
            return undefined;
        }
        const connector = primaryWallet.connector;
        return connector._selectedChainId || connector.lastUsedChainId;
    }, [primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector]);
    const [simulationState, setSimulationState] = React.useState({
        status: SimulationStatus.LOADING,
    });
    const [recipient, setRecipient] = React.useState(undefined);
    const isFetchingSimulationRef = React.useRef(false);
    const fetchSimulationResult = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _a, _b, _c, _d, _e, _f, _g;
        if (simulationState.status !== SimulationStatus.LOADING) {
            return;
        }
        if (isFetchingSimulationRef.current) {
            // Already fetching, prevent duplicate call
            return;
        }
        isFetchingSimulationRef.current = true;
        if (sendBalanceTransaction || hideModal) {
            setSimulationState({ status: SimulationStatus.SKIPPED });
            isFetchingSimulationRef.current = false;
            return;
        }
        if (!primaryWallet || (!chainId && (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.chain) !== 'SOL')) {
            logger.logger.error('[TransactionConfirmationView] Simulation failed:', {
                chain: primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.chain,
                chainId,
                primaryWallet,
            });
            setSimulationState({ status: SimulationStatus.FAILED });
            isFetchingSimulationRef.current = false;
            return;
        }
        try {
            let result;
            if (primaryWallet.connector.key === 'zerodev') {
                const connector = primaryWallet.connector;
                const { userOperation, sponsored } = yield connector.getCurrentUserOperation(transaction);
                setIsGasSponsored(sponsored);
                setIsGasSponsoredLoading(false);
                if (userOperation) {
                    const formattedUserOperation = yield connector.formatUserOperation(userOperation);
                    // Set the gas fee on the transaction, only for zero dev
                    transaction.fee.gas = calculateGasUnits(userOperation);
                    const entryPoint = yield ((_a = connector.getAccountAbstractionProvider()) === null || _a === void 0 ? void 0 : _a.account.entryPoint);
                    if (!entryPoint) {
                        logger.logger.error('[TransactionConfirmationView] Simulation failed: No entry point address found');
                        setSimulationState({ status: SimulationStatus.FAILED });
                        return;
                    }
                    setRecipient((_b = transaction === null || transaction === void 0 ? void 0 : transaction.getTransactionRecipient) === null || _b === void 0 ? void 0 : _b.call(transaction));
                    result = yield blockaid.simulateBlockaidUserOperation({
                        chainId: String(chainId),
                        entryPoint,
                        environmentId,
                        userOperation: formattedUserOperation,
                        value: ((_c = transaction.value) === null || _c === void 0 ? void 0 : _c.toString()) || '0',
                    });
                }
                else {
                    setSimulationState({ status: SimulationStatus.FAILED });
                    return;
                }
            }
            else {
                // Handle SOLANA
                if ((walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain) === 'SOL') {
                    const encodedTransactions = (_d = transaction.multipleTransactions) === null || _d === void 0 ? void 0 : _d.map((tx) => bs58__default["default"].encode(tx.serialize({ requireAllSignatures: false })));
                    if (!encodedTransactions) {
                        logger.logger.error('[TransactionConfirmationView] Simulation failed: No encoded transactions');
                        setSimulationState({ status: SimulationStatus.FAILED });
                        return;
                    }
                    result = yield blockaid.simulateBlockaidSVMTransaction({
                        accountAddress: transaction.from,
                        chain: (yield (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.getNetwork(true))),
                        environmentId,
                        transactions: encodedTransactions,
                    });
                }
                else if ((walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain) === 'EVM') {
                    setRecipient((_e = transaction === null || transaction === void 0 ? void 0 : transaction.getTransactionRecipient) === null || _e === void 0 ? void 0 : _e.call(transaction));
                    // EVM
                    result = yield blockaid.simulateBlockaidEVMTransaction({
                        chainId: String(chainId),
                        data: transaction.data || '0x',
                        environmentId,
                        from: transaction.from,
                        to: transaction.to || '',
                        value: ((_f = transaction.value) === null || _f === void 0 ? void 0 : _f.toString()) || '0',
                    });
                }
            }
            if (!result && ((_g = primaryWallet.connector) === null || _g === void 0 ? void 0 : _g.key) !== 'zerodev') {
                logger.logger.warn('[TransactionConfirmationView] Simulation failed: No result');
                setSimulationState({ status: SimulationStatus.FAILED });
                return;
            }
            setSimulationState(result
                ? { result, status: SimulationStatus.SUCCESS }
                : { status: SimulationStatus.FAILED });
        }
        catch (error) {
            logger.logger.error('[TransactionConfirmationView] Simulation failed:', error);
            setSimulationState({ status: SimulationStatus.FAILED });
        }
        finally {
            isFetchingSimulationRef.current = false;
        }
    }), [
        sendBalanceTransaction,
        hideModal,
        primaryWallet,
        chainId,
        environmentId,
        transaction,
        walletConnector,
        simulationState.status,
        setSimulationState,
    ]);
    React.useEffect(() => {
        if (simulationState.status === SimulationStatus.SUCCESS ||
            simulationState.status === SimulationStatus.SKIPPED) {
            return;
        }
        fetchSimulationResult();
    }, [fetchSimulationResult, primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, simulationState.status]);
    /**
     * Update transaction fee and trigger a react update
     * to reflect the new fee on the UI
     */
    const fetchTransactionFee = React.useCallback(() => {
        var _a;
        if (((primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.chain) === sdkApiCore.ChainEnum.Sol &&
            transaction.fee.gas !== undefined) ||
            (primaryWallet && ((_a = primaryWallet.connector) === null || _a === void 0 ? void 0 : _a.key) === 'zerodev')) {
            return;
        }
        transaction.fetchFee().finally(update);
    }, [primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.chain, transaction, update]);
    React.useEffect(() => {
        var _a;
        // solana gas sponsorship check
        if ((_a = transaction.isGasSponsored) === null || _a === void 0 ? void 0 : _a.call(transaction)) {
            setIsGasSponsored(true);
        }
    }, [transaction]);
    const { mutate: send, isLoading, error: transactionError, } = useMutation.useMutation(mutation, {
        onFailure: React.useCallback((error) => {
            fetchTransactionFee();
            if (utils.TransactionGasCannotBeSponsoredError.isInstance(error)) {
                logger.logger.debug(error);
                setIsGasSponsored(false);
                if (walletConnectorCore.isAccountAbstractionConnector(walletConnector)) {
                    walletConnector.disableGasSponsorshipOnce();
                }
            }
            logger.logger.error(error);
            onError === null || onError === void 0 ? void 0 : onError(error);
        }, [fetchTransactionFee, onError, walletConnector]),
        onSuccess: React.useCallback((tx) => onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(tx), [onSuccess]),
    });
    // Refresh transaction fee, Solana fees are static based on transaction data, dont need to refresh them
    useInterval.useInterval(fetchTransactionFee, isLoading ? null : FEE_REFRESH_INTERVAL);
    useEffectOnce.useEffectOnce(fetchTransactionFee);
    const total = useTransactionTotal.useTransactionTotal({
        gasTotalPrice: transaction.fee.gas,
        isGasSponsored,
        transactionValue: transaction.value,
    });
    const errorMessage = transactionError && transactionErrorMessage.transactionErrorMessage(transactionError);
    const { data: balance, isLoading: isBalanceLoading } = usePromise.usePromise(() => transaction.getBalance());
    const hasInsufficientFunds = React.useMemo(() => {
        if (total === undefined || balance === undefined)
            return false;
        return balance < total;
    }, [balance, total]);
    const missingFunds = React.useMemo(() => {
        if (total === undefined || balance === undefined)
            return undefined;
        return total - balance;
    }, [total, balance]);
    const alert = React.useMemo(() => {
        if (errorMessage)
            return null;
        // Check for gas sponsorship errors
        if (utils.TransactionGasCannotBeSponsoredError.isInstance(transactionError)) {
            return (jsxRuntime.jsx(Alert.Alert, { icon: 'error', variant: 'error', copykey: 'dyn_send_transaction.error_message.gas_not_sponsored', children: t('dyn_send_transaction.error_message.gas_not_sponsored') }));
        }
        // Check for insufficient gas funds
        if (!isGasSponsoredLoading &&
            !isBalanceLoading &&
            missingFunds === undefined &&
            transaction.fee.gas &&
            !isGasSponsored) {
            return (jsxRuntime.jsx(Alert.Alert, { icon: 'error', variant: 'warning', copykey: 'dyn_send_transaction.warning_message.insufficient_gas_funds', children: jsxRuntime.jsxs(Typography.Typography, { variant: 'body_small', color: 'current-color', "data-testid": 'warning_content', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', copykey: 'dyn_send_transaction.warning_message.insufficient_gas_funds.title', children: t('dyn_send_transaction.warning_message.insufficient_gas_funds.title') }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.warning_message.insufficient_gas_funds.description', children: t('dyn_send_transaction.warning_message.insufficient_gas_funds.description', {
                                amountLeft: transaction.format(transaction.fee.gas, {
                                    precision: 6,
                                }),
                                currencySymbol: currency === null || currency === void 0 ? void 0 : currency.symbol,
                            }) })] }) }));
        }
        // Check for insufficient funds
        const showInsufficientFundsWarningMessage = hasInsufficientFunds && missingFunds;
        if (showInsufficientFundsWarningMessage) {
            const amountLeft = transaction.format(missingFunds, { precision: 6 });
            return (jsxRuntime.jsx(Alert.Alert, { icon: 'error', variant: 'error', copykey: 'dyn_send_transaction.warning_message.insufficient_funds', children: jsxRuntime.jsxs(Typography.Typography, { variant: 'body_small', color: 'current-color', "data-testid": 'warning_content', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', copykey: 'dyn_send_transaction.warning_message.insufficient_funds.title', children: t('dyn_send_transaction.warning_message.insufficient_funds.title') }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.warning_message.insufficient_funds.description', children: t('dyn_send_transaction.warning_message.insufficient_funds.description', {
                                amountLeft,
                                currencySymbol: currency === null || currency === void 0 ? void 0 : currency.symbol,
                            }) })] }) }));
        }
        // Finally, check for simulation failure
        if (simulationState.status === SimulationStatus.FAILED) {
            return (jsxRuntime.jsx(Alert.Alert, { icon: 'error', variant: 'warning', copykey: 'dyn_send_transaction.warning_message.failed_simulation', children: jsxRuntime.jsxs(Typography.Typography, { variant: 'body_small', color: 'current-color', "data-testid": 'warning_content', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', copykey: 'dyn_send_transaction.warning_message.failed_simulation.title', as: 'div', children: t('dyn_send_transaction.warning_message.failed_simulation.title') }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.warning_message.failed_simulation.description', as: 'div', children: t('dyn_send_transaction.warning_message.failed_simulation.description') })] }) }));
        }
        return null;
    }, [
        simulationState.status,
        errorMessage,
        transactionError,
        isGasSponsoredLoading,
        isBalanceLoading,
        missingFunds,
        transaction,
        isGasSponsored,
        hasInsufficientFunds,
        t,
        currency === null || currency === void 0 ? void 0 : currency.symbol,
    ]);
    React.useEffect(() => {
        var _a, _b;
        if (simulationState.status === SimulationStatus.SUCCESS &&
            !sendBalanceTransaction) {
            if (((_a = simulationState.result) === null || _a === void 0 ? void 0 : _a.outAssets.length) === 0 &&
                !chainId &&
                !((_b = transaction.isGasSponsored) === null || _b === void 0 ? void 0 : _b.call(transaction))) {
                // set failed but keep the result so that we have the native price
                setSimulationState({
                    result: simulationState.result,
                    status: SimulationStatus.FAILED,
                });
            }
        }
    }, [simulationState, chainId, transaction, sendBalanceTransaction]);
    const layoutProps = React.useMemo(() => {
        var _a;
        return ({
            alert,
            copykey,
            currentToken,
            disableSendButton: isBalanceLoading,
            displayPoweredByDynamicFooter,
            error: errorMessage,
            hideModal,
            isGasSponsored,
            isGasSponsoredLoading,
            isLoading,
            isNativeToken,
            onClickBack,
            onClickClose,
            onClickSend: () => send(),
            onSuccess: (tx) => onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(tx),
            recipient,
            sendBalanceTransaction,
            simulationResult: (_a = simulationState.result) !== null && _a !== void 0 ? _a : undefined,
            title,
            total,
            transaction,
            transactionValue,
            walletConnector,
            walletKey: (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.key) || '',
        });
    }, [
        total,
        recipient,
        currentToken,
        transactionValue,
        isNativeToken,
        onClickBack,
        onClickClose,
        copykey,
        title,
        hideModal,
        isLoading,
        send,
        onSuccess,
        displayPoweredByDynamicFooter,
        isBalanceLoading,
        errorMessage,
        alert,
        walletConnector,
        transaction,
        isGasSponsored,
        isGasSponsoredLoading,
        primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.key,
        simulationState.result,
        sendBalanceTransaction,
    ]);
    return simulationState.status === SimulationStatus.LOADING ? null : (jsxRuntime.jsx(TransactionConfirmationPageLayout.TransactionConfirmationPageLayout, Object.assign({}, layoutProps)));
};
const calculateGasUnits = (userOp) => {
    // Sum all gas units
    const totalGasUnits = BigInt(userOp.callGasLimit || 0) +
        BigInt(userOp.verificationGasLimit || 0) +
        BigInt(userOp.preVerificationGas || 0);
    // Multiply by maxFeePerGas to get the total gas cost in wei
    const gasCost = totalGasUnits * BigInt(userOp.maxFeePerGas || 0);
    return gasCost;
};

exports.FEE_REFRESH_INTERVAL = FEE_REFRESH_INTERVAL;
exports.TransactionConfirmationView = TransactionConfirmationView;
