A Developer's Intro to DeFi & Building w/GHO

Huge thank you to Carlos & Shiv for their invaluable contributions and learning the ins and outs of GHO with me. 👻

Last week, together with Carlos and Shiv, we participated in ETHGlobal’s LFGHO hackathon. As someone who still considers herself a newbie in DeFi, I've learned a ton. This post is a product of last week's efforts, containing all the information I learned about GHO and building with Aave – a developer's introduction to building in DeFi.

In this post, I aim to answer the following:

  • What's Aave & GHO?

  • How does GHO work? Why is it different from other stablecoins?

  • How to get started building with GHO - hands on 🙂

Don’t worry if you don’t know anything about DeFi, Aave or GHO yet. I’ll be introducing all the concepts from ground 0.


Non-technical Intro to Defi, Aave & GHO

DeFi Primer

DeFi (Decentralized Finance), refers to a range of financial services available on public blockchains. It allows users to lend, borrow, trade, and earn interest on their assets without the need for traditional financial intermediaries like banks. DeFi relies on smart contracts that don't require intermediaries to execute. This makes financial transactions more direct and accessible to anyone with an internet connection.

I know many people who started trading crypto, or opted-in to receive crypto payments because of the issues they faced in their traditional banking systems. DeFi offers an alternative to traditional banking institutions by providing more accessible financial tools that are open to anyone with internet access. This openness can democratize access to financial services. However, it's also super important to recognize the regulatory challenges and risks associated with crypto and DeFi.

Total Value Locked in DeFi, source: defillama.com
Total Value Locked in DeFi, source: defillama.com

AaveUniswap, and Compound are popular DeFi platforms. They offer a variety of financial services:

  • Aave is a lending and borrowing protocol. Imagine lending your cryptocurrency like you would in a savings account and earning interest. Or, borrowing against your crypto assets, much like taking out a mortgage against your house.

  • Uniswap enables decentralized trading. You can swap different cryptocurrencies directly, without the need for a traditional exchange.

  • Compound is similar to Aave, allowing users to earn interest on deposits. Rates fluctuate based on the supply and demand.

More about Aave

Aave is an Open Source Protocol that allows users to lend and borrow crypto.

There are 3 key players in Aave:

  1. Depositor (aka supplier): These are users who add liquidity to Aave by depositing their cryptocurrency into a liquidity pool. In exchange, they receive interest on their deposits.

  2. Borrowers: Users who draw liquidity from these pools by taking out loans. To do this, they must first provide collateral that is worth more than the loan amount — this is known as over-collateralization and helps keep the loan secure. An advantage for borrowers is the possibility of their collateral increasing in value, which can make repaying the loan more beneficial.

  3. Liquidators: Their primary function is to monitor loans and ensure that they remain sufficiently collateralized (the value of the collateral>the value of the loan). If a borrower's collateral value falls below a certain threshold (due to price fluctuations in the cryptocurrency market), the position is considered undercollateralized and can be liquidated. They play a crucial role in maintaining the health and stability of the AAVE protocol.

GHO is a stablecoin native to the Aave protocol. Let’s first cover stablecoins.

Primer on Stablecoins

stablecoin is a type of cryptocurrency designed to have a stable value. This is achieved by pegging the value to a stable asset like the US dollar, aiming to maintain a consistent value unlike other more volatile cryptocurrencies.

Source: https://defillama.com/stablecoins
Source: https://defillama.com/stablecoins

Stablecoins come in various forms, here are some of the most common categories:

  • Centralized, One-to-One Backed Stablecoins: These are pegged to fiat currencies like the US Dollar on a one-to-one basis and are maintained by centralized entities.

    • ExampleUSDT (Tether) and USDC.

    • Benefits: Highly stable, widely accepted, and easy to convert to fiat currencies.

    • Risks: Reliant on the trustworthiness of the central issuer, potential for central points of failure.

  • Decentralized, Crypto-Backed Stablecoins: These tokens are backed by other cryptocurrencies. For each stablecoin minted, there's a corresponding amount of crypto collateral.

    • ExampleDAI - backed by Ethereum and other cryptocurrencies.

    • Benefits: More transparent than centralized stablecoins, with value backed by a diverse range of crypto assets.

    • Risks: Subject to market volatility of the backing cryptocurrencies

  • Algorithmic Stablecoins: These use algorithms to maintain a stable value. Unlike traditional stablecoins. Algorithmic stablecoins rely on the protocol to manage supply and demand, for stabilizing their price.

    • Example: TerraUSD (UST) – Collapsed on May 2022

    • Benefits: Decentralized and not reliant on collateral; new approach to maintaining stability.

    • Risks: The mechanisms are complex and very experimental. Their value heavily depends on market confidence. A loss in confidence can lead to a death spiral, where the mechanism to stabilize the coin fails. We have seen several failures of algorithmic stablecoins like TerraUSD.

Top Stablecoins, source: https://defillama.com/stablecoins
Top Stablecoins, source: https://defillama.com/stablecoins

What about GHO?

GHO is an ERC20 token designed to maintain a stable value, pegged to the US Dollar. It falls in the decentralized and crypto-backed stablecoin bucket.

GHO Properties:

  • Over-collateralized: Users must provide more collateral than the GHO they mint.

  • GHO is minted not supplied: GHO, unlike other tokens, is minted rather than supplied. When you borrow on the protocol, you receive GHO, which is minted at that moment instead of being drawn from pre-existing supplies. The borrowing rate for GHO is not set by market dynamics but is determined by AAVE governance (=1 USD).

  • GHO is natively integrated into the Aave market. This means that interacting with GHO on AAVE is very similar to interacting with any other asset of the protocol.

  • It’s governed by the Aave DAO: GHO introduces a new concept called "facilitators." A Facilitator is a protocol or an entity who is authorized by the Aave DAO to mint GHO.

  • Additionally, there's a discount mechanism in place for stkAAVE holders, allowing them to borrow at lower rates based on their staked assets.

📹 Great presentation by Steven Valeri on GHO & Stablecoins from Devcon.

But really - how does it work?

GHO is minted and burned by the smart contracts on demand.

Borrowing GHO

Here’s how the steps look like to Borrow GHO:

  1. Provide Collateral: eg: User supplies 1 ETH as collateral to Aave

  2. Receive aWETH: In return, the user receives 1aWETH.(aWETH is the token that represents the deposited Ethereum in Aave)

  3. Borrow GHO: The user borrows 10 GHO, this process is minting the GHO

  4. Acquire Debt Tokens: Upon borrowing, the user receives 10 debt tokens.

  5. Interest Accrual: The debt accrues interest over time.

  6. Repay GHO and Accrued Interest: Repaid interest goes to the treasury, instead of the asset supplier.

Supply of GHO

GHO is not supplied, it is minted by the facilitator on demand. When the user pays the GHO they have borrowed (aka their debt position) the GHO is burned by the facilitator and the interest is sent to the GHO treasury.

Important note here is that because there is no supply of GHO, the interest rates are not determined based on the utilization but instead by Aave governance.

Source: https://docs.gho.xyz/concepts/how-gho-works/
Source: https://docs.gho.xyz/concepts/how-gho-works/

🙌 To bring it all together - GHO is unique as it's minted on-demand and burned upon repayment. The interest rate is governed by Aave DAO, not market dynamics.


Building with GHO

Let's dive into the practical side of DeFi by getting into how to build with GHO.

We’ll write a basic smart contract to showcase some interactions with GHO within the Aave ecosystem. The contract will demonstrate how to interact with GHO, including depositing DAI and borrowing GHO from the Aave pool on behalf of a specified address.

You need to have Foundry installed for this workshop, you can follow the steps here.

Set-up

  1. Create a project

    forge init gho-project 
    cd gho-project 
    
  2. Install the dependencies

    forge install aave/aave-v3-core@a00f28e aave/gho-core@2abe8f7
    OpenZeppelin/openzeppelin-contracts@d00acef 
    
  3. Create a 'remappings.txt and add the following onto it:

    aave-v3-core/=lib/aave-v3-core/ 
    aave-v3-periphery/=lib/aave-address-book/lib/aave-v3-periphery/
    ds-test/=lib/forge-std/lib/ds-test/src/ 
    forge-std/=lib/forge-std/src/ 
    gho-core/=lib/gho-core/ 
    @openzeppelin/=lib/openzeppelin-contracts/ 
    
  4. Add the RPC Url to interact with GHO to foundry.toml

    [rpc_endpoints]
    goerli ="https://rpc.ankr.com/eth_goerli"
    

Interacting with GHO: Deposit DAI & Mint GHO

1.    Create a file in the src folder

touch ./src/GhoTest.sol

2. Here is the code for the smart contract, I have added the comments to explain what’s going on:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {IERC20} from "aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20.sol";
import {IPool} from "aave-v3-core/contracts/interfaces/IPool.sol";
import {GhoToken} from "gho-core/src/contracts/gho/GhoToken.sol";
import {IGhoToken} from "gho-core/src/contracts/gho/interfaces/IGhoToken.sol";

contract GhoTest {
   IERC20 public dai;
   IPool public pool;
   GhoToken public gho;
   address public spender;


   constructor( address _daiAddress, address _poolAddress, address _ghoAddress, address _spenderAddress
   ) {
       dai = IERC20(_daiAddress);
       pool = IPool(_poolAddress);
       gho = GhoToken(_ghoAddress);
       spender = _spenderAddress;
   }

   function deposit(uint256 daiAmount) internal {
       // Approve the Aave Pool to pull the specified amount of DAI funds
       dai.approve(address(pool), daiAmount);
       // Supply the specified amount of DAI to Aave Pool
       pool.supply(address(dai), daiAmount, spender, 0);
   }

   function mintGho(uint256 ghoAmount) internal {
       // Borrow the specified amount of GHO
       // Note: This assumes that the necessary DAI has already been deposited
       pool.borrow(address(gho), ghoAmount, 2, 0, spender);

       // eg: you can also borrow the full amount in the contract for certain use-cases
       // but since GHO is overcollateralized you'll need to provide more DAI than the GHO to borrow
   }
}

Let's test this

  1. Create a test file:

    touch ./test/GhoTest.t.sol
    

2. Add the following code to the file, I have added comments to explain what's going on. We’ll be testing on Goerli network, the network addresses are here.

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import "../src/GhoTest.sol";
import "forge-std/Test.sol";
import "forge-std/StdCheats.sol";

contract GhoTestTests is GhoTest, StdCheats, Test {

   constructor() GhoTest(
       0xD77b79BE3e85351fF0cbe78f1B58cf8d1064047C, // DAI address
       0x617Cf26407193E32a771264fB5e9b8f09715CdfB, // Aave Pool address
       0xcbE9771eD31e761b744D3cB9eF78A1f32DD99211, // GHO Token address
       address(0x1) // spender address (or owner address)
   ) {}

   function setUp() public {
       vm.createSelectFork(vm.rpcUrl("goerli"), 9818553); // fork of the Goerli testnet
       deal(address(dai), spender, 100e18);  //  gives 100 DAI to the spender addr
  
       // Transfer the ownership of the GHO token to the owner address
       address owner = gho.owner();
       vm.prank(owner);
       gho.transferOwnership(spender);

       vm.startPrank(spender);
   }

   function testDeposit() public {
       uint256 depositAmount = 10e18; // 10 DAI

       uint256 initialDaiBalance = dai.balanceOf(spender);
       deposit(depositAmount);

       uint256 finalDaiBalance = dai.balanceOf(spender);
       // Check DAI balance before and after deposit
       assertEq(finalDaiBalance, initialDaiBalance - depositAmount, "DAI balance should decrease by the deposit amount");
   }

   function testMintGho() public {
       uint256 daiAmount = 100e18; // Amount of DAI to deposit for collateral
       uint256 ghoAmount = 10e18;  // Amount of GHO to borrow

       // Deposit DAI to provide collateral for borrowing GHO
       deposit(daiAmount);

       // Borrow GHO by miniting
       mintGho(ghoAmount);

       // Assertions to check the final state
       uint256 finalGhoBalance = gho.balanceOf(spender);
       assertEq(finalGhoBalance, ghoAmount, "GHO balance should be equal to the borrowed amount");
   }
}

3. Run the tests:

forge test

Conclusion

DeFi is not as daunting as it seems on the outside. By enabling direct, peer-to-peer financial transactions, it’s breaking down the barriers of traditional finance. Tools like Aave provide a user-friendly platform for experimentation and innovation. You can easily get started learning + building with Aave and GHO.

Last but not least, here’s our hackathon project!

https://ghofund.vercel.app/debug
https://ghofund.vercel.app/debug

See you on the next one. If you have any feedback or comments, please feel free to reach out, my dm’s are open!

Subscribe to Eda
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.