The Publish-Subscribe API of Conflux (also called pub-sub) makes it possible to query certain items on an ongoing basis, without polling through the JSON-RPC HTTP interface. You can use this API on top of a TCP or WebSocket connection.
To use the pub-sub API, please make sure that you have access to a node with its TCP or WebSocket port open. If you maintain your own node, you can set these using the
--jsonrpc-tcp-port PORT and
--jsonrpc-ws-port PORT CLI flags (see
conflux --help) or through the
jsonrpc_ws_port configuration parameters (see
run/default.toml). In this document, we will use the default TCP (
12536) and WebSocket (
You can subscribe to a topic through a
cfx_subscribe JSON-RPC call. This will result in a subscription ID, which can later be used to unsubscribe through a
cfx_unsubscribe JSON-RPC call.
The following example shows how to create a subscription over a TCP connection using
The following example shows how to create a subscription over a WebSocket connection using
Currently, we support the following topics:
newHeads topic streams all new block headers participating in the consensus.
epochs topic streams consensus results: the total order of blocks, as expressed by a sequence of epochs.
The returned series of epoch numbers is monotonically increasing with an increment of one. If you see the same epoch twice, this suggests a pivot chain reorg has happened (this might happen for recent epochs).
For each epoch, the last hash in
epochHashesOrdered is the hash of the pivot block. In the example above, we know that currently the last section of the pivot chain is:
logs topic streams all logs matching a certain filter, in order.
The filter format follows that of the
cfx_getLogs JSON-RPC API. It is a JSON object with the (optional) fields
address (contract address), and
topics (order-dependent array of indexed log topics).
In case of a pivot chain reorg (which might affect recent logs), a special
revert message is sent. All logs received previously that belong to epochs larger than the one in this message should be considered invalid.
In the example above, the
revert message invalidates all logs with an epoch number greater than
0x40f (i.e. epochs
0x411, etc). Transaction
0xf639c7b... is re-executed and the corresponding log is published again. This time, the transaction ends up in epoch
0x410 instead of
0x411. All logs in the epochs up to (and including)
0x40f remain valid.
logs pub-sub topic is not supported on light nodes.
Below is a simple example of using the pub-sub API through Node.js. In this example, we detect pivot chain reorgs using the
epochs topic. We rely on 3rd-party libraries, as
js-conflux-sdk does not support the pub-sub API yet. For simplicity, we omit error handling.
Note: Shallow pivot chain reorgs are quite common as the end of the pivot chain tends to oscillate before it stabilizes.