How to Leverage Farm on Yearn with Gearbox

stfibonacci
7 min readMay 4, 2022

Note: This article is for learning purposes only and is not financial advice.

This article consists of two parts. In the first part, I will describe how to use Gearbox protocol to leverage farm on Yearn Finance. In the second part, I will try to explain how to apply this strategy by writing a simple smart contract. If you are familiar with Gearbox protocol, you can skip the first part and go directly to the second part to read about smart contract integration with Gearbox Protocol and Yearn Finance.

PART 1

Gearbox is a leverage protocol on the Ethereum blockchain. It lets users take leverage and use it with other Defi protocols such as Yearn, Uniswap, and Curve. Users can open a credit account from Gearbox, deposit assets as collateral, and borrow the same asset from the protocol. Gearbox will deposit these borrowed assets to the users' credit account and then let them use the credit account balance (user’s collateral + borrowed amount) to use on other Defi protocols. Users will have the control to use these assets on approved protocols like Yearn but won’t have the custody of these assets to transfer to their wallets.

For example, Alice is a yield farmer and loves to farm on Yearn Finance. Alice has 10K DAI in her account, and she deposits into Yearn vault and gets her 5% APY.

Bob is also a yield farmer, but he is a degen who likes to live on the edge. He wants to farm on Yearn, but he thinks 10K is insufficient. He opens a credit account from Gearbox with 4x leverage and deposits 10K DAI. Gearbox deposits 30K to this credit account. Bob now has a credit account with 40K DAI and deposits this amount to Yearn vault and gets his 5% APY.

As the above example shows, each has 10K DAI, but Bob is farming on Yearn with 40K.

Defi lending protocols like AAVE or Compound let borrowers have to supply some assets as collateral to borrow desired assets and let them have custody of these borrowed assets. Users can transfer these assets wherever they want and even to a traditional bank to buy a car. Still, since Defi users don’t have credit scores as they do in traditional finance, Defi protocols will require the borrowers to over-collateralize the loan, which means the value of the collateral must be worth more than the value of the borrowed assets. Over-Collateralization protects Defi lending protocols from default risk. For example, a user can supply ETH and borrow DAI and use that DAI to buy ETH or another crypto but the value of supplied ETH must be worth more than the value of borrowed DAI. Borrowers can calculate their maximum borrowing power with Loan-to-Value(LTV) ratio.

Higher LTV means higher risk. If the LTV ratio is higher than the Liquidation Threshold, in other words, the collateral value drops below the threshold; liquidators will liquidate the user to repay the loan. Part of the loan will be sold on the market along with the liquidation fee to reach the required collateral value. This is called Liquidation. Each asset has a different LTV ratio based on its risk. Ethereum LTV is 75%, and Liquidation Threshold is 80%.

For example, Alice supplies 10 ETH to AAVE as collateral, and the current price of ETH is $3000. Alice’s 10 ETH is worth $30K, so she can borrow up to $22500 since ETH’s LTV is 75%. Alice would like to play it safe, so she borrows 15000 DAI, and this amount makes the LTV 50%.

Bob also supplies 10 ETH($30K) to AAVE. As we remember from the previous example, Bob is a degen trader, he borrows $22500(max amount!), and the LTV is 75%. He wakes up the following day and checks the price of ETH. It is $2500! This drop makes new LTV 90% which is higher than the Liquidation Threshold(80%).In this situation, Bob will be liquidated.

One of the main differences between Defi lending protocols and Gearbox is users will have custody of the borrowed assets when they borrow from these lending protocols, but they can not borrow more than their collateral value. With Gearbox, Users won’t have the custody of the borrowed assets, BUT they will be able to borrow up to 4X(up to 12X with GearboxV2) more assets than their collateral value.

Gearbox uses a risk model called Health Factor, and a low health factor means higher risk. If the user’s health factor is less than 1 (Liquidation Threshold), the open position will be liquidated.

From the previous example, Bob opens a credit account from Gearbox with 4X leverage and deposits initial collateral of 10K DAI. Gearbox deposits 30K to this credit account. Bob’s total borrowed amount is 30K, and the total value of the credit account is 40K.

Borrowed Amount = 30K

Total Value = 40K

Threshold Weighted Value = 40K * LT

Credit accounts health factor = (40K * LT) / (30K + accrued interest)

For simplicity’s sake Liquidation Threshold (LT) is 95%, and accrued interest is 0.

In this situation, Bob’s health factor is 1.26. If he wants to improve his credit account health, he can add more collateral or close his credit account and open it with lower leverage. Opening a 3x leverage credit account with given parameters makes the health factor 1.42.

Gearbox allows you to take leverage and use it with many different strategies. New protocols and coins will be added to the allowed list. If you want to long ETH, you can open a 3x USDC credit account and buy ETH with the borrowed USDC. You can have more complex strategies by opening 4x BTC credit accounts, selling borrowed BTC for DAI on Uniswap, and farming those funds on Yearn Finance. Gearbox integration with more Defi protocols in the future will open doors to many complex strategies.

PART 2

One of the best ways to learn something is by explaining that to other people. I am a degen Defi trader and learning how to write smart contracts for my daily simple Defi strategies. After describing how Gearbox works, I will try to explain how to write a smart contract to integrate with Gearbox and Yearn.

In this example, we will apply Bob’s strategy. First, we will open a 3x credit account with Gearbox, and then we will farm on Yearn Finance.

I will use the new ERC4626 Tokenized Vault Standard for this contract. If you want to learn more, you can check it here:

https://eips.ethereum.org/EIPS/eip-4626

These are Ethereum mainnet addresses for deployment:

DAI address = “0x6b175474e89094c44da98b954eedeac495271d0f”Gearbox DAI credit manager address= “0x777e23a2acb2fcbb35f6ccf98272d03c722ba6eb”Gearbox yDAI adapter address = “0x403E98b110a4DC89da963394dC8518b5f0E2D5fB”leverage = “200”

“200” leverage will get us two times the amount we deposited into our credit account from Gearbox. If we deposit 100K DAI, we will borrow 200K from Gearbox. Our total balance of credit account will be 300k(3x leverage).

1- Interaction with CreditManager Contract :

to get Credit Filter address :

creditFilter()

to open a credit account :

openCreditAccount(uint256 amount, address onBehalfOf, uint256 leverageFactor, uint256 referralCode);

to add more collateral :

addCollateral( address indexed onBehalfOf, address indexed token, uint256 value);

to get credit account address:

/// will revert if borrower doesn't have a credit account getCreditAccountOrRevert(address borrower);/// will return address(0) if borrower doesn't have a credit account creditAccounts(address borrower);

to get repayment amount:

function calcRepayAmount(address borrower, bool isLiquidated)

to repay credit account :

repayCreditAccount(address to);

to check if borrower has credit account :

//will return bool 
hasOpenedCreditAccount(address borrower);

2- Interaction with CreditFilter Contract :

to get credit account health factor:

calcCreditAccountHealthFactor(address creditAccount);

to calculate total value of credit account :

calcTotalValue(address creditAccount);

3- Interaction with CreditAccount Contract :

to get borrowed amount :

borrowedAmount();

4- Interaction with Gearbox YearnV2 Adapter :

to deposit into Yearn DAI Vault:

deposit(uint256 amount);

to withdraw from Yearn DAI Vault:

withdraw(uint256 maxShares);

to check yDAI balance of the credit account:

balanceOf(address account);

Note: This contract is interacting with the V1 version of Gearbox Protocol. When V2 is released, most transactions and calls will go through the CreditFacade contract. You can find the V2 version of the repo and developer documents here.

https://github.com/Gearbox-protocol/contracts-v2-dev-preview

https://dev.gearbox.fi/docs/documentation/credit/open

The complete contract is here :

Check the GitHub repo to set up a local Ethereum development environment.

GitHub : https://github.com/stfibonacci/leverage_gearbox_yearn

You can find the script here:

https://github.com/stfibonacci/leverage_gearbox_yearn/blob/main/scripts/invest_yearn.py

## Run the scriptbrownie run scripts/invest_yearn.py --network mainnet-fork-new## Running the scriptBrownie v1.16.4 - Python development framework for Ethereum
Compiling contracts...
LeverageGearboxYearnProject is the active project.
Launching 'ganache-cli ...'Alice depositing 20K DAI to the contract ...
Contract Available Balance: 20000.0
Opening credit account with 3X leverage and added 10K DAI ...
Depositing into Yearn ...
Credit account opened and invested into Yearn
Contract Available DAI balance: 10000.0
CA address: 0xa079AffCD1053E6F4127F23e0722B56196F52412
CA health factor: 1.3499
CA collateral :9999.999999999945
CA borrowed amount:20000.0
CA total amount:29999.999999999945
Adding 10K DAI as collateral ...
Contract Available DAI balance: 0.0
Current CA health factor: 1.815
Current CA collateral :20000.009823824294
Current CA borrowed amount:20000.0
Current CA total amount:40000.00982382429
Withdrawing from Yearn ...
Closing Credit Account ...
CA address: 0x0000000000000000000000000000000000000000
Contract total DAI balance: 20000.01010350681

Thanks for reading! Feel free to comment if you have questions or find bugs and mistakes.

--

--