β Borrow and Repay
Intro
In this section we are going to implement the borrower's functions borrow and repay. The following concepts will be covered:
collateral
account liquidity: calculate how much can I borrow?
open price feed: USD price of token to borrow
enter market and borrow
borrowed balance (includes interest)
borrow rate
repay borrow
Code:
Setup
Initialize Compound controller and price feed:
Collateral
Query collateral factor via comptroller.markets():
Account Liquidity
How much can I borrow? We can query the maximal amount we can borrow via comptroller.getAccountLiquidity():
shortfall > 0 means borrowing amount exceeds limit and the collateral is facing liquidation. Under normal circumstances we want liquidity > 0 and shortfall == 0.
_liquidity is in USD.
Price Feed
USD price for borrowing token can be queried via priceFeed.getUnderlyingPrice():
We need this function to compute how many cTokens we can borrow, since _liquidity divided by price gives us the amount of cTokens we can borrow.
borrow() - borrower enters market and borrows loan
We are going to build the borrow() function on top of the helper functions we just wrote. Here is the plan:
Step 1: enter market
Step 2: check account liquidity (how much we can borrow in USD)
Step 3: calculate max amount of cTokens that we can borrow
Step 4: borrow 50% of max borrow
Step 1: enter market
Step 2: check account liquidity (how much we can borrow in USD)
Step 3: calculate max amount of cTokens that we can borrow
Step 4: borrow 50% of max borrow
Here is the complete implementation of borrow():
Two utility functions related to borrow:
repay() - borrower repays loan
Repay the borrowed cTokens via CErc20.repayBorrow():
Test
Test case:
Last updated
Was this helpful?
