'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');
require('@dynamic-labs-sdk/client/core');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.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('@dynamic-labs/utils');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
var errors = require('../../constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
var utils = require('../../../data/api/utils.cjs');
require('@dynamic-labs/locale');
var dynamicContextProps = require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../events/dynamicEvents.cjs');
var getUserProfile = require('../../../client/extension/user/getUserProfile/getUserProfile.cjs');
var getProjectSettings = require('../../../client/extension/projectSettings/getProjectSettings/getProjectSettings.cjs');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
var useDynamicEvents = require('../events/useDynamicEvents/useDynamicEvents.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
var authMode = require('../../../store/state/authMode/authMode.cjs');
require('../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../functions/compareChains/compareChains.cjs');
require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../context/ThemeContext/ThemeContext.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');
var balances = require('../../../data/api/chains/balances.cjs');
var tokenBalances = 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');

// Hook exposed to customers and used internally to fetch account balances
const useTokenBalances = ({ accountAddress, networkId, chainName, tokenAddresses, includeFiat = false, includeNativeBalance = false, filterSpamTokens = true, forceRefresh = false, whitelistedContracts, } = {}) => {
    var _a;
    const tokenBalancesState = tokenBalances.useTokenBalancesState();
    const { tokenBalances: tokenBalances$1, isLoading, error } = tokenBalancesState;
    const { primaryWallet, network } = useInternalDynamicContext.useInternalDynamicContext();
    const walletConnector = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector;
    const requestAccount = accountAddress !== null && accountAddress !== void 0 ? accountAddress : primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address;
    const requestChainName = (_a = chainName !== null && chainName !== void 0 ? chainName : walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain) !== null && _a !== void 0 ? _a : sdkApiCore.ChainEnum.Evm;
    const fetchAccountBalances = React.useCallback((...args_1) => _tslib.__awaiter(void 0, [...args_1], void 0, function* (forceRefresh = false) {
        var _b;
        const user = getUserProfile.getUserProfile();
        const authMode$1 = authMode.getAuthMode();
        if (authMode$1 !== 'connect-only' && !user) {
            tokenBalances.setTokenBalanceVariable('error', errors.USER_NOT_LOGGED_IN);
            return;
        }
        const projectSettings = getProjectSettings.getProjectSettings();
        if (authMode$1 === 'connect-only' &&
            !((_b = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.featureFlags) === null || _b === void 0 ? void 0 : _b.connectOnlyMultiAsset)) {
            return;
        }
        // the reason why we need to get the network here again insteaf of using the value
        // from DynamicContext is because this function might run before the network state is
        // properly set when switching wallets, so we want to make sure we have the latest network
        let requestNetwork = networkId !== null && networkId !== void 0 ? networkId : (yield (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.getNetwork(true)));
        if (requestChainName === sdkApiCore.ChainEnum.Btc) {
            // Bitcoin does not need a network ID to fetch token balances but the request requires a network ID
            requestNetwork = 1;
        }
        const isValidRequest = requestNetwork && !isNaN(Number(requestNetwork));
        logger.logger.logVerboseTroubleshootingMessage('[useTokenBalances] will try to fetch token balances', {
            isLoading,
            isValidRequest,
            networkId,
            requestAccount,
            requestChainName,
            requestNetwork,
        });
        if (isLoading || !requestAccount || !isValidRequest) {
            tokenBalances.setTokenBalanceVariable('tokenBalances', undefined);
            return;
        }
        tokenBalances.setTokenBalanceVariable('isLoading', true);
        let response = [];
        try {
            response = yield balances.getAccountTokenBalances({
                accountAddress: requestAccount,
                chainName: requestChainName,
                environmentId: dynamicContextProps.getEnvironmentId(),
                filterSpamTokens,
                forceRefresh,
                includeNative: includeNativeBalance,
                includePrices: includeFiat,
                networkId: Number(requestNetwork),
                whitelistedContracts,
            });
            if (!response) {
                tokenBalances.setTokenBalanceVariable('error', 'No token balances found');
                return;
            }
            tokenBalances.setTokenBalanceVariable('error', undefined);
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
        }
        catch (e) {
            const logLevel = (e === null || e === void 0 ? void 0 : e.code) >= 500 || (e === null || e === void 0 ? void 0 : e.code) < 400 ? 'error' : 'warn';
            yield utils.logResponseError(e, 'Error getting token balances', logLevel);
            let errorMessage = '';
            if ((e === null || e === void 0 ? void 0 : e.code) === 429) {
                errorMessage = 'Too many requests fetching balances';
            }
            else if (e === null || e === void 0 ? void 0 : e.message) {
                errorMessage = e.message;
            }
            else {
                errorMessage = 'error fetching token balance';
            }
            tokenBalances.setTokenBalanceVariable('error', errorMessage);
        }
        finally {
            // remove tokens with 0 balance.
            // This is needed because native tokens, unlike other tokens,
            // are returned in the response even if the balance is 0
            const filteredResponse = response === null || response === void 0 ? void 0 : response.filter((token) => token.balance !== 0);
            tokenBalances.setTokenBalanceVariable('tokenBalances', filteredResponse);
            tokenBalances.setTokenBalanceVariable('isLoading', false);
        }
    }), [
        requestChainName,
        isLoading,
        requestAccount,
        includeNativeBalance,
        includeFiat,
        filterSpamTokens,
        networkId,
        walletConnector,
    ]);
    useDynamicEvents.useInternalDynamicEvents('tokenBalancesChanged', () => fetchAccountBalances(true));
    React.useEffect(() => {
        fetchAccountBalances(forceRefresh);
    }, [requestAccount, network, networkId, forceRefresh]);
    const { tokensFilter } = dynamicContextProps.useDynamicSettings();
    const lowerTokenAddresses = React.useMemo(() => tokenAddresses === null || tokenAddresses === void 0 ? void 0 : tokenAddresses.map((address) => address.toLowerCase()), [tokenAddresses]);
    const initialTokenBalances = React.useMemo(() => lowerTokenAddresses
        ? tokenBalances$1 === null || tokenBalances$1 === void 0 ? void 0 : tokenBalances$1.filter((token) => lowerTokenAddresses === null || lowerTokenAddresses === void 0 ? void 0 : lowerTokenAddresses.includes(token.address.toLowerCase()))
        : tokenBalances$1, [lowerTokenAddresses, tokenBalances$1]);
    const filteredTokenBalances = React.useMemo(() => (initialTokenBalances ? tokensFilter(initialTokenBalances) : []), [initialTokenBalances, tokensFilter]);
    return {
        error,
        fetchAccountBalances,
        isError: Boolean(error),
        isLoading,
        tokenBalances: filteredTokenBalances,
    };
};

exports.useTokenBalances = useTokenBalances;
