Web3.py Tutorial: How to Transfer Tokens Using Python

·

Blockchain development has become increasingly accessible, and Python—thanks to libraries like web3.py—is one of the most powerful tools for interacting with Ethereum-based networks. This tutorial walks you through the process of connecting to the Ethereum blockchain, creating an account, and transferring tokens using Python. Whether you're new to Web3 or looking to deepen your practical skills, this guide offers a hands-on approach to real-world blockchain interactions.


Connecting to the Blockchain with Web3.py

To begin working with Ethereum programmatically, you need a way to communicate with the network. This is where Infura comes in—a popular service that provides secure, scalable API access to Ethereum and other blockchains.

Setting Up Your Provider

Infura acts as a gateway between your Python script and the Ethereum network. You’ll need an Infura project ID to authenticate your requests. For this tutorial, we’ll use the Rinkeby testnet (note: Rinkeby is now deprecated but still useful for educational purposes).

🔗 Use the following endpoint to connect:

https://rinkeby.infura.io/v3/YOUR_PROJECT_ID

Replace YOUR_PROJECT_ID with your actual Infura key—or use a public one for testing (not recommended for production).

👉 Get started with blockchain connectivity using powerful developer tools.

from web3 import Web3
import json

# Connect to Rinkeby via Infura
w3 = Web3(Web3.HTTPProvider("https://rinkeby.infura.io/v3/8e4cd4b220fa42d3ac2acca966fd07fa"))
⚠️ Always include https:// in your URL—omitting it will cause connection failures.

Adding Middleware for Proof-of-Authority Networks

Testnets like Rinkeby use Proof-of-Authority (PoA) consensus, which requires special handling. Without middleware, transactions may fail silently.

from web3.middleware import geth_poa_middleware
w3.middleware_onion.inject(geth_poa_middleware, layer=0)

This line ensures compatibility with PoA-based networks by correctly formatting block headers.

Verify Connection

Before proceeding, confirm your node connection:

print(w3.is_connected())

If it returns True, congratulations—you're live on the blockchain!

Troubleshooting Tips:


Creating an Ethereum Account

Every transaction on Ethereum requires a sender—an account controlled by a private key.

Generate a Test Account

You can create a new Ethereum account directly in Python:

my_account = w3.eth.account.create('Nobody expects the Spanish Inquisition!')
print("Address:", my_account.address)
print("Private Key:", my_account.key.hex())

Output example:

Address: 0x5b580eB23Fca4f0936127335a92f722905286738
Private Key: 0x265434629c3d2e652550d62225adcb2813d3ac32c6e07c8c39b5cc1efbca18b3
🔒 Security Note: Never expose private keys in production code. Use secure wallets like MetaMask or hardware wallets for real applications.

While generating accounts manually is useful for learning, most developers rely on wallet software that handles key management securely.


Understanding ENS: Human-Readable Addresses

Ethereum addresses are long hexadecimal strings—difficult to remember and prone to errors when copied.

The Ethereum Name Service (ENS) solves this by mapping readable names like coogan.eth to wallet addresses. Think of it as DNS for blockchain.

For example:

coogan.eth → 0x4d3dd8471a289E820Aa9E2Dc5f437C1b2E22F598

Although ENS is not supported on all testnets, it's widely used on mainnet. Future tutorials will explore integrating ENS into Python scripts.


Transferring Tokens Using Smart Contracts

Now comes the core functionality: sending tokens. We’ll use Dai, a stablecoin pegged to the US dollar, deployed as a smart contract on Ethereum.

What Is a Smart Contract?

Smart contracts are self-executing programs stored on the blockchain. Once deployed, they can manage assets, enforce logic, and interact with external accounts—all without intermediaries.

Dai’s contract allows users to:

To interact with it, we need two things:

  1. The contract’s address
  2. Its Application Binary Interface (ABI)

Contract Instantiation with ABI

The ABI defines what functions are available in a smart contract and how to call them.

Here’s the truncated ABI for the testnet Dai contract:

abi = '''[{"constant":true,"inputs":[],"name":"name", ... }]'''
abi = json.loads(abi)

Set the contract address:

address = '0xc3dbf84Abb494ce5199D5d4D815b10EC29529ff8'
dai = w3.eth.contract(address=address, abi=abi)

Now you can interact with Dai’s functions.

👉 Learn how to securely manage digital assets using advanced Web3 tools.

Test the Connection

Check total supply of Dai:

total = dai.functions.totalSupply().call()
print("Total Dai Supply:", w3.from_wei(total, 'ether'))

This confirms your contract instance is working.


Building and Sending a Token Transfer

We’re ready to send Dai from our generated account.

Step 1: Build the Transaction

Use the transfer method from the ABI:

tx = dai.functions.transfer(
    '0xRecipientAddressHere',  # Replace with recipient
    1000000000000000000       # 1 DAI (in wei)
).build_transaction({
    'chainId': 4,               # Rinkeby chain ID
    'gas': 70000,
    'gasPrice': w3.to_wei('10', 'gwei'),
    'nonce': w3.eth.get_transaction_count(my_account.address),
})

Note: Amounts are in wei (1 DAI = 10¹⁸ wei).

Step 2: Sign and Send

Sign with your private key:

signed_tx = w3.eth.account.sign_transaction(tx, my_account.key)
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
print("Transaction Hash:", tx_hash.hex())

Step 3: Wait for Confirmation

Monitor receipt status:

receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
if receipt.status == 1:
    print("Transfer successful!")
else:
    print("Transaction failed.")

Frequently Asked Questions (FAQ)

Q: Can I use web3.py on mainnet?
A: Yes. Simply switch the Infura endpoint from rinkeby to mainnet and ensure your account has ETH for gas fees.

Q: Why do I need an ABI?
A: The ABI tells your script what functions the smart contract exposes and how to format calls—without it, interaction isn’t possible.

Q: Is it safe to generate accounts in code?
A: Only for testing. In production, use encrypted keystores or wallet integrations to prevent exposure of private keys.

Q: What is the difference between ETH and DAI transfers?
A: ETH transfers use w3.eth.send_transaction, while token transfers (like DAI) require calling methods on their respective smart contracts.

Q: How do I check my token balance?
A: Use dai.functions.balanceOf(your_address).call() and divide by 10¹⁸ for human-readable values.

Q: Why did my transaction fail?
A: Common causes include insufficient gas, incorrect nonce, wrong chain ID, or lack of funds (ETH for gas or tokens to send).


Core Keywords for SEO

These terms naturally appear throughout the article, supporting search visibility while maintaining readability.


With this foundation, you’re equipped to build powerful blockchain applications using Python. From querying balances to automating complex DeFi interactions, web3.py unlocks endless possibilities.

👉 Unlock the full potential of decentralized development with cutting-edge Web3 resources.