Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Ethereum Cookbook

You're reading from   Ethereum Cookbook Over 100 recipes covering Ethereum-based tokens, games, wallets, smart contracts, protocols, and Dapps

Arrow left icon
Product type Paperback
Published in Aug 2018
Publisher Packt
ISBN-13 9781789133998
Length 404 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Manoj P R Manoj P R
Author Profile Icon Manoj P R
Manoj P R
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Getting Started FREE CHAPTER 2. Smart Contract Development 3. Interacting with the Contract 4. The Truffle Suite 5. Tokens and ICOs 6. Games and DAOs 7. Advanced Solidity 8. Smart Contract Security 9. Design Decisions 10. Other Protocols and Applications 11. Miscellaneous 12. Other Books You May Enjoy

Interacting with Ethereum using JSON-RPC

You can completely avoid using web3.js and interact with your Ethereum node using JSON-RPC. It is a stateless, lightweight RPC protocol. Etherum JSON-RPC exposes various APIs that can be used within the same process, over sockets, over HTTP, or in various message passing environments.

These APIs are commonly used to interact with blockchain where JavaScript is not supported. In this recipe, you will learn to communicate with Ethereum using various JSON-RPC commands.

Getting ready

You need to have a fully functioning Ethereum node to test these APIs. By default, both geth and Parity expose port 8545 for JSON-RPC. Some examples are given in JavaScript, but you can use any programming language that supports HTTPS requests.

Make sure that you are starting your geth node with enough --rpcapi permissions:

$ geth --rpc --rpcapi "web3,eth,personal"

We will focus on a few important APIs here and you can always find the complete list for reference at github.com/ethereum/wiki/wiki/JSON-RPC.

How to do it...

We will now learn how to use JSON-RPC to interact with Ethereum:

  1. Build a basic JSON-RPC body with four parameters. The parameters are version, method, parameters, and ID:
{
"jsonrpc":"2.0",
"method":"", // method identifier
"params":[], // list of parameters
"id":0 // id
}
  1. Use the net_peerCount method to return the number of peers connected to a node:
curl -X POST 
--data '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":74}'
http://localhost:8545
  1. You will get a response like this for all the requests you make. Some requests will return a hex value instead of a decimal/string. You may have to convert it to the required format manually:
{
  "id":74,
  "jsonrpc": "2.0",
  "result": "0x2" // 2
}
  1. Create the same request in Node.js to get the peer count:
var request = require('request');

request({
url: 'http://localhost:8545',
method: 'POST',
body: '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":74}'
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
  1. Use this in Python:
import requests
data = '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":74}'
response = requests.post('http://localhost:8545/', data=data)
  1. And use this in Go:
body := strings.NewReader(`{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":74}`) 

req, err := http.NewRequest(
"POST", "http://localhost:8545", body)
if err != nil {
// handle err
}

req.Header.Set(
"Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
// handle err
}

defer resp.Body.Close()
  1. Use any programming language that can make HTTP requests for interacting through JSON-RPC.
    Let's look into a few more important examples.
  2. To get the current Ether base of the connected node, use eth_coinbase:
// Request
curl -X POST 
--data '{"jsonrpc":"2.0","method":"eth_coinbase","params":[],"id":64}'
http://localhost;8545
// Response { "id":64, "jsonrpc": "2.0", "result": "0x824e470cCac64CC5fa4Abe953e64FA360EA11366"
}
  1. To view the list of accounts in the node, use eth_accounts:
// Request
curl -X POST 
--data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":1}'
http://localhost:8545
// Response { "id":1, "jsonrpc": "2.0", "result": ["0x824e470cCac64CC5fa4Abe953e64FA360EA11366"] }
  1. To get the current block height, use eth_blockNumber:
// Request
curl -X POST 
--data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":83}'
http://localhost:8545
// Response { "id":83, "jsonrpc": "2.0", "result": "0x53D390" // 5493648 }
  1. To get the balance of an account in the network, use eth_getBalance along with parameters:
// Request
curl -X POST 
--data '{"jsonrpc":"2.0",
"method":"eth_getBalance",
"params":["0x824e470cCac64CC5fa4Abe953e64FA360EA11366", "latest"],
"id":1
}'
http://localhost:8545
// Response { "id":1, "jsonrpc": "2.0", "result": "0x5AF3107A4000" // 100000000000000 }
  1. To send a transaction from an account, use eth_sendTransaction:
// Request
curl -X POST 
--data '{
"jsonrpc":"2.0",
"method":"eth_sendTransaction",
"params": <Trnsaction_Object>,
"id":1
}'
http://localhost:8545
// Response { "id":1, "jsonrpc": "2.0", "result": "0xf456c56efe41db20f32853ccc4cbea3d2ab011b2c11082150f29c36212345dbd" }
  1. To get the transaction receipt, use eth_getTransactionReceipt:
// Request
curl -X POST 
--data '{
"jsonrpc":"2.0",
"method":"eth_getTransactionReceipt",
"params":["<TransactionHash>"],
"id":1
}'
http://localhost:8545
// Result { "id":1, "jsonrpc":"2.0", "result": <Receipt> }
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image