[](https://badge.fury.io/py/web3-ethereum-defi)
[](https://github.com/tradingstrategy-ai/web3-ethereum-defi/actions/workflows/test.yml)
[](https://web3-ethereum-defi.readthedocs.io/)
# Web3-Ethereum-Defi
Web-Ethereum-DeFi (`eth_defi`) Python package allows you to interact and consume data from EVM DeFi protocols.
- [Use cases](#use-cases)
- [Supported protocols, chains and integrations](#supported-protocols-chains-and-integrations)
- [Prerequisites](#prerequisites)
- [Install](#install)
- [Example code](#example-code)
* [Uniswap swap example](#uniswap-swap-example)
- [How to use the library in your Python project](#how-to-use-the-library-in-your-python-project)
- [Documentation](#documentation)
- [Development and contributing](#development-and-contributing)
- [Version history](#version-history)
- [Support ](#support)
- [Social media](#social-media)
- [License ](#license)
# Use cases
Use cases for this package include
- Trading and bots
- Data research, extraction, transformation and loading
- Portfolio management and accounting
- System integrations and backends
- AI agent interaction for EVM chains
# Supported protocols, chains and integrations

| Protocol | Actions | Tutorial and API links |
|:-----------------|:-----------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Uniswap | Token swaps, data research | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/make-uniswap-v3-swap-in-python.html) |
| Gnosis Safe | Safe deployment customisation and modules | [API](https://web3-ethereum-defi.readthedocs.io/api/safe/index.html) |
| Circle USDC | USDC interactions | [API](https://web3-ethereum-defi.readthedocs.io/api/usdc/index.html) |
| ChainLink | Read oracle prices, set up oracles | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/chainlink-native-token.html) |
| PancakeSwap | Token swaps, data research | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/pancakeswap-live-minimal.html) |
| GMX | Leveraged trading, spot trading | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/gmx-swap.html) |
| LFG | Token swaps, data research | [API](https://web3-ethereum-defi.readthedocs.io/api/uniswap_v2/index.html) |
| Aave | Credit, borrow, read rates | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/aave-v3-interest-analysis.html) |
| BENQI | Credit, borrow, read rates | [API](https://web3-ethereum-defi.readthedocs.io/api/aave_v2/index.html) |
| Lendle | Credit, borrow, read rates | [API](https://web3-ethereum-defi.readthedocs.io/api/aave_v2/index.html) |
| Sky (MakerDAO) | Credit, borrow, read rates | [API](https://web3-ethereum-defi.readthedocs.io/api/aave_v3/index.html) |
| Enzyme | Deposit to vaults, deploy, read vault data | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/enzyme-read-vaults.html) |
| Lagoon | Deposit to vaults, deploy, read vault data | [API](https://web3-ethereum-defi.readthedocs.io/api/lagoon/index.html) |
| Velvet | Deposit to vaults, deploy, read vault data | [API](https://web3-ethereum-defi.readthedocs.io/api/lagoon/index.html) | |
| Morpho | Read vault data | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/erc-4626-scan-prices.html) |
| Euler | Read vault data | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/erc-4626-scan-prices.html) | |
| IPOR | Read vault data | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/erc-4626-scan-prices.html) |
| 1delta | Open/close leveraged long/short positions | [API](https://web3-ethereum-defi.readthedocs.io/api/one_delta/index.html) |
| Hypersync | Read historical data fast | [API](https://web3-ethereum-defi.readthedocs.io/api/hypersync/index.html) |
| TokenSniffer | Read token risk core and metricws | [API](https://web3-ethereum-defi.readthedocs.io/api/token_analysis/_autosummary_token_analysis/eth_defi.token_analysis.tokensniffer.html) |
| Foundry | Compile, deploy and verify smart contracts | [API](https://web3-ethereum-defi.readthedocs.io/api/foundry/_autosummary_forge/eth_defi.foundry.forge.html) |
| Etherscan | Deploy and verify smart contracts | [API](https://web3-ethereum-defi.readthedocs.io/api/etherscan/index.html) |
| MEVBlocker | Frontrun protection | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/mev-blocker.html) |
| Ethereum mainnet | Frontrun protection, token mapping | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/mev-blocker.html) | |
| Base | Frontrun protection, token mapping | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/mev-blocker.html) |
| Arbitrum | Frontrun protection, token mapping | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/mev-blocker.html) |
| Avalanche | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) | |
| BNB chain | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |
| Polygon | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |
| BNB Chain | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) | |
| Berachain | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |
| Avalanche | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |
| Hyperliquid | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |
| Mode | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |
| Unichain | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |
| ZKSync | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |
| Soneium | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |
| Google GCloud | Support hardware security module wallets | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.gcloud_hsm_wallet.html) |
| Hot wallet | Secure hot wallet handling | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.hotwallet.html) |
| Multicall3 | Chunked and historical data reading | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/multicall3-with-python.html) |
| Gas | Ethereum gas management | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.gas.html) |
| EIP-4626 | Vault analysis | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/erc-4626-best-vaults.html) |
| EIP-726 | Message signing and decoding | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.eip_712.html#module-eth_defi.eip_712) |
| ERC-20 | High performance reading, data mappings | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html) |
| ABI | High performance smart contract ABI management | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.abi.html) |
| Transactions | Stack traces and symbolic revert reasons | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.gas.html) |
| Anvil | Mainnet works and local unit testing | [API](https://web3-ethereum-defi.readthedocs.io/api/provider/_autosummary_provider/eth_defi.provider.anvil.html) |
| LlamaNodes | Special RPC support | [API](https://web3-ethereum-defi.readthedocs.io/api/provider/_autosummary_provider/eth_defi.provider.llamanodes.html#module-eth_defi.provider.llamanodes) |
| Ankr | Special RPC support | [API](https://web3-ethereum-defi.readthedocs.io/api/provider/_autosummary_provider/eth_defi.provider.ankr.html) |
| dRPC | Special RPC support | [API](https://web3-ethereum-defi.readthedocs.io/api/event_reader/_autosummary_enzyne/eth_defi.event_reader.fast_json_rpc.get_last_headers.html?highlight=get_last_headers) |
👉 [Read the full API documentation](https://web3-ethereum-defi.readthedocs.io/).
This is a MIT-licensed open source project. Those who sponsor and contribute get integrations.
# Prerequisites
To use this package you need to
* Have Python 3.10, Python 3.11, or Python 3.12 (no other versions tested)
* macOS, Linux or Windows Subsystem for Linux (WSL) needed, Microsoft Windows is not officially supported
* For WSL, [make sure you have gcc and other tools installed](https://stackoverflow.com/questions/62215963/how-to-install-gcc-and-gdb-for-wslwindows-subsytem-for-linux/63548362#63548362)
* [Be proficient in Python programming](https://wiki.python.org/moin/BeginnersGuide)
* [Understand of Web3.py library](https://web3py.readthedocs.io/en/stable/)
* [Understand Pytest basics](https://docs.pytest.org/)
# Install
With `pip`:
```shell
pip install "web3-ethereum-defi[data]"
```
With `poetry`:
**N.B.** Currently poetry version `1.8.5` works perfectly. Poetry `>= 2` will be stuck in an infinite loop
```shell
# Poetry version
poetry add -E data web3-ethereum-defi
```
With `poetry` - master Git branch:
```shell
git clone git@github.com:tradingstrategy-ai/web3-ethereum-defi.git
cd web3-ethereum-defi
poetry shell
poetry install --all-extras
```
# Example code
See [the tutorials section in the documentation](https://web3-ethereum-defi.readthedocs.io/tutorials/index.html)
for full code examples.
## Uniswap swap example
- This example shows how to make a trade on Uniswap v3.
- The example is for Polygon, but works on other chains.
- See [tutorials](https://web3-ethereum-defi.readthedocs.io/tutorials/index.html) for more Uniswap and other DEX examples
```python
import datetime
import decimal
import os
import sys
from decimal import Decimal
from eth_account import Account
from eth_account.signers.local import LocalAccount
from web3.middleware import construct_sign_and_send_raw_middleware
from eth_defi.provider.multi_provider import create_multi_provider_web3
from eth_defi.revert_reason import fetch_transaction_revert_reason
from eth_defi.token import fetch_erc20_details
from eth_defi.confirmation import wait_transactions_to_complete
from eth_defi.uniswap_v3.constants import UNISWAP_V3_DEPLOYMENTS
from eth_defi.uniswap_v3.deployment import fetch_deployment
from eth_defi.uniswap_v3.swap import swap_with_slippage_protection
# The address of a token we are going to swap out
#
# Use https://tradingstrategy.ai/search to find your token
#
# For quote terminology see https://tradingstrategy.ai/glossary/quote-token
#
QUOTE_TOKEN_ADDRESS = "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359" # USDC (native)
# The address of a token we are going to receive
#
# Use https://tradingstrategy.ai/search to find your token
#
# For base terminology see https://tradingstrategy.ai/glossary/base-token
BASE_TOKEN_ADDRESS = "0x7ceb23fd6bc0add59e62ac25578270cff1b9f619" # WETH
# Connect to JSON-RPC node
rpc_env_var_name = "JSON_RPC_POLYGON"
json_rpc_url = os.environ.get(rpc_env_var_name)
assert json_rpc_url, f"You need to give {rpc_env_var_name} node URL. Check ethereumnodes.com for options"
# Create a Web3 provider with ability to retry failed requests
# and supporting fallback JSON-RPC nodes. RPC connections
# are extremely flaky and for production grade usage you need to use multiple
# JSON-RPC nodes.
# create_multi_provider_web3() will also take care of any chain-specific
# RPC setup.
web3 = create_multi_provider_web3(json_rpc_url)
print(f"Connected to blockchain, chain id is {web3.eth.chain_id}. the latest block is {web3.eth.block_number:,}")
# Grab Uniswap v3 smart contract addreses for Polygon.
#
deployment_data = UNISWAP_V3_DEPLOYMENTS["polygon"]
uniswap_v3 = fetch_deployment(
web3,
factory_address=deployment_data["factory"],
router_address=deployment_data["router"],
position_manager_address=deployment_data["position_manager"],
quoter_address=deployment_data["quoter"],
)
print(f"Using Uniwap v3 compatible router at {uniswap_v3.swap_router.address}")
# Read and setup a local private key
private_key = os.environ.get("PRIVATE_KEY")
assert private_key is not None, "You must set PRIVATE_KEY environment variable"
assert private_key.startswith("0x"), "Private key must start with 0x hex prefix"
account: LocalAccount = Account.from_key(private_key)
my_address = account.address
# Enable eth_sendTransaction using this private key
web3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))
# Read on-chain ERC-20 token data (name, symbol, etc.)
base = fetch_erc20_details(web3, BASE_TOKEN_ADDRESS)
quote = fetch_erc20_details(web3, QUOTE_TOKEN_ADDRESS)
# Native token balance
# See https://tradingstrategy.ai/glossary/native-token
gas_balance = web3.eth.get_balance(account.address)
print(f"Your address is {my_address}")
print(f"Your have {base.fetch_balance_of(my_address)} {base.symbol}")
print(f"Your have {quote.fetch_balance_of(my_address)} {quote.symbol}")
print(f"Your have {gas_balance / (10 ** 18)} for gas fees")
assert quote.fetch_balance_of(my_address) > 0, f"Cannot perform swap, as you have zero {quote.symbol} needed to swap"
# Ask for transfer details
decimal_amount = input(f"How many {quote.symbol} tokens you wish to swap to {base.symbol}? ")
# Some input validation
try:
decimal_amount = Decimal(decimal_amount)
except (ValueError, decimal.InvalidOperation) as e:
raise AssertionError(f"Not a good decimal amount: {decimal_amount}") from e
# Fat-fingering check
print(f"Confirm swap amount {decimal_amount} {quote.symbol} to {base.symbol}")
confirm = input("Ok [y/n]?")
if not confirm.lower().startswith("y"):
print("Aborted")
sys.exit(1)
# Convert a human-readable number to fixed decimal with 18 decimal places
raw_amount = quote.convert_to_raw(decimal_amount)
# Each DEX trade is two transactions
# - ERC-20.approve()
# - swap (various functions)
# This is due to bad design of ERC-20 tokens,
# more here https://twitter.com/moo9000/status/1619319039230197760
# Uniswap router must be allowed to spent our quote token
# and we do this by calling ERC20.approve() from our account
# to the token contract.
approve = quote.contract.functions.approve(uniswap_v3.swap_router.address, raw_amount)
tx_1 = approve.build_transaction(
{
# approve() may take more than 500,000 gas on Arbitrum One
"gas": 850_000,
"from": my_address,
}
)
#
# Uniswap v3 may have multiple pools per
# trading pair differetiated by the fee tier. For example
# WETH-USDC has pools of 0.05%, 0.30% and 1%
# fees. Check for different options
# in https://tradingstrategy.ai/search
#
# Here we use 5 BPS fee pool (5/10,000).
#
#
# Build a swap transaction with slippage protection
#
# Slippage protection is very important, or you
# get instantly overrun by MEV bots with
# sandwitch attacks
#
# https://tradingstrategy.ai/glossary/mev
#
#
bound_solidity_func = swap_with_slippage_protection(
uniswap_v3,
base_token=base,
quote_token=quote,
max_slippage=20, # Allow 20 BPS slippage before tx reverts
amount_in=raw_amount,
recipient_address=my_address,
pool_fees=[500], # 5 BPS pool WETH-USDC
)
tx_2 = bound_solidity_func.build_transaction(
{
# Uniswap swap should not take more than 1M gas units.
# We do not use automatic gas estimation, as it is unreliable
# and the number here is the maximum value only.
# Only way to know this number is by trial and error
# and experience.
"gas": 1_000_000,
"from": my_address,
}
)
# Sign and broadcast the transaction using our private key
tx_hash_1 = web3.eth.send_transaction(tx_1)
tx_hash_2 = web3.eth.send_transaction(tx_2)
# This will raise an exception if we do not confirm within the timeout.
# If the timeout occurs the script abort and you need to
# manually check the transaction hash in a blockchain explorer
# whether the transaction completed or not.
tx_wait_minutes = 2.5
print(f"Broadcasted transactions {tx_hash_1.hex()}, {tx_hash_2.hex()}, now waiting {tx_wait_minutes} minutes for it to be included in a new block")
print(f"View your transactions confirming at https://polygonscan/address/{my_address}")
receipts = wait_transactions_to_complete(
web3,
[tx_hash_1, tx_hash_2],
max_timeout=datetime.timedelta(minutes=tx_wait_minutes),
confirmation_block_count=1,
)
# Check if any our transactions failed
# and display the reason
for completed_tx_hash, receipt in receipts.items():
if receipt["status"] == 0:
revert_reason = fetch_transaction_revert_reason(web3, completed_tx_hash)
raise AssertionError(f"Our transaction {completed_tx_hash.hex()} failed because of: {revert_reason}")
print("All ok!")
print(f"After swap, you have {base.fetch_balance_of(my_address)} {base.symbol}")
print(f"After swap, you have {quote.fetch_balance_of(my_address)} {quote.symbol}")
print(f"After swap, you have {gas_balance / (10 ** 18)} native token left")
```
# How to use the library in your Python project
Add `web3-ethereum-defi` as a development dependency:
Using [Poetry](https://python-poetry.org/):
```shell
# Data optional dependencies include pandas and gql, needed to fetch Uniswap v3 data
poetry add -D "web3-ethereum-defi[data]"
```
# Documentation
- [Browse API documentation](https://web3-ethereum-defi.readthedocs.io/).
- [Browse tutorials](https://web3-ethereum-defi.readthedocs.io/tutorials/index.html).
# Development and contributing
- [Read development instructions](https://web3-ethereum-defi.readthedocs.io/development.html).
# Version history
- [Read changelog](https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/CHANGELOG.md).
- [See releases](https://pypi.org/project/web3-ethereum-defi/#history).
# Support
- [Join Discord for any questions](https://tradingstrategy.ai/community).
# Social media
- [Watch tutorials on YouTube](https://www.youtube.com/@tradingstrategyprotocol)
- [Follow on Twitter](https://twitter.com/TradingProtocol)
- [Follow on Telegram](https://t.me/trading_protocol)
- [Follow on LinkedIn](https://www.linkedin.com/company/trading-strategy/)
# License
MIT.
[Created by Trading Strategy](https://tradingstrategy.ai).
Raw data
{
"_id": null,
"home_page": "https://web3-ethereum-defi.readthedocs.io/",
"name": "web3-ethereum-defi",
"maintainer": null,
"docs_url": null,
"requires_python": "<4,>=3.10",
"maintainer_email": null,
"keywords": "uniswap, aave, gmx, safe, ethereum, cryptocurrency, erc-20, pancakeswap, bnb smart chain, base, web3, blockchain, avalanche, arbitrum, chainlink",
"author": "Mikko Ohtamaa",
"author_email": "mikko@tradingstrategy.ai",
"download_url": "https://files.pythonhosted.org/packages/ee/30/a0bd712460506420fa334725c986d2073a2b1157844cc49be5f1ec99a8eb/web3_ethereum_defi-0.31.tar.gz",
"platform": null,
"description": "[](https://badge.fury.io/py/web3-ethereum-defi)\n\n[](https://github.com/tradingstrategy-ai/web3-ethereum-defi/actions/workflows/test.yml)\n\n[](https://web3-ethereum-defi.readthedocs.io/)\n\n# Web3-Ethereum-Defi\n\nWeb-Ethereum-DeFi (`eth_defi`) Python package allows you to interact and consume data from EVM DeFi protocols.\n\n- [Use cases](#use-cases)\n- [Supported protocols, chains and integrations](#supported-protocols-chains-and-integrations)\n- [Prerequisites](#prerequisites)\n- [Install](#install)\n- [Example code](#example-code)\n * [Uniswap swap example](#uniswap-swap-example)\n- [How to use the library in your Python project](#how-to-use-the-library-in-your-python-project)\n- [Documentation](#documentation)\n- [Development and contributing](#development-and-contributing)\n- [Version history](#version-history)\n- [Support ](#support)\n- [Social media](#social-media)\n- [License ](#license)\n\n# Use cases\n\nUse cases for this package include\n\n- Trading and bots\n- Data research, extraction, transformation and loading\n- Portfolio management and accounting\n- System integrations and backends\n- AI agent interaction for EVM chains\n\n# Supported protocols, chains and integrations\n\n\n\n| Protocol | Actions | Tutorial and API links |\n|:-----------------|:-----------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Uniswap | Token swaps, data research | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/make-uniswap-v3-swap-in-python.html) |\n| Gnosis Safe | Safe deployment customisation and modules | [API](https://web3-ethereum-defi.readthedocs.io/api/safe/index.html) |\n| Circle USDC | USDC interactions | [API](https://web3-ethereum-defi.readthedocs.io/api/usdc/index.html) |\n| ChainLink | Read oracle prices, set up oracles | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/chainlink-native-token.html) |\n| PancakeSwap | Token swaps, data research | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/pancakeswap-live-minimal.html) |\n| GMX | Leveraged trading, spot trading | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/gmx-swap.html) |\n| LFG | Token swaps, data research | [API](https://web3-ethereum-defi.readthedocs.io/api/uniswap_v2/index.html) |\n| Aave | Credit, borrow, read rates | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/aave-v3-interest-analysis.html) |\n| BENQI | Credit, borrow, read rates | [API](https://web3-ethereum-defi.readthedocs.io/api/aave_v2/index.html) |\n| Lendle | Credit, borrow, read rates | [API](https://web3-ethereum-defi.readthedocs.io/api/aave_v2/index.html) |\n| Sky (MakerDAO) | Credit, borrow, read rates | [API](https://web3-ethereum-defi.readthedocs.io/api/aave_v3/index.html) |\n| Enzyme | Deposit to vaults, deploy, read vault data | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/enzyme-read-vaults.html) |\n| Lagoon | Deposit to vaults, deploy, read vault data | [API](https://web3-ethereum-defi.readthedocs.io/api/lagoon/index.html) |\n| Velvet | Deposit to vaults, deploy, read vault data | [API](https://web3-ethereum-defi.readthedocs.io/api/lagoon/index.html) | |\n| Morpho | Read vault data | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/erc-4626-scan-prices.html) |\n| Euler | Read vault data | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/erc-4626-scan-prices.html) | |\n| IPOR | Read vault data | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/erc-4626-scan-prices.html) |\n| 1delta | Open/close leveraged long/short positions | [API](https://web3-ethereum-defi.readthedocs.io/api/one_delta/index.html) |\n| Hypersync | Read historical data fast | [API](https://web3-ethereum-defi.readthedocs.io/api/hypersync/index.html) |\n| TokenSniffer | Read token risk core and metricws | [API](https://web3-ethereum-defi.readthedocs.io/api/token_analysis/_autosummary_token_analysis/eth_defi.token_analysis.tokensniffer.html) |\n| Foundry | Compile, deploy and verify smart contracts | [API](https://web3-ethereum-defi.readthedocs.io/api/foundry/_autosummary_forge/eth_defi.foundry.forge.html) |\n| Etherscan | Deploy and verify smart contracts | [API](https://web3-ethereum-defi.readthedocs.io/api/etherscan/index.html) |\n| MEVBlocker | Frontrun protection | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/mev-blocker.html) |\n| Ethereum mainnet | Frontrun protection, token mapping | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/mev-blocker.html) | |\n| Base | Frontrun protection, token mapping | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/mev-blocker.html) |\n| Arbitrum | Frontrun protection, token mapping | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/mev-blocker.html) |\n| Avalanche | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) | |\n| BNB chain | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |\n| Polygon | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |\n| BNB Chain | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) | |\n| Berachain | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |\n| Avalanche | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |\n| Hyperliquid | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |\n| Mode | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |\n| Unichain | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |\n| ZKSync | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |\n| Soneium | Token mapping | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html#module-eth_defi.token) |\n| Google GCloud | Support hardware security module wallets | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.gcloud_hsm_wallet.html) |\n| Hot wallet | Secure hot wallet handling | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.hotwallet.html) |\n| Multicall3 | Chunked and historical data reading | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/multicall3-with-python.html) |\n| Gas | Ethereum gas management | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.gas.html) |\n| EIP-4626 | Vault analysis | [Tutorial](https://web3-ethereum-defi.readthedocs.io/tutorials/erc-4626-best-vaults.html) |\n| EIP-726 | Message signing and decoding | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.eip_712.html#module-eth_defi.eip_712) |\n| ERC-20 | High performance reading, data mappings | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.token.html) |\n| ABI | High performance smart contract ABI management | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.abi.html) |\n| Transactions | Stack traces and symbolic revert reasons | [API](https://web3-ethereum-defi.readthedocs.io/api/core/_autosummary/eth_defi.gas.html) |\n| Anvil | Mainnet works and local unit testing | [API](https://web3-ethereum-defi.readthedocs.io/api/provider/_autosummary_provider/eth_defi.provider.anvil.html) |\n| LlamaNodes | Special RPC support | [API](https://web3-ethereum-defi.readthedocs.io/api/provider/_autosummary_provider/eth_defi.provider.llamanodes.html#module-eth_defi.provider.llamanodes) |\n| Ankr | Special RPC support | [API](https://web3-ethereum-defi.readthedocs.io/api/provider/_autosummary_provider/eth_defi.provider.ankr.html) |\n| dRPC | Special RPC support | [API](https://web3-ethereum-defi.readthedocs.io/api/event_reader/_autosummary_enzyne/eth_defi.event_reader.fast_json_rpc.get_last_headers.html?highlight=get_last_headers) |\n\n\n\ud83d\udc49 [Read the full API documentation](https://web3-ethereum-defi.readthedocs.io/).\n\nThis is a MIT-licensed open source project. Those who sponsor and contribute get integrations.\n\n# Prerequisites\n\nTo use this package you need to\n\n* Have Python 3.10, Python 3.11, or Python 3.12 (no other versions tested)\n* macOS, Linux or Windows Subsystem for Linux (WSL) needed, Microsoft Windows is not officially supported\n * For WSL, [make sure you have gcc and other tools installed](https://stackoverflow.com/questions/62215963/how-to-install-gcc-and-gdb-for-wslwindows-subsytem-for-linux/63548362#63548362)\n* [Be proficient in Python programming](https://wiki.python.org/moin/BeginnersGuide)\n* [Understand of Web3.py library](https://web3py.readthedocs.io/en/stable/) \n* [Understand Pytest basics](https://docs.pytest.org/)\n \n\n# Install\n\nWith `pip`:\n\n```shell\npip install \"web3-ethereum-defi[data]\"\n```\n\nWith `poetry`:\n\n**N.B.** Currently poetry version `1.8.5` works perfectly. Poetry `>= 2` will be stuck in an infinite loop \n\n```shell\n# Poetry version\npoetry add -E data web3-ethereum-defi\n```\n\nWith `poetry` - master Git branch: \n\n```shell\ngit clone git@github.com:tradingstrategy-ai/web3-ethereum-defi.git\ncd web3-ethereum-defi\npoetry shell\npoetry install --all-extras\n```\n\n# Example code\n\nSee [the tutorials section in the documentation](https://web3-ethereum-defi.readthedocs.io/tutorials/index.html)\nfor full code examples.\n\n## Uniswap swap example\n\n- This example shows how to make a trade on Uniswap v3.\n- The example is for Polygon, but works on other chains.\n- See [tutorials](https://web3-ethereum-defi.readthedocs.io/tutorials/index.html) for more Uniswap and other DEX examples\n\n```python\n\nimport datetime\nimport decimal\nimport os\nimport sys\nfrom decimal import Decimal\n\nfrom eth_account import Account\nfrom eth_account.signers.local import LocalAccount\nfrom web3.middleware import construct_sign_and_send_raw_middleware\n\nfrom eth_defi.provider.multi_provider import create_multi_provider_web3\nfrom eth_defi.revert_reason import fetch_transaction_revert_reason\nfrom eth_defi.token import fetch_erc20_details\nfrom eth_defi.confirmation import wait_transactions_to_complete\nfrom eth_defi.uniswap_v3.constants import UNISWAP_V3_DEPLOYMENTS\nfrom eth_defi.uniswap_v3.deployment import fetch_deployment\nfrom eth_defi.uniswap_v3.swap import swap_with_slippage_protection\n\n# The address of a token we are going to swap out\n#\n# Use https://tradingstrategy.ai/search to find your token\n#\n# For quote terminology see https://tradingstrategy.ai/glossary/quote-token\n#\nQUOTE_TOKEN_ADDRESS = \"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359\" # USDC (native)\n\n# The address of a token we are going to receive\n#\n# Use https://tradingstrategy.ai/search to find your token\n#\n# For base terminology see https://tradingstrategy.ai/glossary/base-token\nBASE_TOKEN_ADDRESS = \"0x7ceb23fd6bc0add59e62ac25578270cff1b9f619\" # WETH\n\n\n# Connect to JSON-RPC node\nrpc_env_var_name = \"JSON_RPC_POLYGON\"\njson_rpc_url = os.environ.get(rpc_env_var_name)\nassert json_rpc_url, f\"You need to give {rpc_env_var_name} node URL. Check ethereumnodes.com for options\"\n\n# Create a Web3 provider with ability to retry failed requests\n# and supporting fallback JSON-RPC nodes. RPC connections\n# are extremely flaky and for production grade usage you need to use multiple\n# JSON-RPC nodes.\n# create_multi_provider_web3() will also take care of any chain-specific\n# RPC setup.\nweb3 = create_multi_provider_web3(json_rpc_url)\n\nprint(f\"Connected to blockchain, chain id is {web3.eth.chain_id}. the latest block is {web3.eth.block_number:,}\")\n\n# Grab Uniswap v3 smart contract addreses for Polygon.\n#\ndeployment_data = UNISWAP_V3_DEPLOYMENTS[\"polygon\"]\nuniswap_v3 = fetch_deployment(\n web3,\n factory_address=deployment_data[\"factory\"],\n router_address=deployment_data[\"router\"],\n position_manager_address=deployment_data[\"position_manager\"],\n quoter_address=deployment_data[\"quoter\"],\n)\n\nprint(f\"Using Uniwap v3 compatible router at {uniswap_v3.swap_router.address}\")\n\n# Read and setup a local private key\nprivate_key = os.environ.get(\"PRIVATE_KEY\")\nassert private_key is not None, \"You must set PRIVATE_KEY environment variable\"\nassert private_key.startswith(\"0x\"), \"Private key must start with 0x hex prefix\"\naccount: LocalAccount = Account.from_key(private_key)\nmy_address = account.address\n\n# Enable eth_sendTransaction using this private key\nweb3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))\n\n# Read on-chain ERC-20 token data (name, symbol, etc.)\nbase = fetch_erc20_details(web3, BASE_TOKEN_ADDRESS)\nquote = fetch_erc20_details(web3, QUOTE_TOKEN_ADDRESS)\n\n# Native token balance\n# See https://tradingstrategy.ai/glossary/native-token\ngas_balance = web3.eth.get_balance(account.address)\n\nprint(f\"Your address is {my_address}\")\nprint(f\"Your have {base.fetch_balance_of(my_address)} {base.symbol}\")\nprint(f\"Your have {quote.fetch_balance_of(my_address)} {quote.symbol}\")\nprint(f\"Your have {gas_balance / (10 ** 18)} for gas fees\")\n\nassert quote.fetch_balance_of(my_address) > 0, f\"Cannot perform swap, as you have zero {quote.symbol} needed to swap\"\n\n# Ask for transfer details\ndecimal_amount = input(f\"How many {quote.symbol} tokens you wish to swap to {base.symbol}? \")\n\n# Some input validation\ntry:\n decimal_amount = Decimal(decimal_amount)\nexcept (ValueError, decimal.InvalidOperation) as e:\n raise AssertionError(f\"Not a good decimal amount: {decimal_amount}\") from e\n\n# Fat-fingering check\nprint(f\"Confirm swap amount {decimal_amount} {quote.symbol} to {base.symbol}\")\nconfirm = input(\"Ok [y/n]?\")\nif not confirm.lower().startswith(\"y\"):\n print(\"Aborted\")\n sys.exit(1)\n\n# Convert a human-readable number to fixed decimal with 18 decimal places\nraw_amount = quote.convert_to_raw(decimal_amount)\n\n# Each DEX trade is two transactions\n# - ERC-20.approve()\n# - swap (various functions)\n# This is due to bad design of ERC-20 tokens,\n# more here https://twitter.com/moo9000/status/1619319039230197760\n\n# Uniswap router must be allowed to spent our quote token\n# and we do this by calling ERC20.approve() from our account\n# to the token contract.\napprove = quote.contract.functions.approve(uniswap_v3.swap_router.address, raw_amount)\ntx_1 = approve.build_transaction(\n {\n # approve() may take more than 500,000 gas on Arbitrum One\n \"gas\": 850_000,\n \"from\": my_address,\n }\n)\n\n#\n# Uniswap v3 may have multiple pools per\n# trading pair differetiated by the fee tier. For example\n# WETH-USDC has pools of 0.05%, 0.30% and 1%\n# fees. Check for different options\n# in https://tradingstrategy.ai/search\n#\n# Here we use 5 BPS fee pool (5/10,000).\n#\n#\n# Build a swap transaction with slippage protection\n#\n# Slippage protection is very important, or you\n# get instantly overrun by MEV bots with\n# sandwitch attacks\n#\n# https://tradingstrategy.ai/glossary/mev\n#\n#\nbound_solidity_func = swap_with_slippage_protection(\n uniswap_v3,\n base_token=base,\n quote_token=quote,\n max_slippage=20, # Allow 20 BPS slippage before tx reverts\n amount_in=raw_amount,\n recipient_address=my_address,\n pool_fees=[500], # 5 BPS pool WETH-USDC\n)\n\ntx_2 = bound_solidity_func.build_transaction(\n {\n # Uniswap swap should not take more than 1M gas units.\n # We do not use automatic gas estimation, as it is unreliable\n # and the number here is the maximum value only.\n # Only way to know this number is by trial and error\n # and experience.\n \"gas\": 1_000_000,\n \"from\": my_address,\n }\n)\n\n# Sign and broadcast the transaction using our private key\ntx_hash_1 = web3.eth.send_transaction(tx_1)\ntx_hash_2 = web3.eth.send_transaction(tx_2)\n\n# This will raise an exception if we do not confirm within the timeout.\n# If the timeout occurs the script abort and you need to\n# manually check the transaction hash in a blockchain explorer\n# whether the transaction completed or not.\ntx_wait_minutes = 2.5\nprint(f\"Broadcasted transactions {tx_hash_1.hex()}, {tx_hash_2.hex()}, now waiting {tx_wait_minutes} minutes for it to be included in a new block\")\nprint(f\"View your transactions confirming at https://polygonscan/address/{my_address}\")\nreceipts = wait_transactions_to_complete(\n web3,\n [tx_hash_1, tx_hash_2],\n max_timeout=datetime.timedelta(minutes=tx_wait_minutes),\n confirmation_block_count=1,\n)\n\n# Check if any our transactions failed\n# and display the reason\nfor completed_tx_hash, receipt in receipts.items():\n if receipt[\"status\"] == 0:\n revert_reason = fetch_transaction_revert_reason(web3, completed_tx_hash)\n raise AssertionError(f\"Our transaction {completed_tx_hash.hex()} failed because of: {revert_reason}\")\n\nprint(\"All ok!\")\nprint(f\"After swap, you have {base.fetch_balance_of(my_address)} {base.symbol}\")\nprint(f\"After swap, you have {quote.fetch_balance_of(my_address)} {quote.symbol}\")\nprint(f\"After swap, you have {gas_balance / (10 ** 18)} native token left\")\n```\n\n# How to use the library in your Python project\n\nAdd `web3-ethereum-defi` as a development dependency:\n\nUsing [Poetry](https://python-poetry.org/):\n\n```shell\n# Data optional dependencies include pandas and gql, needed to fetch Uniswap v3 data\npoetry add -D \"web3-ethereum-defi[data]\"\n```\n\n# Documentation\n\n- [Browse API documentation](https://web3-ethereum-defi.readthedocs.io/).\n- [Browse tutorials](https://web3-ethereum-defi.readthedocs.io/tutorials/index.html).\n\n# Development and contributing\n\n- [Read development instructions](https://web3-ethereum-defi.readthedocs.io/development.html).\n\n# Version history\n\n- [Read changelog](https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/CHANGELOG.md).\n- [See releases](https://pypi.org/project/web3-ethereum-defi/#history).\n\n# Support \n\n- [Join Discord for any questions](https://tradingstrategy.ai/community).\n\n# Social media\n\n- [Watch tutorials on YouTube](https://www.youtube.com/@tradingstrategyprotocol)\n- [Follow on Twitter](https://twitter.com/TradingProtocol)\n- [Follow on Telegram](https://t.me/trading_protocol)\n- [Follow on LinkedIn](https://www.linkedin.com/company/trading-strategy/)\n\n# License \n\nMIT.\n\n[Created by Trading Strategy](https://tradingstrategy.ai).\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Python library for Uniswap, Aave, ChainLink, Enzyme and other protocols on BNB Chain, Polygon, Ethereum and other blockchains",
"version": "0.31",
"project_urls": {
"Changelog": "https://github.com/tradingstrategy-ai/web3-ethereum-defi/blob/master/CHANGELOG.md",
"Discord": "https://discord.gg/5M88m9nM8H",
"Documentation": "https://web3-ethereum-defi.readthedocs.io/",
"Homepage": "https://web3-ethereum-defi.readthedocs.io/",
"Repository": "https://github.com/tradingstrategy-ai/web3-ethereum-defi",
"Sponsor": "https://tradingstrategy.ai",
"Twitter": "https://twitter.com/tradingprotocol",
"Youtube": "https://www.youtube.com/@tradingstrategyprotocol"
},
"split_keywords": [
"uniswap",
" aave",
" gmx",
" safe",
" ethereum",
" cryptocurrency",
" erc-20",
" pancakeswap",
" bnb smart chain",
" base",
" web3",
" blockchain",
" avalanche",
" arbitrum",
" chainlink"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "fb371e235de485a2f12b0b5bb86a3b2871ef86f9462116ba08783097007cfd13",
"md5": "13860dfacf85e422853fbe45f8ce735e",
"sha256": "84f5f47c7936232b30f24165e38a7be69842739e9240c40554fc1cd2bb76aad6"
},
"downloads": -1,
"filename": "web3_ethereum_defi-0.31-py3-none-any.whl",
"has_sig": false,
"md5_digest": "13860dfacf85e422853fbe45f8ce735e",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4,>=3.10",
"size": 29453431,
"upload_time": "2025-07-16T22:28:36",
"upload_time_iso_8601": "2025-07-16T22:28:36.447802Z",
"url": "https://files.pythonhosted.org/packages/fb/37/1e235de485a2f12b0b5bb86a3b2871ef86f9462116ba08783097007cfd13/web3_ethereum_defi-0.31-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "ee30a0bd712460506420fa334725c986d2073a2b1157844cc49be5f1ec99a8eb",
"md5": "b7f6e1c65b00387923d64758850c3236",
"sha256": "51a70048912c2d2028d564d1920607bd41bfb7fa225354881872ab7f4af6676d"
},
"downloads": -1,
"filename": "web3_ethereum_defi-0.31.tar.gz",
"has_sig": false,
"md5_digest": "b7f6e1c65b00387923d64758850c3236",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4,>=3.10",
"size": 27328372,
"upload_time": "2025-07-16T22:28:47",
"upload_time_iso_8601": "2025-07-16T22:28:47.418914Z",
"url": "https://files.pythonhosted.org/packages/ee/30/a0bd712460506420fa334725c986d2073a2b1157844cc49be5f1ec99a8eb/web3_ethereum_defi-0.31.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-16 22:28:47",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "tradingstrategy-ai",
"github_project": "web3-ethereum-defi",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "web3-ethereum-defi"
}