You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Mar 5, 2025. It is now read-only.
Correct and enhance documentation for subscribing to events (#6129)
* correction and elaboration on `clearSubscriptions` at migration guide
* corrections and elaboration on Web3Eth `subscribe` documentation
* replace “, ”, and " with ' and/or ` at some files
* add clarification and section for web3.eth.subscribe Migration Guide
Copy file name to clipboardExpand all lines: docs/docs/guides/web3_migration_guide/index.md
+4
Original file line number
Diff line number
Diff line change
@@ -32,6 +32,10 @@ const web3 = new Web3();
32
32
33
33
Passing callbacks to functions is no longer supported, except for event listeners.
34
34
35
+
For example, the approach to subscribing-to and listening-for blockchain events has changed in version 4.x. Detailed instructions can be found in the [**`web3.eth.subscribe` Migration Guide**](/docs/guides/web3_migration_guide/subscribe_migration_guide#subscribing-to-events).
36
+
37
+
However, the approach to subscribing to Provider events remains the same, utilizing callbacks as explained in the [Providers Events Listening guide](/docs/guides/web3_providers_guide/events_listening). It is important to note that Providers have undergone some breaking changes, including the renaming of the `on('close', ...)` to `on('disconnect', ...)`.
38
+
35
39
### Not Implemented or Exported
36
40
37
41
-[extend](https://web3js.readthedocs.io/en/v1.7.3/web3.html#extend) Extending web3 modules functionality is not implemented
You subscribe to blockchain events using the `web3.eth.subscribe` API.
13
+
14
+
However, in web3.js version 1.x, for example, you could subscribe to the `newBlockHeaders` event, in one step, with the following code snippet:
15
+
16
+
```typescript
17
+
var subscription =web3.eth.subscribe('newBlockHeaders', function (error, result) {
18
+
if (!error) console.log(result);
19
+
});
20
+
```
21
+
22
+
But, in web3.js Version 4.x, the function signature has changed for `web3.eth.subscribe`. In addition, the way you get notified for `data` and `error` has also changed. It is now in 2 steps: First you subscribe and then you listen to events. Here's an example of how you would subscribe to the same `newBlockHeaders` event in web3.js version 4.x:
// note that in version 4.x the way you get notified for `data` and `error` has changed
29
+
subscription.on('data', asyncblockhead=> {
30
+
console.log('New block header: ', blockhead);
31
+
});
32
+
subscription.on('error', error=>
33
+
console.log('Error when subscribing to New block header: ', error),
34
+
);
35
+
```
36
+
37
+
#### Differences
38
+
39
+
In summary, the differences you need to be aware of when subscribing to blockchain events in web3.js version 4.x are:
40
+
41
+
- The `subscribe` function signature has changed:
42
+
- It does not accept a callback function.
43
+
- It returns a subscription object that you can use to listen to `data` and `error` events.
44
+
- You should now use the `on`, or `once`, method on the newly returned subscription object to listen to `data` and `error` events, instead of passing a callback function directly.
45
+
- You can have multiple event listeners, if you have, for example multiple `on` calls. And you can get the number of listeners in you code by calling `listenerCount(event_name)` or get the listeners with `listeners(event_name)`.
46
+
47
+
Keep in mind that these differences apply to all blockchain event subscriptions, not just to the `newBlockHeaders` event.
48
+
10
49
### New Block Headers event
11
50
12
51
In 1.x, `web3.eth.subscribe('newBlockHeaders')` was used to subscribe to new block headers.
Copy file name to clipboardExpand all lines: packages/web3-core/src/web3_config.ts
+1-1
Original file line number
Diff line number
Diff line change
@@ -282,7 +282,7 @@ export abstract class Web3Config
282
282
}
283
283
284
284
/**
285
-
* The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it should wait for “newBlockHeaders” event before falling back to polling to fetch transaction receipt.
285
+
* The blockHeaderTimeout is used over socket-based connections. This option defines the amount seconds it should wait for `'newBlockHeaders'` event before falling back to polling to fetch transaction receipt.
* This allows to manually set the topics for the event filter. If given the filter property and event signature, (topic[0]) will not be set automatically. Each topic can also be a nested array of topics that behaves as “or” operation between the given nested topics.
73
+
* This allows to manually set the topics for the event filter. If given the filter property and event signature, (topic[0]) will not be set automatically. Each topic can also be a nested array of topics that behaves as `or` operation between the given nested topics.
Copy file name to clipboardExpand all lines: packages/web3-eth/src/web3_eth.ts
+27-16
Original file line number
Diff line number
Diff line change
@@ -1244,13 +1244,13 @@ export class Web3Eth extends Web3Context<Web3EthExecutionAPI, RegisteredSubscrip
1244
1244
}
1245
1245
1246
1246
/**
1247
-
* Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met (“target”).
1247
+
* Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met ('target').
1248
1248
*
1249
1249
* @returns The mining work as an array of strings with the following structure:
1250
1250
*
1251
1251
* String 32 Bytes - at index 0: current block header pow-hash
1252
1252
* String 32 Bytes - at index 1: the seed hash used for the DAG.
1253
-
* String 32 Bytes - at index 2: the boundary condition (“target”), 2^256 / difficulty.
1253
+
* String 32 Bytes - at index 2: the boundary condition ('target'), 2^256 / difficulty.
1254
1254
*
1255
1255
* ```ts
1256
1256
* web3.eth.getWork().then(console.log);
@@ -1424,7 +1424,7 @@ export class Web3Eth extends Web3Context<Web3EthExecutionAPI, RegisteredSubscrip
1424
1424
/**
1425
1425
* @param blockCount Number of blocks in the requested range. Between `1` and `1024` blocks can be requested in a single query. Less than requested may be returned if not all blocks are available.
1426
1426
* @param newestBlock Highest number block of the requested range.
1427
-
* @param rewardPercentiles A monotonically increasing list of percentile values to sample from each block’s effective priority fees per gas in ascending order, weighted by gas used. Example: `[“0”, “25”, “50”, “75”, “100”]` or `[“0”, “0.5”, “1”, “1.5”, “3”, “80”]`
1427
+
* @param rewardPercentiles A monotonically increasing list of percentile values to sample from each block’s effective priority fees per gas in ascending order, weighted by gas used. Example: `['0', '25', '50', '75', '100']` or `['0', '0.5', '1', '1.5', '3', '80']`
1428
1428
* @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted.
1429
1429
* @returns `baseFeePerGas` and transaction effective `priorityFeePerGas` history for the requested block range if available.
1430
1430
* The range between `headBlock - 4` and `headBlock` is guaranteed to be available while retrieving data from the `pending` block and older history are optional to support.
@@ -1553,22 +1553,33 @@ export class Web3Eth extends Web3Context<Web3EthExecutionAPI, RegisteredSubscrip
1553
1553
* - on("error") - Fires when an error in the subscription occurs.
1554
1554
* - on("connected") - Fires once after the subscription successfully connected. Returns the subscription id.
Copy file name to clipboardExpand all lines: packages/web3-eth/src/web3_subscriptions.ts
+12-12
Original file line number
Diff line number
Diff line change
@@ -34,13 +34,13 @@ type CommonSubscriptionEvents = {
34
34
connected: number;
35
35
};
36
36
/**
37
-
* ## subscribe(“logs”)
37
+
* ## subscribe('logs')
38
38
* Subscribes to incoming logs, filtered by the given options. If a valid numerical fromBlock options property is set, web3.js will retrieve logs beginning from this point, backfilling the response as necessary.
39
39
*
40
40
* You can subscribe to logs matching a given filter object, which can take the following parameters:
41
-
* - `fromBlock`: (optional, default: “latest”) Integer block number, or “latest” for the last mined block or “pending”, “earliest” for not yet mined transactions.
41
+
* - `fromBlock`: (optional, default: 'latest') Integer block number, or `'latest'` for the last mined block or `'pending'`, `'earliest'` for not yet mined transactions.
42
42
* - `address`: (optional) Contract address or a list of addresses from which logs should originate.
43
-
* - `topics`: (optional) Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with “or” options.
43
+
* - `topics`: (optional) Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with `or` options.
@@ -97,15 +97,15 @@ export class NewPendingTransactionsSubscription extends Web3Subscription<
97
97
}
98
98
99
99
/**
100
-
* ## subscribe(“newHeads”) ( same as subscribe("newBlockHeaders"))
100
+
* ## subscribe('newHeads') ( same as subscribe('newBlockHeaders'))
101
101
*
102
102
* Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain.
103
103
*
104
104
* The structure of a returned block header is {@link BlockHeaderOutput}:
105
105
* @example
106
106
* ```ts
107
-
* (await web3.eth.subscribe("newHeads")).on( // "newBlockHeaders" would work as well
108
-
* "data",
107
+
* (await web3.eth.subscribe('newHeads')).on( // 'newBlockHeaders' would work as well
108
+
* 'data',
109
109
* console.log
110
110
* );
111
111
* >{
@@ -145,15 +145,15 @@ export class NewHeadsSubscription extends Web3Subscription<
145
145
}
146
146
147
147
/**
148
-
* ## subscribe(“syncing”)
148
+
* ## subscribe('syncing')
149
149
*
150
150
* Subscribe to syncing events. This will return `true` when the node is syncing and when it’s finished syncing will return `false`, for the `changed` event.
0 commit comments