Skip to main content

New blocks

onBlock() calls you for every new block, as soon as it is finalized. No address is needed.

const cg = new ChainGate()

const btc = cg.explore(cg.networks.bitcoin)
btc.onBlock((block) => {
console.log(`Bitcoin block ${block.height}`)
console.log('Hash:', block.hash)
console.log('Transactions:', block.numTxs)
})

const eth = cg.explore(cg.networks.ethereum)
eth.onBlock((block) => {
console.log(`Ethereum block ${block.height} at ${new Date(block.timestamp * 1000)}`)
})

Connectors offer the same method: cg.connect(cg.networks.bitcoin, wallet).onBlock(cb).

Block summary​

FieldTypeUTXOEVMDescription
heightnumber✓✓Block height
hashstring✓✓Block hash
previousHashstring✓✓Hash of the previous block
numTxsnumber✓✓Number of transactions
timestampnumber—✓Block timestamp, in unix seconds

Full blocks​

onFullBlock() delivers the entire block instead of a summary. Full blocks are large — several megabytes on busy networks — so subscribe only when you really need every transaction. To follow one address, use onBalance() or onTransaction() instead.

UTXO networks​

Every transaction comes with its inputs, each one carrying the output it spends already resolved, and its outputs. Amounts are Amount instances.

btc.onFullBlock((block) => {
for (const tx of block.transactions) {
const spent = tx.inputs.reduce((sum, i) => sum + (i.prevOut?.amount.min() ?? 0n), 0n)
const sent = tx.outputs.reduce((sum, o) => sum + o.amount.min(), 0n)
console.log(tx.txid, 'fee:', spent - sent, 'sat') // 0 for the coinbase transaction
}
})
FieldDescription
height, hash, previousHash, numTxsAs in the summary
transactions[].blockIndexPosition of the transaction in the block (0 is the coinbase)
transactions[].txidTransaction id
transactions[].inputs[]{ txid, n, prevTxid, prevN, prevOut } — prevOut is the spent output ({ txid, n, amount }), null for the coinbase input
transactions[].outputs[]{ txid, n, amount }

EVM networks​

The block is delivered exactly as the chain returns it: the standard JSON-RPC block object with every transaction inline. Unlike every other event, quantities here are 0x-prefixed hex strings.

eth.onFullBlock((block) => {
console.log('Block', parseInt(block.number, 16), 'gas used:', BigInt(block.gasUsed))
for (const tx of block.transactions) {
console.log(tx.hash, tx.from, '→', tx.to, BigInt(tx.value), 'wei')
}
})