Skip to main content

PyPI version

Automated test suite

Documentation Status

Web3-Ethereum-Defi

This project contains high level Python API for smart contracts, DeFi trading, wallet management, automated test suites and backend integrations on EVM based blockchains. Supported blockchains include Ethereum, BNB Chain, Polygon, Avalanche C-chain, Arbitrum, others.

Pepe chooses Web3-Ethereum-DeFi and Python

Pepe chooses web3-ethereum-defi and Python.

Use Cases

  • Web3 development
  • DeFi trading
  • Market data services
  • On-chain data research
  • Ethereum integration: token payments, hot wallets, monitors and such

Features

Features include

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 -E data -E docs 

Code examples

For more code examples, see the tutorials section in the documentation.

Deploy and transfer ERC-20 token between wallets

To use the package to deploy a simple ERC-20 token in pytest testing:

import pytest
from web3 import Web3, EthereumTesterProvider

from eth_defi.token import create_token


@pytest.fixture
def tester_provider():
  return EthereumTesterProvider()


@pytest.fixture
def eth_tester(tester_provider):
  return tester_provider.ethereum_tester


@pytest.fixture
def web3(tester_provider):
  return Web3(tester_provider)


@pytest.fixture()
def deployer(web3) -> str:
  """Deploy account."""
  return web3.eth.accounts[0]


@pytest.fixture()
def user_1(web3) -> str:
  """User account."""
  return web3.eth.accounts[1]


@pytest.fixture()
def user_2(web3) -> str:
  """User account."""
  return web3.eth.accounts[2]


def test_deploy_token(web3: Web3, deployer: str):
  """Deploy mock ERC-20."""
  token = create_token(web3, deployer, "Hentai books token", "HENTAI", 100_000 * 10 ** 18)
  assert token.functions.name().call() == "Hentai books token"
  assert token.functions.symbol().call() == "HENTAI"
  assert token.functions.totalSupply().call() == 100_000 * 10 ** 18
  assert token.functions.decimals().call() == 18


def test_tranfer_tokens_between_users(web3: Web3, deployer: str, fund_owner, fund_client):
  """Transfer tokens between users."""
  token = create_token(web3, deployer, "Telos EVM rocks", "TELOS", 100_000 * 10 ** 18)

  # Move 10 tokens from deployer to user1
  token.functions.transfer(fund_owner, 10 * 10 ** 18).transact({"from": deployer})
  assert token.functions.balanceOf(fund_owner).call() == 10 * 10 ** 18

  # Move 10 tokens from deployer to user1
  token.functions.transfer(fund_client, 6 * 10 ** 18).transact({"from": fund_owner})
  assert token.functions.balanceOf(fund_owner).call() == 4 * 10 ** 18
  assert token.functions.balanceOf(fund_client).call() == 6 * 10 ** 18

See full example.

For more information how to user Web3.py in testing, see Web3.py documentation.

Uniswap v2 trade example

import pytest
from web3 import Web3
from web3.contract import Contract

from eth_defi.uniswap_v2.deployment import UniswapV2Deployment, deploy_trading_pair, FOREVER_DEADLINE


def test_swap(web3: Web3, deployer: str, fund_owner, uniswap_v2: UniswapV2Deployment, weth: Contract, usdc: Contract):
    """User buys WETH on Uniswap v2 using mock USDC."""

    # Create the trading pair and add initial liquidity
    deploy_trading_pair(
        web3,
        deployer,
        uniswap_v2,
        weth,
        usdc,
        10 * 10 ** 18,  # 10 ETH liquidity
        17_000 * 10 ** 18,  # 17000 USDC liquidity
    )

    router = uniswap_v2.router

    # Give user_1 500 dollars to buy ETH and approve it on the router
    usdc_amount_to_pay = 500 * 10 ** 18
    usdc.functions.transfer(fund_owner, usdc_amount_to_pay).transact({"from": deployer})
    usdc.functions.approve(router.address, usdc_amount_to_pay).transact({"from": fund_owner})

    # Perform a swap USDC->WETH
    path = [usdc.address, weth.address]  # Path tell how the swap is routed
    # https://docs.uniswap.org/protocol/V2/reference/smart-contracts/router-02#swapexacttokensfortokens
    router.functions.swapExactTokensForTokens(
        usdc_amount_to_pay,
        0,
        path,
        fund_owner,
        FOREVER_DEADLINE,
    ).transact({
        "from": fund_owner
    })

    # Check the user_1 received ~0.284 ethers
    assert weth.functions.balanceOf(fund_owner).call() / 1e18 == pytest.approx(0.28488156127668085)

See the full example.

Uniswap v2 price estimation example

# Create the trading pair and add initial liquidity
deploy_trading_pair(
    web3,
    deployer,
    uniswap_v2,
    weth,
    usdc,
    1_000 * 10**18,  # 1000 ETH liquidity
    1_700_000 * 10**18,  # 1.7M USDC liquidity
)

# Estimate the price of buying 1 ETH
usdc_per_eth = estimate_buy_price_decimals(
    uniswap_v2,
    weth.address,
    usdc.address,
    Decimal(1.0),
)
assert usdc_per_eth == pytest.approx(Decimal(1706.82216820632059904))

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

History

Originally created for Trading Strategy. Originally the package was known as eth-hentai.

License

MIT

Metadata

Release files for web3-ethereum-defi 0.18.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for web3-ethereum-defi 0.18.4
File Size Uploaded Provenance Actions
web3_ethereum_defi-0.18.4.tar.gz 7.7 MB Without provenance Details for web3_ethereum_defi-0.18.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for web3-ethereum-defi 0.18.4
File Interpreter ABI Platform Actions
web3_ethereum_defi-0.18.4-py3-none-any.whl Python 3 none any Details for web3_ethereum_defi-0.18.4-py3-none-any.whl

Total release size: 16.7 MB

Release files / web3_ethereum_defi-0.18.4.tar.gz

Download URL web3_ethereum_defi-0.18.4.tar.gz
Size 7.7 MB
Tags Source
SHA-256 checksum
How to use checksums
2660b9bb47bd2e62781d1905303ffbe713b28704dcc9d73c089b9ba8de790946
BLAKE2b-256 checksum
How to use checksums
171802547617530e1f3b8d87281880e30ae1289524004ef7606ef102e848c3e7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.4.2 CPython/3.10.6 Darwin/22.3.0

Release files / web3_ethereum_defi-0.18.4-py3-none-any.whl

Download URL web3_ethereum_defi-0.18.4-py3-none-any.whl
Size 8.9 MB
Tags Python 3
SHA-256 checksum
How to use checksums
8ed2f56f26be3db8a79960d5773696c6577dcec622b478254240ee8395a4eb85
BLAKE2b-256 checksum
How to use checksums
16a0cdc10eba7e3d670b81abffe5f804cd99d59b0b7b2e48ef8aabe43b64b6a6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.4.2 CPython/3.10.6 Darwin/22.3.0

Security for web3-ethereum-defi 0.18.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.18.4 This release

2 release files No provenance

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