Anton
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Mainnet fork testing guidelines for DeFi using Brownie For a DeFi system, in many cases unit testing is insufficient, since mainnet contracts can behave differently from the testing setup of the platform. Brownie allows to easily configure a testing environment that will use real mainnet contracts and allows to test the behavior of the system in the conditions closest to real. [Brownie documentation](https://eth-brownie.readthedocs.io/en/stable/toctree.html) provides the most complete and up-to-date usage information. These guidelines are meant to be used as addition to the docs, as a shortcut on a way to better testing. Good tutorial from Ben Hauser, that covers the power of brownie: https://iamdefinitelyahuman.medium.com/ethereum-mainnet-testing-with-python-and-brownie-82a61dee0222 Curve video tutorials for brownie that covers a lot of aspects: https://github.com/curvefi/brownie-tutorial ## Installing brownie https://eth-brownie.readthedocs.io/en/stable/install.html Brownie uses `ganache-cli`, and it is recommended to use the most recent version from https://github.com/trufflesuite/ganache. Npm ganache-cli package is outdated and does not support certain things. ``` npm install ganache@7.0.0-alpha.1 --global ``` ## Configuring mainnet fork With default configuration, brownie is configured to be used with Infura service. Infura project ID needs to be set first: https://infura.io/register ``` export WEB3_INFURA_PROJECT_ID=YourProjectID ``` https://eth-brownie.readthedocs.io/en/stable/network-management.html#using-a-forked-development-network ### Using other node provider Forking from Infura can be very slow. If you are using this mode extensively, it may be useful to run your own Geth node or other provider. Mainnet provider API url can be edited: * `brownie networks export networks` * Edit the `networks.yaml` file with relevant mainnet API url. * `brownie networks import networks.yaml True` to apply the config ## Starting with mainnet-fork Providing a flag `--network mainnet-fork` will launch brownie with `brownie <command> --network mainnet-fork` ## Compiling project Official docs: ``` https://eth-brownie.readthedocs.io/en/stable/compile.html ``` Brownie has new hardhat support feature: ``` https://eth-brownie.readthedocs.io/en/stable/install.html?highlight=hardhat#using-brownie-with-hardhat ``` Alternative is adjusting the configuration file of the brownie project. Example `brownie-config.yaml`: ``` autofetch_sources: true compiler: solc: version: 0.7.6 remappings: - "@openzeppelin=OpenZeppelin/openzeppelin-contracts@3.2.1-solc-0.7" - "@opengsn=opengsn/gsn@2.2.2/packages" dependencies: - OpenZeppelin/openzeppelin-contracts@3.2.1-solc-0.7 - opengsn/gsn@2.2.2 ``` Command ` brownie compile` compiles all the contracts in the `contracts/` folder of the brownie project. ## Writing tests [Brownie docs "Writing Unit Tests" page](https://eth-brownie.readthedocs.io/en/stable/tests-pytest-intro.html) contain the most complete source of information for test writing. Reading it is essential for testing. Fixtures are suggested to be used for the fixed external contracts that need to be used by multiple unit tests, since the tests runtime can be quite long. Thus reusing the contracts and definitions via use of fixtures can safe a number of queries to ganache and Etherscan. ### Fetching existing contracts from Etherscan Brownie supports integration with Ethersacn API and in the tests it is possible to query exact token via it: ``` python @pytest.fixture def susd(): susd_addr = "0x57ab1ec28d129707052df4df418d58a2d46d5f51" yield Contract.from_explorer(susd_addr) ``` Brownie will then try to fetch, compile and use the ABI of the code automatically. The storage of the contract on forked mainnet will be used. The ABI is only needed to tell brownie, what functions the contract has and how the calldata should be treated. The rate of Etherscan API queries is limited without API key. Registering and running `export ETHERSCAN_TOKEN=<token>` will allow 5 queries per second, which should be enough for tests. Alternatively, any address can be associated with certain compiled contract: ``` python @pytest.fixture def usdt(): usdt_addr = "0xdac17f958d2ee523a2206206994597c13d831ec7" yield ERC20.at(usdt_addr) ``` This is a simpler and more practical approach for most of the tokens. Especially since USDT is not compiled automatically by brownie from Etherscan due to a solc version problem. Using real tokens is essential for good testing. ## Getting funds ```python= from brownie import accounts ``` By default a ganache fork has 10 accounts, associated with certain mnemonics. These accounts have 100 Ether by default, and since a Mainnet fork is used, these funds can be exchanged into needed assets. [Example in the end](https://iamdefinitelyahuman.medium.com/ethereum-mainnet-testing-with-python-and-brownie-82a61dee0222) In dev environment (mainnet-fork), it is also possible to send transactions without having the private key for them. ``` acc = accounts.at('0x79B2f0CbED2a565C925A8b35f2B402710564F8a2', force=True) ``` ## Testing scenarios Since the system is intended to work with many different tokens, scenarios should involve them, e.g., Tokens with missing return values(USDT), Tokens with Low Decimals (USDC has 6) or High Decimals (YAM-V2 has 24). There is a [repo](https://github.com/d-xo/weird-erc20) that has some good examples. Testing scenarios should include all possible actions, that a user can perform, e.g. deposits, withdrawals, swaps, etc. The contracts that are meant to be upgradeable need to be deployed as proxies. The upgradeability needs to be tested as well as `Initialize` specific logic on the smart contracts. Safe Math can also cause problems with unexpected underflows. It is suggested to test the strategies with big number of tokens values inside as well as with big total value amounts. Minting a lot of tokens can be possible with "force" miner account for existing coins. https://eth-brownie.readthedocs.io/en/stable/core-chain.html#time-travel Using the time-travel functionality, the manager upgradeable parameters can be tested. ## Chain Snapshots and Undo/Redo https://eth-brownie.readthedocs.io/en/stable/core-chain.html#snapshots For testing, sometimes the effect of previous tests needs to be undone, before new cases. This can be done with snapshots and undoing/redoing transactions.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully