作者 | Nicolas Schapeler

責編 | Carol

出品 |  區塊鏈大本營(ID:blockchain_camp

前幾天,作者遇到了這樣一種情況,需要在一個讓web3.py幾乎不可能工作的環境中使用Python與Ethereum網絡進行通信。

由於作者仍然需要與網絡通信,所以作者使用了Ethereum提供的JSON-RPC API,所有的web3庫都構建在這個API之上。原來,這是非常有趣的一件事,讓我們一起來看看吧。

基礎設置

首先,讓我們聲明幾個變量,這將有助於以後發送請求:

import requests
import json
session = requests.Session()
url = "https://ropsten.infura.io/v3/YOUR_INFURA_KEY"
headers = {'Content-type': 'application/json'}

爲了簡單起見,我們使用Infura節點連接到Ethereum Ropsten Testnet。你可以在這裏獲得一個API 密鑰: https://infura.io/

你的第一個請求

讓我們先來了解一下網絡當前的gas價格。我們可以簡單地做以下操作:

# Prepare the data we will send
data = {"jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id":1}
response = session.post(url, json=data, headers=headers)


# Check if response is valid
if response.ok:
    # Get result of the request and decode it to decimal
    gasPriceHex = response.json().get("result")
    gasPriceDecimal = int(gasPriceHex, 16)
else:
    # Handle Error
    print("Error occured")

我們怎麼知道使用哪種方法以及發送什麼參數呢?所有這些都可以在以太坊官方文檔中找到。

獲取最新的塊

讓我們來嘗試一些更有趣的東西——讓我們獲取最新的塊,看看我們可以從那裏讀取什麼?

# Set params and prepare data
blockNumber = "latest"
# Boolean indicating if we want the full transactions (True) or just their hashes (false)
fullTrx = False
params = [ blockNumber, fullTrx]
data = {"jsonrpc": "2.0", "method": "eth_getBlockByNumber","params": params, "id": 1}


response = session.post(url, json=data, headers=headers)


# Check if response is valid
if response.ok:
    # Get the block
    block = response.json().get("result")
    # Get the transactions contained in the block
    transactions = block.get("transactions")
else:
    # Handle Erro

讓我們仔細看看其中一筆交易:

params = [transactions[0]]


data = {"jsonrpc": "2.0", "method": "eth_getTransactionByHash","params": params, "id": 3}


response = session.post(url, json=data, headers=headers)


if response.ok:
    transaction = response.json().get("result")
else:
    # Handle Error
    print("Error occured

可能你已經開始瞭解這些調用的工作模式,所以讓我們嘗試一些更高級的方法。

發送交易

首先,讓我們使用web3.py庫創建一個新帳戶,並向其中加載一些Ropsten ether。

import web3
w3 = web3.Web3()
account = w3.eth.account.create('put any phrase here')
address = account.address
pKey = account.privateKey

要發送創建交易,我們需要隨機數。我們也可以使用與上述相同的模式通過RPC JSON API獲取信息:

# Get the nonce at the latest block
params = [address, "latest"]

data = {"jsonrpc": "2.0", "method": "eth_getTransactionCount","params": params, "id": 3}

response = session.post(url, json=data, headers=headers)

if response.ok:
    nonce = response.json().get("result")
else:
    # Handle Error
    print("Error occured")
接下來,我們將創建並簽名交易,然後再次使用 JSON RPC API 將其發送出去:
# Create our transaction
signed_txn = w3.eth.account.signTransaction({
    # Faucet address
    'to': '0x687422eEA2cB73B5d3e242bA5456b782919AFc85',
    'nonce': nonce,
    'gasPrice': gasPriceHex,
    'gas': 100000,
    'value': w3.toWei(0.5,'ether'),
    # 3 Because we are on Ropsten
    'chainId':3,
    },
  pKey)

如果你要在其他以太坊(Test)網絡上進行測試,請確保相應地設置鏈ID。

params = [signed_txn.rawTransaction.hex()]
data = {"jsonrpc": "2.0", "method": "eth_sendRawTransaction","params": params, "id": 4}
response = session.post(url, json=data, headers=headers)
if response.ok:
    receipt = response.json().get("result")
else:
    # Handle Error
    print("Error occured")

請注意我們是如何重新利用開始時獲取的汽油價格的。

結論

就這樣簡單,你剛剛利用5分鐘學習了使用JSON RPC Ethereum API與世界上最具影響力的區塊鏈進行交互的基礎知識!你可以在這裏找到所有代碼: https://github.com/nschapeler/ethereum-rpcjson

原文:https://hackernoon.com/learn-the-basics-of-the-ethereum-json-api-in-5-minutes-7k3x3yn0

推薦閱讀

老鐵們求在 看! ????

相關文章