How do I update an api call within a while loop?

Question:

I am doing a simple request that returns a confirmation number from a blockchain using a random hash from polygonscan.

The problem I have is with the while loop, it keeps looping with the same confirmation number and not updating the true number that is represented on the blockchain.

e.g when a hash confirmation is 100 it will keep printing 100 while blockchain confirmations go up on polygonscan.

I want the ctc variable to update to the true confirmation within the while loop.

from web3 import Web3
web3 = Web3(Web3.HTTPProvider(<APIKEY>))


check_txn_confirmations = web3.eth.blockNumber - web3.eth.getTransaction('0x7a0b596a664e5b56091b775d294d374364db00cab531b8dc18c70932896ccf44ec').blockNumber

ctc = check_txn_confirmations

    while ctc < 260:
        print("confirmations are:", ctc)
        time.sleep(10)
        print("waiting 10seconds..")
    else:
        print("confirmations are larger")
Asked By: axell2017

||

Answers:

This is what you want to do but also what you shouldn’t do:

while True:

    check_txn_confirmations = web3.eth.blockNumber - web3.eth.getTransaction('0x7a0b596a664e5b56091b775d294d374364db00cab531b8dc18c70932896ccf44ec').blockNumber
    ctc = check_txn_confirmations

    if ctc < 260:
        print("confirmations are:", ctc)
        time.sleep(10)
        print("waiting 10seconds..")
    else:
        print("confirmations are larger")
        break

There are a number of problems with sending requests inside a while loop.

Most of the API’s have a request limit and the request limit is often tied to pay per usage type of agreement. If/when your program gets accidentally stuck in an infinite while loop you have a problem. Either your request limit reaches or your balance reaches 0(Exaggerating but you get the idea).

Instead, I would recommend looking into Callbacks and Async. But for simple applications callbacks should be enough.

Answered By: Geom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.