Building a Pool-Based Lending Protocol on Agoric: A Guide to DeFi Application Development
At , we have dedicated significant resources to blockchain development across various frameworks. This article delves into the pool-based lending protocol we have developed on , a platform that brings JavaScript developers into the decentralised finance (DeFi) space.
What is Agoric?
is a blockchain platform operating within the network, facilitating communication with other networks via the IBC (Inter-Blockchain Communication) .
Its primary innovation lies in enabling over 10 million JavaScript developers to engage in DeFi application development without compromising security. Agoric achieves this through its specialised JavaScript framework, which includes:
Hardened JavaScript: Enhanced security for smart contract development.
Eventual Send with E(): Asynchronous message passing for robust applications.
Far(), Remotable, and Marshaling: Secure object communication.
Notifiers and Subscriptions: Reactive programming for real-time updates.
A notable concept within Agoric is the , a software component with its own message queue, call stack, and object heap, akin to the event loop concurrency model in web browsers and Node.js. VATs facilitate process isolation and enforce , which are central to Agoric's security model.
For a deeper understanding of Agoric's approach to secure distributed programming, refer to the .
The Evolution of Lending and Borrowing
Lending and borrowing have always been integral to the global economy, traditionally managed by banks. With the advent of Web3 and blockchain technologies, decentralised protocols now offer alternatives, reducing reliance on traditional financial institutions.
The Role of Compound Finance in Pool-Based Lending
is a pioneering pool-based lending protocol on the Ethereum network, boasting nearly $4 billion in locked assets and approximately $1 billion in loans at the time of writing.
How Does Compound Finance Work?
In Compound Finance, users can either supply liquidity to pools or borrow assets.
1. Supply Assets
Users deposit assets into pools and receive cTokens in return (e.g., cETH for ETH). These cTokens can later be redeemed for the original asset. Key incentives for supplying liquidity include:
Earning Interest: Interest accrues per block, increasing over time.
COMP Governance Tokens: Users earn COMP tokens, which can be traded or used for governance voting.
2. Borrow Assets
In decentralised protocols like Compound, borrowing is different from traditional bank loans. Banks typically ask personal questions to assess risk, such as:
Have you repaid previous debts?
However, decentralised protocols don't ask these questions. So, how do they avoid bankruptcy when lending to anyone willing to pay interest? The answer is over-collateralisation.
There are two main types of collateralisation:
Under-collateralisation: The collateral value is less than the loan amount. For example, with a 30% collateralisation factor, you’d need to provide £30 to borrow £100. This is a more traditional approach.
Over-collateralisation: The collateral must exceed the loan value. For instance, with £100 collateral and an 80% collateralisation factor, you can borrow £80. This ensures the lender is covered even if the borrower defaults.
Over-Collateralised Debt and Liquidation
Liquidation occurs when the collateral is sold to cover the debt if the borrower defaults. If the borrower’s debt exceeds the collateral’s value, liquidation is triggered to secure the lender’s funds.
<u>An example of liquidation</u>: If you have £100 in collateral and borrow £78, liquidation occurs once the debt exceeds £80. As interest builds, the debt reaches £80, triggering liquidation. The protocol then sells the collateral to settle the debt.
Strategies for Selling Collateral
While Compound uses the second method for decentralisation, our protocol will use the first, as Agoric has its own native AMM.
3. Dynamic Rates
Compound Finance adjusts rates dynamically based on market conditions to ensure liquidity and balance. Rates include:
Utilisation Ratio

Borrow Rate

Exchange Rate

These rates help balance supply and demand, ensuring the market remains liquid.
You can take a look at the markets listed in the Compound protocol if you wish to see how these variables are used in real life.
For more information, check the Compound Whitepaper.
For the implementation, see the Compound Protocol Repository on GitHub.
Implementing a Pool-Based Lending Protocol on Agoric
With this context, let us explore our adaptation of a pool-based lending protocol on Agoric. Before proceeding, ensure familiarity with the following prerequisites:
ERTP: Agoric's framework for digital assets or tokens.
Zoe: A smart contract development framework that safeguards users' assets from bugs and malicious code.
Agoric Offers: The basic logic used when interacting with contracts.
Agoric Native AMM: An Automated Market Maker for trading various tokens, including those imported via IBC.
PriceAuthority: An interface between Zoe and price oracles.
For a comprehensive roadmap and additional information, refer to this .
Overview of the Protocol
The complete code for this protocol is available in this repository. Users can perform five main operations within our protocol:
Functionality for these operations is distributed among multiple components. An high level overview of protocol components can be found below.
Key Modules of the Protocol
LendingPool: Entry point directing users to the correct pools after necessary checks. See the code.
PoolManager: Manages pools for specific assets (e.g., VAN Pool for VAN token), storing underlying assets, minting protocol tokens (e.g., AgVAN), and handling deposits, borrowing, and redemptions. See the code.
PriceManager: Central hub for managing multiple price authorities used by the protocol. See the code.
ProtocolMath: Implements key financial formulas, including exchange rate, utilisation ratio, and borrow rate. See the code.
DebtsPerCollateral: Groups loans with the same collateral and debt type, ensuring consistent responses to market changes, such as liquidation triggers. See the code.
Loan: Core module for loan management, enabling balance adjustments, loan closures, and dapp notifications. See the code.
LiquidationObserver: Monitors price changes and initiates liquidation if loans become undercollateralised. See the code.
A simple but powerful example of an interaction with our protocol can be the scenario where a user deposits money into a pool. The diagram below can help you understand what an end-to-end interaction would look like.
Setup And Deploy Your Environment
Ensure you have the following prerequisites to build and use the agoric-sdk:
Linux shell or equivalent
Node.js (LTS version >= 14.x.x)
1. Install agoric-sdk
We first need to clone the source code and build it in our local environment. A more detailed explanation about installation can be found in the , we're just going over this briefly here.
<u>Clone the agoric-sdk repo and build it locally</u>:
git clone https://github.com/Agoric/agoric-sdk.git
cd agoric-sdk
git checkout beta
git pull
<u>Install dependencies</u>:
yarn install
<u>Add agoric binary to the path</u>:
yarn link-cli ~/bin/agoric
<u>Check the version</u>:
agoric --version
Our protocol is built on the agoric-sdk beta branch so the version should be 0.15.0
2. Startup The Dapp
<u>Get the code and checkout the blog/bytepitch branch</u>:
git clone https://github.com/anilhelvaci/dapp-pool-lending-protocol.git
cd dapp-pool-lending-protocol
git checkout blog/bytepitch
git pull
<u>Start a simulated chain</u>:
In Agoric there are two types of local test chains; a sim-chain and a local-chain. A sim-chain, simulated chain, is where we can test our dapps and contracts but there's no transaction cost. So it's simulated, not real. On the other hand there's a local-chain which is based on the cosmos-sdk, therefore it's based on GoLang. Starting a local-chain requires building some go packages. If you plan to test with multiple clients interacting with the same chain, local-chain is the way to go. Check for further information.
<u>Go to dapp folder and start the sim-chain</u>:
cd dapp-pool-lending-protocol
agoric start --verbose --reset
For Agoric CLI reference, check .
<u>Leave that terminal running and open a new one</u>:
cd dapp-pool-lending-protocol
agoric deploy contract/deploy/deploy.js api/deploy.js
Deployment Details:
The agoric deploy command accepts multiple scripts:
contract/deploy/deploy.js: Sets up the environment (AMM, price authorities, etc.) and starts the LendingPool contract.
api/deploy.js: Requests test tokens and adds liquidity to the pools, bootstrapping the protocol.
<u>Once the deployment is done, start your wallet ui</u>:
agoric open --repl
This command should open a browser automatically. <u>Then, open a new terminal and start the client ui</u>:
cd dapp-pool-lending-protocol/ui
yarn start
Interact With The Dapp: A Step-by-Step Guide
To interact with the dapp, approve it in your wallet and visit localhost:3000. You should be able to see something like this below.
Markets & Activity Tabs:
Markets: Displays general market data and enables you to Supply or Borrow money from a selected pool.
Activity: Shows the user’s activity such as deposited assets and borrows. Also enables the user Redeem, Close or Adjust Loan.
The screenshot above is from the Markets tab. Here's a quick explanation of the data:
APY: Annual Percentage Yield represents the interest paid on debt and earned on supplied assets. In our protocol, the Supply and Borrow APYs are the same since we don’t use a ReserveFactor.
MMR: Minimum Margin Requirement is the ratio between collateral and debt value. For example, with $150 collateral, you can borrow up to $100.
If you switch to the Activity tab, you'll see:
There, you’ll find a list of supplied and borrowed assets for each pool.
The protocol is pre-bootstrapped with liquidity, so the deposits section isn’t empty.
Next, we'll walk through a full scenario where the user's journey is:
Depositing funds into a pool.
Borrowing from another pool using protocol tokens as collateral.
Adjusting the loan by repaying part of the debt.
Closing the loan by repaying in full and reclaiming collateral.
Redeeming the initial deposit.
1. Deposit Money
You might notice that the numbers you see in supply screenshots is inconsistent with rest of the screenshots, that's because I took them out of sync from the rest of the sequence.
Click on VAN market and below dialog should open:
Here, enter the amount you wish to supply and the protocol token you'll receive automatically be calculated, you can also specify slippage rate to protect your transaction from the sudden price changes of the market.
Then go to your wallet and approve the offer below:
Click Approve. Then, wait for the numbers in the purses change. Here, we should care about VAN and AgVAN Purses.
2. Borrow Money
Let's borrow some VAN. Click on VAN market and switch to the Borrow tab in the dialog. Then, enter how much you want to borrow:
Go to your wallet and approve the transaction once you hit Borrow:
You can see that TotalBorrow for the VAN market is now increased, TotalSupply is decreased and APY is increased, as there's less liquidity in the pool, so the value of money is increased. Also, you can see that TotalBorrow for the user in profile is now $110.
You can now view your loans in the Activity tab;
Notice that the exchange rate did not change because there's no interest accrued yet. So let's accrue some interest.
From the below screenshot, you should notice that total borrows for both market and user profile is increased and also the exchange rate for VAN market is also increased.
You can also see that the current debt for the loan is increased in Activity tab;
3. Adjust Loan
Let's pay some of our debt now. Go to Activity tab and click on your loan. From the dialog opened, switch to Adjust tab. From this dialog you can also request some of your collateral, but here we'll just pay some of our debt.
Again, go to your wallet and approve the below transaction:
In the Activity tab, you can see that the Borrow Balance for your loan is decreased and % Of Limit is also updated:
4. Close Loan
Now, let's close our loan by paying all the remaining debt receiving the collateral we first put. Go to Close tab in the loan dialog:
Go to your wallet approve the transaction below:
In the Activity tab, you can see that your loan is gone and your Total Borrow is now $0;
5. Redeem Your Money
Now, click on your VAN deposit on the left side of Activity dialog. The dialog below should pop:
Now, go to your wallet and approve the transaction:
Conclusion
In this article, we explored key concepts and practical implementations related to Agoric and pool-based lending protocols. We covered:
What Agoric is, how it works, and how to develop with it.
How to build a smart contract using Agoric.
The fundamentals of a pool-based lending protocol and its most well-known implementation, Compound Finance.
Our approach to implementing a pool-based lending protocol.
A step-by-step user journey, from depositing funds to repaying loans.
Real-world applications in blockchain, DeFi, DApp development, Web3, Ethereum, smart contracts, and blockchain protocols.
We hope this guide provided valuable insights into building decentralised financial solutions. Feel free to share your thoughts, feedback, or questions in this .
If you're looking to integrate blockchain technology into your business or need expert guidance, connect with us .