1

I wish to make a simple application using KivyMD. I want to display the latest block and pending txns on the ethereum blockchain and have it update automatically with every new block. I'm using infura url and web3.py.

pending_block = web3.eth.getBlock(block_identifier='pending', full_transactions=True)
pending_transactions = pending_block['transactions']

What do I do to make the app automatically get this every time a new block originates? Listeners? Websockets? Or use a while loop that sleeps for a specified time and calls a function to fetch the latest data?

5
  • 1
    web3js.readthedocs.io/en/v1.2.11/… might help. Jul 29, 2021 at 9:36
  • @FlorianCastelain so this will automatically send me every new pending txn? Would this have to go in an infinite while loop to be called recurrently? Also this is a JS library. I'm looking for Python. Jul 29, 2021 at 10:48
  • There is very likely the equivalent in the python module. Check the documentation for events. I have not used it, but i think you do not need a loop. You will probably have to assign a callback/method to execute whenever an event is found. Try it out. Jul 29, 2021 at 11:52
  • @FlorianCastelain I suspect that would require Infura's websocket and not HTTP request. Jul 29, 2021 at 12:40
  • Please RTFM: infura.io/docs/ethereum/wss/eth-subscribe Jul 29, 2021 at 12:59

2 Answers 2

1

You need to listen to blockchain events. From Web3js documentation:

var subscription = web3.eth.subscribe('newBlockHeaders', function(error, result){
    if (!error) {
        console.log(result);

        return;
    }

    console.error(error);
})
.on("connected", function(subscriptionId){
    console.log(subscriptionId);
})
.on("data", function(blockHeader){
    console.log(blockHeader);
})
.on("error", console.error);

// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
    if (success) {
        console.log('Successfully unsubscribed!');
    }
});
2
  • That's JS. I need a python equivalent. Jul 29, 2021 at 12:41
  • Just check Python counterpart. Concept is the same, implemention is just a detail.
    – ferit
    Jul 29, 2021 at 12:43
1

Maybe this code help you. It contains recursive function.

def checkBlockNumber(blockNumber = None):
    if blockNumber:
        if blockNumber == w3.eth.get_block_number():
            time.sleep(1)
            checkBlockNumber(blockNumber)
    else:        
        return w3.eth.get_block_number()

while True:
    block_number = checkBlockNumber()
    print(block_number)
    checkBlockNumber(block_number)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.