import { throttle } from 'lodash-unified' ; import { BalanceOfChains , ProviderType } from '@masknet/web3-shared-evm' ; import { pollingTask } from '@masknet/shared-base' ; import { getBalance , getBlockNumber , resetAllNonce } from '../../../extension/background-script/EthereumService' ; import { startEffects } from '../../../../utils-pure' ; import { UPDATE_CHAIN_STATE_DELAY } from '../constants' ; import { currentMaskWalletAccountSettings , currentAccountSettings , currentBalanceSettings , currentBlockNumberSettings , currentChainIdSettings , currentMaskWalletBalanceSettings , currentMaskWalletChainIdSettings , currentProviderSettings , currentBalancesSettings , } from '../settings' ; let beats = 0 ; const { run } = startEffects ( import . meta . webpackHot ) ; export async function kickToUpdateChainState ( ) { beats += 1 ; } export async function updateBalances ( data ) { const balancesOfChains = { ... currentBalancesSettings . value } ; for ( const [ key , value ] of Object . entries ( data ) ) { balancesOfChains [ key ] = { ... balancesOfChains [ key ] , ... value , } ; } currentBalancesSettings . value = balancesOfChains ; } export async function updateChainState ( ) { resetPoolTask ( ) ; beats = 0 ; try { ; [ currentBlockNumberSettings . value , currentBalanceSettings . value , currentMaskWalletBalanceSettings . value ] = await Promise . all ( [ getBlockNumber ( ) , currentAccountSettings . value ? getBalance ( currentAccountSettings . value , { chainId : currentChainIdSettings . value , providerType : currentProviderSettings . value , } ) . then ( ( value ) => { updateBalances ( { [ currentProviderSettings . value ] : { [ currentChainIdSettings . value ] : value , } , } ) ; return value ; } ) : currentBalanceSettings . value , currentMaskWalletAccountSettings . value ? getBalance ( currentMaskWalletAccountSettings . value , { chainId : currentMaskWalletChainIdSettings . value , providerType : ProviderType . MaskWallet , } ) : currentMaskWalletBalanceSettings . value , ] ) ; } catch { } finally { resetPoolTask ( ) ; } } export const updateChainStateThrottled = throttle ( updateChainState , 300 , { leading : false , trailing : true , } ) ; let resetPoolTask = ( ) => { } ; run ( ( ) => { const { reset , cancel } = pollingTask ( async ( ) => { if ( beats <= 0 ) return false ; await updateChainState ( ) ; return false ; } , { delay : UPDATE_CHAIN_STATE_DELAY , } ) ; resetPoolTask = reset ; return cancel ; } ) ; run ( ( ) => currentChainIdSettings . addListener ( ( ) => { updateChainStateThrottled ( ) ; if ( currentProviderSettings . value === ProviderType . MaskWallet ) resetAllNonce ( ) ; } ) ) ; run ( ( ) => currentMaskWalletChainIdSettings . addListener ( ( ) => { updateChainStateThrottled ( ) ; resetAllNonce ( ) ; } ) ) ; run ( ( ) => currentAccountSettings . addListener ( ( ) => updateChainStateThrottled ( ) ) ) ; run ( ( ) => currentMaskWalletAccountSettings . addListener ( ( ) => updateChainStateThrottled ( ) ) ) ;