A developer’s guide to accessing blockchain data — with Cosmos RPC examples
Summary
- For tasks like deploying a smart contract or retrieving a wallet balance, developers send requests to and receive responses from a node. The standard set of procedures required for this comprises a communication protocol called Remote Procedure Call (RPC)
- Full, archival and trace nodes on Cosmos run Tendermint Core (‘Tendermint nodes’), which consists of a consensus algorithm and P2P networking for data replication across nodes. A Cosmos chain’s data can be commonly accessed through the RPC endpoints exposed by that chain’s Tendermint nodes
- Currently, developers building applications on Cosmos primarily access blockchain data through altruistically-run public nodes, which are rate-limited and insufficient for production grade projects
- Lava Protocol provides scalable, private and uncensored access to accurate blockchain data
Recap — What is RPC?
In the same way that web2 applications like Facebook communicate with backend servers and then databases to store and access data, web3 front-ends need a way to access blockchain data. The fundamental idea of blockchain is that each client can run its own node, which maintains a copy of the latest State.
To access the State, nodes expose RPC endpoints. RPC nodes can be run locally or accessed remotely. Due to the impracticality of running and maintaining nodes, blockchain data is typically accessed through node provider services or public endpoints supported by ecosystem grants.
RPC nodes are required for applications to:
- Read data from the blockchain and present it to the users.
- Receive signed user transactions from wallets and propagate these to the rest of the p2p network, to be used by validators in block building
Applications access blockchain data using nodes, and communication with these nodes works through RPC:
RPC allows one computer to remotely execute functions (procedures) on another computer. RPC is a form of client-server request-response interaction — the client sends a request and the server replies with a response to that request.
These are the sequence of events when making an RPC method call:
- A client is interested in running a function on a remote server
- An RPC call is initiated by the client with all the relevant data (function name, params, etc.)
- The call is sent to the target remote server which processes the request and executes the procedure
- The remote server sends a response to the client
- The client is now able to use the response in order to run its application logic
The Tendermint RPC
In the Cosmos ecosystem, developers use the Cosmos Software Development Kit (SDK) to build appchains. These appchains implement a consensus engine, Tendermint Core, which includes a Byzantine-Fault Tolerant consensus algorithm for ensuring that the same transactions are recorded on every machine in the same order.
In addition, every appchain requires nodes to expose RPC endpoints to serve client queries for blockchain data, as well as propogate transactions to other nodes in the network. On Cosmos, a commonly used endpoint is the Tendermint RPC endpoint, which is independent from the Cosmos SDK. Every node in the network can choose whether to expose their Tendermint RPC endpoints, which will be served by default on port 26657.
Clients can use this endpoint to retrieve up-to-date State data in 3 different ways:
1. URI over HTTP:
curl localhost:26657/block?height=5
2. JSON-RPC over HTTP (post request):
curl --header "Content-Type: application/json" --request POST --data '{"method": "block", "params": ["5"], "id": 1}' localhost:26657
3. JSON-RPC over WebSocket (for async functions):
ws ws://localhost:26657/websocket
> { "jsonrpc": "2.0", "method": "subscribe", "params": ["tm.event='NewBlock'"], "id": 1 }
It’s worth noting that another common way to interact with a node on Cosmos is to use gRPC, a language agnostic, high-performance Remote Procedure Call (RPC) framework. The differences between gRPC and RPC will be explored in later articles.
Blockchain case study: Osmosis RPC
Using RPC, clients (e.g. wallets and apps) are able to send transactions and query blockchains for information like block height, blocks, wallet balance, etc.
For example, let’s say that you want to develop a dapp on the Osmosis chain. Since the Osmosis chain is built using the Cosmos SDK, the first thing that you have to do is import the cosmWasm
library. Then you will have to connect to an RPC Node so your dapp can receive data:
rpcEndpoint
- The RPC URL of an Osmosis node
client
- A CosmWasm client object that will let us interact and retrieve data from Osmosis. Note we will only be reading data, if we wanted to make a transaction we would need to configure a signer with a mnemonic.
Moving on, let’s play with the client object:
Once we have a client object configured with an RPC node, we can start to query the node for information from the blockchain. In the example above, we checked the balance of Cosmostation, which is one of the largest validators on the Osmosis chain. Try running the code again using your own wallet address or another valid address on Osmosis and make sure you get a result similar to this one:
{ denom: 'uosmo', amount: '17134426559' }
As you can see the call resulted in the number 17134426559
which represents the balance of the address osmo1khp3a8edarjaxfvlgdrcwthnjp3vdr3ez6p3xe
.
In the examples above, all the requests generated using the client object, are routed to the Blockchain RPC node through JSON-RPC.
JSON-RPC
JSON-RPC is a stateless, lightweight remote procedure call (RPC) protocol, which uses JSON (RFC 4627) as its data format. In other words, JSON-RPC is an RPC protocol encoded in JSON format, allowing:
- Normal calls (Request — Response form)
- Notifications (data sent to the server that does not require a response)
- Multiple calls to be sent to the server which may be answered asynchronously
JSON-RPC is popularly used for client-server communication in the Cosmos ecosystem and across web3. Most chains have a JSON-RPC specification which describes all the functions that this particular blockchain supports, similar to an API. For example, you can find the Osmosis chain specification in their documentation here.
JSON-RPC Examples
Retrieving Wallet Balances
In the previous section, we were able to retrieve the balance of a specific wallet on the Osmosis chain using the Javascript library CosmWasmClient
. When we execute the function client.getBalance(string address, string searchDenom)
the library implements in the background the JSON-RPC protocol and sends a JSON-RPC request that looks like this:
Breaking down the JSON-RPC request above:
- jsonrpc: The protocol version we’re using
2.0
- method: The method we are calling. In our example, we want to retrieve the address’s balance using the method
balance
- params: Parameters that will be sent to the method that we are calling. In our example, we are requesting the balance of the token
uosmo
for the addressosmo1khp3a8edarjaxfvlgdrcwthnjp3vdr3ez6p3xe
- id: Identification of the client sending the call
The server/node will reply with the following JSON-RPC response:
Breaking down the JSON-RPC response above:
- id: Client identification
- jsonrpc: Protocol version
- result: The result of the executed function
Retrieving Block Data
Another useful example is getting a specific block from the chain. When a client (wallet, dapp, etc..) wants to get the block data at a specific block number (height) of the Osmosis chain, it sends the following JSON-RPC request:
Breaking down the JSON-RPC request above:
- jsonrpc: The protocol version we’re using
2.0
- method: The method we are calling. In our example, we want to get the latest block number using block
- params: Parameters to be sent to the method that we are calling. In our example, we are requesting information for block number
5347769
- id: Identification of the client sending the call
The server/node will reply with the following JSON-RPC response:
Let’s break down the JSON-RPC response above:
- id: Client identification
- jsonrpc: Protocol version
- result: The result of the executed function
In order to learn more about the supported Osmosis and Cosmos RPC methods, check out the Osmosis RPC docs and the Cosmos Tendermint RPC docs.
Accessing RPC endpoints on Cosmos
In more mature ecosystems like Ethereum, RPC service is well provided for by centralized offerings e.g. Alchemy, Infura. However, due to its relative infancy and diversity of clients across its different blockchains, Cosmos is relatively underserved for RPC. The majority of RPC relays made in the Cosmos ecosystem are facilitated by public endpoints, often run by chains themselves.
It is possible to find all the available endpoints for Cosmos chains in the Cosmos chain registry, which provides information about RPC access for chains including Osmosis, Akash, Stride and Secret Network.
Lava Network offers accountable RPC node infrastructure for the Cosmos ecosystem. Applications can permisionlessly access blockchain data through a network of node providers who are rewarded for high quality service and punished for poor service. Service quality is agreed upon by decentralized consensus and also captured by peer-to-peer performance scores. In this way, the protocol ensures censorship-resistance, low latency, maximum uptime, high availability and data integrity.
Conclusion
The RPC infrastructural layer of web3 enables any application to access blockchain data. RPC is used to query blockchain State e.g. a wallet balance, or block data. A common RPC format used across web3 is JSON-RPC.
In more nascent ecosystems like Cosmos, many RPC endpoints are run altruistically by chains themselves. This is unsustainable and does not scale for production grade applications. Lava is a more sustainable solution, providing RPC access for all chains and built with the web3 values of decentralization and censorship-resistance from day 1.
Follow Lava on Twitter to keep updated on our latest developments in this space. You can also learn more at lavanet.xyz.
About Lava
Lava is a protocol that provides applications with scalable, private and uncensored access to accurate blockchain data. Using cryptography and token-aligned incentives, the protocol holds RPC nodes accountable for data integrity and performance quality. Node runners earn rewards for providing robust RPC service, while contributing towards decentralization.
Accountability, not trust 🌋