Overview
Web3.py is a collection of Python libraries that enable developers to interact with Ethereum nodes using HTTP, IPC, or WebSocket protocols. Moonbeam offers Ethereum-compatible APIs, allowing seamless integration with Web3.py for decentralized application development. This tutorial demonstrates how to send transactions and deploy smart contracts on Moonbase Alpha using Web3.py, applicable to Moonbeam, Moonriver, and Moonbeam development nodes.
Prerequisites
Before starting, ensure you have:
- A funded account (obtain DEV tokens from the Moonbase Alpha Faucet)
- An RPC endpoint API key from a supported provider
Setting Up the Python Project
Create a project directory:
mkdir web3-examples && cd web3-examplesInstall dependencies:
pip3 install web3 py-solc-x solc-select
Sending Transactions
Check Balances Script
Create balances.py to monitor account balances:
from web3 import Web3
# Configure provider
provider_rpc = {
"moonbase": "https://rpc.api.moonbase.moonbeam.network",
}
web3 = Web3(Web3.HTTPProvider(provider_rpc["moonbase"]))
# Define addresses
address_from = 'INSERT_FROM_ADDRESS'
address_to = 'INSERT_TO_ADDRESS'
# Fetch balances
balance_from = web3.from_wei(web3.eth.get_balance(address_from), "ether")
balance_to = web3.from_wei(web3.eth.get_balance(address_to), "ether")
print(f"Balance of {address_from}: {balance_from} DEV")
print(f"Balance of {address_to}: {balance_to} DEV")Send Transaction Script
Create transaction.py to transfer 1 DEV:
from web3 import Web3
from web3.gas_strategies.rpc import rpc_gas_price_strategy
# Setup provider and account
web3 = Web3(Web3.HTTPProvider("https://rpc.api.moonbase.moonbeam.network"))
account_from = {
'private_key': 'INSERT_PRIVATE_KEY',
'address': 'INSERT_ADDRESS'
}
address_to = 'INSERT_TO_ADDRESS'
# Set gas strategy and send transaction
web3.eth.set_gas_price_strategy(rpc_gas_price_strategy)
tx = {
"nonce": web3.eth.get_transaction_count(account_from["address"]),
"to": address_to,
"value": web3.to_wei("1", "ether"),
"gas": 21000,
"gasPrice": web3.eth.generate_gas_price(),
}
signed_tx = web3.eth.account.sign_transaction(tx, account_from["private_key"])
tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)
tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
print(f"Transaction hash: {tx_receipt.transactionHash.hex()}")Deploying Smart Contracts
Compile Contract Script
Create compile.py:
import solcx
# Compile Incrementer.sol
compiled = solcx.compile_files(
'Incrementer.sol',
output_values=['abi', 'bin']
)
abi = compiled['Incrementer.sol:Incrementer']['abi']
bytecode = compiled['Incrementer.sol:Incrementer']['bin']Deploy Contract Script
Create deploy.py:
from compile import abi, bytecode
from web3 import Web3
web3 = Web3(Web3.HTTPProvider("https://rpc.api.moonbase.moonbeam.network"))
account_from = {
'private_key': 'INSERT_PRIVATE_KEY',
'address': 'INSERT_ADDRESS'
}
# Deploy contract
Incrementer = web3.eth.contract(abi=abi, bytecode=bytecode)
tx = Incrementer.constructor(5).build_transaction({
"from": account_from["address"],
"nonce": web3.eth.get_transaction_count(account_from["address"]),
})
signed_tx = web3.eth.account.sign_transaction(tx, account_from["private_key"])
tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)
tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
print(f"Contract deployed at: {tx_receipt.contractAddress}")Interacting with Contracts
Read Contract Data
Create get.py:
from compile import abi
from web3 import Web3
web3 = Web3(Web3.HTTPProvider("https://rpc.api.moonbase.moonbeam.network"))
contract_address = 'INSERT_CONTRACT_ADDRESS'
Incrementer = web3.eth.contract(address=contract_address, abi=abi)
number = Incrementer.functions.number().call()
print(f"Current number: {number}")Modify Contract State
Create increment.py and reset.py to update the contract:
# increment.py
from compile import abi
from web3 import Web3
web3 = Web3(Web3.HTTPProvider("https://rpc.api.moonbase.moonbeam.network"))
account_from = { ... } # Add account details
contract_address = 'INSERT_CONTRACT_ADDRESS'
Incrementer = web3.eth.contract(address=contract_address, abi=abi)
tx = Incrementer.functions.increment(3).build_transaction({
"from": account_from["address"],
"nonce": web3.eth.get_transaction_count(account_from["address"]),
})
signed_tx = web3.eth.account.sign_transaction(tx, account_from["private_key"])
tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)
print(f"Tx hash: {tx_hash.hex()}")FAQs
How do I get testnet tokens?
👉 Obtain DEV tokens from the Moonbase Alpha Faucet
Can I use Web3.py with Moonriver?
Yes! Replace the RPC endpoint with a Moonriver-compatible one.
Why is my transaction failing?
Ensure you have sufficient gas and a valid nonce. Use web3.eth.get_transaction_count to verify.
Key Takeaways
- Web3.py seamlessly integrates with Moonbeam networks.
- Always secure private keys and use environment variables.
- Monitor gas prices and nonces for successful transactions.