JSON-RPC With Web3.py
First off, what the heck IS Web3.ps? On the most basic level, web3 is just a library that allows the user to interact with the nodes
More specifically, Web3.py is a python library for interacting with Ethereum. Its API is derived from the Web3.js Javascript API.
In this article, we're going to talk about how to use it with your Ethereum node, with a few practical examples.
Step one
Install:
Web3.py can be installed (preferably in a virtualenv) using pip
as follows:
$ pip install web3
Step two
Usage: To use the web3 library you will need to initialize the Web3
class.
python3 script.py
Notes: RPC connects over standard port 443
https://eth-parity-mainnet-3.bdnodes.net/?auth=TmtpAR7TFbdmxgm3ug_dwAyvs_EWcO1SYSXpKXt4oJ8
var web3 = new Web3(new Web3.providers.HttpProvider('https://eth-parity-mainnet-3.bdnodes.net/?auth=TmtpAR7TFbdmxgm3ug_dwAyvs_EWcO1SYSXpKXt4oJ8'));
Script examples:
Print current blocknumber:
from web3 import Web3, HTTPProvider
web3 = Web3(HTTPProvider('https://ethshared.bdnodes.net'))
print(web3.eth.blockNumber)
Print current gas price (median of the last blocks)
from web3 import Web3, HTTPProvider
web3 = Web3(HTTPProvider('https://ethshared.bdnodes.net'))
print(web3.eth.gasPrice)
Send Ether to another account:
Python3 Code examples
import sys
from web3: import Web3, HTTPProvider
Connect to the Blockdaemon Ethereum endpoint
w3 = Web3(HTTPProvider('https://ethshared.bdnodes.net'))
Get the sender's private key
senderKey = input("Enter sender private key (e.g. export from MetaMask): ")
try:
senderAccount = w3.eth.account.privateKeyToAccount(senderKey)
exception:
print("ERROR: Not a valid private key")
sys.exit(1)
Get the receiver's address
receiver_address = input("Enter receiver address: ")
if not Web3.isAddress(receiver_address):
print("ERROR: Not a valid address")
sys.exit(1)
Create the transaction
transaction = {
'to': receiver_address,
'value': 1, # Sending 1 wei
'gas': 90000, # The default in geth
'gasPrice': w3.eth.gasPrice, # Use the value determined by the node
'nonce': w3.eth.getTransactionCount(senderAccount.address) # Get correct transaction nonce for sender from the node
}
Sign the transaction
signed = w3.eth.account.signTransaction(transaction, senderAccount.privateKey)
Send it!
txHash = w3.eth.sendRawTransaction(signed.rawTransaction)
print(f"Succesfully sent transaction {Web3.toHex(txHash)}")
A video walkthrough of using a smart contract with Ethereum
Helpful docs:
https://web3py.readthedocs.io/en/stable/web3.eth.account.html
https://eth-account.readthedocs.io/en/latest/
More Reference articles:
Working with local private keys
Some Common Uses for Local Private Keys
A common reason to work with local private keys is to interact with a hosted node.
Some common things you might want to do with a Local Private Key are:
Comments
Please sign in to leave a comment.