• Stars
    star
    168
  • Rank 225,507 (Top 5 %)
  • Language
    Python
  • License
    GNU Affero Genera...
  • Created about 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Yearn Strategy Brownie Mix

What you'll find here

  • Basic Solidity Smart Contract for creating your own Yearn Strategy (contracts/Strategy.sol)

  • Interfaces for some of the most used DeFi protocols on ethereum mainnet. (interfaces/)

  • Sample test suite that runs on mainnet fork. (tests/)

This mix is configured for use with Ganache on a forked mainnet.

How does it work for the User

Let's say Alice holds 100 DAI and wants to start earning yield % on them.

For this Alice needs to DAI.approve(vault.address, 100).

Then Alice will call Vault.deposit(100).

Vault will then transfer 100 DAI from Alice to itself, and mint Alice the corresponding shares.

Alice can then redeem those shares using Vault.withdrawAll() for the corresponding DAI balance (exchanged at Vault.pricePerShare()).

Installation and Setup

  1. Install Brownie & Ganache, if you haven't already. Make sure that the version of Ganache that you install is compatible with Brownie. You can check Brownie's Ganache dependency here.

  2. Sign up for Infura and generate an API key. Store it in the WEB3_INFURA_PROJECT_ID environment variable.

export WEB3_INFURA_PROJECT_ID=YourProjectID
  1. Sign up for Etherscan and generate an API key. This is required for fetching source codes of the mainnet contracts we will be interacting with. Store the API key in the ETHERSCAN_TOKEN environment variable.
export ETHERSCAN_TOKEN=YourApiToken
  • Optional Use .env file
    1. Make a copy of .env.example
    2. Add the values for ETHERSCAN_TOKENΒ and WEB3_INFURA_PROJECT_ID NOTE: If you set up a global environment variable, that will take precedence
  1. Download the mix.
brownie bake yearn-strategy

Basic Use

To deploy the demo Yearn Strategy in a development environment:

  1. Open the Brownie console. This automatically launches Ganache on a forked mainnet.
$ brownie console
  1. Create variables for the Yearn Vault and Want Token addresses. These were obtained from the Yearn Registry. We load them from a different repository found in the brownie-config.yml under dependencies (yearn/[email protected]):
from brownie import project
yearnvaults = project.load(config["dependencies"][0]) #load the base vaults project to access the original Vault contract
Vault = yearnvaults.Vault
Token = yearnvaults.Token
vault = Vault.at("0xdA816459F1AB5631232FE5e97a05BBBb94970c95")
token = Token.at("0x6b175474e89094c44da98b954eedeac495271d0f")
gov = "ychad.eth"  # ENS for Yearn Governance Multisig

or you can get the contracts ABI from etherscan API, make sure you have exported your etherscan token.

from brownie import Contract
vault = Contract("0xdA816459F1AB5631232FE5e97a05BBBb94970c95")
token = Contract("0x6b175474e89094c44da98b954eedeac495271d0f")
gov = "ychad.eth"  # ENS for Yearn Governance Multisig
  1. Deploy the Strategy.sol contract.
>>> strategy = Strategy.deploy(vault, {"from": accounts[0]})
Transaction sent: 0xc8a35b3ecbbed196a344ed6b5c7ee6f50faf9b7eee836044d1c7ffe10093ef45
  Gas price: 0.0 gwei   Gas limit: 6721975
  Flashloan.constructor confirmed - Block: 9995378   Gas used: 796934 (11.86%)
  Flashloan deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87
  1. Approve the strategy for the Vault. We must do this because we only approved Strategies can pull funding from the Vault.
# 10% of the vault tokens will be allocated to the strategy

>>> vault.addStrategy(strategy, 1000, 0, 2 ** 256 - 1, 1_000, {"from": gov})
Transaction sent: 0xa70b90eb9a9899e8f6e709c53a436976315b4279c4b6797d0a293e169f94d5b4
  Gas price: 0.0 gwei   Gas limit: 6721975
  Transaction confirmed - Block: 9995379   Gas used: 21055 (0.31%)

If you are getting a revert error, it's most likley because the vault can't add more strategies, you can check the vault.debtRatio() the value should be under 10,000. You can try to lower one of the existing strategy debt ratio vault.updateStrategyDebtRatio("0x1676055fE954EE6fc388F9096210E5EbE0A9070c", 0, {"from": gov})

  1. Now we are ready to put our strategy into action!
>>> harvest_tx = strategy.harvest({"from": accounts[0]})  # perform as many time as desired...

Implementing Strategy Logic

contracts/Strategy.sol is where you implement your own logic for your strategy. In particular:

  • Create a descriptive name for your strategy via Strategy.name().
  • Invest your want tokens via Strategy.adjustPosition().
  • Take profits and report losses via Strategy.prepareReturn().
  • Unwind enough of your position to payback withdrawals via Strategy.liquidatePosition().
  • Unwind all of your positions via Strategy.exitPosition().
  • Fill in a way to estimate the total want tokens managed by the strategy via Strategy.estimatedTotalAssets().
  • Migrate all the positions managed by your strategy via Strategy.prepareMigration().
  • Make a list of all position tokens that should be protected against movements via Strategy.protectedTokens().

Testing

To run the tests:

brownie test

The example tests provided in this mix start by deploying and approving your Strategy.sol contract. This ensures that the loan executes succesfully without any custom logic. Once you have built your own logic, you should edit tests/test_flashloan.py and remove this initial funding logic.

See the Brownie documentation for more detailed information on testing your project.

Debugging Failed Transactions

Use the --interactive flag to open a console immediatly after each failing test:

brownie test --interactive

Within the console, transaction data is available in the history container:

>>> history
[<Transaction '0x50f41e2a3c3f44e5d57ae294a8f872f7b97de0cb79b2a4f43cf9f2b6bac61fb4'>,
 <Transaction '0xb05a87885790b579982983e7079d811c1e269b2c678d99ecb0a3a5104a666138'>]

Examine the TransactionReceipt for the failed test to determine what went wrong. For example, to view a traceback:

>>> tx = history[-1]
>>> tx.traceback()

To view a tree map of how the transaction executed:

>>> tx.call_trace()

See the Brownie documentation for more detailed information on debugging failed transactions.

Known issues

No access to archive state errors

If you are using Ganache to fork a network, then you may have issues with the blockchain archive state every 30 minutes. This is due to your node provider (i.e. Infura) only allowing free users access to 30 minutes of archive state. To solve this, upgrade to a paid plan, or simply restart your ganache instance and redploy your contracts.

Resources

More Repositories

1

yearn-vaults

Yearn Vault smart contracts
Python
522
star
2

yearn-protocol

Yearn smart contracts
Solidity
441
star
3

iearn-finance

Web repository
JavaScript
256
star
4

yearn-security

Security contacts and disclosure reports
195
star
5

yearn-finance

🏦 yearn v2 web interface
JavaScript
169
star
6

yearn-finance-v3

Yearn Finance Web App v3
TypeScript
125
star
7

tokenized-strategy

Contains the Contracts for the Yearn V3 Tokenized Strategy Implementation
Solidity
106
star
8

yearn-vaults-v3

Python
99
star
9

yearn-docs

Old Documentation gitbook for yearn. Replaced by https://github.com/yearn/yearn-devdocs
98
star
10

yearn-exporter

Realtime and historical Yearn metrics
Python
95
star
11

yearn-devdocs

yearn documentation
JavaScript
79
star
12

veYFI

Voting YFI
Python
75
star
13

vaults

Solidity
74
star
14

yearn-pm

72
star
15

itoken

yToken wrappers for automated investment strategy tokenization
JavaScript
72
star
16

yearn-vesting-escrow

token vesting escrow with cliff and clawback
Python
69
star
17

tokenized-strategy-foundry-mix

Create Yearn V3 "Tokenized Strategies" using Foundry
Solidity
63
star
18

tokenized-strategy-periphery

Solidity
60
star
19

yearn-starter-pack

Starter pack strategy for yearn vaults
Solidity
57
star
20

yearn-recycle

dai/usdc/usdt/tusd/ycrv ➝ yusd
Python
56
star
21

yearn-sdk

🦧 SDK for the yearn.finance platform. WIP
TypeScript
53
star
22

ygov-finance

Web repository for yfi staking and voting
JavaScript
50
star
23

ape-tax

TypeScript
46
star
24

YIPS

The Yearn Improvement Proposal repository
HTML
46
star
25

audit

Solidity
37
star
26

woofy

πŸ‘€ nothing to see here
Python
37
star
27

ycredit.finance

StableCreditProtocol, decentralized lending and AMM platform
Solidity
37
star
28

budget

yearn budget requests and audits
Python
36
star
29

hardhat-monorepo

TypeScript
31
star
30

ydaemon

Next gen API for Yearn
Go
29
star
31

yearn-watch-legacy

Yearn Watch is a tool that provides vault and strategies data for management
TypeScript
29
star
32

web-lib

Context and UI library for Yearn
TypeScript
27
star
33

yearn-meta

πŸ—„ Yearn metadata storage on IPFS (static)
JavaScript
26
star
34

yearn-audits

Collection of published audits
26
star
35

yoracle.link

TWAP based 24 hour oracle for on-chain insurance and lending
Solidity
25
star
36

crv.ape.tax

home for experimental vaults
Solidity
24
star
37

vault-periphery

Solidity
24
star
38

zap

Collection of automated on-chain investment strategies
JavaScript
24
star
39

apr-oracle

On-chain APR aggregator for dYdX, Fulcrum, Compound, and Aave
JavaScript
24
star
40

uniswap-roi

On-chain uniswap ROI pool calculations
JavaScript
23
star
41

yearn-api-archived

Collection of serverless API
JavaScript
23
star
42

yearn.fi

TypeScript
22
star
43

macarena-finance

Macarena finance is a simple UI for Yearn Finance, made to be forked!
TypeScript
21
star
44

ydata

Python
20
star
45

yearn-assets

Repo of yearn assets
Python
19
star
46

yearn-comms

Collection of communication, announcements, tweets, newsletters, and other articles about Yearn and a hosted blog for all translation contributors.
JavaScript
19
star
47

yearn-watch

Yearn Watch is a tool that provides vault and strategies data for management
TypeScript
18
star
48

yearn-subgraph

Subgraph for yearn finance: https://yearn.finance
TypeScript
18
star
49

yinsure-finance

JavaScript
18
star
50

ygenius-brain

Python
17
star
51

yearn-lens

Solidity
16
star
52

eth-allowlist

Solidity
16
star
53

yswap-finance

JavaScript
15
star
54

brownie-wrapper-mix

Python
14
star
55

snapshot-strategy

Python
14
star
56

seafood

Seafood
TypeScript
13
star
57

NFTreasury

NFTreasury is a simple yet powerful treasury management tool, powered by Yearn.
TypeScript
13
star
58

keep3r-jobs

Solidity
11
star
59

ygift

Solidity
10
star
60

yearn-treasury

Solidity
10
star
61

strategies-keep3r

Solidity
9
star
62

Yearn-ERC4626-Router

ERC4626 Router for Yearn V3 vaults.
Solidity
9
star
63

yearn-keeper

self-sustainable keeper bots for yearn vaults and strategies
Python
9
star
64

zaps

Repository for v2 Vaults Zaps
Solidity
9
star
65

web-template

Template for the next projects from Yearn.Finance
TypeScript
8
star
66

ygift-ui

TypeScript
8
star
67

yearn-marketing

This repository includes all marketing issues and workstreams
8
star
68

ycredit-finance

JavaScript
8
star
69

yETH

Vyper
7
star
70

yearn-vaults-descriptions

TypeScript
7
star
71

tokenized-strategy-ape-mix

Python
7
star
72

yPartners

Partners website
TypeScript
6
star
73

yearn-caching-api

πŸ• Lightweight Rest API shim for yearn's SDK
JavaScript
5
star
74

yuni.finance

JavaScript
5
star
75

yearn-allowlist

Python
5
star
76

yearn-token

Python
4
star
77

yearn-data

πŸ—„ Yearn live data storage on AWS (dynamic)
TypeScript
4
star
78

iliquidate-finance

JavaScript
4
star
79

ileverage-finance

JavaScript
4
star
80

yBuyback

TypeScript
4
star
81

yearn-multisig-actions

Template repository for Gnosis multisignature wallet automation with eth-brownie and GitHub Actions
Python
4
star
82

iborrow-finance

JavaScript
4
star
83

ygenius-webui

JavaScript
4
star
84

yearn-exporter-api

Python
3
star
85

ySync

TypeScript
3
star
86

yCRV

The best crv yields in defi. mic drop
TypeScript
3
star
87

yearn-workflows

Github actions workflows
Python
3
star
88

governance

JavaScript
3
star
89

tokenlist

2
star
90

JuicedVaults

Freshly squeezed and bursting with yield.
TypeScript
2
star
91

yearn-mainnet-fork

Python
2
star
92

api.yuni.finance

JavaScript
2
star
93

yearn-stb

Yearn Stake the Bridge Setup for Polygon CDK
Solidity
2
star
94

yETH-periphery

Vyper
2
star
95

risk-framework

Solidity
2
star
96

yswaps

TypeScript
2
star
97

yLSTeth

TypeScript
2
star
98

yearn-multisig-ci-scripts

Python
2
star
99

yearn-partner-tracker

Solidity
2
star
100

yearn-integration-hardhat

TypeScript
2
star