您能否解释一下为什么下面的代码两次接收相同的trx哈希?您对此有何建议?
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.");
})
输出:
0x98219dad048aef55649d334a42c69ad094d3be1378f68b294aeaa2ef49ae2f97 received.
test.js:10
0x98219dad048aef55649d334a42c69ad094d3be1378f68b294aeaa2ef49ae2f97 received.
test.js:10
0x7f19d86f3c08c171060b0c29c0ad889dd7b2e69188ff6c8314caa4fb65e5b6a0 received.
test.js:10
0x7f19d86f3c08c171060b0c29c0ad889dd7b2e69188ff6c8314caa4fb65e5b6a0 received.
看起来不像是web3问题,而是RxJS问题或您用来进行那些订阅调用的任何库...您要订阅两次,所以我想这就是为什么您看到事情被触发两次的原因。
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.");
})
我想如果以这种方式编写它,可能会给您带来更好的结果,因为您不需要两次订阅,而是仍将订阅分配给变量,以防您需要引用它:
const subscription = web3Subs.eth.subscribe((error, txHash) => {
if (error) console.log(error);
console.log(txHash + " received.");
});