Warm tip: This article is reproduced from serverfault.com, please click

How to get balance in list

发布于 2020-12-02 02:04:05

I can recover the token balance for each account separately. With these two approaches it worked out to recover the balance individually:

Approach 1

val heldByAccount = QueryCriteria.VaultQueryCriteria().withExternalIds(accountId)
val queryCriteria = tokenAmountWithIssuerCriteria(myTokenType, issuer)
        .and(heldByAccount)
        .and(sumTokenCriteria())
val results = serviceHub.vaultService.queryBy(
        contractStateType = FungibleToken::class.java,
        criteria = queryCriteria)
val tokenbalance = rowsToAmount(myTokenType, results)

Approach 2

val sumAmount = builder { PersistentFungibleToken::amount.sum() }
val sumAmountCriteria = QueryCriteria.VaultCustomQueryCriteria(sumAmount)
val heldByAccount = QueryCriteria.VaultQueryCriteria().withExternalIds(accountId)

val sumAmountFromDB = serviceHub.vaultService.queryBy(
        contractStateType = FungibleToken::class.java,
        criteria = heldByAccount.and(sumAmountCriteria)
).otherResults

In my scenario, I need to recover the balance of many accounts several times, and doing this individually is slow. Is it possible to recover the balance of a list of accounts in a single query by grouping the balance by account?

I tried to use groupByColumns in the PersistentFungibleToken::holder column but it didn't work.

In the link below there is a way to recover the balance via query at the bank. https://www.corda.net/blog/cordas-accounts-tokens-making-blockchain-more-inclusive/

I ran the query below on my database and it really recovers the balance. Does anyone know if this is the only way to recover the balance from a list of accounts?

select ACCOUNTS.IDENTIFIER, sum(FUNGIBLE_TOKEN.AMOUNT)
from VAULT_STATES, FUNGIBLE_TOKEN, STATE_PARTY, PK_HASH_TO_EXT_ID_MAP, ACCOUNTS
where VAULT_STATES.TRANSACTION_ID = FUNGIBLE_TOKEN.TRANSACTION_ID
and VAULT_STATES.OUTPUT_INDEX = FUNGIBLE_TOKEN.OUTPUT_INDEX
and VAULT_STATES.TRANSACTION_ID = STATE_PARTY.TRANSACTION_ID
and VAULT_STATES.OUTPUT_INDEX = STATE_PARTY.OUTPUT_INDEX
and PK_HASH_TO_EXT_ID_MAP.PUBLIC_KEY_HASH = STATE_PARTY.PUBLIC_KEY_HASH
and ACCOUNTS.IDENTIFIER::text = PK_HASH_TO_EXT_ID_MAP.EXTERNAL_ID
group by ACCOUNTS.IDENTIFIER
Questioner
Marcos Pupo
Viewed
1
Marcos Pupo 2020-12-11 21:32:29

I found a solution, I don't know if it is the most elegant or the most efficient, but it is better than being tied to a database structure, and better than doing several queries with SUM in the database.

I made a vaultquery of FungibleToken with the externalIds of the desired accounts. This query returns all states / tokens of the requested accounts, I worked on the answer.

I grouped each state / token by the holder, retrieving the accountInfo by holder.owningKey and increasing the amount.quantity. That is, I did the sum manually.

I believe it is a simple solution that does what I need.