当前位置:首页区块链以太坊JSON-RPC API入门:用Python直接与链上交互

以太坊JSON-RPC API入门:用Python直接与链上交互

前阵子碰到个挺尴尬的场景:环境里 web3.py 基本跑不起来,但又必须用 Python 和以太坊网络通信。绕了一圈发现,所有 web3 库底层其实都构建在以太坊的 JSON-RPC API 之上,直接调它反而最省事。这篇就聊聊怎么用最原始的方式跟链上打交道。

准备工作与 gas 价格查询

先声明几个变量,后面发请求全靠它们:

“`python

import requests

import json

session = requests.Session()

url = “https://ropsten.infura.io/v3/YOUR_INFURA_KEY”

headers = {‘Content-type’: ‘application/json’}

“`

为了简单,这里用 Infura 节点连以太坊 Ropsten 测试网,API key 在 infura.io 上申请。先查一下当前 gas 价格:

“`python

data = {“jsonrpc”: “2.0”, “method”: “eth_gasPrice”, “params”: [], “id”: 1}

response = session.post(url, json=data, headers=headers)

if response.ok:

gasPriceHex = response.json().get(“result”)

gasPriceDecimal = int(gasPriceHex, 16)

else:

print(“Error occured”)

“`

至于用哪个方法、传什么参数,以太坊官方文档里都有。

读取区块与交易数据

试试更有意思的——拿最新区块,看看能读出什么:

“`python

blockNumber = “latest”

fullTrx = False # True 返回完整交易,False 只返回交易哈希

params = [blockNumber, fullTrx]

data = {“jsonrpc”: “2.0”, “method”: “eth_getBlockByNumber”, “params”: params, “id”: 1}

response = session.post(url, json=data, headers=headers)

if response.ok:

block = response.json().get(“result”)

transactions = block.get(“transactions”)

“`

再挑一笔交易细看:

“`python

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:

print(“Error occured”)

“`

创建账户并发送交易

到这里调用模式应该很清楚了,来点进阶的。先用 web3.py 建个新账户,往里面充点 Ropsten 测试 ETH:

“`python

import web3

w3 = web3.Web3()

account = w3.eth.account.create(‘put any phrase here’)

address = account.address

pKey = account.privateKey

“`

发交易需要 nonce,同样可以用 JSON-RPC 拿:

“`python

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:

print(“Error occured”)

“`

接着构造并签名交易,再通过 JSON-RPC 发出去:

“`python

signed_txn = w3.eth.account.signTransaction({

‘to’: ‘0x687422eEA2cB73B5d3e242bA5456b782919AFc85’, # Faucet 地址

‘nonce’: nonce,

‘gasPrice’: gasPriceHex,

‘gas’: 100000,

‘value’: w3.toWei(0.5, ‘ether’),

‘chainId’: 3, # Ropsten

}, 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:

print(“Error occured”)

“`

注意这里复用了开头拿到的 gas 价格。如果换到其他以太坊测试网,记得把 chainId 改成对应的值。

到这就差不多了,用 JSON-RPC 跟以太坊交互的基础套路你算是摸清了。完整代码在:https://github.com/nschapeler/ethereum-rpcjson

温馨提示:

文章标题:以太坊JSON-RPC API入门:用Python直接与链上交互

文章链接:https://www.btchangqing.cn/449798.html

更新时间:2023年01月27日

本站大部分内容均收集于网络,若内容若侵犯到您的权益,请联系我们,我们将第一时间处理。

区块链

SHIB今日行情20230127:SHIB多少钱一个及最新价格走势

2023-1-27 15:45:04

区块链

Blur NFT市场份额逼近30%,累计交易额突破75万枚ETH

2023-1-27 16:07:10

❯
搜索