5分钟!就能学会以太坊 JSON API 基础知识!

作者 | 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

【END】


更多精彩推荐

☞“谷歌杀手”发明者,科学天才 Wolfram

☞漫画:“哈夫曼编码” 是什么鬼?

数据库激荡40年,深入解析PostgreSQL、NewSQL演进历程

黑客用上机器学习你慌不慌?这7种窃取数据的新手段快来认识一下!

超详细!一文告诉你SparkStreaming如何整合Kafka!附代码可实践

Libra的Move语言初探,10行代码实现你第一个智能合约

你点的每个“在看”,我都认真当成了喜欢

发布了1987 篇原创文章 · 获赞 4万+ · 访问量 1849万+

猜你喜欢

转载自blog.csdn.net/csdnnews/article/details/105721659