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

栏目: IT技术 · 发布时间: 6年前

内容简介:作者 | Nicolas Schapeler

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

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

作者 | Nicolas Schapeler

责编 | Carol

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

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

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

5分钟!就能学会以太坊 JSON 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/

5分钟!就能学会以太坊 JSON 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")

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

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

获取最新的块

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

# 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

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

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

发送交易

首先,让我们使用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 API 基础知识!

结论

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

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

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

推荐阅读

老铁们求在 看! ????


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Ajax for Web Application Developers

Ajax for Web Application Developers

Kris Hadlock / Sams / 2006-10-30 / GBP 32.99

Book Description Reusable components and patterns for Ajax-driven applications Ajax is one of the latest and greatest ways to improve users’ online experience and create new and innovative web f......一起来看看 《Ajax for Web Application Developers》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具