其他
5分钟!就能学会以太坊 JSON API 基础知识!
import json
session = requests.Session()
url = "https://ropsten.infura.io/v3/YOUR_INFURA_KEY"
headers = {'Content-type': 'application/json'}
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")
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
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
w3 = web3.Web3()
account = w3.eth.account.create('put any phrase here')
address = account.address
pKey = account.privateKey
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")
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)
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
大促下的智能运维挑战:阿里如何抗住“双11猫晚”? 20万个法人、百万条银行账户信息,正在暗网兜售 当莎士比亚遇见Google Flax:教你用字符级语言模型和归递神经网络写“莎士比亚”式句子 Hyperledger Fabric 和企业级以太坊,谁才是企业首选? 面试时遇到「看门狗」脖子上挂着「时间轮」,我就问你怕不怕? 同期两篇Nature:运行温度高于1K的量子计算平台问世! GitHub 标星 10,000+,Apache 顶级项目 ShardingSphere 的开源之路