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
Discord group chat leaver.

Discord group chat leaver I know many people who have fallen victim to these weird group chat spammers including me. I made this script to help those

cliphd 3 Feb 27, 2022
Simple Craigslist wrapper

python-craigslist A simple Craigslist wrapper. License: MIT-Zero. Disclaimer I don't work for or have any affiliation with Craigslist. This module was

Julio M. Alegria 370 Dec 22, 2022
An Unofficial TikTok API Wrapper In Python

This is an unofficial api wrapper for TikTok.com in python. With this api you are able to call most trending and fetch specific user information as well as much more.

David Teather 2.9k Jan 08, 2023
Simple discord token generator good for memberboosting your server! Uses Hcaptcha bypass

discord-tokens-generator INFO This is a Simple Discord Token Generator which creates unverified discord accounts These accounts are good for member bo

Avenger 41 Dec 20, 2022
Get-Phone-Number-Details-using-Python - To get the details of any number, we can use an amazing Python module known as phonenumbers.

Get-Phone-Number-Details-using-Python To get the details of any number, we can use an amazing Python module known as phonenumbers. We can use the amaz

Coding Taggers 1 Jan 01, 2022
ServiceX DID Finder Girder

ServiceX_DID_Finder_Girder Access datasets for ServiceX from yt Hub Finding datasets This DID finder is designed to take a collection id (https://gird

1 Dec 07, 2021
Sie_banxico - A python class for the Economic Information System (SIE) API of Banco de México

sie_banxico A python class for the Economic Information System (SIE) API of Banco de México. Args: token (str): A query token from Banco de México id_

Dillan 2 Apr 07, 2022
A Discord token grabber written in Python3, with awesome obfuscation and anti-debug protection.

☣️ Plague ☣️ Plague is a Discord token grabber written in Python3, obfuscated with Kramer, protected from traffic analysers with Scarecrow and using t

Billy 125 Dec 20, 2022
The scope of this project will be to build a data ware house on Google Cloud Platform that will help answer common business questions as well as powering dashboards

The scope of this project will be to build a data ware house on Google Cloud Platform that will help answer common business questions as well as powering dashboards.

Shweta_kumawat 2 Jan 20, 2022
Hostapd-mac-monitor - Setup a hostapd AP to conntrol the connections of specific MACs

A brief explanation This script provides way to setup a monitoring service of sp

2 Feb 03, 2022
Anime Streams Scrapper for Telegram Publicly Available for everyone to use

AniRocks Project Structure: ╭─ bot ├──── plugins: directory stored all the plugins ├──── utils: a directory of Utilities to help bot Client to create

ポキ 11 Oct 28, 2022
Discord bot for playing Werewolf game on League of Legends.

LoLWolf LoL人狼をプレイするときのDiscord用botです。 (Discord bot for playing Werewolf game on League of Legends.) 以下のボタンを押してbotをあなたのDiscordに招待することで誰でも簡単に使用することができます。

Hatsuka 4 Oct 18, 2021
Box SDK for Python

Box Python SDK Installing Getting Started Authorization Server-to-Server Auth with JWT Traditional 3-legged OAuth2 Other Auth Options Usage Documentat

Box 371 Dec 29, 2022
Simple script to extract useful informations from the combo BloodHound + Neo4j

bloodhound-quickwin Simple script to extract useful informations from the combo BloodHound + Neo4j. Can help to choose a target. Prerequisites python3

140 Dec 21, 2022
Best badge generator API to count visitors of your Repository / Account 🥇

github visitors badge A badge generator service to count visitors of your markdown file. Hello every one! In this post, I will tell you the story of m

Sᴇɴᴜ Gᴀᴍᴇʀ Bᴏʏ 〽 3 Dec 11, 2021
Powerful and Async API for AnimeWorld.tv 🚀

Powerful and Async API for AnimeWorld.tv 🚀

1 Nov 13, 2021
use python script to fix vmp dump api in ida

FixVmpDump use python script to fix vmp dump api in ida. support x86 and x64. details in my blog: https://blog.csdn.net/yan_star/article/details/11279

97 Nov 02, 2022
DEPRECATED - Official Python Client for the Discogs API

⚠️ DEPRECATED This repository is no longer maintained. You can still use a REST client like Requests or other third-party Python library to access the

Discogs 483 Dec 31, 2022
摩尔庄园手游脚本

摩尔庄园 BlueStacks 脚本 手游上线,情怀再起,但面对游戏中枯燥无味的每日任务和资源采集,你是否觉得肝疼呢? 本项目通过生成 BlueStacks 模拟器的宏脚本,帮助玩家护肝。 使用脚本请阅读 使用方式 和对应的 功能及说明 联系 Telegram 频道 @mole61 Telegram

WH-2099 43 Dec 16, 2022
A Advanced Powerful, Smart And Intelligent Group Management Bot With New And Powerful Features

Vegeta Robot A Advanced Powerful, Smart And Intelligent Group Management Bot With New And Powerful Features ... Written with Pyrogram and Telethon...

⚡ CT_PRO ⚡ 9 Nov 16, 2022