适用于BNB Chain、Polygon、Ethereum和其他区块链上Uniswap、Aave、ChainLink、Enzyme等协议的Python库
项目描述
Web3-Ethereum-Defi
Web-Ethereum-DeFi (eth_defi
) Python包提供了用于智能合约的高级模块,并为DeFi协议集成、钱包管理、JSON-RPC提供者和自动测试套件提供了预包装的ABI文件。该包旨在实现健壮性、代码和文档的高质量。
- 支持的区块链包括以太坊、BNB Chain、Polygon、Avalanche C-chain、Arbitrum以及许多其他EVM兼容的区块链。
- 支持的DeFi 协议包括与其分叉的Uniswap、Aave、USDC、其他Circle 稳定币、Enzyme、Chainlink等。
用例
此软件包的应用场景包括
- 交易和机器人
- 数据研究、提取、转换和加载
- 投资组合管理和会计
- 系统集成和后端
功能
功能包括例如
- 高质量的API文档
- 完全类型提示,以提供良好的开发体验
- MEV保护
- 与Anvil的主网分叉
- 对Solidity错误的回滚原因和堆栈跟踪
- 交换、滑点及价格影响估算
- ERC-20令牌发行和转账
- EIP-712、EIP-3009支持
Web3-Ethereum-Defi支持
- Uniswap(v2和v3)
- Sushi
- Aave
- Enzyme协议
- dHEDGE协议
- 即将推出更多集成
- 内置600多个智能合约的集成,带有预编译的Solidity ABI文件
阅读完整的API文档)。请参阅下面的代码示例。
先决条件
要使用此软件包,您需要
- 拥有Python 3.10、Python 3.11或Python 3.12(未测试其他版本)
- 需要macOS、Linux或Windows Subsystem for Linux(WSL),Microsoft Windows官方不支持
- 精通Python编程
- 了解Web3.py库
- 了解Pytest基础
安装
使用pip
pip install "web3-ethereum-defi[data]"
使用poetry
# Poetry version
poetry add -E data web3-ethereum-defi
使用poetry
- master Git分支
git clone git@github.com:tradingstrategy-ai/web3-ethereum-defi.git
cd web3-ethereum-defi
poetry shell
poetry install --all-extras
示例代码
请参阅文档中的教程部分以获取完整的代码示例。
PancakeSwap交换示例
-
此示例展示了如何读取PancakeSwap以及其他与Uniswap v2兼容的分叉在BNB Smart Chain上的实时交易
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)
# Read the prepackaged ABI files and set up event filter
# for any Uniswap v2 like pool on BNB Smart Chain (not just PancakeSwap).
#
# We use ABI files distributed by SushiSwap project.
#
Pair = get_contract(web3, "sushi/UniswapV2Pair.json")
filter = Filter.create_filter(address=None, event_types=[Pair.events.Swap])
latest_block = web3.eth.block_number
# Keep reading events as they land
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)
# Swap() events are generated by UniswapV2Pool contracts
pair = fetch_pair_details_cached(web3, decoded["address"])
token0 = pair.token0
token1 = pair.token1
block_number = evt["blockNumber"]
# Determine the human-readable order of token tickers
if token0.symbol in QUOTE_TOKENS:
base = token1 # token
quote = token0 # stablecoin/BNB
base_amount = decoded["args"]["amount1Out"] - decoded["args"]["amount1In"]
quote_amount = decoded["args"]["amount0Out"] - decoded["args"]["amount0In"]
else:
base = token0 # stablecoin/BNB
quote = token1 # token
base_amount = decoded["args"]["amount0Out"] - decoded["args"]["amount0Out"]
quote_amount = decoded["args"]["amount1Out"] - decoded["args"]["amount1Out"]
# Calculate the price in Python Decimal class
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:
# We define selling when the stablecoin amount increases
# in the swap
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:
# Swap() event from DEX that is not Uniswap v2 compatible
# print(f"Swap block:{block_number:,} tx:{evt['transactionHash']} could not decode")
pass
else:
# No event detected between these blocks
print(".")
latest_block = end
time.sleep(1)
if __name__ == "__main__":
main()
如何在Python项目中使用该库
将web3-ethereum-defi
添加为开发依赖项
使用Poetry
# Data optional dependencies include pandas and gql, needed to fetch Uniswap v3 data
poetry add -D "web3-ethereum-defi[data]"
文档
开发和贡献
版本历史
支持
社交媒体
许可协议
MIT。