'How can I calculate the average gas cost per a transaction on RSK?
I want to calculate an average gas fee paid for all transactions on the RSK within the last three months. I tried to query the RSK blockchain using the Web3.js library. To get transaction data for just a single block height, I had to do:
const txsPerBlock = await web3.getBlockTransactionCount(block.height);
const txs = await Promise.all(
[...Array(txsPerBlock).keys()].map(
(i) => web3.eth.getTransactionFromBlock(block.height, i))
);
And then to calculate the average gas fee:
const averageGasFee = txs.reduce(
(p, c) => p + Number(c.gasPrice) * c.gas,
0
) / txs.length;
However, within 3 months there were about 230,000 blocks on RSK including about 3 transactions per block. So I had to poll about 600,000 transactions that would take forever to complete. I waited for an hour and then canceled the script. Is there a better to query the RSK blockchain and calculate the average transaction gas fee over such a large number of blocks and transactions?
Solution 1:[1]
You can use the getBlock() method (docs) that is able to return all transactions in the block at once if you pass true as the second param (returnTransactionObjects).
const block = await web3.eth.getBlock(blockNumber, true);
const averageGasFee = block.transactions.reduce(
(p, c) => p + Number(c.gasPrice) * c.gas,
0
) / block.transactions.length;
This results in "only" 230k requests instead the previous 600k.
Solution 2:[2]
It's much easier to accomplish this using Covalent. You can calculate the desired gas fees by performing a single PostgreSQL query:
SELECT AVG(t.gas_spent * t.gas_price) / 10^18 AS gas_paid
FROM chain_rsk_mainnet.block_transactions t
WHERE
t.signed_at > (NOW() - INTERVAL '3 month')
AND t.signed_at <= NOW()
;
The result of this query is 0.000009922904625 (RBTC),
and it took only 4.2 seconds to execute/ obtain the result.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Petr Hejda |
| Solution 2 | Aleks Shenshin |
