Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Aave for DeFi Developers – A Simple Guide with Video

#1
Aave for DeFi Developers – A Simple Guide with Video

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;738415&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;2&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (2 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (2 votes) </div>
</div>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/aave-for-defi-developers/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2Ft9N4StMf-tI%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p>This is in continuation of our <a href="https://blog.finxter.com/getting-started-with-defi/" target="_blank" rel="noreferrer noopener">DeFi series</a>. In this post, we look at yet another decentralized lending and borrowing platform <strong><a href="https://app.aave.com/" data-type="URL" data-id="https://app.aave.com/" target="_blank" rel="noreferrer noopener">Aave</a>.</strong></p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1fa99.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/decentralized-finance-for-coders-free-video-course/" target="_blank">Full DeFi Course</a></strong>: Click the link to access our free full DeFi course that’ll show you the ins and outs of decentralized finance (DeFi).</p>
<h2><a id="_d82p7mz43y4r"></a>Aave</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><a href="https://docs.aave.com/hub/" target="_blank" rel="noreferrer noopener"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/09/image-158.png" alt="" class="wp-image-738448" width="701" height="620" srcset="https://blog.finxter.com/wp-content/uploads/2022/09/image-158.png 900w, https://blog.finxter.com/wp-content/uplo...00x265.png 300w, https://blog.finxter.com/wp-content/uplo...68x679.png 768w" sizes="(max-width: 701px) 100vw, 701px" /></a></figure>
</div>
<p>Aave launched in 2017 is a DeFi protocol similar to <a rel="noreferrer noopener" href="https://blog.finxter.com/yield-farming-borrowing-and-lending-with-compound-a-simple-guide-for-devs/" target="_blank">Compound</a> with a lot of upgrades. </p>
<p>Beyond what Compound provides, Aave gives several extra tokens for supply and borrowing. As of now, Compound offered nine different tokens (various <a href="https://blog.finxter.com/how-does-the-erc-20-token-work/" target="_blank" rel="noreferrer noopener">ERC- 20</a> Ethereum- based assets). </p>
<p>Aave provides these nine besides an additional 13 that Compound does not. </p>
<p>Depositors give the market liquidity to generate a passive income, while borrowers can borrow if they have an over-collateralized token or can avail flash loans for under-collateralized (one-block liquidity).</p>
<p>Currently, we can see two major markets on Aave. </p>
<ul>
<li>The first is for ERC-20 tokens that are more frequently used, like those of Compound, and their underlying assets, such as <a href="https://blog.finxter.com/introduction-to-ethereums-gas-in-solidity-development/" data-type="post" data-id="37644" target="_blank" rel="noreferrer noopener">ETH</a>, DAI and USDC. </li>
<li>The latter is only available with <a href="https://academy.finxter.com/university/uniswap-development-for-blockcain-engineers/" target="_blank" rel="noreferrer noopener">Uniswap</a> LP tokens. </li>
</ul>
<p>For instance, a user receives an LP token signifying market ownership when they deposit collateral into a liquidity pool on the Uniswap platform. To provide additional benefits, the LP tokens can be sold on the Uniswap market of Aave.</p>
<p>As per DeFi pulse, Aave has a TVL (Total Value Locked) of $4.09B as of today.</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="624" height="264" src="https://blog.finxter.com/wp-content/uploads/2022/09/image-159.png" alt="" class="wp-image-738474" srcset="https://blog.finxter.com/wp-content/uploads/2022/09/image-159.png 624w, https://blog.finxter.com/wp-content/uplo...00x127.png 300w" sizes="(max-width: 624px) 100vw, 624px" /><figcaption><strong><em>Fig</em></strong><em>: Defi Pulse for Aave</em></figcaption></figure>
</div>
<h2><a id="_ze3jgd37zegl"></a>Aave Versions</h2>
<p>Aave has released three versions (v1, v2 and v3) as of now and the Governance token of Aave is <strong>‘AAVE’</strong>. Version 1 or v1 is the base version launched in 2017 and then there have been upgrades with multiple new features added. Below is a short comparison of when to use v2 or v3.</p>
<p>You should use Aave V2 when:</p>
<ul>
<li>You won’t need to borrow many tokens.</li>
<li>Little profit</li>
<li>You borrow important tokens like WETH, USDC, etc.</li>
</ul>
<p>You should use Aave V3 when:</p>
<ul>
<li>Many tokens must be borrowed</li>
<li>High profit margin</li>
<li>You borrow mid-cap tokens like <a href="https://blog.finxter.com/earn-passive-and-active-income-200-h-as-a-chainlink-validator-and-freelance-consultant/" data-type="post" data-id="36581" target="_blank" rel="noreferrer noopener">LINK</a>, etc.</li>
</ul>
<h2><a id="_mtj40sir8iyr"></a>Borrow and Lending in Aave</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><a href="https://docs.aave.com/hub/" target="_blank" rel="noreferrer noopener"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/09/image-158.png" alt="" class="wp-image-738448" width="701" height="620" srcset="https://blog.finxter.com/wp-content/uploads/2022/09/image-158.png 900w, https://blog.finxter.com/wp-content/uplo...00x265.png 300w, https://blog.finxter.com/wp-content/uplo...68x679.png 768w" sizes="(max-width: 701px) 100vw, 701px" /></a><figcaption><strong>Fig</strong>: Aave borrow and lend (pic credit: https://docs.aave.com)</figcaption></figure>
</div>
<h3><a id="_2vml0ze9194i"></a>Borrow</h3>
<p>You must deposit any asset to be used as collateral before borrowing.</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The amount you can borrow up to depends on the value you have deposited and the readily available liquidity. </p>
<p>For instance, if there isn’t enough liquidity or if your health factor (minimum threshold of the collateral = 1, below this value, liquidation of your collateral is triggered) prevents it, you can’t borrow an asset.</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The loan is repaid with the same asset that you borrowed. </p>
<p>For instance, if you borrow 1 ETH, you’ll need to pay back 1 ETH plus interest. </p>
<p>In the updated Version 2 of the Aave Protocol, you can also use your collateral to make payments. You can borrow any of the stable coins like USDC, DAI, USDT, etc. if you want to repay the loan based on the price of the USD.</p>
<h4><a id="_3ug43e3edtap"></a>Stable vs Variable Interest Rate</h4>
<p>In the short-term, <strong>stable</strong> rates function as a fixed rate, but they can be rebalanced in the long run in reaction to alterations in the market environment. Depending on supply and demand in Aave, the <strong>variable</strong> rate can change.</p>
<p>The stable rate is the better choice for forecasting how much interest you will have to pay because, as its name suggests, it will remain fairly stable. The variable rate changes over time and, depending on market conditions, could be the optimal rate.</p>
<p>Through your dashboard, you can switch between the stable and variable rate at any time.</p>
<h3><a id="_fvo1t16f6n00"></a>Deposit/Lending</h3>
<p>Lenders share the interest payments made by borrowers based on the utilization rate multiplied by the average borrowing rate. The yield for depositors increases as reserve utilization increases.</p>
<p>Lenders are also entitled to a portion of the Flash Loan fees, equal to .09% of the Flash Loan volume.</p>
<p>There is no minimum or maximum deposit amount; you may deposit any amount you choose.</p>
<h2><a id="_q3wxg92kl62s"></a>Flash Loans in Aave</h2>
<p>Flash Loans are unique business agreements that let you borrow an asset as long as you repay the borrowed money (plus a fee) before the deal expires (also called One Block Borrows). Users are not required to provide collateral for these transactions in order to proceed. </p>
<p>Flash Loans have no counterpart in the real world, so understanding how state is controlled within blocks in blockchains is a prerequisite.</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Flash-loan enables users to access pool liquidity <strong>for a single transaction</strong> as long as the amount borrowed plus fees are returned or (if permitted) a debt position is opened by the end of the transaction.</p>
<p>For flash loans, Aave V3 provides two choices:</p>
<p>(1) “<strong>flashLoan</strong>”: enables borrowers to access the liquidity of several reserves in a single flash loan transaction. In this situation, the borrower also has the choice to open a fixed or variable-rate loan position secured by provided collateral.</p>
<p><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The fee for flashloan is waived for approved flash borrowers.</p>
<p>(2) <strong>“flashLoanSimple”</strong>: enables the borrower to access a single reserve’s liquidity for the transaction. For individuals looking to take advantage of a straightforward flash loan with a single reserve asset, this approach is gas-efficient.</p>
<p><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The fee for flashloanSimple is not waived for the flash borrowers. The Flashloan fee on Aave V3 is 0.05%.</p>
<h2><a id="_6q15nvst9n5n"></a>Let’s Code a Simple Flash Loan</h2>
<p>Let’s code a simple flash loan in Aave, where we buy and repay the asset in the same transaction without having to provide any collateral. First, we set up the environment for writing the code.</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/25b6.png" alt="▶" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note:</strong> It is recommended to follow the video along for a better understanding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$npm install -g truffle # in case truffle not installed
$mkdir aave_flashloan $cd aave_flashloan
$truffle init
$npm install @aave/core-v3
$npm install @openzeppelin/contracts
$npm install @openzeppelin/test-helpers </pre>
<p class="has-global-color-8-background-color has-background"><strong>Note:</strong> Aave3 is currently available on <a rel="noreferrer noopener" href="https://blog.finxter.com/polygon-quickstart-for-developers/" target="_blank">Polygon</a>, Arbitrum, Avalanche, and other L2 chains. As of now, it is not available on the <a href="https://blog.finxter.com/category/ethereum/" target="_blank" rel="noreferrer noopener">Ethereum</a> mainnet. Thus, we will fork the Polygon mainnet for our tests.</p>
<p>Set up a new app in <a href="https://dashboard.alchemy.com/" target="_blank" rel="noreferrer noopener">Alchemy</a> with the chain as Polygon mainnet and note down the API key.</p>
<p>Create a new file <code>.env</code> and enter the below info.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$WEB3_ALCHEMY_POLYGON_ID=&lt;API key noted above>
$USDC_WHALE=0x075e72a5eDf65F0A5f44699c7654C1a76941Ddc8</pre>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/solidity/" data-type="post" data-id="37379" target="_blank">Solidity Crash Course — Your First Smart Contract</a></p>
<h3><a id="_g3lcn7rqxnvs"></a>Simple Flash Loan Contract</h3>
<p>The contract code (<code>FlashLoanPolygon.sol</code>) in the <code>contracts</code> folder.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// 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 { using SafeMath for uint256; using SafeERC20 for IERC20; event Log(string message, uint256 val); constructor(IPoolAddressesProvider provider) FlashLoanSimpleReceiverBase(provider) {} function aaveFlashloan(address loanToken, uint256 loanAmount) external { IPool(address(POOL)).flashLoanSimple( address(this), loanToken, loanAmount, "0x", 0 ); } function executeOperation( address asset, uint256 amount, uint256 premium, address initiator, bytes memory ) public override returns (bool) { require( amount &lt;= IERC20(asset).balanceOf(address(this)), "Invalid balance for the contract" ); // pay back the loan amount and the premium (flashloan fee) uint256 amountToReturn = amount.add(premium); require( IERC20(asset).balanceOf(address(this)) >= amountToReturn, "Not enough amount to return loan" ); approveToken(asset, address(POOL), amountToReturn); emit Log("borrowed amount", amount); emit Log("flashloan fee", premium); emit Log("amountToReturn", amountToReturn); return true; }
}</pre>
<p>The contract code contains two important functions.</p>
<ul>
<li><strong><code>aaveFlashloan()</code></strong> which calls the pools function <code>flashLoanSimple()</code>. Our test code must call this function to initiate a flash loan.</li>
<li><strong><code>executeOperation()</code></strong> is a callback function of the pool which pays the loan + interest back to the pool.</li>
</ul>
<h3><a id="_v0asinpmqfkt"></a>Testing Contract</h3>
<p>In the test folder, create a <a rel="noreferrer noopener" href="https://blog.finxter.com/javascript-developer-income-and-opportunity/" data-type="post" data-id="191233" target="_blank">JavaScript</a> file <strong><code>config.js</code></strong> with the following content:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const USDC = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"; const aavePoolAddressesProvider = "0xa97684ead0e402dC232d5A977953DF7ECBaB3CDb"; const USDC_WHALE = process.env.USDC_WHALE; module.exports = { USDC, USDC_WHALE, aavePoolAddressesProvider,
}</pre>
<p>In the test folder, create another file <strong><code>testAaveFlashLoanSimple.js</code></strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const BN = require("bn.js");
const IERC20 = artifacts.require("IERC20");
const AaveFlashLoan = artifacts.require("AaveFlashloan");
const {USDC,aavePoolAddressesProvider,USDC_WHALE} = require("./config"); function sendEther(web3, from, to, amount) { return web3.eth.sendTransaction({ from, to, value: web3.utils.toWei(amount.toString(), "ether"), });
} contract("AaveFlashLoan", (accounts) => { const WHALE = USDC_WHALE const TOKEN_BORROW = USDC const DECIMALS = 6 // USDC uses 6 decimal places and not 18 like other ERC20 // We fund more because we need to pay back along with the fees during Flash loan. // So let us fund extra (2 million round figure to the calculations simple) 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) // send ether to USDC WHALE contract to cover tx fees await sendEther(web3, accounts[0], WHALE, 1) // send enough token to cover fee const bal = await token.balanceOf(WHALE) assert(bal.gte(FUND_AMOUNT), "balance &lt; FUND") // Send USDC tokens to AaveFlashLoan contract await token.transfer(aaveFlashLoanInstance.address, FUND_AMOUNT, { from: WHALE, }) console.log("balance of USDC in AAveFlashLoan contract:", bal2.toString()) }) it("aave simple flash loan", async () => { const tx = await aaveFlashLoanInstance.aaveFlashloan(token.address, BORROW_AMOUNT) console.log("token address:",token.address) for (const log of tx.logs) { console.log(log.args.message, log.args.val.toString()) } }) });</pre>
<p>Again, feel free to watch the video at the beginning of this tutorial to understand the testing process.</p>
<p>Open two terminals. </p>
<p><strong>In terminal 1:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$source .env
$npx ganache-cli i – fork https://polygon-mainnet.g.alchemy.com/v2/$WEB3_ALCHEMY_POLYGON_ID \
--unlock $USDC_WHALE \
--networkId 999</pre>
<p>This should start a local fork of the Polygon mainnet.</p>
<p><strong>In terminal 2:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ source .env
$ env $(cat .env) npx truffle test – network polygon_main_fork test/testAaveFlashLoanSimple.js</pre>
<p>This should run the flash loan test case, and it must pass.</p>
<h2><a id="_jcn33wkhhowf"></a>Conclusion</h2>
<p>This tutorial discussed Aave, a leading <a href="https://blog.finxter.com/top-defi-articles/" data-type="post" data-id="395129" target="_blank" rel="noreferrer noopener">Dapp</a> lending and borrowing provider. </p>
<p>It covered some basic functionalities supported in Aave, such as lending, borrowing, and flash loans. </p>
<p>There are many other features Aave supports and it is not possible to cover it in one post, such as governance, liquidation, and advanced features such as Siloed Borrowing, Credit Delegation, and many more. </p>
<p>The post also examined a simple flash loan contract using Aave API.</p>
<p>You can explore more about borrowing and lending with Aave in this <a rel="noreferrer noopener" href="https://github.com/MatricksDeCoder/AaveDeFi" target="_blank">link</a>. It has a full stack Defi Aave dapp with frontend to perform borrowing and lending.</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/crypto-trading-bot-developer-income-and-opportunity/" data-type="URL" data-id="https://blog.finxter.com/crypto-trading-bot-developer-income-and-opportunity/" target="_blank" rel="noreferrer noopener">Crypto Trading Bot Developer — Income and Opportunity</a></p>
</div>


https://www.sickgaming.net/blog/2022/09/...ith-video/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016