This tutorial is in continuation of the first part of our DeFi series. In this part, let’s discuss the DeFi lending protocol Compound.
🪙 Full DeFi Course: Click the link to access our free full DeFi course that’ll show you the ins and outs of decentralized finance (DeFi).
Compound
Operated by Compound, it is a popular lending and borrowing platform for various ERC-20 tokens. As per DeFi pulse, Compound has a Total Value Locked (TVL) of $2.56 billion USD.

Operation Model
You can deposit items that can be pledged as collateral for loans through Compound.
Based on your collateral, you are only permitted to borrow up to a particular percentage (about 60–70%). Credit ratings are meaningless, and since Ethereum accounts are anonymous, it is nearly impossible to get payment in the event of a loan default.
As a result, each loan has an additional collateral asset that is not part of the loan being made.
A borrower’s position is liquidated to pay back the loan if their collateralization ratio falls below a predetermined threshold level.
It is important to note that for Compound, the tokens use the letter ‘c’ before the token. E.g. DAI will be cDAI, ETH will be cETH and so on. The lenders and borrowers in Compound are rewarded with COMP tokens (like MKR token in case of MakerDAO).

Compound is an algorithmic, autonomous interest rate protocol that integrates with and underpins a myriad of DeFi systems (other apps built on Compound) such as Dharma, PoolTogether, Argent.
By establishing interest rate marketplaces on Ethereum, Compound enables users to get interest on cryptocurrency they have contributed to the lending pool.
Automatically connecting borrowers and lenders, the Compound smart contract determines interest rates depending on the borrowed-to-supplied asset ratio.
Compound is a perfect example of the exponential opportunity in the DeFi space: as more devices adopt the Compound protocol, more crypto assets will be able to generate income even when dormant.
Yield Farming with Compound
One of the earliest DeFi solutions to offer a governance token was Compound.
The phenomena of DeFi “yield farming,” which is just a trading strategy intended to maximize DeFi platform incentive structures, was introduced by the debut of its COMP coin in June 2020.
🧑🌾 The term “yield farmer” refers to those that provide crypto assets to various DeFi networks for governance tokens. Then, these governance tokens are used in other DeFi dApps, where they might get access to a variety of digital assets and financial instruments or earn interest.
Other DeFi platforms imitated Compound’s model after seeing how well yield farming works to bring in new capital to a system and the increasing value of governance tokens.
Innovators in blockchain governance, such as DeFi solutions and platforms, show that efficient governance need not sacrifice decentralization.
Even while DeFi governance is still developing, the popularity of governance tokens and fair launches indicates that its primary practices will have a long-lasting impact on the blockchain ecosystem.
Compound Borrow
Enough theory, let’s write some code. In this part, we discuss a quick start to borrowing Ethereum assets from the compound protocol using JS code. Ensure you have installed Node.js LTS and npx
.
Clone the repo and cd
to the root directory.
$ git clone https://github.com/compound-developers/compound-borrow-examples.git $ cd compound-borrow-examples/ $ npm install $ npm install -g npx # global install
Create an Infura account at https://infura.io/ and a new project. Note the API INFURA KEY for the project you create for the Ethereum mainnet.
Create a .env
file with the following content:
WEB3_INFURA_PROJECT_ID='INFURA API KEY' export MAINNET_PROVIDER_URL="https://mainnet.infura.io/v3/$WEB3_INFURA_PROJECT_ID" export DEV_ETH_MNEMONIC="clutch captain shoe salt awake harvest setup primary inmate ugly among become"
Source the .env
file and run the hardhat node locally with the below command
$ source .env $ node ./scripts/run-localhost-fork.js
This will seed our first hardhat local account (mnemonic account) with test Ether and ERC20’s.
You should get an output like below (addresses may differ).
$./scripts/run-localhost-fork.jslhost-fork.js Running a hardhat localhost fork of mainnet at http://localhost:8545 Impersonating address on localhost... 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643 Impersonating address on localhost... 0x35a18000230da775cac24873d00ff85bccded550 Impersonating address on localhost... 0x39AA39c021dfbaE8faC545936693aC917d5E7563 Local test account successfully seeded with DAI Local test account successfully seeded with UNI Local test account successfully seeded with USDC DAI amount in first localhost account wallet: 100.00020088272375 UNI amount in first localhost account wallet: 10 USDC amount in first localhost account wallet: 100 Ready to test locally! To exit, hold Ctrl+C.
As you can see in the above terminal when you run the script, the ERC20 tokens DAI, UNI and USDC are automatically credited to the hardhat local account.
Open another terminal (with open new tab option). On this terminal, run the below script to borrow DAI with ETH collateral.
$ source .env $ node examples-js/web3-js/borrow-erc20-with-eth-collateral.js My Wallet's ETH Balance: 10000 My Wallet's cETH Balance: 0 My Wallet's DAI Balance: 100.00020088272375 Supplying ETH to the protocol as collateral (you will get cETH in return)... My Wallet's ETH Balance: 9998.99960067 My Wallet's cETH Balance: 49.82984632 My Wallet's DAI Balance: 100.00020088272375 Entering market (via Comptroller contract) for ETH (as collateral)... Calculating your liquid assets in the protocol...
Fetching cETH collateral factor... Fetching DAI price from the price feed... Fetching borrow rate per block for DAI borrowing... You have 1414.2063374441461 of LIQUID assets (worth of USD) pooled in the protocol. You can borrow up to 82.5% of your TOTAL collateral supplied to the protocol as DAI. 1 DAI == 1.000379 USD You can borrow up to 1413.6705563033072 DAI from the protocol. NEVER borrow near the maximum amount because your account will be instantly liquidated. Your borrowed amount INCREASES (1.0254012296e-8 * borrowed amount) DAI per block. This is based on the current borrow rate. Now attempting to borrow 50 DAI... My Wallet's ETH Balance: 9998.9985743775 My Wallet's cETH Balance: 49.82984632 My Wallet's DAI Balance: 150.00020088272376 Fetching DAI borrow balance from cDAI contract... Borrow balance is 50 DAI This part is when you do something with those borrowed assets! Now repaying the borrow... Approving DAI to be transferred from your wallet to the cDAI contract... Borrow repaid. My Wallet's ETH Balance: 9998.9980410225 My Wallet's cETH Balance: 49.82984632 My Wallet's DAI Balance: 100.00020088272375
Highlights of the above terminal output
- You provide almost 2 ETH as collateral and in return get cETH (49.82984). DAI balance is 100.0002. See the first My Wallet’s balances.
- cETH collateral factor – determines how much a user can borrow. In our case, it is almost up to a maximum of 82.5% (~=1413.67 DAI).
- The script attempts to borrow only 50 DAI based on the borrow rate. The borrow rate is the average current interest rate of the asset they are borrowing and gets updated every Ethereum block. After the borrow is successful, the DAI balance is 150.0002. See the second My Wallet’s balances.
- After some time you repay back the DAI balance, after you make use of your borrowed asset. See the third My Wallet’s balances, the DAI balance restored back to 100.002.
Compound Lending
Similar to borrowing, we discuss a quick start to supplying Ethereum assets from the compound protocol using JS code.
Clone the repo and cd
to the root directory.
git clone https://github.com/compound-developers/compound-supply-examples.git cd compound-supply examples/ npm install
Create a .env
file with the following content (same as above):
WEB3_INFURA_PROJECT_ID='INFURA API KEY' export MAINNET_PROVIDER_URL="https://mainnet.infura.io/v3/$WEB3_INFURA_PROJECT_ID" export DEV_ETH_MNEMONIC="clutch captain shoe salt awake harvest setup primary inmate ugly among become"
Source the .env
file and run the hardhat node locally with the below command
$ source .env $ node ./scripts/run-localhost-fork.js
This will seed our first hardhat local account (mnemonic account) with test Ether and ERC20’s.
You should get an output like below (addresses may differ).
$ node ./scripts/run-localhost-fork.js Running a hardhat localhost fork of mainnet at http://localhost:8545 Impersonating address on localhost... 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643 Impersonating address on localhost... 0x35a18000230da775cac24873d00ff85bccded550 Impersonating address on localhost... 0x39AA39c021dfbaE8faC545936693aC917d5E7563 Local test account successfully seeded with DAI Local test account successfully seeded with UNI Local test account successfully seeded with USDC DAI amount in first localhost account wallet: 100.00020088272375 UNI amount in first localhost account wallet: 10 USDC amount in first localhost account wallet: 100 Ready to test locally! To exit, hold Ctrl+C.
Open another terminal (with open new tab option). On this terminal, run the below script to supply some DAI.
$ node ./examples-js/web3-js/supply-erc20.js My wallet's DAI Token Balance: 100.00020088272375 DAI contract "Approve" operation successful. Supplying DAI to the Compound Protocol... cDAI "Mint" operation successful. DAI supplied to the Compound Protocol: 9.999999999995602 My wallet's cDAI Token Balance: 453.2961167 My wallet's DAI Token Balance: 90.00020088272375 Current exchange rate from cDAI to DAI: 0.02206063460855499 Redeeming the cDAI for DAI... Exchanging all cDAI based on cToken amount... My wallet's cDAI Token Balance: 0 My wallet's DAI Token Balance: 100.00020092079512
Highlights of the above output
- DAI balance is initially 100.0002. After DAI is supplied, we get cDAI in return. The DAI balance is 90.0002 and cDAI is 453.296.
- We redeem back cDAI for DAI and thus the DAI balance is 100.0002, cDAI becomes 0.
❤️ Source: https://github.com/compound-developers/compound-borrow-examples
Summary
In this tutorial, we peeked into the widely used lending and borrowing platform – Compound.
We saw how Compound operates and its use case in Yield farming.
Finally, we also used JavaScript code to borrow and lend the ERC20 assets with compound protocol.
In the upcoming DeFi series posts we shall look into Aave protocol and also using the Solidity code to borrow and lend with compound.