1. 首页 > 知趣科技

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

前几天,作者遇到了这样一种情况,需要在一个让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与世界上最具影响力的区块链进行交互的基础知识!你可以在这里找到所有代码:htt

ps://github/nschapeler/ethereum-rpcjson。

本文采摘于网络,不代表本站立场,转载联系作者并注明出处:http://www.fjxmta.com/zqkj/10268.html

联系我们

在线咨询:点击这里给我发消息

微信号:wx123456