import { ApiRx } from '@polkadot/api' ; import { createType } from '@polkadot/types' ; import { u8aToHex } from '@polkadot/util' ; import { decodeAddress } from '@polkadot/util-crypto' ; import BN from 'bn.js' ; import { Nomination , OfflineValidator , TableRowData , Validator , } from '../types' ; interface JoinNominationsAndOffline { validatorController : string ; validatorStash : string ; nominatorController : string ; nominatorStash : string ; stakedAmount : string ; wasOfflineThisSession : boolean ; } export function joinDataIntoTableRow ( api , currentNominations , currentOffline , currentValidators ) { const currentOfflineDecoded = [ ] ; const dedup = new Set ( ) ; let result = [ ] ; const final = { } ; currentOffline && currentOffline . length && currentOffline . map ( ( offline ) => { const pubkey = u8aToHex ( decodeAddress ( offline . validatorId ) ) ; currentOfflineDecoded . push ( { ... offline , validatorId : pubkey , } ) ; } ) ; currentNominations . map ( ( nomination ) => { if ( currentOfflineDecoded . length ) { currentOfflineDecoded . map ( ( offline ) => { if ( nomination . validatorStash === offline . validatorId || nomination . validatorController === offline . validatorId ) { dedup . add ( { ... nomination , wasOfflineThisSession : true , } ) ; } else { dedup . add ( { ... nomination , wasOfflineThisSession : false , } ) ; } } ) ; } else { dedup . add ( { ... nomination , wasOfflineThisSession : false , } ) ; } } ) ; result = Array . from ( dedup ) ; result . map ( ( value ) => { if ( ! final [ value . validatorStash ] ) { const preferences = currentValidators . find ( ( validator ) => validator . stash === value . validatorStash ) ?. preferences ; final [ value . validatorStash ] = { validatorController : value . validatorController , validatorStash : value . validatorStash , nominators : [ value . nominatorStash ] , stakedAmount : createType ( api . registry , 'Balance' , value . stakedAmount ) . toBn ( ) , preferences , wasOfflineThisSession : value . wasOfflineThisSession , } ; } else { const stakedAmount = ( final [ value . validatorStash ] . stakedAmount as BN ) . add ( createType ( api . registry , 'Balance' , value . stakedAmount ) . toBn ( ) ) ; final [ value . validatorStash ] = { ... final [ value . validatorStash ] , stakedAmount , } ; final [ value . validatorStash ] . nominators . push ( value . nominatorStash ) ; } } ) ; return final ; }