1

I want to get the unconfirmed balance for an address. Presently, I do it in the following manner:

ethGetTxpool = async function(address){
    var self = this;
    return new Promise((resolve, reject) => {
        self.client.call(
          {"jsonrpc": "2.0", "method": "txpool_content", "params": [], "id": 1},
          function (err, res) {
            if( err ) resolve(null);
            else {
                resolve(res.result);
            }
          }
        );
    });
};

and then filtering in JS like so:

var unconfirmedBalance = 0;
    Object.keys(txpool.pending).forEach(( txid ) => {
        Object.keys(txpool.pending[txid]).forEach(( nonce ) => {
            var tx = txpool.pending[txid][nonce];
            if( tx != null && (tx.from === address || tx.to === address) ){
                var value = Number(parseInt(tx.value, 16));
                if( tx.from === address ) unconfirmedBalance -= value;
                if( tx.to === address ) unconfirmedBalance += value;
            }
        });
    });

This works, however the data received from txpool_content API is quite big (4MB). So, the API is slow and also fails sometimes.

I came across web3.eth.filter and tried to use it in the following manner:

web3.eth.filter({
        "address": <My address>>
    }).get((error, logs) => {
        if(error)
            console.log(error);
        console.log(logs);
        });

However, it always returns an empty array even when I can see a pending transaction on etherscan.

Is there a better way to do this, apart from modifying the geth source code?

0

Have you considered using Web3.js 1.0 and WebSockets to stream the pending transactions?

https://web3js.readthedocs.io/en/1.0/web3-eth-subscribe.html

var subscription = web3.eth.subscribe('pendingTransactions', function(error, result){
    if (!error)
        console.log(result);
})
.on("data", function(transaction){
    console.log(transaction);
});

Starting from when you subscribe to the WebSockets, you will get a stream of all the pending transactions. You can then do what you were doing by looking up the transactions, extract the users involved and the amount, and update their 'unconfirmed balance'. Of course, this can all happen asynchronously, so you should never get bogged down.

I had written a small tutorial on using WebSockets and Web3.js 1.0 to build a force-directed graph drawing.

  • How do I update the unconfirmed balance after a transaction changes from unconfirmed to confirmed. Is this also triggered when it changes from pending to successful? – Koustubh Sep 12 '18 at 1:17
  • You can also set up a subscription to listen for when a new block gets formed, and get all the transactions included in that block. – Shawn Tabrizi Sep 12 '18 at 5:34

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.