Build a Decentralized Lending App With Compound

Build a Decentralized Lending App With Compound


I remember the excitement I felt when I first heard the idea of Airbnb. People share unused space to travelers who need to have a place to stay.


Now I am feeling the same kind of excitement in the crypto industry. With the Compound protocol, we can share unused crypto assets to borrowers who can make good use of it. The Compound is the crypto equivalent of Airbnb that allows lenders to earn up to 10% in the almost risk-free way.


The goal of this post is to build a simple application that lends SAI and withdraws it with interests. You can see the finished code here.


Before we start coding, I cover the basics of the Compound first. Then we play with some smart contracts in Etherscan which are going to be called in our code.

Note: MakerDAO announced that they call the old Single Collateral DAI SAI and the new Multi-Collateral DAI DAI. Thus, in this post, I call the old Single Collateral DAI SAI.

Compound in a Nutshell

Compound is a decentralized lending protocol on the Ethereum blockchain. Anyone around the world can participate in the protocol.


They create interest rates market for Ethereum tokens and ether. As of November 20, 2019, they have seven markets:

There is a separate lending smart contract for each market. As a lender, you can supply assets to their smart contract and earn interests. As a borrower, you can borrow assets from the reserved assets in the smart contract by depositing some collateral and paying interests.


Neither a lender or a borrower has to specify interest rates. The interest rate is automatically determined by market forces. When the demand to borrow an asset is low, interest rate is low. Conversely, when the demand to borrow an asset is high, interest rate is high. More on this later.


Also, neither a lender or a borrower has to specify a duration. As I mentioned before, the protocol requires borrowers to maintain excess collateral to avoid the risk of a borrower defaulting. Just like MakerDAO, their collateral is subject to liquidation if the price goes below a certain amount.


Traditionally, you’d have to match lenders and borrowers, and then negotiate terms such as interest rate, collateral, and maturity. The Compound reduces the cost of coordinating lenders and borrowers through their reserve system, and reduces the negotiation cost through their automatic interest rates mechanism, pre-defined collateral types, and a duration-free model. As a result, people can lend/borrow tokens much easier and faster.

An Equilibrium Interest Rate Model

Interest rates change dynamically by following the liquidity available in each market, and fluctuate every block based on supply and demand. The less liquidity there is, the higher interest rates are. The more liquidity there is, the lower the interest rates are.


If you look at the Compound dashboard, you can see that interest rates (aka. Annual Percentage Rates) fluctuate. You can also check the Utilization for the liquidity available in each market (see the example of SAI below). The utilization rate is the percentage of total assets being loaned out to borrowers from the liquidity pool. If the utilization rate were 90%10% of SAI is available for withdrawals. Thus, when the utilization rate is high, APR is high. When the utilization rate is low, APR is low.


How do lenders gain interests ex? Let’s take a look at a transaction where somebody supplies SAI to the Compound smart contract. In this transaction, you can see she supplies 7600 SAI. You can also see that she gets about 361,487 cSAI in exchange.

*Ignore the USD value. It’s wrong.
Ignore the USD value. It’s wrong.

cSAI is an ERC20 token that represents your balance including the value of SAI and interests accrued. In Compound, earning interest is as simple as holding this cSAI.


The value of cSAI increases over time as it accumulates interest every Ethereum block. If you want to withdraw SAI, you simply exchange it with your cSAI (cSAI is burned at this point). Then you can get back your SAI with interests.


cSAI is one of cTokens that exists in Compound. Each market has its own cToken like cSAI, cETH, cBAT, etc.


Using ERC20 compliant methods and other methods in cToken contracts, users can supply assets, withdraw them, borrow them, repay a borrow, transfer them, etc.

Play in Etherscan to Understand the Smart Contracts

Next, let’s play with smart contracts in Etherscan to understand some features we are going to build.


We will send some transactions using MetaMask. You need to have some mainnet ETH and SAI. If you have some ETH but not any SAI, go to Uniswap to get some.


There are three steps to supply and then withdraw SAI.

  1. call the approve function in the SAI token contract to give approval to the cSAI contract to transfer some SAI
  2. call the mint function in the cSAI contract to supply some SAI and get some cSAI in exchange
  3. call the redeemUnderlying function in the cSAI contract to exchange my cSAI with SAI

1. the approve function

Go to Etherscan’s SAI token contract page. Click on “Connect to Web3” and log in to MetaMask. Now you can send transactions with MetaMask.


Before supplying SAI, you must first approve the cSAI contract to access your SAI balance. Go to the “Write Contract” tabs. Scroll down to the approve function. Specify the amount of SAI you want to approve.

Make sure you give eighteen 0s. The math in Solidity is fixed-point, and the SAI contract specifies decimals as 18.


Thus, if you want to approve 1SAI, you need to pass:



Click on the Write button and send a transaction. Wait for your transaction to be mined. Add more gas if it is too slow.


Now the cSAI contract should have the approval to transfer 1 SAI on behalf of you.

2. the mint function

Next, go to the cSAI smart contract page. Click on ”Connect to Web3” and log in to MetaMask again.


By supplying your SAI into the cSAI contract with the mint function, you can get some minted cSAI tokens back.



Specify the amount of SAI you want to supply in the mint function.

Click on the Write button and send a transaction.


You should be able to see that 1SAI is subtracted and some cSAI is added from/to your account.

3. the redeemUnderlying function

There are two ways to withdraw your SAI. You can specify the number of SAI or the number of cSAI to exchange with SAI.


The redeemUnderlying function takes the amount of SAI as an argument. The redeem function takes the amount of cSAI. We will use the redeemUnderlying function here for simplicity:



Specify the amount of SAI you want to withdraw in the redeemUnderlying function:

Click on the Write button and send a transaction.


You can see that you returned cSAI and received SAI instead.


You should also be able to see that there is still a tiny amount of cSAI in your account. That’s the interest you accumulated.


All right, let’s get started with our application. Again, we will build a simple JavaScript application that lends and withdraws SAI. You can see this repository for the finished code.


Obtain Your Private Key and Address
First, obtain your private key and address in vanity-eth. Click on the “Generate” button at the bottom. Keep them somewhere for now. Please do NOT use them other than testing purposes. It’s not safe.


Get Some ETH and SAI
Send some ETH and SAI to the address you just obtained. 0.01 ETH should be enough to pay for the gas. I will supply only 1 SAI in this post.

*We will use mainnet cSAI as, unfortunately, it is difficult to get testnet SAI tokens.

Get the Infura Endpoint
We will use Infura as a provider to communicate with the Ethereum network. Make an Infura account and get the endpoint at Mainnet by making a new project. It should look something like this:


Start a New npm Project

*If you don’t have npm and nodejs, install them from here.


Initialize Git


Install the web3 Package

web3 is the Ethereum JavaScript API. It is an interface to Ethereum networks. It communicates with an Ethereum node or transacts with smart contracts deployed on the blockchain from your JavaScript application.


Install the ethereumjs-tx Package

We use ethereumjs-tx to create and sign transactions.


Add Scripts to package.json

mjs is a file extension that allows you to write with ES6 syntax.


Make saiTokenContract.mjs file and cSaiContract.mjs file
You can just copy the files from here and here.


In these files, I am simply declaring and exporting the abi and the address of sai token contract and the cSAI contract.

Implement the Feature to Lend SAI

Now we will start writing code. Let’s start from a lending feature.


We will make two separate files:

  1. approveSaiMain.mjs
  2. supplySaiMain.mjs

1. approveSaiMain.mjs

Make a New File
Make a new file approveSaiMain.mjs.


Import Packages


Import cSaiContract and saiTokenContract


Set Up Web3
Set up Web3 to use Infura as your web3 provider:


Declare Your Address and Private Key Variables


Instantiate the SAI Token Contract
You use the Contract method of web3 with the address and abi to instantiate the SAI token contract.


Now we are ready to call the sai token contract methods.


Declare Const Variables to Pass to the approve Function


You can pass 1 * 10 ** 18 to the second argument of the approve function, but in practice, it’s a common convention to pass -1 so that your users never have to approve again. If you want to understand how this works, read this.


Encode the Abi for the approve Function


Declare the sendSignedTx Function
Make a function to sign a transaction object and then propagate that to an Ethereum network:


Construct a Transaction Object and Then Execute sendSignedTx

Set the gasLimit to 100000. You can change gasPrice if you want to pay less. Check out the current optimal gasPrice in EthGasStation. You can convert its gwei value to wei in Ethereum unit converter.


Run the File

Once you get a transaction hash like this 0xa18d71767ba95b95831fbf3a441494165002bc5f4104afdb0406511ebce7cbe3, you can go to Etherscan to see the detail of your transaction. Below is my transaction as an example. If your transaction doesn’t go through, increase your gasPrice and send another transaction.

You can see that I called the approve function in “Input Data”.

2. supplySaiMain.mjs

I make another file, supplySaiMain.mjs, and call the mint function this time. I am going to skip the detail as most of the code is going to be the same. You can see the finished code in the repo.


Encode the abi of the mint function with the amount of SAI you want to mint.



Pass this ABI to a data property in a transaction object. Also, set the gasLimit to 200000 this time:



Run the file:



You can see that 1SAI is transferred from your account. You can also see that you get some cSAI in exchange.

Implement the Feature to Withdraw SAI

Lastly, we are going to build a feature to withdraw SAI. Again, I am going to skip the detail as most of the code is going to be the same. You can see the finished code here. I make another file, withdrawSaiMain.mjs, and call the redeemUnderlying function this time.


Encode the abi of the redeemUnderlying function with the amount of SAI you want to withdraw.



Pass this ABI to a data property in a transaction object. Also, set the gasLimit to 400000 this time:



Run the file:



You can see that you get your 1SAI back and sent some cSAI back to the cSAI contract.

When you see your cSAI balance, you still have a tiny amount. That’s the interest you accumulated.


We learned that the Compound is a decentralized lending protocol on the Ethereum blockchain that allows everybody in the world to lend or borrow crypto assets with no permission. Since it eliminates the coordination cost and the negotiation cost, it’s much easier and faster to use in comparison to other p2p crypto lending systems that have existed.


We also learned that lending and withdrawing in Compound is as simple as calling three methods in smart contracts. You can integrate this simple app into your dapp or wallet to accelerate the open finance revolution.


I hope now we share the same excitement of the crypto sharing economy.



Taisuke Mino
Crypto Developer
Tai is currently building on a mobile wallet specifically designed for MakerDAO. He is also involved in a dapps game in ICOVO as a software engineer.