-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
server: Extract balances related logic from LedgerPostgresDataHandler
- Loading branch information
Showing
2 changed files
with
62 additions
and
55 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
58 changes: 58 additions & 0 deletions
58
server/app/com/xsn/explorer/util/TransactionBalancesHelper.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package com.xsn.explorer.util | ||
|
||
import com.xsn.explorer.models.persisted.{Balance, Transaction} | ||
import com.xsn.explorer.models.values.Address | ||
|
||
object TransactionBalancesHelper { | ||
|
||
def computeSpendMap(transactions: List[Transaction.HasIO]): Map[Address, BigDecimal] = { | ||
val addressValueList = for { | ||
tx <- transactions | ||
input <- tx.inputs | ||
address <- input.addresses | ||
} yield address -> input.value | ||
|
||
addressValueList | ||
.groupBy(_._1) | ||
.mapValues { list => | ||
list.map(_._2).sum | ||
} | ||
} | ||
|
||
def computeReceiveMap(transactions: List[Transaction.HasIO]): Map[Address, BigDecimal] = { | ||
val addressValueList = for { | ||
tx <- transactions | ||
output <- tx.outputs | ||
address <- output.addresses | ||
} yield address -> output.value | ||
|
||
addressValueList | ||
.groupBy(_._1) | ||
.mapValues { list => | ||
list.map(_._2).sum | ||
} | ||
} | ||
|
||
def computeBalances(transactions: List[Transaction.HasIO]): Iterable[Balance] = { | ||
val spentList = computeSpendMap(transactions).map { | ||
case (address, spent) => | ||
Balance(address, spent = spent) | ||
} | ||
|
||
val receiveList = computeReceiveMap(transactions).map { | ||
case (address, received) => | ||
Balance(address, received = received) | ||
} | ||
|
||
val result = (spentList ++ receiveList) | ||
.groupBy(_.address) | ||
.mapValues { _.reduce(mergeBalances) } | ||
.values | ||
|
||
result | ||
} | ||
|
||
private def mergeBalances(a: Balance, b: Balance): Balance = { | ||
Balance(a.address, spent = a.spent + b.spent, received = a.received + b.received) | ||
} | ||
} |