简体   繁体   中英

Why am I receiving the same transaction hash twice?

Can you please explain to me why the following code is receiving the same transaction hash twice? I want to avoid that

var Web3 = require('web3')
    const web3Subs = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws/v3/XXX'))
    const web3Trx = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws/v3/XXX'))
    const subscription = web3Subs.eth.subscribe('pendingTransactions')
    subscription.subscribe((error, txHash) => {
        if (error) console.log(error);
        console.log(txHash + " received.");
    })

output:

0x98219dad048aef55649d334a42c69ad094d3be1378f68b294aeaa2ef49ae2f97 received.
test.js:10
0x98219dad048aef55649d334a42c69ad094d3be1378f68b294aeaa2ef49ae2f97 received.
test.js:10
0x7f19d86f3c08c171060b0c29c0ad889dd7b2e69188ff6c8314caa4fb65e5b6a0 received.
test.js:10
0x7f19d86f3c08c171060b0c29c0ad889dd7b2e69188ff6c8314caa4fb65e5b6a0 received.

Doesn't look like a web3 issue, rather an RxJS issue or whatever library you're using to make those subscribe calls... You're subscribing twice, so I'd imagine that's why you're seeing things firing twice.

const subscription = web3Subs.eth.subscribe('pendingTransactions'); // You subscribe here
subscription.subscribe((error, txHash) => {  // And you subscribe again to that subscription
        if (error) console.log(error);
        console.log(txHash + " received.");
    })

I'd imagine this might give you better results if you wrote it this way, as you don't subscribe twice and still assign the subscription to a variable in case you need to reference it:

const subscription = web3Subs.eth.subscribe((error, txHash) => {
        if (error) console.log(error);
        console.log(txHash + " received.");
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM