Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.

Commit 88ac791

Browse files
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
1 parent daaaff7 commit 88ac791

File tree

7 files changed

+99
-34
lines changed

7 files changed

+99
-34
lines changed

docs/docs/guides/web3_migration_guide/index.md

+4
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ const web3 = new Web3();
3232

3333
Passing callbacks to functions is no longer supported, except for event listeners.
3434

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+
3539
### Not Implemented or Exported
3640

3741
- [extend](https://web3js.readthedocs.io/en/v1.7.3/web3.html#extend) Extending web3 modules functionality is not implemented

docs/docs/guides/web3_migration_guide/subscribe_migration_guide.md

+52-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,45 @@ sidebar_label: web3.eth.subscribe
77

88
## Breaking Changes
99

10+
### Subscribing to events
11+
12+
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:
23+
24+
```typescript
25+
// in 4.x
26+
const subscription = await web3.eth.subscribe('newHeads');
27+
28+
// note that in version 4.x the way you get notified for `data` and `error` has changed
29+
subscription.on('data', async blockhead => {
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+
1049
### New Block Headers event
1150

1251
In 1.x, `web3.eth.subscribe('newBlockHeaders')` was used to subscribe to new block headers.
@@ -30,7 +69,18 @@ web3.eth.clearSubscriptions(function (error, success) {
3069

3170
// in 4.x
3271
const subscription = await web3.eth.subscribe('newHeads');
33-
subscription.unsubscribe().then(
34-
console.log(), // [...] Array of subsription ids
72+
73+
// note that in version 4.x the way you get notified for `data` and `error` has changed
74+
newBlocksSubscription.on('data', async blockhead => {
75+
console.log('New block header: ', blockhead);
76+
});
77+
newBlocksSubscription.on('error', error =>
78+
console.log('Error when subscribing to New block header: ', error),
3579
);
80+
81+
const ids = await web3.eth.clearSubscriptions();
82+
console.log(ids); // [...] An array of subscription ids that were cleared
83+
84+
// note that you can unsubscribe from a specific subscription by calling unsubscribe()
85+
// on that subscription object: `await subscription.unsubscribe();` and this would return void if succeeded.
3686
```

packages/web3-core/src/web3_config.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ export abstract class Web3Config
282282
}
283283

284284
/**
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.
286286
* Default is `10` seconds.
287287
*/
288288
public get blockHeaderTimeout() {

packages/web3-eth-contract/src/types.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ export interface ContractEventOptions {
7070
*/
7171
fromBlock?: BlockNumberOrTag;
7272
/**
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.
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.
7474
*/
7575
topics?: string[];
7676
}

packages/web3-eth/src/web3_eth.ts

+27-16
Original file line numberDiff line numberDiff line change
@@ -1244,13 +1244,13 @@ export class Web3Eth extends Web3Context<Web3EthExecutionAPI, RegisteredSubscrip
12441244
}
12451245

12461246
/**
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').
12481248
*
12491249
* @returns The mining work as an array of strings with the following structure:
12501250
*
12511251
* String 32 Bytes - at index 0: current block header pow-hash
12521252
* 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.
12541254
*
12551255
* ```ts
12561256
* web3.eth.getWork().then(console.log);
@@ -1424,7 +1424,7 @@ export class Web3Eth extends Web3Context<Web3EthExecutionAPI, RegisteredSubscrip
14241424
/**
14251425
* @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.
14261426
* @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']`
14281428
* @param returnFormat ({@link DataFormat} defaults to {@link DEFAULT_RETURN_FORMAT}) - Specifies how the return data from the call should be formatted.
14291429
* @returns `baseFeePerGas` and transaction effective `priorityFeePerGas` history for the requested block range if available.
14301430
* 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
15531553
* - on("error") - Fires when an error in the subscription occurs.
15541554
* - on("connected") - Fires once after the subscription successfully connected. Returns the subscription id.
15551555
*
1556-
* @example
1556+
* @example **Subscribe to Smart Contract events**
15571557
* ```ts
1558-
* const subscription = web3.eth.subscribe('logs', {
1558+
* // Subscribe to `logs`
1559+
* const logSubscription = web3.eth.subscribe('logs', {
15591560
* address: '0x1234567890123456789012345678901234567890',
15601561
* topics: ['0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234']
1561-
* }, function(error, result){
1562-
* if (!error)
1563-
* console.log(result);
15641562
* });
1563+
* logSubscription.on('data', (data: any) => console.log(data));
1564+
* logSubscription.on('error', (error: any) => console.log(error));
15651565
*
1566-
* const subscription = web3.eth.subscribe('logs', {
1567-
* address: '0x1234567890123456789012345678901234567890',
1568-
* topics: ['0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234']
1569-
* })
1570-
* .then(logs => console.log(logs))
1571-
* .catch(error => console.log(error));
1566+
* ```
1567+
*
1568+
* @example **Subscribe to new block headers**
1569+
* ```ts
1570+
* // Subscribe to `newBlockHeaders`
1571+
* const newBlocksSubscription = await web3.eth.subscribe('newBlockHeaders');
1572+
*
1573+
* newBlocksSubscription.on('data', async blockhead => {
1574+
* console.log('New block header: ', blockhead);
1575+
*
1576+
* // You do not need the next line, if you like to keep notified for every new block
1577+
* await newBlocksSubscription.unsubscribe();
1578+
* console.log('Unsubscribed from new block headers.');
1579+
* });
1580+
* newBlocksSubscription.on('error', error =>
1581+
* console.log('Error when subscribing to New block header: ', error),
1582+
* );
15721583
* ```
15731584
*/
15741585
public async subscribe<
@@ -1614,11 +1625,11 @@ export class Web3Eth extends Web3Context<Web3EthExecutionAPI, RegisteredSubscrip
16141625
* Resets subscriptions.
16151626
*
16161627
* @param notClearSyncing If `true` it keeps the `syncing` subscription.
1617-
* @returns `true` if successful, otherwise `false`.
1628+
* @returns A promise to an array of subscription ids that were cleared.
16181629
*
16191630
* ```ts
16201631
* web3.eth.clearSubscriptions().then(console.log);
1621-
* > true
1632+
* > [...] An array of subscription ids that were cleared
16221633
* ```
16231634
*/
16241635
public clearSubscriptions(notClearSyncing = false): Promise<string[]> | undefined {

packages/web3-eth/src/web3_subscriptions.ts

+12-12
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,13 @@ type CommonSubscriptionEvents = {
3434
connected: number;
3535
};
3636
/**
37-
* ## subscribe(logs)
37+
* ## subscribe('logs')
3838
* 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.
3939
*
4040
* 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.
4242
* - `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.
4444
*
4545
*/
4646
export class LogsSubscription extends Web3Subscription<
@@ -68,13 +68,13 @@ export class LogsSubscription extends Web3Subscription<
6868
}
6969

7070
/**
71-
* ## subscribe(pendingTransactions)
71+
* ## subscribe('pendingTransactions')
7272
* Subscribes to incoming pending transactions.
7373
*
74-
* You can subscribe to pending transactions by calling web3.eth.subscribe(pendingTransactions).
74+
* You can subscribe to pending transactions by calling web3.eth.subscribe('pendingTransactions').
7575
* @example
7676
* ```ts
77-
* web3.eth.subscribe('pendingTransactions').on("data", console.log(transaction);
77+
* (await web3.eth.subscribe('pendingTransactions')).on('data', console.log);
7878
* ```
7979
*/
8080
export class NewPendingTransactionsSubscription extends Web3Subscription<
@@ -97,15 +97,15 @@ export class NewPendingTransactionsSubscription extends Web3Subscription<
9797
}
9898

9999
/**
100-
* ## subscribe(newHeads) ( same as subscribe("newBlockHeaders"))
100+
* ## subscribe('newHeads') ( same as subscribe('newBlockHeaders'))
101101
*
102102
* Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain.
103103
*
104104
* The structure of a returned block header is {@link BlockHeaderOutput}:
105105
* @example
106106
* ```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',
109109
* console.log
110110
* );
111111
* >{
@@ -145,15 +145,15 @@ export class NewHeadsSubscription extends Web3Subscription<
145145
}
146146

147147
/**
148-
* ## subscribe(syncing)
148+
* ## subscribe('syncing')
149149
*
150150
* 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.
151151
* @example
152152
* ```ts
153-
* (await web3.eth.subscribe("syncing")).on("changed", console.log);
153+
* (await web3.eth.subscribe('syncing')).on('changed', console.log);
154154
* > `true` // when syncing
155155
*
156-
* (await web3.eth.subscribe("syncing")).on("data", console.log);
156+
* (await web3.eth.subscribe('syncing')).on('data', console.log);
157157
* > {
158158
* startingBlock: 0,
159159
* currentBlock: 0,

packages/web3-types/src/eth_contract_types.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,12 @@ export interface ContractInitOptions {
5050
export interface NonPayableCallOptions {
5151
nonce?: HexString;
5252
/**
53-
* The address the call `transaction` should be made from. For calls the `from` property is optional however it is
53+
* The address which is the call (the transaction) should be made from. For calls the `from` property is optional however it is
5454
* highly recommended to explicitly set it or it may default to address(0) depending on your node or provider.
5555
*/
5656
from?: Address;
5757
/**
58-
* The maximum gas provided for this call “transaction” (gas limit)
58+
* The maximum gas (gas limit) provided for this call (this transaction)
5959
*/
6060
gas?: string;
6161
maxPriorityFeePerGas?: HexString;

0 commit comments

Comments
 (0)