import { useSelector } from 'react-redux' ; import { addTxToAccount as addTxToAccountRedux , destroyAccount , getStoreAccounts , updateAccount as updateAccountRedux , updateAccounts as updateAccountsRedux , useDispatch } from '@store' ; import { Asset , IAccount , ITxReceipt , NetworkId , StoreAccount , TUuid } from '@types' ; import { eqBy , prop , unionWith } from '@vendor' ; import { getAccountByAddressAndNetworkName as getAccountByAddressAndNetworkNameFunc } from './helpers' ; export interface IAccountContext { accounts : IAccount [ ] ; deleteAccount ( account ) : void ; updateAccount ( uuid , accountData ) : void ; addTxToAccount ( account , transaction ) : void ; getAccountByAddressAndNetworkName ( address , networkId ) : IAccount | undefined ; updateAccountAssets ( account , assets ) : Promise < void > ; updateAllAccountsAssets ( accounts , assets ) : Promise < void > ; updateAccounts ( toUpdate ) : void ; toggleAccountPrivacy ( uuid ) : void ; } function useAccounts ( ) { const accounts = useSelector ( getStoreAccounts ) ; const dispatch = useDispatch ( ) ; const deleteAccount = ( account ) => dispatch ( destroyAccount ( account . uuid ) ) ; const updateAccount = ( _ , account ) => dispatch ( updateAccountRedux ( account ) ) ; const addTxToAccount = ( account , tx ) => dispatch ( addTxToAccountRedux ( { account , tx } ) ) ; const removeTxFromAccount = ( accountData , tx ) => { const newAccountData = { ... accountData , transactions : [ ... accountData . transactions . filter ( ( t ) => t . hash !== tx . hash ) ] } ; updateAccount ( accountData . uuid , newAccountData ) ; } ; const getAccountByAddressAndNetworkName = getAccountByAddressAndNetworkNameFunc ( accounts ) ; const updateAccounts = ( toUpdate ) => { const newAccounts = unionWith ( eqBy ( prop ( 'uuid' ) ) , toUpdate , accounts ) . filter ( Boolean ) ; dispatch ( updateAccountsRedux ( newAccounts ) ) ; } ; const toggleAccountPrivacy = ( uuid ) => { const existingAccount = accounts . find ( ( x ) => x . uuid === uuid ) ; if ( ! existingAccount ) return ; updateAccount ( uuid , { ... existingAccount , isPrivate : existingAccount . isPrivate ? ! existingAccount . isPrivate : true } ) ; } ; return { accounts , deleteAccount , updateAccount , addTxToAccount , removeTxFromAccount , getAccountByAddressAndNetworkName , updateAccounts , toggleAccountPrivacy } ; } export default useAccounts ;