JSON-RPC API (original) (raw)

In order for a software application to interact with the Ethereum blockchain - either by reading blockchain data or sending transactions to the network - it must connect to an Ethereum node.

For this purpose, every Ethereum client implements a JSON-RPC specification(opens in a new tab), so there is a uniform set of methods that applications can rely on regardless of the specific node or client implementation.

JSON-RPC(opens in a new tab) is a stateless, light-weight remote procedure call (RPC) protocol. It defines several data structures and the rules around their processing. It is transport agnostic in that the concepts can be used within the same process, over sockets, over HTTP, or in many various message passing environments. It uses JSON (RFC 4627) as data format.

Client implementations

Ethereum clients each may utilize different programming languages when implementing the JSON-RPC specification. See individual client documentation for further details related to specific programming languages. We recommend checking the documentation of each client for the latest API support information.

Convenience Libraries

While you may choose to interact directly with Ethereum clients via the JSON-RPC API, there are often easier options for dapp developers. Many JavaScript and backend API libraries exist to provide wrappers on top of the JSON-RPC API. With these libraries, developers can write intuitive, one-line methods in the programming language of their choice to initialize JSON-RPC requests (under the hood) that interact with Ethereum.

Consensus client APIs

This page deals mainly with the JSON-RPC API used by Ethereum execution clients. However, consensus clients also have an RPC API that allows users to query information about the node, request Beacon blocks, Beacon state, and other consensus-related information directly from a node. This API is documented on the Beacon API webpage(opens in a new tab).

An internal API is also used for inter-client communication within a node - that is, it enables the consensus client and execution client to swap data. This is called the 'Engine API' and the specs are available on GitHub(opens in a new tab).

Execution client spec

Read the full JSON-RPC API spec on GitHub(opens in a new tab). This API is documented on the Execution API webpage(opens in a new tab) and includes an Inspector to try out all the available methods.

Conventions

Hex value encoding

Two key data types get passed over JSON: unformatted byte arrays and quantities. Both are passed with a hex encoding but with different requirements for formatting.

Quantities

When encoding quantities (integers, numbers): encode as hex, prefix with "0x", the most compact representation (slight exception: zero should be represented as "0x0").

Here are some examples:

Unformatted data

When encoding unformatted data (byte arrays, account addresses, hashes, bytecode arrays): encode as hex, prefix with "0x", two hex digits per byte.

Here are some examples:

The default block parameter

The following methods have an extra default block parameter:

When requests are made that act on the state of Ethereum, the last default block parameter determines the height of the block.

The following options are possible for the defaultBlock parameter:

Examples

On this page we provide examples of how to use individual JSON_RPC API endpoints using the command line tool, curl(opens in a new tab). These individual endpoint examples are found below in the Curl examples section. Further down the page, we also provide an end-to-end example for compiling and deploying a smart contract using a Geth node, the JSON_RPC API and curl.

Curl examples

Examples of using the JSON_RPC API by making curl(opens in a new tab) requests to an Ethereum node are provided below. Each example includes a description of the specific endpoint, its parameters, return type, and a worked example of how it should be used.

The curl requests might return an error message relating to the content type. This is because the --data option sets the content type to application/x-www-form-urlencoded. If your node does complain about this, manually set the header by placing -H "Content-Type: application/json" at the start of the call. The examples also do not include the URL/IP & port combination which must be the last argument given to curl (e.g. 127.0.0.1:8545). A complete curl request including these additional data takes the following form:

Gossip, State, History

A handful of core JSON-RPC methods require data from the Ethereum network, and fall neatly into three main categories: Gossip, State, and History. Use the links in these sections to jump to each method, or use the table of contents to explore the whole list of methods.

Gossip Methods

These methods track the head of the chain. This is how transactions make their way around the network, find their way into blocks, and how clients find out about new blocks.

State Methods

Methods that report the current state of all the data stored. The "state" is like one big shared piece of RAM, and includes account balances, contract data, and gas estimations.

History Methods

Fetches historical records of every block back to genesis. This is like one large append-only file, and includes all block headers, block bodies, uncle blocks, and transaction receipts.

JSON-RPC API Playground

You can use the playground tool(opens in a new tab) to discover and try out the API methods. It also shows you which methods and networks are supported by various node providers.

JSON-RPC API Methods

web3_clientVersion

Returns the current client version.

Parameters

None

Returns

String - The current client version

Example

web3_sha3

Returns Keccak-256 (not the standardized SHA3-256) of the given data.

Parameters

  1. DATA - The data to convert into a SHA3 hash

Returns

DATA - The SHA3 result of the given string.

Example

net_version

Returns the current network id.

Parameters

None

Returns

String - The current network id.

The full list of current network IDs is available at chainlist.org(opens in a new tab). Some common ones are:

Example

net_listening

Returns true if client is actively listening for network connections.

Parameters

None

Returns

Boolean - true when listening, otherwise false.

Example

net_peerCount

Returns number of peers currently connected to the client.

Parameters

None

Returns

QUANTITY - integer of the number of connected peers.

Example

eth_protocolVersion

Returns the current Ethereum protocol version. Note that this method is not available in Geth(opens in a new tab).

Parameters

None

Returns

String - The current Ethereum protocol version

Example

eth_syncing

Returns an object with data about the sync status or false.

Parameters

None

Returns

The precise return data varies between client implementations. All clients return False when the node is not syncing, and all clients return the following fields.

Object|Boolean, An object with sync status data or FALSE, when not syncing:

However, the individual clients may also provide additional data. For example Geth returns the following:

Whereas Besu returns:

Refer to the documentation for your specific client for more details.

Example

eth_coinbase

Returns the client coinbase address.

Note: This method has been deprecated as of v1.14.0 and is no longer supported. Attempting to use this method will result in a "Method not supported" error.

Parameters

None

Returns

DATA, 20 bytes - the current coinbase address.

Example

eth_chainId

Returns the chain ID used for signing replay-protected transactions.

Parameters

None

Returns

chainId, hexadecimal value as a string representing the integer of the current chain id.

Example

eth_mining

Returns true if client is actively mining new blocks. This can only return true for proof-of-work networks and may not be available in some clients since The Merge.

Parameters

None

Returns

Boolean - returns true of the client is mining, otherwise false.

Example

eth_hashrate

Returns the number of hashes per second that the node is mining with. This can only return true for proof-of-work networks and may not be available in some clients since The Merge.

Parameters

None

Returns

QUANTITY - number of hashes per second.

Example

eth_gasPrice

Returns an estimate of the current price per gas in wei. For example, the Besu client examines the last 100 blocks and returns the median gas unit price by default.

Parameters

None

Returns

QUANTITY - integer of the current gas price in wei.

Example

eth_accounts

Returns a list of addresses owned by client.

Parameters

None

Returns

Array of DATA, 20 Bytes - addresses owned by the client.

Example

eth_blockNumber

Returns the number of most recent block.

Parameters

None

Returns

QUANTITY - integer of the current block number the client is on.

Example

eth_getBalance

Returns the balance of the account of given address.

Parameters

  1. DATA, 20 Bytes - address to check for balance.
  2. QUANTITY|TAG - integer block number, or the string "latest", "earliest", "pending", "safe", or "finalized", see the default block parameter

Returns

QUANTITY - integer of the current balance in wei.

Example

eth_getStorageAt

Returns the value from a storage position at a given address.

Parameters

  1. DATA, 20 Bytes - address of the storage.
  2. QUANTITY - integer of the position in the storage.
  3. QUANTITY|TAG - integer block number, or the string "latest", "earliest", "pending", "safe", "finalized", see the default block parameter

Returns

DATA - the value at this storage position.

ExampleCalculating the correct position depends on the storage to retrieve. Consider the following contract deployed at 0x295a70b2de5e3953354a6a8344e616ed314d7251 by address 0x391694e7e0b0cce554cb130d723a9d27458f9298.

Retrieving the value of pos0 is straight forward:

Retrieving an element of the map is harder. The position of an element in the map is calculated with:

This means to retrieve the storage on pos1["0x391694e7e0b0cce554cb130d723a9d27458f9298"] we need to calculate the position with:

The geth console which comes with the web3 library can be used to make the calculation:

Now to fetch the storage:

eth_getTransactionCount

Returns the number of transactions sent from an address.

Parameters

  1. DATA, 20 Bytes - address.
  2. QUANTITY|TAG - integer block number, or the string "latest", "earliest", "pending", "safe" or "finalized", see the default block parameter

Returns

QUANTITY - integer of the number of transactions send from this address.

Example

eth_getBlockTransactionCountByHash

Returns the number of transactions in a block from a block matching the given block hash.

Parameters

  1. DATA, 32 Bytes - hash of a block

Returns

QUANTITY - integer of the number of transactions in this block.

Example

eth_getBlockTransactionCountByNumber

Returns the number of transactions in a block matching the given block number.

Parameters

  1. QUANTITY|TAG - integer of a block number, or the string "earliest", "latest", "pending", "safe" or "finalized", as in the default block parameter.

Returns

QUANTITY - integer of the number of transactions in this block.

Example

eth_getUncleCountByBlockHash

Returns the number of uncles in a block from a block matching the given block hash.

Parameters

  1. DATA, 32 Bytes - hash of a block

Returns

QUANTITY - integer of the number of uncles in this block.

Example

eth_getUncleCountByBlockNumber

Returns the number of uncles in a block from a block matching the given block number.

Parameters

  1. QUANTITY|TAG - integer of a block number, or the string "latest", "earliest", "pending", "safe" or "finalized", see the default block parameter

Returns

QUANTITY - integer of the number of uncles in this block.

Example

eth_getCode

Returns code at a given address.

Parameters

  1. DATA, 20 Bytes - address
  2. QUANTITY|TAG - integer block number, or the string "latest", "earliest", "pending", "safe" or "finalized", see the default block parameter

Returns

DATA - the code from the given address.

Example

eth_sign

The sign method calculates an Ethereum specific signature with: sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))).

By adding a prefix to the message makes the calculated signature recognizable as an Ethereum specific signature. This prevents misuse where a malicious dapp can sign arbitrary data (e.g. transaction) and use the signature to impersonate the victim.

Note: the address to sign with must be unlocked.

Parameters

  1. DATA, 20 Bytes - address
  2. DATA, N Bytes - message to sign

Returns

DATA: Signature

Example

eth_signTransaction

Signs a transaction that can be submitted to the network at a later time using with eth_sendRawTransaction.

Parameters

  1. Object - The transaction object

Returns

DATA, The RLP-encoded transaction object signed by the specified account.

Example

eth_sendTransaction

Creates new message call transaction or a contract creation, if the data field contains code, and signs it using the account specified in from.

Parameters

  1. Object - The transaction object

Returns

DATA, 32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available.

Use eth_getTransactionReceipt to get the contract address, after the transaction was proposed in a block, when you created a contract.

Example

eth_sendRawTransaction

Creates new message call transaction or a contract creation for signed transactions.

Parameters

  1. DATA, The signed transaction data.

Returns

DATA, 32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available.

Use eth_getTransactionReceipt to get the contract address, after the transaction was proposed in a block, when you created a contract.

Example

eth_call

Executes a new message call immediately without creating a transaction on the blockchain. Often used for executing read-only smart contract functions, for example the balanceOf for an ERC-20 contract.

Parameters

  1. Object - The transaction call object
  1. QUANTITY|TAG - integer block number, or the string "latest", "earliest", "pending", "safe" or "finalized", see the default block parameter

Returns

DATA - the return value of executed contract.

Example

eth_estimateGas

Generates and returns an estimate of how much gas is necessary to allow the transaction to complete. The transaction will not be added to the blockchain. Note that the estimate may be significantly more than the amount of gas actually used by the transaction, for a variety of reasons including EVM mechanics and node performance.

Parameters

See eth_call parameters, except that all properties are optional. If no gas limit is specified geth uses the block gas limit from the pending block as an upper bound. As a result the returned estimate might not be enough to executed the call/transaction when the amount of gas is higher than the pending block gas limit.

Returns

QUANTITY - the amount of gas used.

Example

eth_getBlockByHash

Returns information about a block by hash.

Parameters

  1. DATA, 32 Bytes - Hash of a block.
  2. Boolean - If true it returns the full transaction objects, if false only the hashes of the transactions.

Returns

Object - A block object, or null when no block was found:

Example

eth_getBlockByNumber

Returns information about a block by block number.

Parameters

  1. QUANTITY|TAG - integer of a block number, or the string "earliest", "latest", "pending", "safe" or "finalized", as in the default block parameter.
  2. Boolean - If true it returns the full transaction objects, if false only the hashes of the transactions.

ReturnsSee eth_getBlockByHash

Example

Result see eth_getBlockByHash

eth_getTransactionByHash

Returns the information about a transaction requested by transaction hash.

Parameters

  1. DATA, 32 Bytes - hash of a transaction

Returns

Object - A transaction object, or null when no transaction was found:

Example

eth_getTransactionByBlockHashAndIndex

Returns information about a transaction by block hash and transaction index position.

Parameters

  1. DATA, 32 Bytes - hash of a block.
  2. QUANTITY - integer of the transaction index position.

ReturnsSee eth_getTransactionByHash

Example

Result see eth_getTransactionByHash

eth_getTransactionByBlockNumberAndIndex

Returns information about a transaction by block number and transaction index position.

Parameters

  1. QUANTITY|TAG - a block number, or the string "earliest", "latest", "pending", "safe" or "finalized", as in the default block parameter.
  2. QUANTITY - the transaction index position.

ReturnsSee eth_getTransactionByHash

Example

Result see eth_getTransactionByHash

eth_getTransactionReceipt

Returns the receipt of a transaction by transaction hash.

Note That the receipt is not available for pending transactions.

Parameters

  1. DATA, 32 Bytes - hash of a transaction

Returns Object - A transaction receipt object, or null when no receipt was found:

It also returns either :

Example

eth_getUncleByBlockHashAndIndex

Returns information about a uncle of a block by hash and uncle index position.

Parameters

  1. DATA, 32 Bytes - The hash of a block.
  2. QUANTITY - The uncle's index position.

ReturnsSee eth_getBlockByHash

Example

Result see eth_getBlockByHash

Note: An uncle doesn't contain individual transactions.

eth_getUncleByBlockNumberAndIndex

Returns information about a uncle of a block by number and uncle index position.

Parameters

  1. QUANTITY|TAG - a block number, or the string "earliest", "latest", "pending", "safe", "finalized", as in the default block parameter.
  2. QUANTITY - the uncle's index position.

ReturnsSee eth_getBlockByHash

Note: An uncle doesn't contain individual transactions.

Example

Result see eth_getBlockByHash

eth_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.

**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:

  1. Object - The filter options:

Returns QUANTITY - A filter id.

Example

eth_newBlockFilter

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

ParametersNone

Returns QUANTITY - A filter id.

Example

eth_newPendingTransactionFilter

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

ParametersNone

Returns QUANTITY - A filter id.

Example

eth_uninstallFilter

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

Parameters

  1. QUANTITY - The filter id.

Returns Boolean - true if the filter was successfully uninstalled, otherwise false.

Example

eth_getFilterChanges

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

Parameters

  1. QUANTITY - the filter id.

Returns Array - Array of log objects, or an empty array if nothing has changed since last poll.

eth_getFilterLogs

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

Parameters

  1. QUANTITY - The filter id.

ReturnsSee eth_getFilterChanges

Example

Result see eth_getFilterChanges

eth_getLogs

Returns an array of all logs matching a given filter object.

Parameters

  1. Object - The filter options:

ReturnsSee eth_getFilterChanges

Example

Result see eth_getFilterChanges

Usage Example

Deploying a contract using JSON_RPC

This section includes a demonstration of how to deploy a contract using only the RPC interface. There are alternative routes to deploying contracts where this complexity is abstracted away—for example, using libraries built on top of the RPC interface such as web3.js(opens in a new tab) and web3.py(opens in a new tab). These abstractions are generally easier to understand and less error-prone, but it is still helpful to understand what is happening under the hood.

The following is a straightforward smart contract called Multiply7 that will be deployed using the JSON-RPC interface to an Ethereum node. This tutorial assumes the reader is already running a Geth node. More information on nodes and clients is available here. Please refer to individual client documentation to see how to start the HTTP JSON-RPC for non-Geth clients. Most clients default to serving on localhost:8545.

The first thing to do is make sure the HTTP RPC interface is enabled. This means we supply Geth with the --http flag on startup. In this example we use the Geth node on a private development chain. Using this approach we don't need ether on the real network.

This will start the HTTP RPC interface on http://localhost:8545.

We can verify that the interface is running by retrieving the coinbase address (by obtaining the first address from the array of accounts) and balance using curl(opens in a new tab). Please note that data in these examples will differ on your local node. If you want to try these commands, replace the request params in the second curl request with the result returned from the first.

Because numbers are hex encoded, the balance is returned in wei as a hex string. If we want to have the balance in ether as a number we can use web3 from the Geth console.

Now that there is some ether on our private development chain, we can deploy the contract. The first step is to compile the Multiply7 contract to byte code that can be sent to the EVM. To install solc, the Solidity compiler, follow the Solidity documentation(opens in a new tab). (You might want to use an older solc release to match the version of compiler used for our example(opens in a new tab).)

The next step is to compile the Multiply7 contract to byte code that can be send to the EVM.

Now that we have the compiled code we need to determine how much gas it costs to deploy it. The RPC interface has an eth_estimateGas method that will give us an estimate.

And finally deploy the contract.

The transaction is accepted by the node and a transaction hash is returned. This hash can be used to track the transaction. The next step is to determine the address where our contract is deployed. Each executed transaction will create a receipt. This receipt contains various information about the transaction such as in which block the transaction was included and how much gas was used by the EVM. If a transaction creates a contract it will also contain the contract address. We can retrieve the receipt with the eth_getTransactionReceipt RPC method.

Our contract was created on 0x4d03d617d700cf81935d7f797f4e2ae719648262. A null result instead of a receipt means the transaction has not been included in a block yet. Wait for a moment and check if your consensus client is running and retry it.

Interacting with smart contracts

In this example we will be sending a transaction using eth_sendTransaction to the multiply method of the contract.

eth_sendTransaction requires several arguments, specifically from, to and data. From is the public address of our account, and to is the contract address. The data argument contains a payload that defines which method must be called and with which arguments. This is where the ABI (application binary interface)(opens in a new tab) comes into play. The ABI is a JSON file that defines how to define and encode data for the EVM.

The bytes of the payload defines which method in the contract is called. This is the first 4 bytes from the Keccak hash over the function name and its argument types, hex encoded. The multiply function accepts an uint which is an alias for uint256. This leaves us with:

The next step is to encode the arguments. There is only one uint256, say, the value 6. The ABI has a section which specifies how to encode uint256 types.

int<M>: enc(X) is the big-endian two’s complement encoding of X, padded on the higher-order (left) side with 0xff for negative X and with zero > bytes for positive X such that the length is a multiple of 32 bytes.

This encodes to 0000000000000000000000000000000000000000000000000000000000000006.

Combining the function selector and the encoded argument our data will be 0xc6888fa10000000000000000000000000000000000000000000000000000000000000006.

This can now be sent to the node:

Since a transaction was sent, a transaction hash was returned. Retrieving the receipt gives:

The receipt contains a log. This log was generated by the EVM on transaction execution and included in the receipt. The multiply function shows that the Print event was raised with the input times 7. Since the argument for the Print event was a uint256 we can decode it according to the ABI rules which will leave us with the expected decimal 42. Apart from the data it is worth noting that topics can be used to determine which event created the log:

This was just a brief introduction into some of the most common tasks, demonstrating direct usage of the JSON-RPC.