Thursday, May 2, 2024
HomePythonAave for DeFi Builders – A Easy Information with Video – Finxter

Aave for DeFi Builders – A Easy Information with Video – Finxter


That is in continuation of our DeFi collection. On this publish, we take a look at one more decentralized lending and borrowing platform Aave.

🪙 Full DeFi Course: Click on the hyperlink to entry our free full DeFi course that’ll present you the ins and outs of decentralized finance (DeFi).

Aave

Aave launched in 2017 is a DeFi protocol much like Compound with lots of upgrades.

Past what Compound offers, Aave provides a number of additional tokens for provide and borrowing. As of now, Compound supplied 9 totally different tokens (numerous ERC- 20 Ethereum- primarily based belongings).

Aave offers these 9 apart from a further 13 that Compound doesn’t.

Depositors give the market liquidity to generate a passive earnings, whereas debtors can borrow if they’ve an over-collateralized token or can avail flash loans for under-collateralized (one-block liquidity).

At the moment, we are able to see two main markets on Aave.

  • The primary is for ERC-20 tokens which might be extra incessantly used, like these of Compound, and their underlying belongings, reminiscent of ETH, DAI and USDC.
  • The latter is just obtainable with Uniswap LP tokens.

As an illustration, a consumer receives an LP token signifying market possession after they deposit collateral right into a liquidity pool on the Uniswap platform. To offer extra advantages, the LP tokens could be offered on the Uniswap market of Aave.

As per DeFi pulse, Aave has a TVL (Whole Worth Locked) of $4.09B as of in the present day.

Fig: Defi Pulse for Aave

Aave Variations

Aave has launched three variations (v1, v2 and v3) as of now and the Governance token of Aave is ‘AAVE’. Model 1 or v1 is the bottom model launched in 2017 after which there have been upgrades with a number of new options added. Under is a brief comparability of when to make use of v2 or v3.

You must use Aave V2 when:

  • You received’t must borrow many tokens.
  • Little revenue
  • You borrow vital tokens like WETH, USDC, and so forth.

You must use Aave V3 when:

Borrow and Lending in Aave

Fig: Aave borrow and lend (pic credit score: https://docs.aave.com)

Borrow

You have to deposit any asset for use as collateral earlier than borrowing.

💡 The quantity you may borrow as much as relies on the worth you may have deposited and the available liquidity.

As an illustration, if there isn’t sufficient liquidity or in case your well being issue (minimal threshold of the collateral = 1, under this worth, liquidation of your collateral is triggered) prevents it, you may’t borrow an asset.

💡 The mortgage is repaid with the identical asset that you simply borrowed.

As an illustration, for those who borrow 1 ETH, you’ll must pay again 1 ETH plus curiosity.

Within the up to date Model 2 of the Aave Protocol, it’s also possible to use your collateral to make funds. You may borrow any of the secure cash like USDC, DAI, USDT, and so forth. if you wish to repay the mortgage primarily based on the value of the USD.

Steady vs Variable Curiosity Charge

Within the short-term, secure charges perform as a hard and fast charge, however they are often rebalanced in the long term in response to alterations out there setting. Relying on provide and demand in Aave, the variable charge can change.

The secure charge is the higher selection for forecasting how a lot curiosity you’ll have to pay as a result of, as its identify suggests, it’ll stay pretty secure. The variable charge modifications over time and, relying on market situations, may very well be the optimum charge.

By means of your dashboard, you may change between the secure and variable charge at any time.

Deposit/Lending

Lenders share the curiosity funds made by debtors primarily based on the utilization charge multiplied by the typical borrowing charge. The yield for depositors will increase as reserve utilization will increase.

Lenders are additionally entitled to a portion of the Flash Mortgage charges, equal to .09% of the Flash Mortgage quantity.

There is no such thing as a minimal or most deposit quantity; you might deposit any quantity you select.

Flash Loans in Aave

Flash Loans are distinctive enterprise agreements that allow you to borrow an asset so long as you repay the borrowed cash (plus a payment) earlier than the deal expires (additionally referred to as One Block Borrows). Customers aren’t required to offer collateral for these transactions in an effort to proceed.

Flash Loans haven’t any counterpart in the actual world, so understanding how state is managed inside blocks in blockchains is a prerequisite.

💡 Flash-loan allows customers to entry pool liquidity for a single transaction so long as the quantity borrowed plus charges are returned or (if permitted) a debt place is opened by the top of the transaction.

For flash loans, Aave V3 offers two selections:

(1) “flashLoan”: allows debtors to entry the liquidity of a number of reserves in a single flash mortgage transaction. On this state of affairs, the borrower additionally has the selection to open a hard and fast or variable-rate mortgage place secured by supplied collateral.

👉 The payment for flashloan is waived for authorized flash debtors.

(2) “flashLoanSimple”: allows the borrower to entry a single reserve’s liquidity for the transaction. For people trying to benefit from an easy flash mortgage with a single reserve asset, this strategy is gas-efficient.

👉 The payment for flashloanSimple shouldn’t be waived for the flash debtors. The Flashloan payment on Aave V3 is 0.05%.

Let’s Code a Easy Flash Mortgage

Let’s code a easy flash mortgage in Aave, the place we purchase and repay the asset in the identical transaction with out having to offer any collateral. First, we arrange the setting for writing the code.

▶️ Observe: It is strongly recommended to comply with the video alongside for a greater understanding.

$npm set up -g truffle  # in case truffle not put in
$mkdir aave_flashloan 
$cd aave_flashloan
$truffle init
$npm set up @aave/core-v3
$npm set up @openzeppelin/contracts
$npm set up @openzeppelin/test-helpers 

Observe: Aave3 is presently obtainable on Polygon, Arbitrum, Avalanche, and different L2 chains. As of now, it isn’t obtainable on the Ethereum mainnet. Thus, we are going to fork the Polygon mainnet for our exams.

Arrange a brand new app in Alchemy with the chain as Polygon mainnet and be aware down the API key.

Create a brand new file .env and enter the under data.

$WEB3_ALCHEMY_POLYGON_ID=<API key famous above>
$USDC_WHALE=0x075e72a5eDf65F0A5f44699c7654C1a76941Ddc8

👉 Really useful Tutorial: Solidity Crash Course — Your First Good Contract

Easy Flash Mortgage Contract

The contract code (FlashLoanPolygon.sol) within the contracts folder.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@aave/core-v3/contracts/interfaces/IPool.sol";
import "@aave/core-v3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";

contract AaveFlashloan is FlashLoanSimpleReceiverBase {
    utilizing SafeMath for uint256;
    utilizing SafeERC20 for IERC20;
    occasion Log(string message, uint256 val);
    constructor(IPoolAddressesProvider supplier)
        FlashLoanSimpleReceiverBase(supplier)
    {}

    perform aaveFlashloan(tackle loanToken, uint256 loanAmount) exterior {
        IPool(tackle(POOL)).flashLoanSimple(
            tackle(this),
            loanToken,
            loanAmount,
            "0x",
            0
        );
    }

    perform executeOperation(
        tackle asset,
        uint256 quantity,
        uint256 premium,
        tackle initiator,
        bytes reminiscence
    ) public override returns (bool) {
        require(
            quantity <= IERC20(asset).balanceOf(tackle(this)),
            "Invalid stability for the contract"
        );
        // pay again the mortgage quantity and the premium (flashloan payment)
        uint256 amountToReturn = quantity.add(premium);
        require(
            IERC20(asset).balanceOf(tackle(this)) >= amountToReturn,
            "Not sufficient quantity to return mortgage"
        );

        approveToken(asset, tackle(POOL), amountToReturn);
        emit Log("borrowed quantity", quantity);
        emit Log("flashloan payment", premium);
        emit Log("amountToReturn", amountToReturn);

        return true;
    }
}

The contract code accommodates two vital capabilities.

  • aaveFlashloan() which calls the swimming pools perform flashLoanSimple(). Our check code should name this perform to provoke a flash mortgage.
  • executeOperation() is a callback perform of the pool which pays the mortgage + curiosity again to the pool.

Testing Contract

Within the check folder, create a JavaScript file config.js with the next content material:

const USDC = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";

const aavePoolAddressesProvider =
  "0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb";

const USDC_WHALE = course of.env.USDC_WHALE;

module.exports = {
    USDC,
    USDC_WHALE,
    aavePoolAddressesProvider,
}

Within the check folder, create one other file testAaveFlashLoanSimple.js:

const BN = require("bn.js");
const IERC20 = artifacts.require("IERC20");
const AaveFlashLoan = artifacts.require("AaveFlashloan");
const {USDC,aavePoolAddressesProvider,USDC_WHALE} = require("./config");


perform sendEther(web3, from, to, quantity) {
  return web3.eth.sendTransaction({
    from,
    to,
    worth: web3.utils.toWei(quantity.toString(), "ether"),
  });
}

contract("AaveFlashLoan", (accounts) => {
  const WHALE = USDC_WHALE
  const TOKEN_BORROW = USDC
  const DECIMALS = 6  // USDC makes use of 6 decimal locations and never 18 like different ERC20
  // We fund extra as a result of we have to pay again together with the charges throughout Flash mortgage.
  // So allow us to fund additional (2 million spherical determine to the calculations easy)
  const FUND_AMOUNT = new BN(10).pow(new BN(DECIMALS)).mul(new BN(500)); 500 USDC
  const BORROW_AMOUNT = new BN(10).pow(new BN(DECIMALS)).mul(new BN(1000000)); // 1 million USDC

  let aaveFlashLoanInstance
  let token

  beforeEach(async () => {
    token = await IERC20.at(TOKEN_BORROW) // USDC token
    aaveFlashLoanInstance = await AaveFlashLoan.new(aavePoolAddressesProvider)

    // ship ether to USDC WHALE contract to cowl tx charges
    await sendEther(web3, accounts[0], WHALE, 1)

    // ship sufficient token to cowl payment
    const bal = await token.balanceOf(WHALE)
    assert(bal.gte(FUND_AMOUNT), "stability < FUND")
    // Ship USDC tokens to AaveFlashLoan contract
    await token.switch(aaveFlashLoanInstance.tackle, FUND_AMOUNT, {
      from: WHALE,
    })
    console.log("stability of USDC in AAveFlashLoan contract:", bal2.toString())

  })
    it("aave easy flash mortgage", async () => {
        const tx = await aaveFlashLoanInstance.aaveFlashloan(token.tackle, BORROW_AMOUNT)
        console.log("token tackle:",token.tackle)
        for (const log of tx.logs) {
        console.log(log.args.message, log.args.val.toString())
        }
    })

});

Once more, be happy to look at the video initially of this tutorial to know the testing course of.

Open two terminals.

In terminal 1:

$supply .env
$npx ganache-cli i – fork https://polygon-mainnet.g.alchemy.com/v2/$WEB3_ALCHEMY_POLYGON_ID 
--unlock $USDC_WHALE 
--networkId 999

This could begin an area fork of the Polygon mainnet.

In terminal 2:

$ supply .env
$ env $(cat .env) npx truffle check – community polygon_main_fork check/testAaveFlashLoanSimple.js

This could run the flash mortgage check case, and it should move.

Conclusion

This tutorial mentioned Aave, a number one Dapp lending and borrowing supplier.

It lined some primary functionalities supported in Aave, reminiscent of lending, borrowing, and flash loans.

There are various different options Aave helps and it isn’t potential to cowl it in a single publish, reminiscent of governance, liquidation, and superior options reminiscent of Siloed Borrowing, Credit score Delegation, and plenty of extra.

The publish additionally examined a easy flash mortgage contract utilizing Aave API.

You may discover extra about borrowing and lending with Aave on this hyperlink. It has a full stack Defi Aave dapp with frontend to carry out borrowing and lending.

👉 Really useful Tutorial: Crypto Buying and selling Bot Developer — Earnings and Alternative

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments