import { IVoteTracker , HEX_ZERO_HASH } from "./interface" ; import { ProtoArrayError , ProtoArrayErrorCode } from "./errors" ; /**
 * Returns a list of `deltas`, where there is one delta for each of the indices in `indices`
 *
 * The deltas are formed by a change between `oldBalances` and `newBalances`, and/or a change of vote in `votes`.
 *
 * ## Errors
 *
 * - If a value in `indices` is greater to or equal to `indices.length`.
 */ export function computeDeltas ( indices , votes , oldBalances , newBalances ) { const deltas = Array . from ( { length : indices . size } , ( ) => 0 ) ; const zeroHash = HEX_ZERO_HASH ; for ( let vIndex = 0 ; vIndex < votes . length ; vIndex ++ ) { const vote = votes [ vIndex ] ; if ( vote === undefined ) { continue ; } const { currentRoot , nextRoot } = vote ; if ( currentRoot === zeroHash && nextRoot === zeroHash ) { continue ; } const oldBalance = oldBalances [ vIndex ] || 0 ; const newBalance = newBalances [ vIndex ] || 0 ; if ( currentRoot !== nextRoot || oldBalance !== newBalance ) { const currentDeltaIndex = indices . get ( currentRoot ) ; if ( currentDeltaIndex !== undefined ) { if ( currentDeltaIndex >= deltas . length ) { throw new ProtoArrayError ( { code : ProtoArrayErrorCode . INVALID_NODE_DELTA , index : currentDeltaIndex , } ) ; } deltas [ currentDeltaIndex ] -= oldBalance ; } const nextDeltaIndex = indices . get ( nextRoot ) ; if ( nextDeltaIndex !== undefined ) { if ( nextDeltaIndex >= deltas . length ) { throw new ProtoArrayError ( { code : ProtoArrayErrorCode . INVALID_NODE_DELTA , index : nextDeltaIndex , } ) ; } deltas [ nextDeltaIndex ] += newBalance ; } } vote . currentRoot = nextRoot ; } return deltas ; }