alchemy-sdk-js icon indicating copy to clipboard operation
alchemy-sdk-js copied to clipboard

Impossible to subscribe to `newHeads` event

Open andkom opened this issue 2 years ago • 2 comments

Environment

  • Browser version: Node v16.13
  • Alchemy SDK version: 2.2.3

Describe the problem

It's impossible to subscribe to newHeads websocket event via sdk methods. Subscription to block event only returns block number.

How to reproduce:

Method 1:

alchemy.ws.on('newHeads', (data) => {
   console.log(data);
});

// result:
unhandled: Event {
  tag: 'newheads',
  listener: [Function (anonymous)],
  once: false,
  _lastBlockNumber: -2,
  _inflight: false
}

no further events

Method 2:

alchemy.ws.on({ method: 'newHeads' }, (data) => {
   console.log(data);
});

// Unhandled rejection Error: Invalid method name newHeads. Accepted method names: alchemy_pendingTransactions,alchemy_minedTransactions

Relevant code or sample repro:

andkom avatar Nov 25 '22 10:11 andkom

You must use 'block' as the event name when using the SDK, like this:

alchemy.ws.on('block', (blockNumber: number) => {
  console.log(blockNumber)
})

luisgerardodev avatar Dec 01 '22 14:12 luisgerardodev

@luisgerardodev yes, but i want receive full header object. Alchemy WS API supports it.

andkom avatar Dec 01 '22 14:12 andkom

@andkom There hasn't been much demand for subscribing to the full block info, and the underlying ethers dependency does not support it either. May I ask what your use case is for the full block info?

In the meantime, you can subscribe directly by accessing the underlying ethers websocket provider to send your own custom subscription:

const provider = await alchemy.config.getWebsocketProvider();
await provider._subscribe("newHeads", ["newHeads"], (result) => {
  // Parse and format the block data into the same format as `getBlock()` would provide
  const block = this.formatter.block(result);
  // your code here...
});

This code block was copied over from the ethers discussion.

thebrianchen avatar Dec 12 '22 18:12 thebrianchen

@thebrianchen thanks, I need it to receive base fee updates.

andkom avatar Dec 17 '22 11:12 andkom

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs

github-actions[bot] avatar Jan 17 '23 02:01 github-actions[bot]

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs

github-actions[bot] avatar Feb 25 '23 02:02 github-actions[bot]

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs

github-actions[bot] avatar Mar 30 '23 02:03 github-actions[bot]