How to use the Aave Contract to lend and earn interest đź‘»
Introduction
“There is nothing permanent except change.” — Heraclitus
Keep your money in the bank. It is safe in there.
If you can relate, high-five. We’ve heard this at every possible corner and phase in our lives. Now, this could quite easily shape into one of my unmitigated rants about the banking system, but that’s not what you're here for. For rant — Click here.
The thing is everyone has a bank account. Every individual keeps their wealth(FIAT) inside these accounts with the assurance that their money is safe and secure. As an incentive to keep your money inside the bank accounts, banks promise you interest, extra money which you earn passively. Sounds lucrative, isn’t it? Unfortunately, all that glitters is not gold, nor is it silver.
Behind the Scenes: You deposit your money in the account. Bank makes an entry in their ledger of the deposited amount. They lend out your money to borrowers. They levy heavy interest rates on the lent-out money. Part of this interest amount is paid out to you on a monthly or quarterly basis.
So, if they are charging 12% interest on the lent-out amount, all you get as interest is 4% on YOUR OWN MONEY! The remaining 8% belongs to? Dat’s right. The banks, themselves.
All of the bank’s structural costs are covered using the rest of the unpaid interest and the rest is pure profit. In short. Your Funds. Their Power.
“Aap Chronology samjhiye!”(Understand the Chronology)
Aave- The De-Fi is a major improvement upon the traditional banking system. History Time: Launched in 2017 as ETHLend, it introduced peer-to-peer lending and borrowing of digital assets in a decentralized and non-custodial fashion. What changed? Your Funds. Your Power. You are in complete control of your funds.
They improved upon the initial idea to include pool-based lending/borrowing and rebranded to Aave Protocol. As the name suggests, these are pools of funds into which a user can deposit some assets to receive a special token called aToken. It is pegged against the original assets.
The advantage of these tokens is that you can use them in other Defi protocols as if they were the same even though they are currently being used in Aave to borrow assets. This makes you the true owner of the assets. The lender uses these tokens to earn interest. Anyone who is in need of an asset can borrow from these pools and can repay the amount along with some interest. Smooth, but not a criminal. Sorry, MJ.
Now, a borrower has to maintain a stable health ratio. If it drops below a certain threshold, the lent assets will get liquidated automatically. Eliminating bad actors in a more efficient way, basically.
Implementing Aave Contract
Now, you can go to the official website and you can interact with the Aave through their UI. But we are developers. We don’t sleep without writing code. So, let’s do it. In this, we will use the Aave contracts deployed in Polygon Mumbai network to lend some Matic token. We will see the interest generated by those tokens. In the end, we will claim those tokens as well as withdraw the whole fund.
First, we will create a file name AaveTesting.sol
.
//SPDX-License-Identifier:UNLICENSED
pragma solidity >=0.5.0 <=0.9.0;interface IWETHGateway {
function depositETH(
address lendingPool,
address onBehalfOf,
uint16 referralCode
) external payable; function withdrawETH(
address lendingPool,
uint256 amount,
address onBehalfOf
) external;}interface ILendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
}interface IERC20 {
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
}interface IAaveIncentivesController{
function claimRewards( address[] calldata assets,uint256 amount,address to) external returns (uint256);
function getRewardsBalance(address[] calldata assets, address user)external view returns (uint256);
}
First we are defining the solidity compiler version.
IWETHGateway
: When we deal with native tokens of a blockchain (like ETH of Ethereum and Matic of Polygon), we will need to use the following interface to deposit and withdraw our funds.
ILendingPoolAddressesProvider
: We use this to get the address of the lending pool.
IERC20
: For withdrawing, we will need to return back the aToken(in this case aMatic). As aTokens are ERC20 tokens, we will need to approve the IWETHGateway
to burn those tokens.
IAaveIncentivesController
: We will use this interface to know about the interest we have earned as well as to claim the interest.
contract aaveLending{
fallback() external payable {}
receive() external payable {}
address[] reward=[0xF45444171435d0aCB08a8af493837eF18e86EE27];
address aaveIncentive = 0xd41aE58e803Edf4304334acCE4DC4Ec34a63C644;
address ethGateWayAddress= 0xee9eE614Ad26963bEc1Bec0D2c92879ae1F209fA;
address lendingPoolProviderAddress = 0x178113104fEcbcD7fF8669a0150721e231F0FD4B;
address aMaticToken = 0xF45444171435d0aCB08a8af493837eF18e86EE27;
//Lend to Aave
function lendToAave() public payable{
IWETHGateway ethGateWay = IWETHGateway(ethGateWayAddress);
ILendingPoolAddressesProvider lendingProvider = ILendingPoolAddressesProvider(
lendingPoolProviderAddress
);
ethGateWay.depositETH{value:msg.value}(lendingProvider.getLendingPool(), address(this),0);
}
//get the amount of token that can be claimed
function getClaimAmount() public view returns(uint){
IAaveIncentivesController claim = IAaveIncentivesController(aaveIncentive);
return(claim.getRewardsBalance(reward,address(this)));
}
//to claim the reward amount
function claimReward(uint _amount) public{
IAaveIncentivesController claim = IAaveIncentivesController(aaveIncentive);
claim.claimRewards(reward,_amount,msg.sender);
}
//approve the ethgateway contract to use aMatic
function setApproval(uint _amount) public{
IERC20(aMaticToken).approve(ethGateWayAddress,_amount);
}
// get the allownace amount
function getAllowanceAmount(address _owner, address _spender) public view returns(uint256){
return(IERC20(aMaticToken).allowance(_owner,_spender));
}
// Withdraw from Aave
function withDrawFromAave(uint256 _amount) public payable{
IWETHGateway ethGateWay = IWETHGateway(ethGateWayAddress);
ILendingPoolAddressesProvider lendingProvider = ILendingPoolAddressesProvider(
lendingPoolProviderAddress
);
ethGateWay.withdrawETH(lendingProvider.getLendingPool(),_amount,msg.sender);
}
}
First of all, we store the addresses of deployed Aave contracts in the state variables.
lendToAave
: We use this function to lend our Matic token to Aave. FIrst we create an instance of IWETHGateway
and ILendingPoolAddressesProvider
using their contract address and store them in ethGateWay
and lendingProvider
. Next, we use the depositETH
function present in ethGateWay
to deposit funds. In this, we pass the lendingPool address which we are getting from getLendingPool
, the address that will receive the aMatic, and the referral code which in our case is 0
. ethGateWay.depositETH{value:msg.value}
is used to send Matic tokens to the contract.
getClaimAmount
: We first create an instance of IAaveIncentivesController
using the deployed contract address. Next, we use the getRewardsBalance
to get the interest that we have earned. The amount we will see is in Wei i.e. if you see 2000 as the amount, it's actually not 2000 Matic but 2000*10^(-18) Matic. In this function, we pass an array that consists of aToken addresses(in our case just aMatic address) and the account whose interest we want to see. Since our contract is holding the aToken, so we will pass the contract address as second parameter. Now, keep note of the amount as we will use it to claim the interest in the next function.
claimReward
:This function takes in the amount of token we want to claim as input. Next, we create an instance of IAaveIncentivesController
using the deployed contract address. We call the claimRewards
function to claim our interest. It takes in the array of token addresses whose interest we want to claim, the amount we want to claim and the address which should receive the amount. In this case, we will pass the rewards
variable that contains the aMatic token address in an array, the amount we got from getClaimAmount
function and at last we want to transfer the amount to our wallet, so we are passing mg.sender
. You can pass any other address if you want.
Now we will mainly use three functions to withdraw our funds from Aave.
setApproval
: To withdraw our Matic token, we will first have to return back the aMatic token to Aave so that they can be burned and in response to that Matic tokens will be returned back. So for that, we will need to approve the WETHGateway
contract to use the aMatic token. We call the approve
function present in the ERC20
contract. In that, we pass the spender address which is WETHGateway
and the amount the contract is allowed to spend. In our case, it will be same as the amount we lended to Aave. One thing to note is that the amount set is the maximum amount of funds, the contract is allowed to use. If the spender tries to spend more than the specified amount, the contract will shout at us with an error message.
getAllowanceAmount
: This is an additional function that lets us see how much allowance is there a spender. In this function, if we pass our contract address and the WETHGateway
address, you should see it's same as the amount we gave in setApproval
function.
withDrawFromAave
: Now, it's time to get back our funds. So, it takes in the amount of funds we want to withdraw. Make sure the amount is either less than or equal to the approved amount. We create an instance of IWETHGateway
and ILendingPoolAddressesProvider
using their contract address and store them in ethGateWay
and lendingProvider
. At last, we call the withdrawETH
function of ethGateWay
. In this, we are passing the lending pool address which we are getting from getLendingPool
function, the amount of funds we want to withdraw and the receiver of the fund as the third parameter. The amount would then reflect in your wallet address.
For reference, here is the deployed contract.
Conclusion
We were successfully able to use Aave protocol to lend our Matic token to earn interest. We were able to visualize our interests, claim them and at the end, we were able to withdraw the whole fund back to our wallet.
c̶h̶r̶o̶n̶o̶l̶o̶g̶y̶. Community. Decentralization. Web3. You’re welcome.
Edited by — Arka Sengupta