Introduction

Infura's websocket endpoint provides support for Pub/Sub API as well as JSON-RPC filter support. Additionally, the regular Ethereum JSON-RPC API is also supported over a websocket connection and documented in the 'EXAMPLE' portion for each 'Ethereum JSON-RPC' call.

All examples in this reference section uses wscat, but will work with any tool that supports websockets.

Some tools you can use for making these requests

Websocket authentication by Project ID

Websocket subscription requests should include your PROJECT_ID in the websocket API url.

wscat -c wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID

Websocket authentication by Project ID and Project Secret

Subscriptions initiated from a secure environment can include the Project Secret as shown below:

wscat -c wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID --auth ":YOUR-PROJECT-SECRET"

EXAMPLE

The following is an example showing a connection to the websocket endpoint and using subscriptions through web3.js 1.0.

NOTE: web3.js 1.0.0-beta.34 has an open issue with request headers (https://github.com/ethereum/web3.js/issues/1559); use version 1.0.0-beta.36 or newer or revert to version 1.0.0-beta.33 to avoid this issue.

const Web3 = require("web3");

let web3 = new Web3(
  // Replace YOUR-PROJECT-ID with a Project ID from your Infura Dashboard
  new Web3.providers.WebsocketProvider("wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID")
);

const instance = new web3.eth.Contract(<abi>, <address>);

instance.getPastEvents(
    "SomeEvent",
    { fromBlock: "latest", toBlock: "latest" },
    (errors, events) => {
        if (!errors) {
            // process events
        }
    }
);

newBlockFilter

Creates a filter in the node, to notify when a new block arrives. To check if the state has changed, call eth_getFilterChanges.

EXAMPLE

>wscat -c wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID

>{"jsonrpc":"2.0","method":"eth_newBlockFilter","params":[],"id":1}

RESPONSE

RESULT FIELDS

  • FILTER ID - A string denoting the newly created filter id

BODY

{
    "jsonrpc":"2.0",
    "id":1,
    "result":"0xfe704947a3cd3ca12541458a4321c869"
}

newFilter

Creates a filter object, based on filter options, to notify when the state changes (logs). To check if the state has changed, call eth_getFilterChanges

REQUEST PAYLOAD

  • FILTER OBJECT
    • address [optional] - a contract address or a list of addresses from which logs should originate.
    • fromBlock [optional, default is "latest"] - an integer block number, or the string "latest", "earliest" or "pending"
    • toBlock [optional, default is "latest"] - an integer block number, or the string "latest", "earliest" or "pending"
    • topics[optional] - Array of 32 Bytes DATA topics. Topics are order-dependent.

A note on specifying topic filters: Topics are order-dependent. A transaction with a log with topics [A, B] will be matched by the following topic filters:

  • [] - anything"
  • [A] - A in first position (and anything after)
  • [null, B] - anything in first position AND B in second position (and anything after)
  • [A, B] - A in first position AND B in second position (and anything after)"
  • [[A, B], [A, B]] - (A OR B) in first position AND (A OR B) in second position (and anything after)

EXAMPLE

>wscat -c wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID

>{"jsonrpc":"2.0","method":"eth_newFilter","params":[{"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]}],"id":1}

RESPONSE

RESULT FIELDS

  • FILTER ID - A string denoting the newly created filter id

BODY

{
    "jsonrpc":"2.0",
    "id":1,
    "result":"0x7db09f66a25e197d995d3895278b731"
}

getFilterChanges

Polling method for a filter, which returns an array of logs which occurred since last poll.

EXAMPLE

>wscat -c wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID

>{"jsonrpc":"2.0","method":"eth_getFilterChanges","params":["0xfe704947a3cd3ca12541458a4321c869"],"id":1}

RESPONSE

RESULT FIELDS

  • LOG OBJECT ARRAY - Array of log objects, or an empty array if nothing has changed since last poll.
    • For filters created with eth_newBlockFilter the return are block hashes (32 Bytes), e.g. ["0x3454645634534..."].
    • For filters created with eth_newFilter logs are objects with following params:
  • removed: true when the log was removed, due to a chain reorganization. false if its a valid log.
  • logIndex: integer of the log index position in the block. null when its pending log.
  • transactionIndex: integer of the transactions index position log was created from. null when its pending log.
  • transactionHash: 32 Bytes - hash of the transactions this log was created from. null when its pending log.
  • blockHash: 32 Bytes - hash of the block where this log was in. null when its pending. null when its pending log.
  • blockNumber: the block number where this log was in. null when its pending. null when its pending log.
  • address: 20 Bytes - address from which this log originated.
  • data: DATA - contains the non-indexed arguments of the log.
  • topics: Array of DATA - Array of 0 to 4 32 Bytes DATA of indexed log arguments. (In solidity: The first topic is the hash of the signature of the event (e.g. Deposit(address,bytes32,uint256)), except you declared the event with the anonymous specifier.)

BODY

{
    "jsonrpc": "2.0",
    "id": 73,
    "result": [{
        "address": "0xb5a5f22694352c15b00323844ad545abb2b11028",
        "blockHash": "0x99e8663c7b6d8bba3c7627a17d774238eae3e793dee30008debb2699666657de",
        "blockNumber": "0x5d12ab",
        "data": "0x0000000000000000000000000000000000000000000000a247d7a2955b61d000",
        "logIndex": "0x0",
        "removed": false,
        "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x000000000000000000000000bdc0afe57b8e9468aa95396da2ab2063e595f37e", "0x0000000000000000000000007503e090dc2b64a88f034fb45e247cbd82b8741e"],
        "transactionHash": "0xa74c2432c9cf7dbb875a385a2411fd8f13ca9ec12216864b1a1ead3c99de99cd",
        "transactionIndex": "0x3"
    }, {
        "address": "0xe38165c9f6deb144afc9c32c206b024817e1496d",
        "blockHash": "0x99e8663c7b6d8bba3c7627a17d774238eae3e793dee30008debb2699666657de",
        "blockNumber": "0x5d12ab",
        "data": "0x0000000000000000000000000000000000000000000000000000000025c6b720",
        "logIndex": "0x3",
        "removed": false,
        "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x00000000000000000000000080e73e47173b2d00b531bf83bc39e710157125c3", "0x0000000000000000000000008f6cc93795969e5bbbf07c66dfee7d41ad24f1ef"],
        "transactionHash": "0x9e8f1cb1facb9a11a1cf947634053a0b2d557399f926b12127aa10497a2f0153",
        "transactionIndex": "0x5"
    }
}

getFilterLogs

Returns an array of all logs matching filter with given id.

REQUEST PARAMS

  • FILTER OBJECT
    • fromBlock[optional, default: "latest"] Integer block number, or "latest" for the last mined block or "pending", "earliest" for not yet mined transactions.
    • toBlock[optional, default: "latest"] Integer block number, or "latest" for the last mined block or "pending", "earliest" for not yet mined transactions.
    • address: [optional] (20 Bytes) Contract address or a list of addresses from which logs should originate.
    • topics: [optional] Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with "or" options.
    • blockhash: [optional] With the addition of EIP-234, blockHash restricts the logs returned to the single block with the 32-byte hash blockHash. Using blockHash is equivalent to fromBlock = toBlock = the block number with hash blockHash. If blockHash is present in the filter criteria, then neither fromBlock nor toBlock are allowed.

EXAMPLE

>wscat -c wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID

>{"jsonrpc":"2.0","method":"eth_getFilterLogs","params":["0xfe704947a3cd3ca12541458a4321c869"],"id":1}

RESPONSE

RESULT FIELDS

  • LOG OBJECT ARRAY - Array of log objects, or an empty array if nothing has changed since last poll.
    • logs are objects with following params:
  • removed: true when the log was removed, due to a chain reorganization. false if its a valid log.
  • logIndex: integer of the log index position in the block. null when its pending log.
  • transactionIndex: integer of the transactions index position log was created from. null when its pending log.
  • transactionHash: 32 Bytes - hash of the transactions this log was created from. null when its pending log.
  • blockHash: 32 Bytes - hash of the block where this log was in. null when its pending. null when its pending log.
  • blockNumber: the block number where this log was in. null when its pending. null when its pending log.
  • address: 20 Bytes - address from which this log originated.
  • data: DATA - contains the non-indexed arguments of the log.
  • topics: Array of DATA - Array of 0 to 4 32 Bytes DATA of indexed log arguments. (In solidity: The first topic is the hash of the signature of the event (e.g. Deposit(address,bytes32,uint256)), except you declared the event with the anonymous specifier.)

BODY

{
    "jsonrpc": "2.0",
    "id": 73,
    "result": [{
        "address": "0xb5a5f22694352c15b00323844ad545abb2b11028",
        "blockHash": "0x99e8663c7b6d8bba3c7627a17d774238eae3e793dee30008debb2699666657de",
        "blockNumber": "0x5d12ab",
        "data": "0x0000000000000000000000000000000000000000000000a247d7a2955b61d000",
        "logIndex": "0x0",
        "removed": false,
        "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x000000000000000000000000bdc0afe57b8e9468aa95396da2ab2063e595f37e", "0x0000000000000000000000007503e090dc2b64a88f034fb45e247cbd82b8741e"],
        "transactionHash": "0xa74c2432c9cf7dbb875a385a2411fd8f13ca9ec12216864b1a1ead3c99de99cd",
        "transactionIndex": "0x3"
    }, {
        "address": "0xe38165c9f6deb144afc9c32c206b024817e1496d",
        "blockHash": "0x99e8663c7b6d8bba3c7627a17d774238eae3e793dee30008debb2699666657de",
        "blockNumber": "0x5d12ab",
        "data": "0x0000000000000000000000000000000000000000000000000000000025c6b720",
        "logIndex": "0x3",
        "removed": false,
        "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x00000000000000000000000080e73e47173b2d00b531bf83bc39e710157125c3", "0x0000000000000000000000008f6cc93795969e5bbbf07c66dfee7d41ad24f1ef"],
        "transactionHash": "0x9e8f1cb1facb9a11a1cf947634053a0b2d557399f926b12127aa10497a2f0153",
        "transactionIndex": "0x5"
    }
}

uninstallFilter

Uninstalls a filter with given id. Should always be called when watch is no longer needed. Additonally Filters timeout when they aren't requested with eth_getFilterChanges for a period of time.

EXAMPLE

>wscat -c wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID

>{"jsonrpc":"2.0","method":"eth_uninstallFilter","params":["0xfe704947a3cd3ca12541458a4321c869"],"id":1}

RESPONSE

RESULT FIELDS

  • UNINSTALLED FLAG - true if the filter was successfully uninstalled, otherwise false.

BODY

{
    "jsonrpc":"2.0",
    "id":1,
    "result":true
}

subscribe

Creates a new subscription over particular events. The node will return a subscription id. For each event that matches the subscription a notification with relevant data is sent together with the subscription id.

REQUEST PARAMS

  • SUBSCRIPTION TYPE NAME [required]
    • newHeads- Subscribing to this, fires a notification each time a new header is appended to the chain, including chain reorganizations. In case of a chain reorganization the subscription will emit all new headers for the new chain. Therefore the subscription can emit multiple headers on the same height.
    • logs - Returns logs that are included in new imported blocks and match the given filter criteria. In case of a chain reorganization previous sent logs that are on the old chain will be resend with the removed property set to true. Logs from transactions that ended up in the new chain are emitted. Therefore a subscription can emit logs for the same transaction multiple times.
      • address (optional) - either an address or an array of addresses. Only logs that are created from these addresses are returned (optional)
      • topics (optional) - only logs which match the specified topics (optional)
    • newPendingTransactions - Returns the hash for all transactions that are added to the pending state and are signed with a key that is available in the node. When a transaction that was previously part of the canonical chain isn't part of the new canonical chain after a reogranization its again emitted.
    • syncing - Indicates when the node starts or stops synchronizing. The result can either be a boolean indicating that the synchronization has started (true), finished (false) or an object with various progress indicators. NOT SUPPORTED ON KOVAN!

EXAMPLE

>wscat -c wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID

// newHeads
>{"jsonrpc":"2.0", "id": 1, "method": "eth_subscribe", "params": ["newHeads"]}

// logs
>{"jsonrpc":"2.0", "id": 1, "method": "eth_subscribe", "params": ["logs", {"address": "0x8320fe7702b96808f7bbc0d4a888ed1468216cfd", "topics": ["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"]}]}

// newPendingTransactions
>{"jsonrpc":"2.0", "id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}

// syncing (not supported on Kovan)
>{"jsonrpc":"2.0", "id": 1, "method": "eth_subscribe", "params": ["syncing"]}

RESPONSE

RESULT FIELDS

  • SUBSCRIPTION ID - ID of the newly created subscription on the node

BODY

// New Subscription response
{
    "id": 1, 
    "jsonrpc": "2.0", 
    "result": "0x9cef478923ff08bf67fde6c64013158d"
}

// newHeads
{
  "jsonrpc": "2.0",
  "method": "eth_subscription",
  "params": {
    "result": {
      "difficulty": "0x15d9223a23aa",
      "extraData": "0xd983010305844765746887676f312e342e328777696e646f7773",
      "gasLimit": "0x47e7c4",
      "gasUsed": "0x38658",
      "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
      "miner": "0xf8b483dba2c3b7176a3da549ad41a48bb3121069",
      "nonce": "0x084149998194cc5f",
      "number": "0x1348c9",
      "parentHash": "0x7736fab79e05dc611604d22470dadad26f56fe494421b5b333de816ce1f25701",
      "receiptRoot": "0x2fab35823ad00c7bb388595cb46652fe7886e00660a01e867824d3dceb1c8d36",
      "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
      "stateRoot": "0xb3346685172db67de536d8765c43c31009d0eb3bd9c501c9be3229203f15f378",
      "timestamp": "0x56ffeff8",
      "transactionsRoot": "0x0167ffa60e3ebc0b080cdb95f7c0087dd6c0e61413140e39d94d3468d7c9689f"
    },
    "subscription": "0x9ce59a13059e417087c02d3236a0b1cc"
  }
}

// logs Subscription
{
    "jsonrpc":"2.0",
    "method":"eth_subscription",
    "params": {
        "subscription":"0x4a8a4c0517381924f9838102c5a4dcb7",
        "result": {
            "address":"0x8320fe7702b96808f7bbc0d4a888ed1468216cfd","blockHash":"0x61cdb2a09ab99abf791d474f20c2ea89bf8de2923a2d42bb49944c8c993cbf04",
            "blockNumber":"0x29e87","data":"0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003",
            "logIndex":"0x0",
            "topics":["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"],"transactionHash":"0xe044554a0a55067caafd07f8020ab9f2af60bdfe337e395ecd84b4877a3d1ab4",
            "transactionIndex":"0x0"
        }
    }
}

// newPendingTransaction Subscription
{
    "jsonrpc":"2.0",
    "method":"eth_subscription",
    "params":{
        "subscription":"0xc3b33aa549fb9a60e95d21862596617c",
        "result":"0xd6fdc5cc41a9959e922f30cb772a9aef46f4daea279307bc5f7024edc4ccd7fa"
    }
}

// syncing subscription (not supported on Kovan)
{
    "jsonrpc":"2.0",
    "subscription":"0xe2ffeb2703bcf602d42922385829ce96",
    "result": { 
        "syncing":true,
        "status": {
            "startingBlock":674427,
            "currentBlock":67400,
            "highestBlock":674432,
            "pulledStates":0,
            "knownStates":0
        }
    }
}

unsubscribe

Subscriptions are cancelled with a regular RPC call with eth_unsubscribe as method and the subscription id as first parameter. It returns a bool indicating if the subscription was cancelled successful.

REQUEST PARAMS

  • SUBSCRIPTION ID [required]

EXAMPLE

>wscat -c wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID

>{"jsonrpc":"2.0", "id": 1, "method": "eth_unsubscribe", "params": ["0x9cef478923ff08bf67fde6c64013158d"]}

RESPONSE

RESULT FIELDS

  • UNSUBSCRIBED FLAG - true if the subscription was cancelled successful.

BODY

{
    "id": 1, 
    "jsonrpc": "2.0", 
    "result": true
}

parity_subscribe

Starts a subscription (on WebSockets / IPC / TCP transports) to results of calling some other RPC method. For every change in returned value of that RPC call a JSON-RPC notification with result and subscription ID will be sent to a client. NOTE: parity_subscribe is only supported on the Kovan network

REQUEST PARAMS

  • RPC method name [required]
    • RPC method name (string type)
  • OPTIONAL ARGUMENTS
    • Params - Parameters passed to RPC method

EXAMPLE

>wscat -c wss://kovan.infura.io/ws/v3/YOUR-PROJECT-ID

// subscribe to eth_getBalance
>{"jsonrpc":"2.0", "id":1, "method":"parity_subscribe", "params":["eth_getBalance",["0x004702bdcC3C7dbFfd943136107E70B827028600", "latest"]]}

RESPONSE

RESULT FIELDS

  • RESULT - ID of the newly created subscription on the node

BODY

// New Subscription response
{
    "jsonrpc": "2.0",
    "result": "0x070fa1c4d1b3fd81",
    "id": 1
}

// eth_getBalance subscription notification
{
    "jsonrpc":"2.0",
    "method":"parity_subscription",
    "params": {
        "result":"0x36464dbbdd98953718",
        "subscription":"0x49a3a64111acb418"
    }
}

parity_unsubscribe

Unsubscribes from a subscription. NOTE: parity_unsubscribe is only supported on the Kovan network

REQUEST PARAMS

  • SUBSCRIPTION ID [required]

EXAMPLE

>wscat -c wss://kovan.infura.io/ws/v3/YOUR-PROJECT-ID

>{"jsonrpc":"2.0", "id":1, "method":"parity_unsubscribe", "params":["0x070fa1c4d1b3fd81"]}

RESPONSE

RESULT FIELDS

  • UNSUBSCRIBED FLAG - true if the subscription was cancelled successful.

BODY

{
    "id": 1, 
    "jsonrpc": "2.0", 
    "result": true
}

FAQ / FYI

What is the Infura endpoint for WebSockets?

There is an endpoint for each supported network (Mainnet, Ropsten, Rinkeby, Kovan, Görli); see the Getting started guide for details.

Is batch support available?

Yes

Is compression enabled?

Yes

What is the max payload size?

128MB

Why does my websocket connection disconnect after a while?

Idle connections that exceed beyond an hour will get disconnected. Adding 'pings' to your websocket connection will prevent the connection from going idle. Any unrecognized requests will trigger the server to close the connection with an error message.

Non-empty 'Sec-WebSocket-Protocol' header error?

web3.js 1.0.0-beta.34 has an open issue with request headers https://github.com/ethereum/web3.js/issues/1559. Please revert/downgrade to 1.0.0-beta.33.

Why is includeTransactions option not working for eth_subscribe?

Though the includeTransactions option is included in the Ethereum Pub/Sub API documentation, currently it is not returning the expected results. For more information: https://github.com/ethereum/go-ethereum/issues/15804.

Other Resources