5分钟!就能学会以太坊 JSON API 基础知识!
import requests
import json
session = requests.Session()
url =
"https://ropsten.infura.io/v3/YOUR_INFURA_KEY"
headers = {'Content-type': 'application/json'}
# 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
import web3
w3 = web3.Web3()
account = w3.eth.account.create('put any phrase here')
address = account.address
pKey = account.privateKey
# 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)
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
更多精彩推荐
☞
☞
☞
☞
