How To Use JSON-RPC With Web3.py

Follow

First off, what the heck IS Web3.ps? 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

 

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:

 

 

 

 

 

 

0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.