web3.py
Connect to NodeFlare using web3.py — the Python library for Ethereum.
web3.py is the Python library for interacting with Ethereum. It provides a simple interface for reading chain data, sending transactions, and interacting with smart contracts.
Installation
Terminal
pip install web3Connect a Provider
Python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider("https://rpc.nodeflare.app/eth/v1/YOUR_KEY"))
print(w3.is_connected()) # TrueSwitch chains by changing the chain slug in the path (e.g. /base/ → /arb/):
Python
base_w3 = Web3(Web3.HTTPProvider("https://rpc.nodeflare.app/base/v1/YOUR_KEY"))
arb_w3 = Web3(Web3.HTTPProvider("https://rpc.nodeflare.app/arb/v1/YOUR_KEY"))
bnb_w3 = Web3(Web3.HTTPProvider("https://rpc.nodeflare.app/bnb/v1/YOUR_KEY"))Read the Latest Block
Python
block_number = w3.eth.block_number
print(f"Block: {block_number}")Get an Account Balance
Python
address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
balance_wei = w3.eth.get_balance(address)
balance_eth = w3.from_wei(balance_wei, "ether")
print(f"{balance_eth} ETH")Call a Contract
Python
abi = [{"inputs":[{"name":"account","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]
usdc_address = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
usdc = w3.eth.contract(address=usdc_address, abi=abi)
balance = usdc.functions.balanceOf("0xYourAddress").call()
print(f"{balance / 1e6} USDC")Send a Transaction
Python
from eth_account import Account
private_key = "0xYOUR_PRIVATE_KEY"
account = Account.from_key(private_key)
tx = {
"to": "0xRecipientAddress",
"value": w3.to_wei(0.01, "ether"),
"gas": 21000,
"gasPrice": w3.eth.gas_price,
"nonce": w3.eth.get_transaction_count(account.address),
"chainId": 1,
}
signed = w3.eth.account.sign_transaction(tx, private_key)
tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print(f"Confirmed in block {receipt['blockNumber']}")Filter Logs
Python
event_filter = w3.eth.filter({
"fromBlock": "latest",
"address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"topics": [
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" # Transfer
],
})
for event in event_filter.get_all_entries():
print(event)