0

I'm trying to get a stream of all transactions being sent to a specific contract. Is there a way to add a filter to the below code to do that, or is it better to get all transactions and filter them as they come in?

As a followup, instead of using 'pendingTransactions' is there a way to get transactions that have been included on X blocks and can therefore be considered 'confirmed'?

subscription = web3.eth.subscribe('pendingTransactions', function (error, result) {
}).on("data", function (transactionHash) {
        web3.eth.getTransaction(transactionHash)
            .then(function (transaction) {
                console.log(transaction);
            });
    })
1

I would highly recommend taking a look at the subscription documentaion page of web3js here.

You're looking for a mixed subscription, and that will answer both your queries i.e. 1. Transactions being sent to one specific address and 2. get only confirmed transactions.

Copying and pasting directly from the documentations page

var subscription = web3.eth.subscribe('logs', {
    address: '0x123456..',
    topics: ['0x12345...']
}, function(error, result){
    if (!error)
        console.log(result);
});

In the above code address is the address of the contract. topic is generated from the event ABI. In case someone needs it, here's the way to generate the topic.

web3.eth.abi.encodeEventSignature('myEvent(uint256,bytes32)')
> 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97

The reason you are getting the pending transactions is because you're subscribed to pendingTransactions, instead use event logs, from there you can get the block numbers as well, as the events are fired once the transaction is carried out into the blockchain. To further determine the 'depth', you can calculate the block distance between the current event and the current blocknumber.

| improve this answer | |

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.