Skip to main content

DeFi integration library for smart contracts, DeFi trading (Uniswap, PancakeSwap), Ethereum JSON-RPC, EVM transactions and automated test suites.

Project description

PyPI version

Automated test suite

Documentation Status

Web3-Ethereum-Defi

This project contains common Ethereum smart contracts and utilities, for trading, wallets, automated test suites and backend integrations for EVM based blockchains.

Pepe chooses Web3-Ethereum-DeFi and Python

Pepe chooses web3-ethereum-defi and Python.

Features

Features include

Unlike ApeWorX or Brownie, which are smart contracte development frameworks, web3-ethereum-defi is a library. It is designed to be included in any other Python application and you can only use bits of its that you need. There are no expectations on configuration files or folder structure.

[Read the full API documentation](High-quality API documentation](https://web3-ethereum-defi.readthedocs.io/)). For code examples please see below.

Prerequisites

To use this package you need to

Install

# Install with Jupyter notebook and data access libraries
pip install "web3-ethereum-defi[data]"
# Poetry version
poetry add -E data web3-ethereum-defi

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, user_1: str, user_2: str):
    """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(user_1, 10 * 10**18).transact({"from": deployer})
    assert token.functions.balanceOf(user_1).call() == 10 * 10**18

    # Move 10 tokens from deployer to user1
    token.functions.transfer(user_2, 6 * 10**18).transact({"from": user_1})
    assert token.functions.balanceOf(user_1).call() == 4 * 10**18
    assert token.functions.balanceOf(user_2).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, user_1: str, 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(user_1, usdc_amount_to_pay).transact({"from": deployer})
    usdc.functions.approve(router.address, usdc_amount_to_pay).transact({"from": user_1})

    # 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,
        user_1,
        FOREVER_DEADLINE,
    ).transact({
        "from": user_1
    })

    # Check the user_1 received ~0.284 ethers
    assert weth.functions.balanceOf(user_1).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

Notes

Currently there is no Brownie support. To support Brownie, one would need to figure out how to import an existing Hardhat based project (Sushiswap) to Brownie project format.

History

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

License

MIT

Project details


Release history Release notifications | RSS feed

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.13.5.tar.gz (808.8 kB 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.13.5-py3-none-any.whl (1.0 MB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: web3_ethereum_defi-0.13.5.tar.gz
  • Upload date:
  • Size: 808.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.1 CPython/3.10.6 Darwin/22.1.0

File hashes

Hashes for web3_ethereum_defi-0.13.5.tar.gz
Algorithm Hash digest
SHA256 00c52cfce80f93b0a2a22ea963240b42ada46e9963af744ab7090eee4af912a8
MD5 0b7ec3ba6f692348c167f3ab739f64e5
BLAKE2b-256 666099d60efbdcd692e1d3938f90067cc0779401609f836caa22e47f6cf3ea31

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for web3_ethereum_defi-0.13.5-py3-none-any.whl
Algorithm Hash digest
SHA256 1e796afc29cc8a325396f8d6b9f9e02ddb3828ff3d8afb8ef305e37c364995f2
MD5 d5f9d8b9ee6856a6bada9e26e06df82a
BLAKE2b-256 848c3d2e13c7d17ae6d7d00d5af2edbfd490aefd3bf1453d617760eaedcda8d9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page