5分钟内学会以太坊JSON API的基础知识

Python实战 木人张 3年前 (2020-04-09) 883次浏览 0个评论 扫描二维码
文章目录[隐藏]

基本设定

首先,我们先声明一些变量,这些变量在以后发送请求时会有所帮助:

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

为简单起见,我们使用Infura节点连接到以太坊Ropsten Testnet。在此处获取API密钥。

第一个请求

我们先来一个简单的尝试,例如我们来获取当前以太坊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 Error

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

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库创建一个新帐户,并领取一些测试币。

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与以太坊进行交互的基础知识!


木人张,版权所有丨如未注明 , 均为原创,禁止转载。
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址