Skip to content

Instantly share code, notes, and snippets.

@nullun
Created December 30, 2023 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nullun/1de5eb46862830254f20e0d3fa948ca7 to your computer and use it in GitHub Desktop.
Save nullun/1de5eb46862830254f20e0d3fa948ca7 to your computer and use it in GitHub Desktop.
Algorand TPS (defaults to 100 rounds)
import algosdk from 'algosdk';
const BLOCKRANGE = 100;
const blocks = [];
const algod = new algosdk.Algodv2(
'',
'https://mainnet-api.algonode.cloud',
443
);
// Recursively count transactions. Including transactions created by smart contracts.
function countTransactions(txns) {
let n = 0;
for (const txn of txns) {
if ('dt' in txn && 'itx' in txn['dt']) {
n += countTransactions(txn['dt']['itx']);
}
n++;
}
return n;
}
const start = await algod.status().do();
let lastRound = start['last-round'];
console.log("Algorand TPS");
console.log("Waiting for next block...");
while (true) {
const status = await algod.statusAfterBlock(lastRound).do();
lastRound = status['last-round'];
const block = await algod.block(lastRound).do();
blocks.push({
timestamp: block['block']['ts'],
round: block['block']['rnd'],
transactions: countTransactions(block['block']['txns'])
});
if (blocks.length > BLOCKRANGE) blocks.shift();
const newBlock = blocks.length - 1;
const duration = blocks[newBlock]['timestamp'] - blocks[0]['timestamp'];
const totalTxns = blocks.reduce((sum, blk) => { return sum + blk['transactions']; }, 0);
const tps = duration ? totalTxns / duration : totalTxns;
console.log(`[${new Date(blocks[newBlock]['timestamp'] * 1000).toLocaleString()}] Round: ${blocks[newBlock]['round']} Txns: ${blocks[newBlock]['transactions'].toString().padEnd(5)} (${tps.toFixed(2)} tx/s)`);
}
@pbennett
Copy link

I'd recommend instead of recursively looping through counting transactions you could instead use the 'tc' property of the block. This is the raw transaction counter. ie: Block 100, tc: 5,000,000. Block 101, tc: 5,001,235. From that alone you know that 235 transactions occurred in that block. Track across blocks and can get averages.

Comment from the block header code:
// TxnCounter is the number of the next transaction that will be
// committed after this block. Genesis blocks can start at either
// 0 or 1000, depending on a consensus parameter (AppForbidLowResources).
TxnCounter uint64 codec:"tc"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment