Scanning Blocks
To implement a simple function to wait for a given block:
- TypeScript
- Python
async function waitForBlock(blockHeight: number) {
let latestBlock = (await networkStatus()).current_block_identifier.index
while (true) {
if (blockHeight <= latestBlock) {
return await block(blockHeight)
}
await sleep(10000)
latestBlock = (await networkStatus()).current_block_identifier.index
}
}
def wait_for_block(block_index):
"""
Checks if block with given index exist
Once the /block response is succesful - returns the response
Otherwise, retries fetching it with 10 seconds delay
"""
latest_block = network_status()["current_block_identifier"]["index"]
while True:
if block_index <= latest_block:
return block(block_index)
sleep(10)
latest_block = network_status()["current_block_identifier"]["index"]
It can be used to scan blocks like this:
- TypeScript
- Python
let latestBlockHeight = (await network_status()).current_block_identifier.index
while (true) {
const lastBlock = waitForBlock(latestBlockHeight)
// some processing according to business logic
latestBlockHeight += 1
}
latest_block = network_status()["current_block_identifier"]["index"]
while True:
last_block = wait_for_block(latest_block)
# some processing according to business logic
latest_block += 1