βœ…Supply and Redeem

Intro

Supply and Redeem

TestCompoundErc20.sol provides the following 4 functionalities:

  • supply() (lender deposits collateral)

  • redeem() (lender withdraws collateral)

  • borrow() (borrower enters market and borrows loan)

  • repay() (borrower pays back loan)

In this section we are going to implement the lender's functions supply and redeem. The sample code is here:

TestCompoundErc20.sol

Setup

In the constructor, we initialize the ERC20 token that we wish to use as collateral and cToken contract address:

supply() - lender deposits collateral

Lender calls supply(uint _amount) to deposit ERC20 token as collateral and get cToken back as "receipt token":

When calling cToken.mint(), the ERC20 token in this contract will be transferred to the cToken contract via transferFrom(). This is why we have to do token.approve() first.

redeem() - lender withdraws collateral

This function is the opposite of supply(). Lender calls redeem() to burn cToken and get ERC20 token back (interest is included in cToken price):

This is just a wrapper that calls cToken.redeem().

Utility Functions

We need a getter to query cToken balance:

Query exchange rate and supply rate:

We can estimate underlying asset balance by the formula cTokenBal * exchangeRate. And figure out some messy decimals things:

Official API for querying underlying asset balance:

Tests

test-compound-erc20.js

In the setup, we create a whale user with each WBTC to run this demo:

Create a function snapshot() that logs current states:

Test case:

Last updated

Was this helpful?