Query the ledger for transactions

The ledger data (Transaction, Receipt, Log, Transfers, Contract, etc) can be access from self.context.ledger.

The code to query the number of transaction per block uses the aggregation function.

with self.context.ledger.Transaction as q:
    count = q.select(
    aggregates=[(f'COUNT(DISTINCT {q.HASH})', 'count_tx')],
    where=q.BLOCK_NUMBER.gt(self.context.block_number - input.block_number_count))

The returned count is a LedgerModelOutput object. We can get the result from count.data.

We can first test drive the ledger query in Cmf console. Temporarily moving away from the editor to the console. Type credmark-dev run console,

> credmark-dev run console
2022-10-25 14:52:34,498 - credmark.cmf.engine.context - INFO - Using latest block number 15823165
Entering Credmark Model Console at block 15823165.
Help: help(), Quit: quit()
Available vars: context, models, ledger, web3, etc.
Available types: BlockNumber, Address, Contract, Token...

In [1]:

You could put the above with some tweak the where clause, we only query the current block number. In Cmf console, variable block_number is auto-created to store the current block number, equal to self.context.block_number.

In [2]: with self.context.ledger.Transaction as q:
...:        count = q.select(aggregates=[(f'COUNT(DISTINCT {q.HASH})', 'count_tx')],
...:                         where=q.BLOCK_NUMBER.eq(block_number))
...:
In [3]: count
Out[3]: LedgerModelOutput(data=[{'count_tx': 21}])

q.HASH.count_distinct_() is translated to f'COUNT(DISTINCT {q.HASH})' in the back end. We have included some SQL functions to be applied to the field, press . inside the console to know more of them. If you would like to add more, please talk to us.

The various object levels and their values are:

count
# LedgerModelOutput(data=[{'count_tx': 21}])

count.data
# [{'count_tx': 21}]

count.data[0]
# {'count_tx': 21}

count.data[0]['count_tx']
# 21

Last updated