Ethereum & Python - Future of Web3 V3

Ethereum & Python - Future of Web3 V3

Harnessing the Power of Ethereum and Python for Blockchain Innovation

ยท

6 min read

In this article, we will explore the fascinating world of Ethereum transactions using Python and the Web3 library. With the power of Python and the Web3 library, developers can interact with the Ethereum network, create transactions, and send value seamlessly. We will dive into the code and step-by-step instructions to understand how to connect to the Ethereum network, define sender and recipient addresses, create and sign transactions, and verify their success. This article is not an introduction to BlockChain or Ethereum, those topics are pre-requisites, more information can be found here, Do read V12of the article, regarding smart Contracts 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

HTTP Provider

We will be using Polygon Mumbai Testnet API, provided by Alchemy

Step 1

Hop on to https://dashboard.alchemy.com/ and create a new app, post registration

Step 2

Enter the basic information, Select Polygon POS & Polygon Mumbai, and Create App

Step 3

Click View Key to expose endpoint. Copy the HTTPS One

MetaMask

As discussed in V1 article set up a Polygon Metamask Account, and get $MATIC from https://mumbaifaucet.com/

For Transaction, from this account, we need the Address & a private Key, both of which can be got by clicking the 3 dots, and checking Account Details. Export the Private key and keep it safe. Do not publish it over Internet

Code

Libraries & Client

import os
from web3 import Web3
from eth_account import Account
# Connect to Polygon TestNet Node
w3 = Web3(Web3.HTTPProvider('https://polygon-mumbai.g.alchemy.com/v2/<API KEY>'))
# Print if web3 is successfully connected
print(w3.is_connected())

Output:

True

Check Balance

private_key = "<key from metamask>"

sender_address = '<your metamask address>'
receiver_address = '<Receiver address>'


#check balance in ether
balance = w3.eth.get_balance(sender_address)
print('Balance of address:', balance)

Output:

Balance of address: 1382464273993450838

Nounce & Amount to send

#Amount of $ETHER to send in wei
amount_wei = w3.to_wei(0.000000001, 'ether')

# # Get the nonce
nonce = w3.eth.get_transaction_count(sender_address)
print('Nonce:', nonce)

Wei is the smallest unit of ether in the Ethereum blockchain. Wei is used to represent the value or quantity of ether in transactions and smart contracts. Other ether units, such as gwei (gigawei) and ether, are derived from wei. 1 ether is equal to 10^18 wei.

Nonce is a sequential number that ensures the uniqueness and order of transactions from a specific sender's address. It acts as a counter, incrementing with each new transaction sent from the address. The nonce is an important component of a transaction because it prevents replay attacks and maintains the integrity of the transaction history. Each transaction must have a unique nonce value associated with the sender's address to be considered valid by the Ethereum network.

Output:

Nonce: 69

Build a Transaction

# Build a transaction
transaction = {
    'to': receiver_address,
    'value': amount_wei,
    'gas': 21000,
    'gasPrice': w3.eth.gas_price,
    'nonce': nonce,
    'chainId': 80001
}
  • to: receiver_address: Specifies the recipient's address for the transaction.

  • value: amount_wei: Sets the amount of ether (in wei) to be sent in the transaction.

  • gas: 21000: Defines the amount of gas units to be used for the transaction, typically for a simple transfer.

  • gasPrice: w3.eth.gas_price: Specifies the price of gas (in wei) to be paid for each unit of gas used in the transaction.

  • nonce: Provides the nonce value associated with the sender's address to ensure transaction uniqueness.

  • chainId: 80001: Indicates the ID of the Ethereum network or chain on which the transaction will be executed (80001 represents Polygon).

Gas is a unit of measurement in Ethereum that represents the computational effort required to execute a transaction or perform a smart contract operation. Each operation in Ethereum consumes a certain amount of gas, and the total gas cost of a transaction is determined by the cumulative gas costs of its operations. Gas is used to allocate resources and prevent malicious or inefficient code from overwhelming the network. Gas costs are paid by the transaction sender in the form of ether. Learn more about it here

Sign a transaction & Send it

# Sign the transaction
signed_transaction = w3.eth.account.sign_transaction(transaction, private_key)

# Send the transaction
transaction_hash = w3.eth.send_raw_transaction(signed_transaction.rawTransaction)
  • signed_transaction = w3.eth.account.sign_transaction(transaction, private_key) signs the transaction data with the private key of the sender.

  • transaction_hash = w3.eth.send_raw_transaction(signed_transaction.rawTransaction) sends the signed transaction to the Ethereum network and returns the transaction hash.

Transaction Receipt


# Wait for the transaction to be mined
transaction_receipt = w3.eth.wait_for_transaction_receipt(transaction_hash)

# Print the transaction receipt
print(transaction_receipt)

Transaction receipt contains information about the transaction's status and details.

Output:

AttributeDict({'blockHash': HexBytes('0x<>'), 'blockNumber': 35971344, 'contractAddress': None, 'cumulativeGasUsed': 3569032, 'effectiveGasPrice': 1500000000, 'from': '0x<>', 'gasUsed': 21000, 'logs': [AttributeDict({'address': '0x<>', 'topics': [HexBytes('0x<>'), HexBytes('0x<>'), HexBytes('0x<>'), HexBytes('0x<>')], 'data': HexBytes('0x<>'), 'blockNumber': 35971344, 'transactionHash': HexBytes('0x<>'), 'transactionIndex': 5, 'blockHash': HexBytes('0x<>'), 'logIndex': 71, 'removed': False}), AttributeDict({'address': '0x<>', 'topics': [HexBytes('0x<>'), HexBytes('0x<>'), HexBytes('0x<>'), HexBytes('0x<>')], 'data': HexBytes('0x<>'), 'blockNumber': 35971344, 'transactionHash': HexBytes('0x<>'), 'transactionIndex': 5, 'blockHash': HexBytes('0x<>'), 'logIndex': 72, 'removed': False})], 'logsBloom': HexBytes('0x<>'), 'status': 1, 'to': '0x<>', 'transactionHash': HexBytes('0x<>'), 'transactionIndex': 5, 'type': 0})

The Transaction Hash is an important component of this receipt, as it allows us to search further details on etherscan sites like https://mumbai.polygonscan.com/ in this case

Use Transaction Hash to get more Details

transaction = w3.eth.get_transaction(transaction_hash)

print(transaction)

Output:

AttributeDict({'blockHash': HexBytes('0x<>'), 'blockNumber': 35971344, 'from': '0x<>', 'gas': 21000, 'gasPrice': 1500000000, 'hash': HexBytes('0x<>'), 'input': '0x', 'nonce': 69, 'to': '0x<>', 'transactionIndex': 5, 'value': 1000000000, 'type': 0, 'v': 160038, 'r': HexBytes('0x<>'), 's': HexBytes('0x<>')})

Transaction Confirmation

In addition to the receipt, we can also confirm transactions by blocks

# Transaction confirmation
print(transaction_receipt['blockNumber'] - transaction['blockNumber'])

This calculates the difference between the block number of the transaction receipt and the block number of the initial transaction. This can be used to determine the number of blocks it took for the transaction to be mined and included in the blockchain.

When the difference is greater than zero, it means that the transaction has been successfully mined and confirmed by the network. The more blocks that have been added since the transaction was included, the higher the level of confirmation. Generally, a higher number of confirmations indicates a more secure and finalized transaction. It is common to wait for multiple confirmations before considering a transaction fully confirmed and irreversible.

Conclusion

In conclusion, this article has provided an overview of working with Ethereum transactions using Python and the Web3 library. We explored the process of creating and sending transactions, signing them with private keys, and waiting for transaction confirmation through mining. By leveraging the power of Python and Web3, developers can easily interact with the Ethereum blockchain and perform various transactions. Whether it's sending Ether or interacting with smart contracts, Python and Web3 provide a convenient and flexible environment for blockchain development. With the knowledge gained from this article, readers are well-equipped to dive deeper into Ethereum transaction processing and unlock the potential of decentralized applications and blockchain technology.

What's Next

This article marks the end of EthX Python. In the next article, we will dive into the exciting world of IPFS (InterPlanetary File System) and its integration with Python. We will explore how IPFS revolutionizes decentralized file storage and sharing, and demonstrate how to interact with IPFS networks using Python libraries. Stay tuned for an in-depth guide on leveraging IPFS for secure and distributed data storage in your Python applications.

Did you find this article valuable?

Support Ankur by becoming a sponsor. Any amount is appreciated!

ย