Web3-Ethereum-Defi
Web-Ethereum-DeFi (eth_defi
) Python package provides high level modules for smart
contracts, with prepackaged ABI files for DeFi protocol integration,
wallet management, JSON-RPC providers and automated test suites. The
package aims for robustness, high quality of the code and documentation.
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
Features
Features include e.g.
Web3-Ethereum-Defi supports
- Uniswap (both v2 and v3)
- Sushi
- Aave
- Enzyme Protocol
- dHEDGE Protocol
- More integrations to come
- Built-in integration for over 600 smart contracts with precompiled Solidity ABI files
Read the full API documentation).
For code examples please see below.
Prerequisites
To use this package you need to
Install
With pip
:
pip install "web3-ethereum-defi[data]"
With poetry
:
# Poetry version
poetry add -E data web3-ethereum-defi
With poetry
- master Git branch:
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
for full code examples.
PancakeSwap swap example
import os
import time
from functools import lru_cache
from web3 import HTTPProvider, Web3
from eth_defi.abi import get_contract
from eth_defi.chain import install_chain_middleware
from eth_defi.event_reader.filter import Filter
from eth_defi.event_reader.logresult import decode_log
from eth_defi.event_reader.reader import read_events, LogResult
from eth_defi.uniswap_v2.pair import fetch_pair_details, PairDetails
QUOTE_TOKENS = ["BUSD", "USDC", "USDT"]
@lru_cache(maxsize=100)
def fetch_pair_details_cached(web3: Web3, pair_address: str) -> PairDetails:
return fetch_pair_details(web3, pair_address)
def main():
json_rpc_url = os.environ.get("JSON_RPC_BINANCE", "https://bsc-dataseed.binance.org/")
web3 = Web3(HTTPProvider(json_rpc_url))
web3.middleware_onion.clear()
install_chain_middleware(web3)
Pair = get_contract(web3, "sushi/UniswapV2Pair.json")
filter = Filter.create_filter(address=None, event_types=[Pair.events.Swap])
latest_block = web3.eth.block_number
while True:
start = latest_block
end = web3.eth.block_number
evt: LogResult
for evt in read_events(
web3,
start_block=start,
end_block=end,
filter=filter,
):
decoded = decode_log(evt)
pair = fetch_pair_details_cached(web3, decoded["address"])
token0 = pair.token0
token1 = pair.token1
block_number = evt["blockNumber"]
if token0.symbol in QUOTE_TOKENS:
base = token1
quote = token0
base_amount = decoded["args"]["amount1Out"] - decoded["args"]["amount1In"]
quote_amount = decoded["args"]["amount0Out"] - decoded["args"]["amount0In"]
else:
base = token0
quote = token1
base_amount = decoded["args"]["amount0Out"] - decoded["args"]["amount0Out"]
quote_amount = decoded["args"]["amount1Out"] - decoded["args"]["amount1Out"]
if base_amount and quote_amount:
human_base_amount = base.convert_to_decimals(base_amount)
human_quote_amount = quote.convert_to_decimals(quote_amount)
price = human_quote_amount / human_base_amount
if human_quote_amount > 0:
direction = "sell"
else:
direction = "buy"
price = abs(price)
print(f"Swap block:{block_number:,} tx:{evt['transactionHash']} {direction} price:{price:,.8f} {base.symbol}/{quote.symbol}")
else:
pass
else:
print(".")
latest_block = end
time.sleep(1)
if __name__ == "__main__":
main()
How to use the library in your Python project
Add web3-ethereum-defi
as a development dependency:
Using Poetry:
# Data optional dependencies include pandas and gql, needed to fetch Uniswap v3 data
poetry add -D "web3-ethereum-defi[data]"
Documentation
Development and contributing
Version history
Support
Social media
License
MIT.
Created by Trading Strategy.