How to Transfer ETH and Tokens Using Web3.py in Python

·

Web3.py is a powerful Python library for interacting with the Ethereum blockchain. This guide provides a step-by-step tutorial on sending ETH and ERC-20 tokens using Web3.py, complete with code examples and best practices.


Getting Started with Web3.py

1. Install Web3.py

Begin by installing the Web3.py library using pip:

pip install web3.py

2. Set Up an Infura Node

To connect to the Ethereum network:

  1. Register for a free account on Infura.
  2. Create a project to receive your Ethereum node URL (available in project settings).
  3. Choose between HTTPS or WebSocket endpoints based on your needs.

👉 Need an alternative to Infura? Explore reliable node providers here


Code Implementation

Transferring ERC-20 Tokens (e.g., USDT)

from web3 import Web3
import json
from decimal import Decimal

class EthereumTransactor:
    def __init__(self):
        self.web3 = Web3(Web3.HTTPProvider('YOUR_INFURA_URL'))
        self.contract_address = 'TOKEN_CONTRACT_ADDRESS'
        self.wallet = 'YOUR_WALLET_ADDRESS'
        self.wallet_key = 'YOUR_PRIVATE_KEY'
        
        with open('token_abi.json') as f:
            self.abi = json.load(f)
        
        self.contract = self.web3.eth.contract(
            address=self.contract_address,
            abi=self.abi
        )
        self.token_name = 'USDT'

    def transfer_token(self, recipient, amount):
        try:
            balance = self.contract.functions.balanceOf(self.wallet).call()
            if Decimal(Web3.fromWei(balance, 'ether')) < Decimal(amount):
                return None, 'Insufficient token balance'
            
            nonce = self.web3.eth.get_transaction_count(self.wallet)
            tx = {
                'from': self.wallet,
                'nonce': nonce,
                'gas': 100000,
                'gasPrice': Web3.toWei('50', 'gwei'),
                'chainId': 1
            }
            
            txn = self.contract.functions.transfer(
                Web3.toChecksumAddress(recipient),
                Web3.toWei(amount, 'ether')
            ).build_transaction(tx)
            
            signed_tx = self.web3.eth.account.sign_transaction(txn, self.wallet_key)
            tx_hash = self.web3.eth.send_raw_transaction(signed_tx.rawTransaction)
            return Web3.toHex(tx_hash), 'Transfer successful'
            
        except Exception as e:
            return None, str(e)

Transferring ETH

    def transfer_eth(self, recipient, amount):
        try:
            balance = self.web3.eth.get_balance(self.wallet)
            if Decimal(Web3.fromWei(balance, 'ether')) < Decimal(amount):
                return None, 'Insufficient ETH balance'
                
            nonce = self.web3.eth.get_transaction_count(self.wallet)
            tx = {
                'nonce': nonce,
                'to': Web3.toChecksumAddress(recipient),
                'gas': 100000,
                'gasPrice': Web3.toWei('50', 'gwei'),
                'value': Web3.toWei(amount, 'ether'),
                'chainId': 1
            }
            
            signed_tx = self.web3.eth.account.sign_transaction(tx, self.wallet_key)
            tx_hash = self.web3.eth.send_raw_transaction(signed_tx.rawTransaction)
            return Web3.toHex(tx_hash), 'Transfer successful'
            
        except Exception as e:
            return None, str(e)

Key Considerations

  1. Gas Fees: Optimize gas prices using tools like Etherscan Gas Tracker.
  2. Security: Never expose private keys in your code. Use environment variables.
  3. Error Handling: Implement comprehensive logging for transaction failures.

👉 Learn advanced blockchain development techniques


FAQ

Q: How do I estimate gas fees accurately?

A: Use web3.eth.estimate_gas() or check current network conditions via Etherscan.

Q: Can I use this for other EVM-compatible chains?

A: Yes! Adjust the chainId parameter (e.g., 56 for BSC, 137 for Polygon).

Q: How do I verify transactions?

A: Track transactions using Etherscan with the returned tx_hash.

Q: What's the difference between ERC-20 and ETH transfers?

A: ERC-20 requires token contract interaction, while ETH transfers are native to Ethereum.


Best Practices

For more complex operations like batch transfers or smart contract interactions, consider using developer tools from leading platforms.

👉 Discover comprehensive Web3 solutions


This Markdown document is optimized for: