Ethereum & Python - Future of Web3 V2
Harnessing the Power of Ethereum and Python for Blockchain Innovation
In this article, we will embark on an exciting journey into the world of Web3 development, where we will witness the dynamic synergy between Ethereum and Python. This powerful combination has the potential to redefine the landscape of blockchain technology and bring forth groundbreaking innovations across diverse sectors. By harnessing the capabilities of Python and leveraging the decentralized nature of Ethereum's network, we will uncover the seamless integration of these technologies, with a specific focus on Smart Contracts. This article is not an introduction to BlockChain or Ethereum, those topics are pre-requisites, more information can be found here, Do read V1 of the article, regarding Ethereum and account setup here
Let's Get Going...
Configuration
Libraries
Configure venv using
python -m venv venv
Activate venv using
source <path>/venv/bin/activate
Install Necessary Libraries
pip install web3
Smart Contract Development
A smart contract is a self-executing contract with the terms of the agreement directly written into lines of code. It operates on a blockchain platform, such as Ethereum, and automatically executes actions and enforces conditions based on predefined rules. Smart contracts eliminate the need for intermediaries, ensuring transparency, security, and efficiency in various decentralized applications. he most common language for creating smart contracts on the Ethereum blockchain is Solidity. Solidity is a high-level, statically typed language that resembles JavaScript and is optimized for Ethereum's virtual machine.
Remix IDE
Remix IDE is an online integrated development environment (IDE) specifically designed for smart contract development on the Ethereum blockchain. It provides a user-friendly interface for writing, testing, and deploying smart contracts. Learn more about Remix here
In this experiment, we will be using Remix to Write and Deploy a code in Solidity. Pre-Requisites are a Polygon Testnet account, as discussed in last blog, on which the contract will be deployed.
Step 1
Head on to - https://remix.ethereum.org/
The interface is very similar to VS code, When in production or application, the Contract should be versioned using GitHub, we will be using hello.sol
code for this experiment.
Step 2 - Code
We are using the HelloWorld equivalent, but it can be changed to the contract of your choice. Check this link to know more about contracts.
// Specifies that the source code is for a version
// of Solidity greater than 0.5.10
pragma solidity ^0.5.10;
// A contract is a collection of functions and data (its state)
// that resides at a specific address on the Ethereum blockchain.
contract HelloWorld {
// The keyword "public" makes variables accessible from outside a contract
// and creates a function that other contracts or SDKs can call to access the value
string public message;
// A special function only run during the creation of the contract
constructor(string memory initMessage) public {
// Takes a string value and stores the value in the memory data storage area,
// setting `message` to that value
message = initMessage;
}
// A publicly accessible function that takes a string as a parameter
// and updates `message`
function update(string memory newMessage) public {
message = newMessage;
}
}
Remix View
The given code is a Solidity smart contract written in version 0.5.10. It defines a contract called "HelloWorld"
that contains a string variable called "message"
. The contract has two functions: a constructor and an "update" function.
The constructor function is executed only once during the creation of the contract. It takes a string parameter called "initMessage"
and assigns its value to the "message"
variable.
The "update"
function is publicly accessible and takes a string parameter called "newMessage"
. It updates the value of the "message"
variable with the new value provided.
The keyword "public" in front of the "message"
variable creates a getter function automatically, allowing other contracts or SDKs to retrieve the value of "message"
by calling the function.
Step 3 - Compile
Select Compiler version, as defined in code and click compile.
Following screen appears post compilation
We can publish this contract directly on IPFS or InterPlanetary File System
Do copy ABI and Bytecode, as they will be useful while working on contracts with Python.
ABI
In the context of blockchain and smart contracts, ABI refers to the interface or specification that defines how to interact with a smart contract. It describes the structure and types of the contract's functions and their parameters, as well as the return types. ABI serves as a standardized way for different components of the blockchain ecosystem, such as other contracts, decentralized applications (DApps), or external tools, to interact with smart contracts. It provides a set of rules and guidelines for encoding and decoding data when calling contract functions.
Generally a JSON, it is used in Python as a list containing Dict.
[
{
"constant": false,
"inputs": [
{
"name": "newMessage",
"type": "string"
}
],
"name": "update",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "message",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"name": "initMessage",
"type": "string"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
}
]
Step 4 - Deploy
Once Compiled, a green tick should appear. Now move forward with deployment
Do check the Enviounmnet & Account carefully before deployment. We will be using our Polygon Testnet since it has some Matic that is provided for free by https://mumbaifaucet.com/
Select Enviournment as Injected provider - Metamask, to use metamask.
Sign-in and choose account
when Metamask shows connected and Account is the same in Metamask and Remix, we are good to go.
Click Deploy to Deploy on Ethereum Blockchain. Here, too, we have the option to Publish to IPFS, if needed.
Click Confirm to proceed
And Deployment is successful. We now will see more details using Etherscan.
Do copy the Transaction Hash
Step 5 - Review
Since we are using Mumbai Testnet Polygon, head over to https://mumbai.polygonscan.com/
Enter Transaction Hash
Details of Transaction Hash, Status, Block, From (Testnet Account), To (Contract hash) all are available. We will be needed all of these for the code.
Coding time
Python Code to Access Smart Contracts
Step 1
Import Libraries and Connect to Infura Mainnet, as discussed in the last article
import os
from web3 import Web3
from eth_account import Account
#
# Connect to Infura Mainnet - Etherium Node
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/<API KEY>'))
Step 2
ABI and Contract Access
contract_address = '0x<>'
abi = [
{
"constant": False,
"inputs": [
{
"name": "newMessage",
"type": "string"
}
],
"name": "update",
"outputs": [],
"payable": False,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"name": "initMessage",
"type": "string"
}
],
"payable": False,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"constant": True,
"inputs": [],
"name": "message",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": False,
"stateMutability": "view",
"type": "function"
}
]
contract = w3.eth.contract(address=contract_address,abi=abi)
print('Contract:', contract)
Contract Address is To / contract Hash as discussed in the previous section
Output
Contract: <web3._utils.datatypes.Contract object at 0x10741fac0>
Access more information from the Contract
# Get contract balance
contract_balance = w3.eth.get_balance(contract.address)
print(f"Contract Balance: {w3.from_wei(contract_balance, 'ether')} ETH")
# Get latest block number
latest_block_number = w3.eth.block_number
print(f"Latest Block Number: {latest_block_number}")
# Get block information
block = w3.eth.get_block(latest_block_number)
print(f"Block Hash: {block.hash.hex()}")
print(f"Block Timestamp: {block.timestamp}")
# More block properties can be accessed as needed
Output
Contract: <web3._utils.datatypes.Contract object at 0x1071cfe50>
Contract Balance: 0 ETH
Latest Block Number: 17301697
Block Hash: 0x<>
Block Timestamp: 1684598567
Based on ABI, you can also call various functions, provided necessary access is provided, and the chain is synced properly
# Access the 'message' function (read-only)
message = contract.functions.message().call()
print(f"Current message: {message}")
# Access the 'update' function (transaction)
new_message = "Hello, World!"
account = web3.eth.accounts[0] # Replace with your Ethereum account address
tx_hash = contract.functions.update(new_message).transact({'from': account})
print(f"Transaction Hash: {tx_hash.hex()}")
Conclusion
In conclusion, this article has provided an introduction to working with smart contracts using Python and Ethereum. We explored the powerful combination of Ethereum's decentralized network and Python's extensive capabilities, highlighting the seamless integration through practical code examples. By leveraging the Web3 library, developers can access and interact with smart contracts, and retrieve important details such as contract balance, owner, and account balances. The ability to work with smart contracts using Python opens up new possibilities for building decentralized applications and leveraging blockchain technology to transform various industries.
What's Next
In the next article, we will continue our exploration of smart contract development using Python and Ethereum. We will shift our focus to account-to-account transactions, enabling users to send and receive digital assets on the Ethereum blockchain. By diving into transaction management, gas fees, and interacting with contract functions that involve transfers, we will unlock a deeper understanding of how Python can facilitate seamless and secure transactions in a decentralized ecosystem. Stay tuned for the upcoming article and take your smart contract development skills to the next level.