Automating Blockchain Transactions

By the end of this post, readers will be able to:

  • Develop code by using Python and Web3.py to connect to a local Ganache blockchain.
  • Use Web3.py in conjunction with Ganache to test your transaction.
  • Formulate code to sign and send a transaction by using Web3.py.
  • Use Streamlit and Web3.py together to build an application that communicates with the blockchain.
  • Test a blockchain web application by using Ganache.

Truffle Suite - Ganache

Ganache is a personal local blockchain with accounts that are preloaded with ether. The ether in these accounts have no real value on the Ethereum blockchain, as this blockchain is local only. Ganache is a useful tool for testing transactions and smart contracts. Each time you launch Ganache, a new list of accounts with different addresses and keys are created:

Ganache interface
Ganache interface

Here is the Truffle Suite - Ganache download link:

Web3.py and Streamlit

In this guide, we will be integrating the account functionality of Ethereum's blockchain with the Streamlit web application. Web3.py will handle the transactions in the web application. In most decentralized applications that are built on the blockchain, Web3 is used to interact with smart contracts and read the block data. When you create a new contract object, you give it the JSON interface of the respective smart contract, and web3 will auto-convert all calls into low-level ABI calls over the remote procedure call (RPC).

Streamlit can be found here:

We will add functions that automate the process of accessing the balance of an address from the Ganache blockchain as well as sending a signed transaction. We will then incorporate these functions into the Streamlit web application. Visual Studio Code is the IDE used in this material to construct the python script below.

Ethereum Python Script

# Imports
import os
import requests
from dotenv import load_dotenv
load_dotenv()
from bip44 import Wallet
from web3 import Account
from web3 import middleware
from web3.gas_strategies.time_based import medium_gas_price_strategy
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:7545'))

# Create a function called `generate_account` that automates the Ethereum
# account creation process
def generate_account(w3):
    """Create a digital wallet and Ethereum account from a mnemonic seed phrase."""
    # Access the mnemonic phrase from the `.env` file
    mnemonic = os.getenv("MNEMONIC")

    # Create Wallet object instance
    wallet = Wallet(mnemonic)

    # Derive Ethereum private key
    private, public = wallet.derive_account("eth")

    # Convert private key into an Ethereum account
    account = Account.privateKeyToAccount(private)

    # Return the account from the function
    return account

# Create a function called `get_balance` that calls = converts the wei balance of the account to ether, and returns the value of ether
def get_balance(w3, address):
    """Using an Ethereum account address access the balance of Ether"""
    # Get balance of address in Wei
    wei_balance = w3.eth.get_balance(address)

    # Convert Wei value to ether
    ether = w3.fromWei(wei_balance, "ether")

    # Return the value in ether
    return ether

# Create a function called `send_transaction` that creates a raw transaction, signs it, and sends it. Return the confirmation hash from the transaction
def send_transaction(w3, account, receiver, ether):
    """Send an authorized transaction."""
    # Set a medium gas price strategy
    w3.eth.setGasPriceStrategy(medium_gas_price_strategy)

    # Convert eth amount to Wei
    wei_value = w3.toWei(ether, "ether")

    # Calculate gas estimate
    gas_estimate = w3.eth.estimateGas({"to": receiver, "from": account.address, "value": wei_value})

    # Construct a raw transaction
    raw_tx = {
        "to": receiver,
        "from": account.address,
        "value": wei_value,
        "gas": gas_estimate,
        "gasPrice": 0,
        "nonce": w3.eth.getTransactionCount(account.address)
    }

    # Sign the raw transaction with ethereum account
    signed_tx = account.signTransaction(raw_tx)

    # Send the signed transactions
    return w3.eth.sendRawTransaction(signed_tx.rawTransaction)

Deploy your Streamlit application to read in the python script above.

Streamlit Python Script

# Imports
import streamlit as st

# Import the functions from ethereum.py
from ethereum import w3, generate_account, get_balance, send_transaction
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:7545'))

# Streamlit application headings
st.markdown("# Automating Ethereum with Streamlit!")

# Generate the Ethereum account
account = generate_account(w3)

# The Ethereum Account Address
st.text("\n")
st.text("\n")
st.markdown("## Ethereum Account Address:")

# Write the Ethereum account address to the Streamlit page
st.write(account.address)

# Display the Etheremum Account balance
st.text("\n")
st.text("\n")
st.markdown("## Ethereum Account Balance:")

# Call the get_balance function and write the account balance to the screen
ether_balance = get_balance(w3, account.address)
st.write(ether_balance)

# An Ethereum Transaction
st.text("\n")
st.text("\n")
st.markdown("## An Ethereum Transaction")

# Create inputs for the receiver address and ether amount
receiver = st.text_input("Input the receiver address")
ether = st.number_input("Input the amount of ether")

# Create a button that calls the `send_transaction` function and returns the transaction hash
if st.button("Send Transaction"):

    transaction_hash = send_transaction(w3, account, receiver, ether)

    # Display the Etheremum Transaction Hash
    st.text("\n")
    st.text("\n")
    st.markdown("## Ethereum Transaction Hash:")

    st.write(transaction_hash)

Navigate to the folder in your terminal and type 'streamlit run ' - The following Streamlit page should open in your browser:

Streamlit web application
Streamlit web application

It’s that easy to automate an Ethereum transaction and get the results to display on the Streamlit application webpage! Congrats for learning how to use Ganache as a mock blockchain in conjunction with Steamlit and Web3.py.

Until next time, here’s a twitter thread summary of this post:

Subscribe to jackofcrypto
Receive the latest updates directly to your inbox.
Verification
This entry has been permanently stored onchain and signed by its creator.