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:
-
First install and import web3 in python:
from web3 import Web3
-
Now create connection with your network using web3
w = Web3(Web3.HTTPProvider('https://ropsten.infura.io/v3/
<API_TOKEN>
')) -
Now create nonce for you payment (Note: Nonce is a unique whole number which can be used only once)
nonce = w.eth.getTransactionCount(account)
-
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
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
-
Now we will convert amount for ethereum using Wei
balance = w.eth.get_balance(checksum_encoded)
ether_value = w.fromWei(balance, 'ether')
-
Now we will check account signature using private key
signed_tx = w.eth.account.sign_transaction(tx, private_key1)
-
Now we will send the transaction
tx_hash = w.eth.sendRawTransaction(signed_tx.rawTransaction)
-
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.