Nodes and JSON-RPC Endpoints

Nodes and JSON-RPC Endpoints

Generally speaking, a JSON-RPC is a remote procedure call (RPC) protocol that utilizes JSON to encode data. For Web3, they refer to the specific JSON-RPCs that DApp developers use to send requests and receive responses from blockchain nodes, making it a crucial element in interactions with smart contracts. They allow frontend user interfaces to seamlessly interact with the smart contracts and provide users with real-time feedback on their actions. They also allow developers to deploy their smart contracts in the first place!

To get a JSON-RPC to communicate with a Moonbeam blockchain, you need to run a node. But that can be expensive, complicated, and a hassle. Fortunately, as long as you have access to a node, you can interact with the blockchain. Moonbase Alpha has a handful of free and paid node options. For this tutorial, we will be using the Moonbeam Foundation's public node for Moonbase Alpha, but you are encouraged to get your own private endpoint.

https://rpc.api.moonbase.moonbeam.network

So now you have a URL. How do you use it? Over HTTPS, JSON-RPC requests are POST requests that include specific methods for reading and writing data, such as eth_call for executing a smart contract function in a read-only manner or eth_sendRawTransaction for submitting signed transactions to the network (calls that change the blockchain state). The entire JSON request structure will always have a structure similar to the following:

{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "eth_getBalance",
    "params": ["0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac", "latest"]
}

This example is getting the balance (in DEV on Moonbase Alpha) of the 0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac account. Let's break down the elements:

  • jsonrpc — the JSON-RPC API version, usually "2.0"

  • id — an integer value that helps identify a response to a request. Can usually just keep it as `

  • method — the specific method to read/write data from/to the blockchain. You can see many of the RPC methods on our docs site

  • params — an array of the input parameters expected by the specific method

There are also additional elements that can be added to JSON-RPC requests, but those four will be seen the most often.

Now, these JSON-RPC requests are pretty useful, but when writing code, it can be a hassle to create a JSON object over and over again. That's why there exist libraries that help abstract and facilitate the usage of these requests. Moonbeam provides documentation on many libraries, and the one that we will be using in this tutorial is Ethers.js. Just understand that whenever we interact with the blockchain through the Ethers.js package, we're really using JSON-RPC!

Last updated