Ethereum's JSON-RPC API serves as the fundamental interface for developers to interact with the Ethereum blockchain. This powerful API allows applications to read blockchain data, send transactions, deploy smart contracts, and monitor network activity through a standardized JSON-based protocol.
Understanding JSON-RPC Basics
JSON-RPC is a lightweight remote procedure call protocol that uses JSON to encode requests and responses. Ethereum clients implement this specification to provide consistent access to blockchain functionality across different implementations.
Key Data Types and Encoding
Two primary data types are encoded differently when passing through JSON-RPC:
Quantities (Integers)
- Encode as hex with "0x" prefix
- Use most compact representation (zero is "0x0")
- Examples: 0x41 (65), 0x400 (1024)
- Invalid: 0x (empty), 0x0400 (leading zeros), ff (missing prefix)
Unformatted Data (Byte Arrays)
- Encode as hex with "0x" prefix
- Two hex digits per byte required
- Examples: 0x41 (size 1, "A"), 0x004200 (size 3, "\0B\0")
- Invalid: 0xf0f0f (odd digits), 004200 (missing prefix)
Default Block Parameter
Several methods accept an additional default block parameter that determines the block height for state-related queries. The following options are available:
HEX String: Integer block number"earliest": The genesis block"latest": The latest mined block"pending": The pending state/transactions
Methods using this parameter include eth_getBalance, eth_getCode, eth_getTransactionCount, eth_getStorageAt, and eth_call.
Core JSON-RPC Methods
Network and Client Information
web3_clientVersion
Returns the current client version, helping identify the Ethereum implementation and its capabilities.
net_version
Returns the current network ID, with mainnet using "1" and testnets like Ropsten ("3"), Rinkeby ("4"), and Kovan ("42") having their respective identifiers.
net_peerCount
Provides the number of peers currently connected to the client, indicating network connectivity health.
net_listening
Returns a boolean indicating whether the client is actively listening for network connections.
Blockchain State Methods
eth_blockNumber
Returns the number of the most recent block, essential for tracking blockchain progress.
eth_getBalance
Retrieves the balance of a specified address at a given block, returning the value in wei.
eth_getTransactionCount
Returns the number of transactions sent from a specific address, useful for determining the next nonce.
eth_getCode
Returns the code at a given address, allowing verification of smart contract deployment.
Transaction Methods
eth_sendTransaction
Creates new message call transactions or contract creations. Requires a transaction object containing from, to, gas, gasPrice, value, data, and nonce parameters.
eth_sendRawTransaction
Creates transactions from already signed transaction data, enabling offline transaction signing.
eth_call
Executes a message call immediately without creating a transaction, perfect for reading contract state without spending gas.
eth_estimateGas
Generates an estimate of how much gas is necessary for a transaction to complete, helping set appropriate gas limits.
Block and Transaction Information
eth_getBlockByHash and eth_getBlockByNumber
Return comprehensive information about blocks, including transaction lists, timestamps, difficulty, and other metadata.
eth_getTransactionByHash
Returns information about specific transactions, including sender, receiver, value, and input data.
eth_getTransactionReceipt
Provides transaction receipts containing execution results, gas used, and contract addresses for deployments.
Advanced Filtering and Event Monitoring
Ethereum's JSON-RPC includes powerful filtering capabilities for monitoring blockchain events in real-time.
eth_newFilter
Creates filter objects to notify when state changes occur based on specified criteria including block ranges, addresses, and topics.
eth_newBlockFilter
Creates filters that notify when new blocks arrive, enabling real-time blockchain monitoring.
eth_newPendingTransactionFilter
Creates filters that notify when new pending transactions arrive, useful for tracking transaction pools.
eth_getFilterChanges
Polling method that returns new logs since the last poll, supporting real-time event monitoring for dApps.
👉 Explore advanced blockchain monitoring tools
Smart Contract Development Support
eth_getCompilers
Returns available compilers in the client, though many modern setups use external compilation.
eth_compileSolidity
Compiles Solidity code directly through the client, returning bytecode and ABI information.
eth_estimateGas
Crucial for estimating contract deployment and execution costs before submitting transactions.
Practical Implementation Examples
When working with JSON-RPC, most developers use HTTP POST requests with properly formatted JSON objects. Here's a basic example using curl:
curl -X POST -H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
http://localhost:8545This request would return the current block number in hexadecimal format, which can then be converted to decimal for human-readable use.
Frequently Asked Questions
What is the difference between eth_sendTransaction and eth_sendRawTransaction?
eth_sendTransaction requires the node to manage your private key and sign the transaction, while eth_sendRawTransaction accepts already signed transaction data, allowing for offline signing and enhanced security.
How often should I poll eth_getFilterChanges?
The polling frequency depends on your application needs, but typically every 1-5 seconds for real-time applications. Be mindful of rate limits and performance considerations on your node.
Why are values returned in hexadecimal format?
Hexadecimal encoding ensures consistent representation across different programming languages and systems, while also efficiently handling very large numbers common in blockchain applications.
What's the purpose of the default block parameter?
This parameter allows querying historical state at specific block heights, enabling applications to access blockchain data as it existed at any point in history rather than just the current state.
How do I handle the gas estimation for complex transactions?
For complex transactions, it's recommended to use eth_estimateGas with similar transactions first, then add a buffer (typically 10-20%) to account for execution variations before sending the actual transaction.
Can I use these methods with any Ethereum client?
Most standard JSON-RPC methods work across different Ethereum clients like Geth, OpenEthereum, and Nethermind, though some implementation-specific variations may exist, particularly with newer methods or optimizations.
Best Practices for JSON-RPC Usage
When working with Ethereum's JSON-RPC API, consider these best practices:
- Always implement proper error handling and timeout management
- Use batch requests when making multiple calls to reduce latency
- Implement retry logic for transient network issues
- Cache frequently accessed data that doesn't change often
- Monitor your node's performance and adjust request rates accordingly
- Use the appropriate network for your needs (mainnet vs testnets)
👉 Access comprehensive blockchain development resources
By understanding and properly implementing Ethereum's JSON-RPC API, developers can build powerful decentralized applications that seamlessly interact with the Ethereum blockchain, from simple balance checks to complex smart contract interactions and real-time event monitoring.