'use client'
'use strict';

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

var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var reactI18next = require('react-i18next');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
var tooltip = require('../../shared/assets/tooltip.cjs');
require('../../context/ViewContext/ViewContext.cjs');
require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../shared/consts/index.cjs');
var networksAndChains = require('../../utils/functions/networksAndChains/networksAndChains.cjs');
var Icon = require('../Icon/Icon.cjs');
var Typography = require('../Typography/Typography.cjs');
require('../../context/DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../events/dynamicEvents.cjs');
require('../../../../_virtual/_tslib.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');
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('../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../context/ThemeContext/ThemeContext.cjs');
require('../../utils/hooks/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('../../utils/hooks/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('../Accordion/components/AccordionItem/AccordionItem.cjs');
require('../Alert/Alert.cjs');
var Tooltip = require('../Tooltip/Tooltip.cjs');
require('../IconButton/IconButton.cjs');
require('../InlineWidget/InlineWidget.cjs');
require('../Input/Input.cjs');
require('../IsBrowser/IsBrowser.cjs');
require('../MenuList/Dropdown/Dropdown.cjs');
require('../OverlayCard/OverlayCard.cjs');
require('../Transition/ZoomTransition/ZoomTransition.cjs');
require('../Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../Transition/OpacityTransition/OpacityTransition.cjs');
require('../PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../Popper/Popper/Popper.cjs');
require('../Popper/PopperContext/PopperContext.cjs');
require('../ShadowDOM/ShadowDOM.cjs');
require('react-focus-lock');
require('qrcode');
var useFetchChain = require('../../widgets/DynamicWidget/hooks/useFetchChain/useFetchChain.cjs');
var shortenWalletAddress = require('../../shared/utils/functions/shortenWalletAddress/shortenWalletAddress.cjs');
require('formik');
require('../../utils/hooks/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');
var useNetworkConfigurationsFromProjectSettings = require('../../utils/hooks/useNetworkConfigurationsFromProjectSettings/useNetworkConfigurationsFromProjectSettings.cjs');
require('../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../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');

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

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

const TransactionCard = ({ transaction, simulationResult, isGasSponsored, isAATransaction, recipient, }) => {
    var _a, _b, _c, _d, _e, _f, _g;
    const { t } = reactI18next.useTranslation();
    const { primaryWallet, projectSettings, overrides } = useInternalDynamicContext.useInternalDynamicContext();
    const networkInfo = useNetworkConfigurationsFromProjectSettings.useNetworkConfigurationsFromProjectSettings({
        evmNetworksOverrides: overrides === null || overrides === void 0 ? void 0 : overrides.evmNetworks,
        projectSettings,
    });
    const { chain } = useFetchChain.useFetchChain(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector);
    const networkInfoEntry = networksAndChains.getNetworkInfoEntry({
        chain: (_a = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector) === null || _a === void 0 ? void 0 : _a.connectedChain,
        networkId: chain === null || chain === void 0 ? void 0 : chain.chainId,
        networkInfo,
    });
    const { symbol: nativeCurrencySymbol, decimals: nativeCurrencyDecimals } = (_b = networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.nativeCurrency) !== null && _b !== void 0 ? _b : {};
    const blockaidOn = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.showTotalFiat;
    const feeInUsd = React.useMemo(() => {
        var _a;
        const nativeTokenUsdPrice = (_a = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.priceData) === null || _a === void 0 ? void 0 : _a.nativeTokenUsdPrice;
        if (!nativeTokenUsdPrice || !nativeCurrencyDecimals) {
            return undefined;
        }
        return ((Number(nativeTokenUsdPrice) * Number(transaction.fee.gas)) /
            Math.pow(10, nativeCurrencyDecimals));
    }, [simulationResult, nativeCurrencyDecimals, transaction.fee.gas]);
    const getFeeInUsdDisplay = (feeInUsd) => {
        if (!feeInUsd)
            return undefined;
        return feeInUsd < 0.01 ? '<$0.01' : `~$${feeInUsd.toFixed(2)}`;
    };
    const totalAmountInUsd = React.useMemo(() => {
        var _a;
        const outgoingAssetsTotal = ((_a = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.outAssets) === null || _a === void 0 ? void 0 : _a.reduce((acc, transfer) => {
            var _a;
            const transferOutTotal = ((_a = transfer.transferOut) === null || _a === void 0 ? void 0 : _a.reduce((sum, t) => sum + Number((t === null || t === void 0 ? void 0 : t.usdPrice) || 0), 0)) || 0;
            return acc + transferOutTotal;
        }, 0)) || 0;
        if (blockaidOn && isAATransaction) {
            return outgoingAssetsTotal;
        }
        // for solana, the fee is included in the outgoing assets already
        return (outgoingAssetsTotal +
            (nativeCurrencySymbol === 'SOL' || isGasSponsored ? 0 : feeInUsd || 0));
    }, [simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.outAssets, nativeCurrencySymbol, feeInUsd]);
    const getTotalAmountInUsdDisplay = (totalAmountInUsd) => {
        if (!totalAmountInUsd)
            return undefined;
        return totalAmountInUsd < 0.01
            ? '<$0.01'
            : `~$${totalAmountInUsd.toFixed(2)}`;
    };
    const renderAssetTransfer = (transfer, index, array) => {
        var _a, _b, _c;
        if (['NATIVE', 'SOL', 'ETH'].includes(transfer.asset.type) &&
            ((_a = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector) === null || _a === void 0 ? void 0 : _a.connectedChain) === 'SOL' &&
            transaction.fee.gas) {
            transfer.amount = (Number(transfer.amount) -
                Number(transaction.fee.gas) / Math.pow(10, 9)).toString();
            transfer.usdPrice = (Number(transfer.usdPrice) - Number(feeInUsd)).toString();
        }
        const getAmountDisplay = () => {
            const amount = Number(transfer.amount);
            if (Number.isInteger(amount)) {
                return amount;
            }
            return amount < 0.000001 ? '<0.000001' : amount.toFixed(6);
        };
        const getUsdPriceDisplay = () => {
            const usdPrice = Number(transfer.usdPrice);
            if (usdPrice < 0.01) {
                return '<$0.01';
            }
            return `$${usdPrice.toFixed(2)}`;
        };
        return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: `transaction-card__${transfer.direction}`, children: jsxRuntime.jsxs("div", { className: 'transaction-card__info-container', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', children: transfer.direction === 'in' ? 'Receive' : 'Send' }), jsxRuntime.jsxs("div", { className: 'transaction-card__amount-symbol', children: [jsxRuntime.jsxs("div", { className: 'transaction-card__token-info', children: [jsxRuntime.jsxs("div", { className: 'transaction-card__token-row', children: [jsxRuntime.jsxs(Typography.Typography, { variant: 'body_normal', color: transfer.direction === 'in' ? 'green-1' : 'error-1', children: [transfer.direction === 'out' ? '-' : '+', getAmountDisplay()] }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', children: (_b = (transfer.asset.symbol || transfer.asset.name)) !== null && _b !== void 0 ? _b : nativeCurrencySymbol })] }), Number(transfer.usdPrice) > 0 && (jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', color: transfer.direction === 'in' ? 'green-1' : 'error-1', children: getUsdPriceDisplay() }))] }), jsxRuntime.jsx("div", { className: 'transaction-card__icon', children: jsxRuntime.jsx("div", { className: 'transaction-card__icon__container', children: jsxRuntime.jsx("img", { src: transfer.asset.logoUrl ||
                                                    (networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.nativeCurrency.iconUrl), alt: (_c = transfer.asset.symbol) !== null && _c !== void 0 ? _c : nativeCurrencySymbol, width: 32, height: 32, className: 'transaction-card__icon__container__main' }) }) })] })] }) }), index < array.length - 1 && (jsxRuntime.jsx("div", { className: 'transaction-card__divider' }))] }));
    };
    const inAssets = ((_c = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.inAssets) === null || _c === void 0 ? void 0 : _c.flatMap((assetDiff) => {
        var _a;
        return ((_a = assetDiff.transferIn) === null || _a === void 0 ? void 0 : _a.map((inTransfer) => {
            var _a, _b;
            return ({
                amount: (_a = inTransfer === null || inTransfer === void 0 ? void 0 : inTransfer.value) !== null && _a !== void 0 ? _a : '',
                asset: assetDiff.asset,
                direction: 'in',
                usdPrice: (_b = inTransfer === null || inTransfer === void 0 ? void 0 : inTransfer.usdPrice) !== null && _b !== void 0 ? _b : '',
            });
        })) || [];
    })) || [];
    const outAssets = ((_d = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.outAssets) === null || _d === void 0 ? void 0 : _d.flatMap((assetDiff) => {
        var _a;
        return ((_a = assetDiff.transferOut) === null || _a === void 0 ? void 0 : _a.map((outTransfer) => {
            var _a, _b;
            return ({
                amount: (_a = outTransfer === null || outTransfer === void 0 ? void 0 : outTransfer.value) !== null && _a !== void 0 ? _a : '',
                asset: assetDiff.asset,
                direction: 'out',
                usdPrice: (_b = outTransfer === null || outTransfer === void 0 ? void 0 : outTransfer.usdPrice) !== null && _b !== void 0 ? _b : '',
            });
        })) || [];
    })) || [];
    // for solana, the simulation out asset includes the gas fee.
    // so if the gas fee is the same as the total solana spend, then there is no solana being sent, only a gas fee
    const outAssetsWithoutFee = outAssets.filter((asset) => !((asset.asset.type === 'NATIVE' || asset.asset.type === 'SOL') &&
        asset.asset.chainName === 'Solana' &&
        Number(asset.amount) === Number(transaction.fee.gas) / Math.pow(10, 9)));
    //for evm AA with blockaid ON, the outAssets includes the gas fee,
    //so we need to remove it if the transaction doesnt have a tx.value (ETH spend)
    const outAssetsWithoutFeeEvm = outAssetsWithoutFee.filter((asset) => !(asset.asset.type === 'NATIVE' &&
        transaction.chain === 'EVM' &&
        !transaction.value));
    const allAssets = [...outAssetsWithoutFeeEvm, ...inAssets];
    const getGasFeeDisplay = () => {
        if (feeInUsd) {
            return getFeeInUsdDisplay(feeInUsd);
        }
        if (transaction.fee.gas) {
            return `${transaction.format(transaction.fee.gas, {
                precision: 8,
            })} ${nativeCurrencySymbol}`;
        }
        return `-- ${nativeCurrencySymbol}`;
    };
    return (jsxRuntime.jsxs("div", { className: 'transaction-card-container', children: [allAssets.length > 0 && (jsxRuntime.jsx("div", { className: 'transaction-card', children: jsxRuntime.jsx("div", { className: 'transaction-card__assets-container', children: allAssets.map((asset, index, array) => (jsxRuntime.jsx(React__default["default"].Fragment, { children: renderAssetTransfer(asset, index, array) }, `asset-${index}`))) }) })), jsxRuntime.jsx("div", { className: 'transaction-card', children: jsxRuntime.jsxs("div", { className: 'transaction-card__details', children: [recipient && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: 'transaction-card__row', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.confirmation.data.recipient', children: t('dyn_send_transaction.confirmation.data.recipient') }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', "data-testid": 'transaction-recipient', children: shortenWalletAddress.shortenWalletAddress(recipient) })] }), jsxRuntime.jsx("div", { className: 'transaction-card__divider' })] })), !recipient &&
                            (transaction.to || ((_e = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.counterparties) === null || _e === void 0 ? void 0 : _e[0])) && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: 'transaction-card__row', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.confirmation.data.destination', children: t('dyn_send_transaction.confirmation.data.destination') }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', "data-testid": 'transaction-destination', children: shortenWalletAddress.shortenWalletAddress((_f = transaction.to) !== null && _f !== void 0 ? _f : (_g = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.counterparties) === null || _g === void 0 ? void 0 : _g[0]) })] }), jsxRuntime.jsx("div", { className: 'transaction-card__divider' })] })), jsxRuntime.jsxs("div", { className: 'transaction-card__row', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.confirmation.data.network', children: t('dyn_send_transaction.confirmation.data.network') }), jsxRuntime.jsxs("div", { className: 'transaction-card__network-info', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', children: (networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.name) || 'Ethereum' }), jsxRuntime.jsx("img", { src: networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.iconUrls[0], alt: (networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.name) || 'Network icon', width: 16, height: 16, className: 'transaction-card__network-icon' })] })] }), !isGasSponsored && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: 'transaction-card__divider' }), jsxRuntime.jsxs("div", { className: 'transaction-card__row', children: [jsxRuntime.jsxs("div", { className: 'transaction-card__label-with-tooltip', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.confirmation.data.gas_estimate', children: t('dyn_send_transaction.confirmation.data.gas_estimate') }), jsxRuntime.jsx(Tooltip.Tooltip, { content: 'Network fees are paid to process your transaction', className: 'transaction-confirmation', children: jsxRuntime.jsx(Icon.Icon, { size: 'small', className: 'fee-tooltip', children: jsxRuntime.jsx(tooltip.ReactComponent, {}) }) })] }), jsxRuntime.jsx("div", { className: 'transaction-card__value', children: jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', "data-testid": 'transaction-estimated-gas-fee', children: getGasFeeDisplay() }) })] })] })), blockaidOn &&
                            totalAmountInUsd !== undefined &&
                            totalAmountInUsd > 0 &&
                            !(isAATransaction && !isGasSponsored) && (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { className: 'transaction-card__divider' }), jsxRuntime.jsxs("div", { className: 'transaction-card__row', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', weight: 'bold', copykey: 'dyn_send_transaction.confirmation.data.total', children: t('dyn_send_transaction.confirmation.data.total') }), jsxRuntime.jsx("div", { className: 'transaction-card__total-amount', children: jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', "data-testid": 'transaction-estimated-total', children: getTotalAmountInUsdDisplay(totalAmountInUsd) }) })] })] }))] }) })] }));
};

exports.TransactionCard = TransactionCard;
