前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >5分钟!就能学会以太坊 JSON API 基础知识!

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

作者头像
区块链大本营
发布2023-03-31 15:41:39
5520
发布2023-03-31 15:41:39
举报
文章被收录于专栏:区块链大本营区块链大本营

作者 | Nicolas Schapeler

责编 | Carol

出品 |  区块链大本营(ID:blockchain_camp)

前几天,作者遇到了这样一种情况,需要在一个让web3.py几乎不可能工作的环境中使用Python与Ethereum网络进行通信。

由于作者仍然需要与网络通信,所以作者使用了Ethereum提供的JSON-RPC API,所有的web3库都构建在这个API之上。原来,这是非常有趣的一件事,让我们一起来看看吧。

基础设置

首先,让我们声明几个变量,这将有助于以后发送请求:

代码语言:javascript
复制
代码语言:javascript
复制
import requests
import json
session = requests.Session()
url = "https://ropsten.infura.io/v3/YOUR_INFURA_KEY"
headers = {'Content-type': 'application/json'}
代码语言:javascript
复制

为了简单起见,我们使用Infura节点连接到Ethereum Ropsten Testnet。你可以在这里获得一个API 密钥:https://infura.io/

你的第一个请求

让我们先来了解一下网络当前的gas价格。我们可以简单地做以下操作:

代码语言:javascript
复制
# 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")
代码语言:javascript
复制

我们怎么知道使用哪种方法以及发送什么参数呢?所有这些都可以在以太坊官方文档中找到。

获取最新的块

让我们来尝试一些更有趣的东西——让我们获取最新的块,看看我们可以从那里读取什么?

代码语言:javascript
复制
# 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
代码语言:javascript
复制

让我们仔细看看其中一笔交易:

代码语言:javascript
复制
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
代码语言:javascript
复制

可能你已经开始了解这些调用的工作模式,所以让我们尝试一些更高级的方法。

发送交易

首先,让我们使用web3.py库创建一个新帐户,并向其中加载一些Ropsten ether。

代码语言:javascript
复制
import web3
w3 = web3.Web3()
account = w3.eth.account.create('put any phrase here')
address = account.address
pKey = account.privateKey

要发送创建交易,我们需要随机数。我们也可以使用与上述相同的模式通过RPC JSON API获取信息:

代码语言:javascript
复制
# 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")
代码语言:javascript
复制
接下来,我们将创建并签名交易,然后再次使用 JSON RPC API 将其发送出去:
代码语言:javascript
复制
# 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。

代码语言:javascript
复制
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")
代码语言:javascript
复制

请注意我们是如何重新利用开始时获取的汽油价格的。

结论

就这样简单,你刚刚利用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

推荐阅读

老铁们求在看!👇

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 区块链大本营 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档