Skip to main content

PyPI version

Automated test suite

Documentation Status

Web3-Ethereum-Defi

Web-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.

Supported protocols include Uniswap, Aave, others

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)

    # 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()

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.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

web3_ethereum_defi-0.22.11.tar.gz (4.4 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

web3_ethereum_defi-0.22.11-py3-none-any.whl (5.3 MB view details)

Uploaded Python 3

File details

Details for the file web3_ethereum_defi-0.22.11.tar.gz.

File metadata

  • Download URL: web3_ethereum_defi-0.22.11.tar.gz
  • Upload date:
  • Size: 4.4 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.6.1 CPython/3.11.5 Darwin/22.6.0

File hashes

Hashes for web3_ethereum_defi-0.22.11.tar.gz
Algorithm Hash digest
SHA256 28b9b0ca8dbc62d7b86eb2d4bc63083be9e3bce71727a8ff0ad1928c36705adb
MD5 f366a814609c44fa238e13361197a7d9
BLAKE2b-256 f316f5e781e21da73f484133f3df29b3e091dfb03d4925a80caee64ead208dad

See more details on using hashes here.

File details

Details for the file web3_ethereum_defi-0.22.11-py3-none-any.whl.

File metadata

File hashes

Hashes for web3_ethereum_defi-0.22.11-py3-none-any.whl
Algorithm Hash digest
SHA256 04a471e759e3e82319eb87fbd3dfac7bd5788c0e0c4a8143e993dedd38846bc4
MD5 5e0265dc41e84900cdd059d1c02d9b6d
BLAKE2b-256 8550d9a38dd49fa8d364504899abcea14aaeb5b69fbdd819d3486ca8e37acf8e

See more details on using hashes here.

Release history Release notifications | RSS feed

1.2

2 files

1.1

2 files

1.0.2

2 files

1.0.1

2 files

1.0

2 files

0.41

2 files

0.40

2 files

0.39

2 files

0.38

2 files

0.37

2 files

0.36

2 files

0.35

2 files

0.34

2 files

0.33

2 files

0.32

2 files

0.31

2 files

0.30

2 files

0.29.1

2 files

0.29

2 files

0.28.1

2 files

0.28

2 files

0.27

2 files

0.26.1

2 files

0.26

2 files

0.25.7

2 files

0.25.6

2 files

0.25.5

2 files

0.25.4

2 files

0.25.3

2 files

0.25.2

2 files

0.25.1

2 files

0.25

2 files

0.24.6

2 files

0.24.5

2 files

0.24.4

2 files

0.24.3

2 files

0.24.2

2 files

0.24.1

2 files

0.24

2 files

0.23.1

2 files

0.23

2 files

0.22.30

2 files

0.22.29

2 files

0.22.28

2 files

0.22.27

2 files

0.22.26

2 files

0.22.25

2 files

0.22.24

2 files

0.22.23

2 files

0.22.22

2 files

0.22.21

2 files

0.22.20

2 files

0.22.19

2 files

0.22.18

2 files

0.22.17

2 files

0.22.16

2 files

0.22.15

2 files

0.22.14

2 files

0.22.13

2 files

0.22.12

2 files

This release

0.22.11 This release

2 files

0.22.10

2 files

0.22.9

2 files

0.22.8

2 files

0.22.7

2 files

0.22.6

2 files

0.22.5

2 files

0.22.3

2 files

0.22.2

2 files

0.22.1

2 files

0.22

2 files

0.21.8

2 files

0.21.7

2 files

0.21.6

2 files

0.21.5

2 files

0.21.4

2 files

0.21.3

2 files

0.21.2

2 files

0.21.1

2 files

0.21

2 files

0.20.1

2 files

0.20

2 files

0.19.2

2 files

0.19.1

2 files

0.19

2 files

0.18.4

2 files

0.18.3

2 files

0.18.2

2 files

0.18.1

2 files

0.18

2 files

0.17

2 files

0.16.1

2 files

0.16

2 files

0.15.3

2 files

0.15.2

2 files

0.15.1

2 files

0.15

2 files

0.14.1

2 files

0.14

2 files

0.13.11

2 files

0.13.10

2 files

0.13.9

2 files

0.13.8

2 files

0.13.7

2 files

0.13.6

2 files

0.13.5

2 files

0.13.4

2 files

0.13.3

2 files

0.13.2

2 files

0.13.1

2 files

0.13

2 files

0.12

2 files

0.11.3

2 files

0.11.2

2 files

0.11.1

2 files

0.11

2 files

0.10

2 files

0.9

2 files

0.8

2 files

0.7.1

2 files

0.7

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page