Web3 Ethereum DeFi toolkit for smart contracts, Uniswap and PancakeSwap trades, Ethereum JSON-RPC utilities, wallets and automated test suites.

Overview

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

Precompiled ABI file distribution

The project provides a precompiled smart contract bundle, including ABI files, full source and debug maps, to make deploying test instances trivial.

This package primarly supports Python, Web3.p3 and Brownie developers. For other programming languages and frameworks, you can find precompiled Solidity smart contracts in abi folder.

These files are good to go with any framework:

  • Web3.js
  • Ethers.js
  • Hardhat
  • Truffle
  • Web3j

Each JSON file has abi and bytecode keys you need to deploy a contract.

Just download and embed in your project. The compiled source code files are mixture of MIT and GPL v2 license.

Python usage

The Python support is available as web3-ethereum-defi Python package.

The package depends only on web3.py and not others, like Brownie. It grabs popular ABI files with their bytecode and compilation artifacts so that the contracts are easily deployable on any Ethereum tester interface. No Ganache is needed and everything can be executed on faster eth-tester enginer.

Unlike Brownie, which is a framework, 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

ERC-20 token example

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

See full example.

How to use the library in your Python project

Add web3-ethereum-defi as a development dependency:

Using Poetry:

poetry add -D web3-ethereum-defi

Development and contributing

Read development instructions.

Version history

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

Owner
Trading Strategy
Algorithmic trading for decentralised markets
Trading Strategy
Pdisk Link Converter Telegram Bot, Convert link in a single click

Pdisk Converter Bot Make short link by using Pdisk API key Installation The Easy Way Required Variables BOT_TOKEN: Create a bot using @BotFather, and

Ayush Kumar Jaiswal 6 Jul 28, 2022
Telegram bot for making Heroku app.json by @AbirHasan2005

Heroku-app.json A Telegram bot for making Heroku app.json by @AbirHasan2005. Demo Bot Host Bot Deploy to Heroku Click Below Button to Deploy to Heroku

Abir Hasan 46 Nov 13, 2022
C Y B Ξ R UserBot is a project that simplifies the use of Telegram.

C Y B Ξ R USΞRBOT 🇦🇿 C Y B Ξ R UserBot is a project that simplifies the use of Telegram. All rights reserved. Automatic Setup Android: open Termux p

FVREED 4 Dec 07, 2022
An async python wrapper to interact with the Steam API and its CMs

steam.py A modern, easy to use, and async ready package to interact with the Steam API. Heavily inspired by discord.py and borrowing functionality fro

James Hilton-Balfe 90 Dec 15, 2022
Automatic login to Microsoft Teams conferences

Automatic login to Microsoft Teams conferences

Xhos 1 Jan 24, 2022
Herramienta para transferir eventos de Sucuri WAF hacia Azure Data Tables.

Transfiere eventos de Sucuri hacia Azure Data Tables Script para transferir eventos del Sucuri Web Application Firewall (WAF) hacia Azure Data Tables,

CSIRT-RD 1 Dec 22, 2021
A Telegram Video Watermark Adder Bot in Pyrogram by @AbirHasan2005

Watermark-Bot A Telegram Video Watermark Adder Bot by @AbirHasan2005 Features: Save Custom Watermark Image. Auto Resize Watermark According to Video q

Abir Hasan 95 Nov 20, 2022
💻 A fully functional local AWS cloud stack. Develop and test your cloud & Serverless apps offline!

LocalStack - A fully functional local AWS cloud stack LocalStack provides an easy-to-use test/mocking framework for developing Cloud applications. Cur

LocalStack 45.3k Jan 02, 2023
Portal Backend for Yuta management

Portal Backend for Yuta management Prerequisites Python 3.10 or above. pip, pdm installed. Quickstart Install the required packages: pdm install Runn

Loc Mai 1 Dec 20, 2021
Braintree Python library

Braintree Python library The Braintree Python library provides integration access to the Braintree Gateway. TLS 1.2 required The Payment Card Industry

Braintree 230 Dec 18, 2022
Module to use some statistics from Spotify API

statify Module to use some statistics from Spotify API To use it you have to import the functions into your own project. You have also to authenticate

Miguel Cózar 2 Jun 02, 2022
Repository for the Nexus Client software.

LinkScope Client Description This is the repository for the LinkScope Client Online Investigation software. LinkScope allows you to perform online inv

107 Dec 30, 2022
A webhook API for Discord.

Webhook API A webhook API for Discord. Requirements requests Usage

1 Feb 08, 2022
Built for streamlining development of Google Assistant Actions

Apprentice Apprentice is a framework built for developing Google Actions via Dialogflow and Google Cloud (serverless) Functions. Includes: plug-and-pl

Andrew Graham-Yooll 9 May 16, 2019
Updater for PGCG (Paradox Game Converters Group) converters written in Python.

Updater Updater for PGCG (Paradox Game Converters Group) converters written in Python. Needs to be put inside an "Updater" directory in the root conve

Paradox Game Converters 2 Jan 10, 2022
RichWatch is wrapper around AWS Cloud Watch to display beautiful logs with help of Python library Rich.

RichWatch is TUI (Textual User Interface) for AWS Cloud Watch. It formats and pretty prints Cloud Watch's logs so they are much more readable. Because

21 Jul 25, 2022
Slam Mirror Bot is a multipurpose Telegram Bot written in Python for mirroring files on the Internet to our beloved Google Drive.

Slam Mirror Bot is a multipurpose Telegram Bot written in Python for mirroring files on the Internet to our beloved Google Drive.

Abinash939 1 Oct 10, 2021
Linkvertise-Bypass - Bypass Linkvertise advertisement

Linkvertise-Bypass Bypass Linkvertise advertisement 📕 instructions Copy And Pas

Flex Tools 4 Jun 10, 2022
Centralized whale instance using github actions, sourcing metadata from bigquery-public-data.

Whale Demo Instance: Bigquery Public Data This is a fully-functioning demo instance of the whale data catalog, actively scraping data from Bigquery's

Hyperquery 17 Dec 14, 2022
domhttpx is a google search engine dorker with HTTP toolkit built with python, can make it easier for you to find many URLs/IPs at once with fast time.

domhttpx is a google search engine dorker with HTTP toolkit built with python, can make it easier for you to find many URLs/IPs at once with fast time

Naufal Ardhani 59 Dec 04, 2022