Package: web3-ethereum-defi
Web3-Ethereum-DefiWeb-Ethereum-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 casesPrerequisitesInstallCode examplesDeploy and transfer ERC-20 token between walletsUniswap v2 trade exampleUniswap v2 price estimation exampleHow to use the library in your Python projectDocumentationDevelopment and contributingVersion historySupportSocial mediaHistoryLicenseSupportedblockchainsinclude
Ethereum, BNB Chain, Polygon, Avalanche C-chain, Arbitrum and many
otherEVM-compatible
blockchains.SupportedDeFiprotocolsincludeUniswapwith itsclones,Aave,USDC, other Circlestablecoin tokens,Enzyme,
Chainlink and many others.Use casesUse cases for this package includeTrading and botsData research, extraction, transformation and loadingPortfolio management and accountingSystem integrations and backendsFeaturesFeatures include e.g.High-quality API documentationFully type hintedfor good developer experienceMEV protectionMainnet forking with AnvilRevert reasons and stack traces for Solidity errorsSwap, slippage and price impact estimationERC-20 token issuance and transfersEIP-712, EIP-3009 supportWeb3-Ethereum-Defi supportsUniswap (both v2 and v3)SushiAaveEnzyme ProtocoldHEDGE ProtocolMore integrations to comeBuilt-in integration for over 600 smart contracts with precompiled Solidity ABI filesRead the full API documentation).
For code examples please see below.PrerequisitesTo use this package you need toHave 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 supportedBe proficient in Python programmingUnderstand of Web3.py libraryUnderstand Pytest basicsInstallWithpip:pipinstall"web3-ethereum-defi[data]"Withpoetry:# Poetry versionpoetryadd-Edataweb3-ethereum-defiWithpoetry- master Git branch:gitclonegit@github.com:tradingstrategy-ai/web3-ethereum-defi.gitcdweb3-ethereum-defi
poetryshell
poetryinstall--all-extrasExample codeSeethe tutorials section in the documentationfor full code examples.PancakeSwap swap exampleThis example shows how to read the live trades of PancakeSwap,
and otherUniswap v2 compatible forkson BNB Smart ChainSee the instructions and full example source code in Tutorialsimportosimporttimefromfunctoolsimportlru_cachefromweb3importHTTPProvider,Web3frometh_defi.abiimportget_contractfrometh_defi.chainimportinstall_chain_middlewarefrometh_defi.event_reader.filterimportFilterfrometh_defi.event_reader.logresultimportdecode_logfrometh_defi.event_reader.readerimportread_events,LogResultfrometh_defi.uniswap_v2.pairimportfetch_pair_details,PairDetailsQUOTE_TOKENS=["BUSD","USDC","USDT"]@lru_cache(maxsize=100)deffetch_pair_details_cached(web3:Web3,pair_address:str)->PairDetails:returnfetch_pair_details(web3,pair_address)defmain():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 landwhileTrue:start=latest_blockend=web3.eth.block_numberevt:LogResultforevtinread_events(web3,start_block=start,end_block=end,filter=filter,):decoded=decode_log(evt)# Swap() events are generated by UniswapV2Pool contractspair=fetch_pair_details_cached(web3,decoded["address"])token0=pair.token0token1=pair.token1block_number=evt["blockNumber"]# Determine the human-readable order of token tickersiftoken0.symbolinQUOTE_TOKENS:base=token1# tokenquote=token0# stablecoin/BNBbase_amount=decoded["args"]["amount1Out"]-decoded["args"]["amount1In"]quote_amount=decoded["args"]["amount0Out"]-decoded["args"]["amount0In"]else:base=token0# stablecoin/BNBquote=token1# tokenbase_amount=decoded["args"]["amount0Out"]-decoded["args"]["amount0Out"]quote_amount=decoded["args"]["amount1Out"]-decoded["args"]["amount1Out"]# Calculate the price in Python Decimal classifbase_amountandquote_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_amountifhuman_quote_amount>0:# We define selling when the stablecoin amount increases# in the swapdirection="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")passelse:# No event detected between these blocksprint(".")latest_block=endtime.sleep(1)if__name__=="__main__":main()How to use the library in your Python projectAddweb3-ethereum-defias a development dependency:UsingPoetry:# Data optional dependencies include pandas and gql, needed to fetch Uniswap v3 datapoetryadd-D"web3-ethereum-defi[data]"DocumentationBrowse API documentation.Browse tutorials.Development and contributingRead development instructions.Version historyRead changelog.See releases.SupportJoin Discord for any questions.Social mediaWatch tutorials on YouTubeFollow on TwitterFollow on TelegramFollow on LinkedInLicenseMIT.Created by Trading Strategy.