Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebSocketProvider subscribing to events does not work #6094

Closed
Muhammad-Altabba opened this issue May 15, 2023 · 4 comments · Fixed by #6129
Closed

WebSocketProvider subscribing to events does not work #6094

Muhammad-Altabba opened this issue May 15, 2023 · 4 comments · Fixed by #6129
Assignees
Labels
4.x 4.0 related Bug Addressing a bug Investigate

Comments

@Muhammad-Altabba
Copy link
Contributor

Muhammad-Altabba commented May 15, 2023

Expected behavior

To be able to subscribe to events.

Actual behavior

The WebSocketProvider does not notify for new events. Actually, the same behavior happened with all events. However, the example below is with newBlockHeaders.

(Note; I am not sure if IpcProvider has the same problem. It should be checked).

Steps to reproduce the behavior

The following works with version 1.10:

    const { Web3 } = require('web3');
    // if you are trying in version 1.x use the following instead of the above:
    // const Web3 = require('web3');

   // Connect to the Ethereum network using WebSocket provider
   const ganacheUrl = 'ws://localhost:7545';
   const wsProvider = new Web3.providers.WebsocketProvider(ganacheUrl);
   const web3 = new Web3(wsProvider);

   async function main() {
       try {
           // Subscribe to new block headers
           const subscription = await web3.eth.subscribe('newBlockHeaders', (error, result) => {
                if (!error) {
                    console.log('New block header:', result);
                } else  {
                    console.log(error)
                }
           });

           // Wait for 2 seconds, then stop the subscription
           setTimeout(() => {
               subscription.unsubscribe((error, success) => {
                   if (success) {
                       console.log('Unsubscribed from new block headers');
                   }
                   if (error) {
                        console.log(error)
                   }                 
                   wsProvider.disconnect();
               });      
           }, 2000);
            
           // Get the list of accounts in the connected node which is in this case: Ganache.
           const accounts = await web3.eth.getAccounts();

           // Send a transaction to the network
           const transactionReceipt = await web3.eth.sendTransaction({
               from: accounts[0],
               to: accounts[1],
               value: web3.utils.toWei('0.001', 'ether')
           });
           console.log('Transaction Receipt:', transactionReceipt);
       } catch (error) {
           console.error(error);
       }
   }

   main();

Logs

In version 1.10, the following is printed and the program ends with no issues:

New block header: {
  logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
  miner: '0x0000000000000000000000000000000000000000',
  difficulty: '0',
  totalDifficulty: '0',
  extraData: '0x',
  gasLimit: 6721975,
  gasUsed: 21000,
  hash: '0xd315cecf3336640bcd1301930805370b7fe7528c894b931dcf8a3b1c833b68c8',
  mixHash: '0x1304070fde1c7bee383f3a59da8bb94d515cbd033b2638046520fb6fb596d827',
  nonce: '0x0000000000000000',
  number: 40,
  parentHash: '0xeb7ce3260911db2596ac843df11dbcbef302e813e1922db413f6f0b2a54d584d',
  receiptsRoot: '0xf78dfb743fbd92ade140711c8bbc542b5e307f0ab7984eff35d751969fe57efa',
  stateRoot: '0x95e416eec0932e725ec253779a4e28b3d014d05e41e63c3369f5da42d26d1240',
  timestamp: 1684165088,
  transactionsRoot: '0x8f87380cc7acfb6d10633e10f72567136492cb8301f52a41742eaca9449bb378',
  sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347',
  baseFeePerGas: 4959456,
  size: undefined
}
Transaction Receipt: {
  transactionHash: '0xccaf3ad0fca26860fd7399562780aa2459f58c46883d5a488dca19e0c92700e2',
  transactionIndex: 0,
  blockNumber: 40,
  blockHash: '0xd315cecf3336640bcd1301930805370b7fe7528c894b931dcf8a3b1c833b68c8',
  from: '0xf88bf07e251b37f4a96b20615f0eceb15bb36b0c',
  to: '0x82b4eff8e69535f7fbdde866923d1aa5d7e3ab49',
  cumulativeGasUsed: 21000,
  gasUsed: 21000,
  contractAddress: null,
  logs: [],
  logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
  status: true,
  effectiveGasPrice: 2504959456,
  type: '0x2'
}
Unsubscribed from new block headers

However, for the same piece of code, in version 4.0.1-rc.1, the output is as follows and the execution hangs without finishing:

Transaction Receipt: {
  transactionHash: '0xe2a9c9ef83b51dca697226cd77380b38ce42a0fbae73aaaddc1b8592995a741e',
  transactionIndex: 0n,
  blockNumber: 47n,
  blockHash: '0x8852c3691800a76f1a638a883598522a657a02604188b602c61c1e0e4f4e0c6b',
  from: '0xf88bf07e251b37f4a96b20615f0eceb15bb36b0c',
  to: '0x82b4eff8e69535f7fbdde866923d1aa5d7e3ab49',
  cumulativeGasUsed: 21000n,
  gasUsed: 21000n,
  logs: [],
  logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
  status: 1n,
  effectiveGasPrice: 20000000000n,
  type: 0n
}

Environment

node.js

@Muhammad-Altabba Muhammad-Altabba added Bug Addressing a bug 4.x 4.0 related labels May 15, 2023
@MiguelGonzales-WIV
Copy link

MiguelGonzales-WIV commented May 15, 2023

Same problem, except mine does not work with type "logs"

@jdevcs
Copy link
Contributor

jdevcs commented May 16, 2023

#4618 ?

@Muhammad-Altabba
Copy link
Contributor Author

#4618 ?

Thanks for referring to that. However, it seems not related. Because, at this issue (#6094), we are able to receive Transaction Receipt but we are not able to receive any event from any subscription. And the same code in this issue works well with 1.x.

@Muhammad-Altabba Muhammad-Altabba self-assigned this May 24, 2023
@Muhammad-Altabba
Copy link
Contributor Author

Sorry, there is no issue with the provider. Actually, the way how subscribing to data had changed in version 4.x. Here is how it works with version 4.x:

const { Web3 } = require('web3');

// Connect to the Ethereum network using WebSocket provider
const ganacheUrl = 'ws://localhost:8545';
const wsProvider = new Web3.providers.WebsocketProvider(ganacheUrl);
const web3 = new Web3(wsProvider);

async function main() {
	try {
		console.log(
		'Does the provider support subscriptions?:',
			wsProvider.supportsSubscriptions(),
		);

		// Subscribe to new block headers
		const subscription = await web3.eth.subscribe('newBlockHeaders');

		subscription.on("data", async (blockhead) => {
			console.log('New block header: ', blockhead);

			// You do not need the next line if you like to keep notified for every new block
			await subscription.unsubscribe(); 
			console.log('Unsubscribed from new block headers.');
		});
		subscription.on("error", (error) => 
			console.log('Error when subscribing to New block header: ', error)
		);
		
		// Get the list of accounts in the connected node which is in this case: Ganache.
		const accounts = await web3.eth.getAccounts();
		// Send a transaction to the network
		const transactionReceipt = await web3.eth.sendTransaction({
			from: accounts[0],
			to: accounts[1],
			value: web3.utils.toWei('0.001', 'ether')
		});
		console.log('Transaction Receipt:', transactionReceipt);
		
	} catch (error) {
		console.error(error);
	}
}

main();

However, since we missed this point. It seems we need to emphasize it in the documentation. Additionally, I spotted one or two places in the documentation where the old style is used. So, I will open an MR to update the documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
4.x 4.0 related Bug Addressing a bug Investigate
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants