Nodejs

為什麼我無法與 Infura 建立套接字連接?項目 ID 正確,我檢查了三次

  • February 27, 2021

我想訂閱和收聽涉及資金轉移到我的錢包的事件,但是由於某種原因我無法建立到 Infura 節點的套接字連接。

首先我npm initnpm web3

編碼:

const Web3 = require('web3');

class TransactionChecker {
   web3;
   web3ws;
   account;
   subscription;

   constructor(projectId, account) {
       web3ws = new Web3.providers.WebsocketProvider('wss://kovan.infura.io/ws/v3/' + projectId);
       web3 = new Web3.providers.HttpProvider('https://kovan.infura.io/v3/' + projectId);
       account = account.toLowerCase();
   }

   subscribe(topic) {
       this.subscription = web3ws.eth.subscribe(topic, (err, res) => {
           if (err) console.error(err);
       });
   }

   watchTransactions() {
       console.log('Watching all pending transactions...');
       this.subscription.on('data', (txHash) => {
           setTimeout(async () => {
               try {
                   let tx = await this.web3.eth.getTransaction(txHash);
                   if (tx != null) {
                       if (this.account == tx.to.toLowerCase()) {
                           console.log({address: tx.from, value: this.web3.utils.fromWei(tx.value, 'ether'), timestamp: new Date()});
                       }
                   }
               } catch (err) {
                   console.error(err);
               }
           }, 60000)
       });
   }
}

let txChecker = new TransactionChecker('projectId', 'address');
txChecker.subscribe('pendingTransactions');
txChecker.watchTransactions();

給我以下錯誤:'failed to create stateful backend, closing connection: websocket: bad handshake'

網址都很好,為什麼會出錯?

它正在創建一個提供者實例,它還需要使用提供者創建一個 Web3。它可以像這樣結合兩個步驟

web3 = new Web3('wss://kovan.infura.io/ws/v3/' + projectId)

它正在做類似的事情

web3provider = new Web3.providers.WebsocketProvider('wss://kovan.infura.io/ws/v3/' + projectId)
web3 = new Web3(web3provider)

引用自:https://ethereum.stackexchange.com/questions/94018