How to Send ERC-20 Tokens using Web3.py and Python | QuickNode (2024)

6 min read

Overview

In this guide, we delve into the practical aspects of interacting with the Ethereum blockchain, specifically focusing on the transfer of ERC-20 tokens. ERC-20 tokens are a standard type of Ethereum token, widely used in various applications. We'll explore how to accomplish this using the popular library: Web3.py for Python.

What You Will Do


  • Understand the basics of ERC-20 tokens and their transfer methods
  • Set up your development environment with the necessary libraries
  • Implement an ERC-20 token transfer to an Ethereum address
  • Implement an ERC-20 token approval and transfer on behalf of a smart contract

What You Will Need


  • Basic understanding of Ethereum and smart contracts.
  • Familiarity with Python
  • A text editor or an IDE (e.g., VS Code)
  • Access to an Ethereum node or a service like QuickNode for connecting to the Ethereum network (or 24 other blockchains and counting! Sign up for free here
  • An EVM wallet (with access to your private key, like MetaMask or a burner wallet)
DependencyVersion
Python3.9.6
web3.py6.18.0

ERC-20 Tokens & Approvals

For a detailed understanding of ERC-20 tokens, their roles in the Ethereum ecosystem, and insights into the 'approve' function crucial for ERC-20 smart contract approvals, please refer to our comprehensive guide: How to Send ERC-20 Tokens using the QuickNode SDK. This guide will specifically focus on the practical implementation aspects using Web3py.

Now, before we delve into the technicalities of sending ERC-20 tokens, let's first set up a free QuickNode endpoint and fund our wallet.

Project Prerequisite: Create a QuickNode Endpoint

You're welcome to use public nodes or deploy and manage your own infrastructure; however, if you'd like 8x faster response times, you can leave the heavy lifting to us. Sign up for a free account here.

Once logged in, click the Create an endpoint button, then select the blockchain and network you want to deploy on. For the purpose of this guide, we'll choose the Ethereum Sepolia chain.

After creating your endpoint, keep the page handy, as we'll need it in the technical coding portion of this guide.

How to Send ERC-20 Tokens using Web3.py and Python | QuickNode (1)

tip

Note that although we are using Ethereum Sepolia for the demonstration of this guide, you can also use other EVM-compatible chains like Base, Polygon, Arbitrum, and more to interact with smart contracts and ERC-20 tokens.

With our infrastructure created, let's now move on to the technical part.

Project Prerequisite: Fund Your Wallet

If you're in need of ETH on Sepolia testnet, the Multi-Chain QuickNode Faucet makes it easy to obtain test ETH!

Navigate to the Multi-Chain QuickNode Faucet and connect your wallet (e.g., MetaMask, Coinbase Wallet) or paste in your wallet address to retrieve test ETH. Note that there is a mainnet balance requirement of 0.001 ETH on Ethereum Mainnet to use the EVM faucets. You can also tweet or login with your QuickNode account to get a bonus!

How to Send ERC-20 Tokens using Web3.py and Python | QuickNode (2)

For the remainder of this guide, we'll transition to the coding portion and demonstrate how to send ERC-20 tokens to an Ethereum address and approve a smart contract a certain allocation of ERC-20 tokens.

Send an ERC-20 Token using Web3.py

We'll be using a popular web3 SDK called Web3.py designed for Ethereum interaction. With Web3.py, developers and users can send transactions, interact with smart contracts, read block data, and a variety of other use cases.

Step 1: Install the SDK and Set Up Project

First, make sure you have Python (version 3+) installed, then open your terminal and install the Web3py library via Pip:

pip install web3

If you encounter issues during the installation process, it's possible that your environment is not configured correctly. Refer to the troubleshooting guide for instructions on how to establish a clean environment.

Step 2: Create and Configure the File

Next, let's create a file called main.py:

echo > main.py

Following, let's input the following Python code:

from web3 import Web3
from web3.middleware import geth_poa_middleware
import json

# Constants for the RPC URL and contract details
RPC_URL = 'YOUR_QUICKNODE_ENDPOINT'
CONTRACT_ADDRESS = Web3.to_checksum_address('ERC20_CONTRACT_ADDRESS')
TO_ADDRESS = 'TO_ADDRESS' # Adjust the to address

# Replace with your private key
private_key = 'YOUR_PRIVATE_KEY'

# Check if the private key is provided
if not private_key:
raise ValueError("Private key not provided.")

# Create a Web3 instance connected to the specified RPC URL
w3 = Web3(Web3.HTTPProvider(RPC_URL))

# Inject PoA middleware for networks using Proof of Authority consensus
w3.middleware_onion.inject(geth_poa_middleware, layer=0)

# Check for connection to the Ethereum network
if not w3.is_connected():
raise ConnectionError("Failed to connect to HTTPProvider")

# Load the contract ABI from a file
with open('abi.json') as abi_file:
contract_abi = json.load(abi_file)

# Create a contract object
contract = w3.eth.contract(address=CONTRACT_ADDRESS, abi=contract_abi)

# Define transaction details
token_amount = w3.to_wei(1, 'ether') # Adjust the amount as needed

# Get the nonce for the transaction
nonce = w3.eth.get_transaction_count(w3.eth.account.from_key(private_key).address)

# Build the transaction
transaction = contract.functions.transfer(TO_ADDRESS, token_amount).build_transaction({
'chainId': w3.eth.chain_id,
'gas': 2000000, # Adjust the gas limit as needed
'gasPrice': w3.eth.gas_price, # Adjust the gas price as needed or use w3.eth.generate_gas_price()
'nonce': nonce,
})

# Sign the transaction with the private key
signed_txn = w3.eth.account.sign_transaction(transaction, private_key)

# Attempt to send the transaction
try:
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
print(f"Transaction sent! Hash: {tx_hash.hex()}")
except Exception as e:
print(f"Error sending transaction: {e}")

Remember to replace the placeholders, YOUR_QUICKNODE_ENDPOINT, YOUR_PRIVATE_KEY, ERC20_CONTRACT_ADDRESS and TO_ADDRESS with their actual values.

IMPORTANT: You will also need to create a abi.json file in the same directory and include the ABI of the smart contract (ERC-20 token) from which you are transferring tokens. If the ERC-20 token you are transferring has its smart contract verified on Etherscan, you can retrieve the ABI via the Contract tab.

Step 3: Execute and Send the ERC-20 Token

Finally, we can execute the code by running the following terminal command:

python main.py

The output will look similar too:

Transaction sent! Hash: 0x9fc4ea7be48f5af020e257023e5e56c28246fe3d54c815bc5b623e45d5ef1aab

That's it!

Grant ERC-20 Token Access to Smart Contracts

As mentioned in the Approve section in this guide, you do not need to use the approve function to transfer ERC-20 tokens to a smart contract; however, if you would like the smart contract to access some or all of your ERC-20 tokens on your behalf, you will need to call the approve function first.

Let's demonstrate how to do this. We won't go over in-depth to set up your file (since it's the same process as above), so just follow along without coding.

transaction = contract.functions.approve(spender_address, token_amount).build_transaction({
'chainId': w3.eth.chain_id,
'gas': 2000000, # Adjust the gas limit as needed
'nonce': nonce,
})

Notice the only changes were to the function name and argument fields. We updated the function to approve since that's the function we want to call and updated the parameter value to spender_address, which should reference the contract address you want to approve tokens to. So to recap, the main thing you'll need to add or change when using the approve function will be to call that new function and update the address to reference the spender_address address (smart contract).

Final Thoughts

Congratulations on completing this guide! You've now equipped yourself with the knowledge to send ERC-20 tokens using Web3.py confidently. This skill is a fundamental part of interacting with the Ethereum blockchain and a valuable asset in your Web3 toolbox.

What's Next?


  • Experiment and Explore: Try sending tokens between different accounts or integrate these methods into your own projects.
  • Deepen Your Knowledge: Dive deeper into smart contract development and explore other token standards like ERC-721 or ERC-1155.
  • Join the Community: Engage with other developers, share your experiences, and collaborate on projects.

Remember, blockchain development is an ever-evolving field, and staying updated is 🔑. Subscribe to our newsletter for more articles and guides on Web3 and blockchain. If you have any questions or need further assistance, feel free to join our Discord server or provide feedback using the form below. Stay informed and connected by following us on Twitter (@QuickNode) and Telegram announcement channel.

We ❤️ Feedback!

Let us know if you have any feedback or requests for new topics. We'd love to hear from you.

How to Send ERC-20 Tokens using Web3.py and Python | QuickNode (2024)

FAQs

How to Send ERC-20 Tokens using Web3.py and Python | QuickNode? ›

Sending ERC-20 tokens is as simple as entering or pasting the recipient's Ethereum wallet address. There are mainly two places you can send your ERC-20 tokens from: a wallet from your centralized exchange (Binance, Coinbase, etc) and a software wallet, also called hot wallet (Metamask, Trust Wallet, etc).

How to get ERC20 token balance using Web3? ›

In order to get the ERC-20 token balance, you will need to do a number of things.
  1. Connect to an Ethereum Endpoint.
  2. Write up the ABI (Application Binary Interface) for the smart contract that you want to use to interact with the blockchain.
  3. Find an ERC20 token to get the balance of.
  4. Find a wallet to get the balance of.
Aug 13, 2024

How do I send ERC-20 token? ›

Sending ERC-20 tokens is as simple as entering or pasting the recipient's Ethereum wallet address. There are mainly two places you can send your ERC-20 tokens from: a wallet from your centralized exchange (Binance, Coinbase, etc) and a software wallet, also called hot wallet (Metamask, Trust Wallet, etc).

How to transfer tokens in Web3? ›

Approach
  1. Set up the web3. ...
  2. Retrieve the ERC20 contract instance using the contract address.
  3. Estimate the gas limit and gas price required for the transaction.
  4. Sign the transaction using the private key of the sender's account.
  5. Submit the signed transaction to the Ethereum network.
Jan 6, 2023

How do I send ERC-20 tokens to multiple addresses? ›

Efficient Token Multisender: How to Send ERC20&BEP20 Tokens to Multiple Addresses in a Single Transaction (Tutorial)
  1. Step 1: Visit Bulk Sender App. ...
  2. Step 2: Connect your wallet. ...
  3. Step 3: Select token address. ...
  4. Step 4: Fill out the list of recipients. ...
  5. Step 5: Approve ERC-20 tokens. ...
  6. Step 6: Send tokens.
Feb 6, 2024

How do I connect my wallet to Web3? ›

Navigate to the Web3 Wallet that you wish to connect to WalletConnect. Click the connection icon (next to Overview and Transactions in the upper-right corner of the screen). Go to a Web3 protocol. Find an option to connect a wallet and select Wallet Connect.

How do I withdraw my Web3 coin? ›

How to withdraw Crypto from Web3 to your primary wallet:
  1. Login to your Mobile App.
  2. Go to the account menu.
  3. Select Web3.
  4. Select the currency you wish to transfer.
  5. Select "Transfer".
  6. Select “Transfer to your primary wallet”.
  7. Enter the amount you wish to transfer or select MAX to transfer all of your selected Crypto.

How to send USDT ERC-20? ›

How to Transfer USDT with ERC-20 Network
  1. Log in on Ka. app.
  2. Click/tap the 'Send' icon.
  3. Enter the recipient's mobile number and continue.
  4. Select 'USDT. '
  5. Enter the amount of USDT that you'd like to send.
  6. Confirm with your passcode.
Feb 29, 2024

Do I need ETH to send ERC-20 tokens? ›

Please note that this policy applies to exchanges, if you want to exchange an ERC20 token to another coin (for example USDT to ETH), you need some ETH to cover the mining fees, because the exchange needs an Ethereum transaction.

Can you send any ERC20 token to Ledger? ›

Although your Ledger device can secure most Ethereum ERC20 tokens, not all ERC20 tokens are supported by the Ledger Live app. Non-supported ERC20 token deposits will not show in Ledger Live and will not create a transaction record in the Latest operations section in Ledger Live.

How to send an ERC-20 token with Python? ›

Send an ERC-20 Token using Web3.py​
  1. Step 1: Install the SDK and Set Up Project​ First, make sure you have Python (version 3+) installed, then open your terminal and install the Web3py library via Pip: ...
  2. Step 2: Create and Configure the File​ ...
  3. Step 3: Execute and Send the ERC-20 Token​
Aug 13, 2024

How do I send a transaction on Web3? ›

Sending Transactions
  1. Review prerequisites.
  2. Create a new directory and initialize a new Node. js project.
  3. Set up Web3. js and Hardhat.
  4. Send a transaction and review the results.
  5. Send a transaction and subscribe to its events.
  6. Send a raw transaction.

How do I transfer from Web3 to Coinbase? ›

You should see two options; Primary balance (your wallet that is full managed by Coinbase) and web3 wallet (your wallet for accessing Dapps) Select 'web3 wallet', then once you arrive on the web3 wallet page, select 'Add'. Select the first option: 'Transfer within Coinbase'

How do I transfer my ERC 20 token? ›

Sending an ERC-20 token takes only five steps:
  1. Import userop.js and ethers.js. You only need two libraries - ethers and userop. ...
  2. Build account preset. Userop. ...
  3. Import ERC-20 interface. The user operation will call the ERC-20 token's transfer function. ...
  4. Create the user operation. ...
  5. Send the user operation.

How do I create and deploy an ERC 20 token? ›

Create an ERC20 Token on Kaleido
  1. Step 1: Create a Kaleido account. If you haven't already, sign up for a Kaleido account here. ...
  2. Step 2: Create a blockchain network. To get started, create a blockchain network. ...
  3. Step 3: Create a Token pool. ...
  4. Step 4: ERC20 Transactions. ...
  5. Step 5: Transferring Tokens.
Dec 12, 2023

How do I send ERC-20 tokens to Coinbase? ›

Step 1: Deploy your ERC-20 Token on Base Mainnet

Write and deploy a compliant ERC-20 token smart contract. Test it and then deploy on Base Mainnet. Once your ERC-20 contract is deployed, your asset is swappable instantly on Coinbase Wallet in the swap flow.

How to check ERC20 token balance? ›

Retrieve the balance of an ERC-20 token
  1. Create a project directory​ Create a new directory for your project. ...
  2. Install required packages​ Install the web3 package in the project directory:
  3. Set up the script​ ...
  4. Set the ABI​ ...
  5. Select a token address​ ...
  6. Request the token balance​ ...
  7. Convert the token units​ ...
  8. Run the script​
Sep 5, 2024

How do I convert my ERC20 tokens to cash? ›

Safely exchange your ERC20 tokens through Ledger

In the Ledger Live app Swap tab, select any ERC20 tokens and the accounts of origin and destination. Enter the amount you want to exchange and check the rate. Before confirming the swap, you'll see a summary on Ledger Live.

How to read the balance of your MetaMask wallet with Web3 JS? ›

After detecting that the user has MetaMask installed what we are going to do is instantiate our version of Web3 with the provider information from the global object. Once we did that, we are already connected to the wallet, which means that we can access the current balance. var accounts = await web3. eth.

How do I withdraw my ERC20 tokens? ›

Withdraw an ERC20 token
  1. Add the sender and recipient addresses​ Open Ronin Bridge. ...
  2. Choose the token and amount​ ...
  3. Confirm your withdrawal​ ...
  4. Receive the tokens in your Ethereum wallet​
Jun 26, 2024

Top Articles
Does Having a Solid State Hard Drive Provide the Equivalent of Having More RAM?
What Does Staking Mean in Crypto? | The Motley Fool
Omega Pizza-Roast Beef -Seafood Middleton Menu
Craigslist Houses For Rent In Denver Colorado
Methstreams Boxing Stream
Research Tome Neltharus
Seething Storm 5E
Dr Lisa Jones Dvm Married
Miles City Montana Craigslist
Mail Healthcare Uiowa
Flat Twist Near Me
Oriellys St James Mn
Miami Valley Hospital Central Scheduling
Oro probablemente a duna Playa e nomber Oranjestad un 200 aña pasa, pero Playa su historia ta bay hopi mas aña atras
Vcuapi
Craftology East Peoria Il
Find Such That The Following Matrix Is Singular.
Lazarillo De Tormes Summary and Study Guide | SuperSummary
Missouri Highway Patrol Crash
Why do rebates take so long to process?
Homeaccess.stopandshop
All Breed Database
Naval Academy Baseball Roster
پنل کاربری سایت همسریابی هلو
Gma' Deals & Steals Today
Waters Funeral Home Vandalia Obituaries
Why comparing against exchange rates from Google is wrong
Kristen Hanby Sister Name
Indiana Jones 5 Showtimes Near Jamaica Multiplex Cinemas
The Menu Showtimes Near Amc Classic Pekin 14
15 Downer Way, Crosswicks, NJ 08515 - MLS NJBL2072416 - Coldwell Banker
Google Jobs Denver
Family Fare Ad Allendale Mi
Dallas City Council Agenda
Latest Nigerian Music (Next 2020)
Cranston Sewer Tax
Encompass.myisolved
My Locker Ausd
Emily Tosta Butt
Tattoo Shops In Ocean City Nj
Frontier Internet Outage Davenport Fl
3500 Orchard Place
Lesson 5 Homework 4.5 Answer Key
18 Seriously Good Camping Meals (healthy, easy, minimal prep! )
Jimmy John's Near Me Open
Deshuesadero El Pulpo
Game Akin To Bingo Nyt
De Donde Es El Area +63
Best brow shaping and sculpting specialists near me in Toronto | Fresha
Duffield Regional Jail Mugshots 2023
Latest Posts
Article information

Author: Domingo Moore

Last Updated:

Views: 6668

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.