Transaction from metamask using web3 in python

Posted By : Aman Sharma | 24-Jun-2022

How to perform transaction from ethereum wallet on metamask


 

Steps to be followed:

  1. First install and import web3 in python:

          from web3 import Web3
  2. Now create connection with your network using web3

    w = Web3(Web3.HTTPProvider('https://ropsten.infura.io/v3/<API_TOKEN>'))

     

  3. Now create nonce for you payment (Note: Nonce is a unique whole number which can be used only once)

    nonce = w.eth.getTransactionCount(account)

     

  4. Now we will verify account using checksum

    addr_bytes = eth_utils.to_bytes(hexstr=account_2)

    checksum_encoded = checksum_encode(addr_bytes)

 

 

# Checksum (checksum_encode()) function

def checksum_encode(addr): 

    hex_addr = addr.hex()

    checksummed_buffer = ""

    # Treat the hex address as ascii/utf-8 for keccak256 hashing

    hashed_address = eth_utils.keccak(text=hex_addr).hex()

    # Iterate over each character in the hex address

    for nibble_index, character in enumerate(hex_addr):

        if character in "0123456789":

            # We can't upper-case the decimal digits

            checksummed_buffer += character

        elif character in "abcdef":

            # Check if the corresponding hex digit (nibble) in the hash is 8 or higher

            hashed_address_nibble = int(hashed_address[nibble_index], 16)

           if hashed_address_nibble > 7:

               checksummed_buffer += character.upper()

           else:

               checksummed_buffer += character

       else:

           raise eth_utils.ValidationError(

               f"Unrecognized hex character {character!r} at position {nibble_index}"

           )

   return "0x" + checksummed_buffer

 

  1. Now we will convert amount for ethereum using Wei

    balance = w.eth.get_balance(checksum_encoded)

    ether_value = w.fromWei(balance, 'ether')

     

  2. Now we will check account signature using private key

    signed_tx = w.eth.account.sign_transaction(tx, private_key1)

     

  3. Now we will send the transaction

    tx_hash = w.eth.sendRawTransaction(signed_tx.rawTransaction)

     

  4. Below is the full code

from web3 import Web3

def payment_by_metamask(acc1, acc2, pkey, amount, chain_id):

    res = False

    # Ropsten Test Net

    if chain_id == '0x3':

        w = Web3(Web3.HTTPProvider('https://ropsten.infura.io/v3/<API_TOKEN>'))

    # Main net

    if chain_id == '0x1':

        w = Web3(Web3.HTTPProvider('https://mainnet.infura.io/<API_TOKEN>'))

    account_1 = acc1

    private_key1 = pkey

    account_2 = acc2

    nonce = w.eth.getTransactionCount(account_1)

    addr_bytes = eth_utils.to_bytes(hexstr=account_2)

    checksum_encoded = checksum_encode(addr_bytes)

    balance = w.eth.get_balance(checksum_encoded)

    ether_value = w.fromWei(balance, 'ether')

    tx = {

        'nonce': nonce,

        'to': checksum_encoded,

        'value': w.toWei(amount, 'ether'),

        'gas': 2000000,

        'gasPrice': w.toWei('50', 'gwei')

    }

    signed_tx = w.eth.account.sign_transaction(tx, private_key1)

    # send transaction

    tx_hash = w.eth.sendRawTransaction(signed_tx.rawTransaction)

    res = w.toHex(tx_hash)

    return res



 

About Author

Author Image
Aman Sharma

Aman is an accomplished Backend developer with extensive industry experience, specializing in Odoo technology. He has a profound understanding and expertise in Python, Odoo ERP, Flask, MySQL, PostgreSQL, JavaScript, and payment gateway integration, particularly with Stripe. Aman's exceptional contributions to projects like Mymandi, Pando store, Markivia, DataInsite, and Tundra have been instrumental in driving the growth of his company. His strong analytical skills are pivotal in ensuring the success of his work, as he is able to identify and solve complex problems efficiently. Beyond his professional endeavors, he possesses a genuine passion for learning new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..