import { Account } from 'shared/model/account' ; import { getAddressByPublicKey } from 'shared/util/account' ; import DelegateRepository from 'core/repository/delegate' ; import { Address , PublicKey , SerializedAccount } from 'shared/model/types' ; export type Statistics = { tokenHolders : number ; totalStakeAmount : number ; totalStakeHolders : number ; } ; class AccountRepository { private memoryAccountsByAddress : Map < Address , Account > = new Map < Address , Account > ( ) ; public add ( accountData ) { const accountModel = new Account ( accountData ) ; this . memoryAccountsByAddress . set ( accountData . address , accountModel ) ; return accountModel ; } getByAddress ( accountAddress ) { return this . memoryAccountsByAddress . get ( accountAddress ) || null ; } getByPublicKey ( accountPublicKey ) { const address = getAddressByPublicKey ( accountPublicKey ) ; return this . memoryAccountsByAddress . get ( address ) || null ; } getAll ( ) { const accounts = [ ] ; for ( let value of this . memoryAccountsByAddress . values ( ) ) { accounts . push ( value ) ; } return accounts ; } getStatistics ( ) { let tokenHolders = 0 ; let totalStakeAmount = 0 ; let totalStakeHolders = 0 ; for ( const account of this . memoryAccountsByAddress . values ( ) ) { if ( account . actualBalance > 0 ) { tokenHolders ++ ; } const activeStakes = account . stakes . filter ( stake => stake . isActive ) ; if ( activeStakes . length > 0 ) { totalStakeAmount += activeStakes . reduce ( ( sum , stake ) => sum += stake . amount , 0 ) ; totalStakeHolders += 1 ; } } return { tokenHolders , totalStakeAmount , totalStakeHolders } ; } delete ( account ) { this . memoryAccountsByAddress . delete ( account . address ) ; } updateBalance ( account , balance ) { this . memoryAccountsByAddress . get ( account . address ) . actualBalance = balance ; } updateBalanceByAddress ( address , difference ) { this . memoryAccountsByAddress . get ( address ) . actualBalance += difference ; } updateVotes ( account , votes ) { this . memoryAccountsByAddress . get ( account . address ) . votes = votes ; } updateReferralByAddress ( address , referrals ) { this . memoryAccountsByAddress . get ( address ) . referrals = referrals ; } serialize ( account , withDelegates = true ) { return { address : account . address . toString ( ) , isDelegate : Boolean ( account . delegate ) , publicKey : account . publicKey , secondPublicKey : account . secondPublicKey , actualBalance : account . actualBalance , referrals : account . referrals . map ( acc => acc . address . toString ( ) ) , votes : withDelegates ? account . votes . map ( ( publicKey ) => DelegateRepository . serialize ( DelegateRepository . getDelegate ( publicKey ) ) ) . reverse ( ) : account . votes , stakes : [ ... account . stakes ] . reverse ( ) , } ; } } export default new AccountRepository ( ) ;