Mock smart contracts for writing Ethereum test suites

Overview

Automated test suite

Documentation Status

Mock smart contracts for writing Ethereum test suites

This package contains common Ethereum smart contracts to be used in automated test suites. This was created for Trading Strategy, but can be used for any other projects as well. As opposite to slower and messier mainnet forking test strategies, this project aims to explicit clean deployments and very fast test execution.

Smart contract support includes

  • ERC-20 token
  • SushiSwap: router, factory, pool (Uniswap v2, PancakeSwape, QuickSwap, Trader Joe and others are 99% Sushiswap compatible)
  • High-quality API documentation
  • Full type hinting support for optimal developer experience
  • (More integrations to come)

Table of contents

Precompiled ABI file distribution

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

[Read the full API documnetation](High-quality API documentation). 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:

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">
import pytest
from web3 import Web3, EthereumTesterProvider

from smart_contracts_for_testing.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 swap example

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)">
import pytest
from web3 import Web3
from web3.contract import Contract

from smart_contracts_for_testing.uniswap_v2 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.

How to use the library in your Python project

Add smart_contract_test_fixtures as a development dependency:

Using Poetry:

poetry add -D smart_contract_test_fixtures

Development

This step will extract compiled smart contract from Sushiswap repository.

Requires

  • Node v14
  • npx
  • yarn
  • GNU Make
  • Unix shell

Make

To build the ABI distribution:

git submodule update --recursive --init
make all

See SushiSwap continuous integration files for more information.

Version history

See change log.

Discord

Join Discord for any questions.

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.

License

MIT

Owner
Trading Strategy
Algorithmic trading for decentralised markets
Trading Strategy
WIP SAT benchmarking tooling, written with only my personal use in mind.

SAT Benchmarking Some early work in progress tooling for running benchmarks and keeping track of the results when working on SAT solvers and related t

Jannis Harder 1 Dec 26, 2021
✅ Python web automation and testing. 🚀 Fast, easy, reliable. 💠

Build fast, reliable, end-to-end tests. SeleniumBase is a Python framework for web automation, end-to-end testing, and more. Tests are run with "pytes

SeleniumBase 3k Jan 04, 2023
tidevice can be used to communicate with iPhone device

tidevice can be used to communicate with iPhone device

Alibaba 1.8k Jan 08, 2023
Compiles python selenium script to be a Window's executable

Problem Statement Setting up a Python project can be frustrating for non-developers. From downloading the right version of python, setting up virtual

Jerry Ng 8 Jan 09, 2023
Find index entries in $INDEX_ALLOCATION attributes

INDXRipper Find index entries in $INDEX_ALLOCATION attributes Timeline created using mactime.pl on the combined output of INDXRipper and fls. See: sle

32 Nov 05, 2022
masscan + nmap 快速端口存活检测和服务识别

masnmap masscan + nmap 快速端口存活检测和服务识别。 思路很简单,将masscan在端口探测的高速和nmap服务探测的准确性结合起来,达到一种相对比较理想的效果。 先使用masscan以较高速率对ip存活端口进行探测,再以多进程的方式,使用nmap对开放的端口进行服务探测。 安

starnightcyber 75 Dec 19, 2022
Scraping Bot for the Covid19 vaccination website of the Canton of Zurich, Switzerland.

Hi 👋 , I'm David A passionate developer from France. 🌱 I’m currently learning Kotlin, ReactJS and Kubernetes 👨‍💻 All of my projects are available

1 Nov 14, 2021
User-interest mock backend server implemnted using flask restful, and SQLAlchemy ORM confiugred with sqlite

Flask_Restful_SQLAlchemy_server User-interest mock backend server implemnted using flask restful, and SQLAlchemy ORM confiugred with sqlite. Backend b

Austin Weigel 1 Nov 17, 2022
A Demo of Feishu automation testing framework

FeishuAutoTestDemo This is a automation testing framework which use Feishu as an example. Execute runner.py to run. Technology Web UI Test pytest + se

2 Aug 19, 2022
It's a simple script to generate a mush on code forces, the script will accept the public problem urls only or polygon problems.

Codeforces-Sheet-Generator It's a simple script to generate a mushup on code forces, the script will accept the public problem urls only or polygon pr

Ahmed Hossam 10 Aug 02, 2022
Plugin for generating HTML reports for pytest results

pytest-html pytest-html is a plugin for pytest that generates a HTML report for test results. Resources Documentation Release Notes Issue Tracker Code

pytest-dev 548 Dec 28, 2022
a plugin for py.test that changes the default look and feel of py.test (e.g. progressbar, show tests that fail instantly)

pytest-sugar pytest-sugar is a plugin for pytest that shows failures and errors instantly and shows a progress bar. Requirements You will need the fol

Teemu 963 Dec 28, 2022
Penetration testing

Penetration testing

3 Jan 11, 2022
Bayesian A/B testing

bayesian_testing is a small package for a quick evaluation of A/B (or A/B/C/...) tests using Bayesian approach.

Matus Baniar 35 Dec 15, 2022
CNE-OVS-SIT - OVS System Integration Test Suite

CNE-OVS-SIT - OVS System Integration Test Suite Introduction User guide Discussion Introduction CNE-OVS-SIT is a test suite for OVS end-to-end functio

4 Jan 09, 2022
Coverage plugin for pytest.

Overview docs tests package This plugin produces coverage reports. Compared to just using coverage run this plugin does some extras: Subprocess suppor

pytest-dev 1.4k Dec 29, 2022
Auto Click by pyautogui and excel operations.

Auto Click by pyautogui and excel operations.

Janney 2 Dec 21, 2021
pywinauto is a set of python modules to automate the Microsoft Windows GUI

pywinauto is a set of python modules to automate the Microsoft Windows GUI. At its simplest it allows you to send mouse and keyboard actions to windows dialogs and controls, but it has support for mo

3.8k Jan 06, 2023
pytest_pyramid provides basic fixtures for testing pyramid applications with pytest test suite

pytest_pyramid pytest_pyramid provides basic fixtures for testing pyramid applications with pytest test suite. By default, pytest_pyramid will create

Grzegorz Śliwiński 12 Dec 04, 2022
GitHub action for AppSweep Mobile Application Security Testing

GitHub action for AppSweep can be used to continuously integrate app scanning using AppSweep into your Android app build process

Guardsquare 14 Oct 06, 2022