Tutorials and Examples: Building a Simple DeFi Lending dApp
This tutorial will walk you through developing a simple decentralized finance (DeFi) lending dApp on JuChain. Users can deposit JU (JuChain’s native token) as collateral, borrow a portion of JU based on that collateral, and retrieve their collateral after repaying the loan. We’ll use Solidity to write the smart contract, leverage JuChain’s EVM compatibility for deployment, and create a frontend for user interaction.
This example highlights JuChain’s near-instant transaction confirmations and ultra-low costs, making it ideal for DeFi use cases.
Tutorial: Simple DeFi Lending dApp
Prerequisites
Development Environment
Node.js: v16 or higher
Truffle Suite: Install via npm install -g truffle
MetaMask: Browser extension, configured for JuChain Testnet
Knowledge: Familiarity with Solidity and Web3.js
JuChain Testnet
Testnet RPC: https://testnet-rpc.juchain.org
Network ID: 202599 (assumed)
Test JU: Obtainable via the JuChain Testnet faucet
Step 1: Set Up the Project
Create and Initialize the Project:
mkdir JuChainLending
cd JuChainLending
truffle init
Install Dependencies:
npm install @openzeppelin/contracts web3
Step 2: Write the Lending Smart Contract
Create LendingPool.sol in the contracts/ folder:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract LendingPool is ReentrancyGuard {
mapping(address => uint256) public collateral; // User's deposited JU collateral
mapping(address => uint256) public borrowed; // User's borrowed JU amount
uint256 public constant LTV = 50; // Loan-to-Value ratio, 50%
uint256 public constant INTEREST_RATE = 5; // 5% interest rate (simplified per repayment)
event Deposited(address indexed user, uint256 amount);
event Borrowed(address indexed user, uint256 amount);
event Repaid(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
constructor() {
// No parameters needed; JU is the native token
}
// Deposit JU as collateral
function depositCollateral() external payable nonReentrant {
require(msg.value > 0, "Amount must be greater than 0");
collateral[msg.sender] += msg.value;
emit Deposited(msg.sender, msg.value);
}
// Borrow JU based on 50% LTV of collateral
function borrow(uint256 amount) external nonReentrant {
require(amount > 0, "Amount must be greater than 0");
uint256 maxBorrow = (collateral[msg.sender] * LTV) / 100;
require(borrowed[msg.sender] + amount <= maxBorrow, "Exceeds max borrowable amount");
borrowed[msg.sender] += amount;
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
emit Borrowed(msg.sender, amount);
}
// Repay loan (including interest)
function repay(uint256 amount) external payable nonReentrant {
require(amount > 0, "Amount must be greater than 0");
require(borrowed[msg.sender] >= amount, "Repay exceeds borrowed amount");
uint256 interest = (amount * INTEREST_RATE) / 100;
uint256 totalRepay = amount + interest;
require(msg.value >= totalRepay, "Insufficient payment");
borrowed[msg.sender] -= amount;
emit Repaid(msg.sender, amount);
// Refund excess JU
if (msg.value > totalRepay) {
(bool success, ) = msg.sender.call{value: msg.value - totalRepay}("");
require(success, "Refund failed");
}
}
// Withdraw collateral (after repaying all loans)
function withdrawCollateral(uint256 amount) external nonReentrant {
require(amount > 0, "Amount must be greater than 0");
require(collateral[msg.sender] >= amount, "Insufficient collateral");
require(borrowed[msg.sender] == 0, "Must repay all loans first");
collateral[msg.sender] -= amount;
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
emit Withdrawn(msg.sender, amount);
}
// View user status
function getUserStatus(address user) external view returns (uint256, uint256, uint256) {
uint256 maxBorrow = (collateral[user] * LTV) / 100;
return (collateral[user], borrowed[user], maxBorrow);
}
}
Functionality Explained:
depositCollateral(): Users send JU (native token) as collateral.
borrow(uint256 amount): Borrow up to 50% of collateral’s value in JU.
repay(uint256 amount): Repay the loan with 5% interest; excess JU is refunded.
withdrawCollateral(uint256 amount): Retrieve collateral after full repayment.
getUserStatus(address user): Returns collateral, borrowed amount, and max borrowable JU.
Security: Uses ReentrancyGuard to prevent reentrancy attacks.
Note: JU is JuChain’s native token, handled via msg.value and call, not an ERC20 token.
Step 3: Configure Truffle
Edit truffle-config.js to connect to the JuChain Testnet:
ABI: Copy the full ABI from build/contracts/LendingPool.json and replace the abi variable.
Contract Address: Update contractAddress with the address from Step 4.
Run: Serve index.html with a local server (e.g., npx http-server) and connect via MetaMask on the JuChain Testnet.
Step 7: Run and Test
Switch MetaMask to the JuChain Testnet and ensure sufficient test JU is available.
Open index.html in a browser and test:
Deposit Collateral: Enter 100 JU and click "Deposit Collateral".
Borrow JU: Enter 50 JU and click "Borrow JU".
Repay Loan: Enter 50 JU and click "Repay Loan" (includes 5% interest, total 52.5 JU).
Withdraw Collateral: Enter 100 JU and click "Withdraw Collateral".
JuChain’s near-instant confirmations ensure transactions complete in seconds, with fees typically below 0.001 JU.
Outcome
You’ve built and deployed a simple DeFi lending dApp:
Users can deposit JU as collateral.
Borrow up to 50% of their collateral’s value in JU.
Repay loans with 5% interest to reclaim collateral.
The frontend displays collateral, borrowed amounts, and max borrowable JU in real-time.
This dApp demonstrates JuChain’s high-performance infrastructure, perfect for scaling into more complex DeFi applications (e.g., multi-asset support or dynamic rates).
Notes
Security:
For production, add liquidation mechanisms (to handle undercollateralization) and conduct a code audit.
The current contract doesn’t address edge cases (e.g., insufficient JU balance).
Testnet:
Ensure your account has enough test JU for interactions.
Scalability:
Enhance with time-based interest calculations or additional asset support as needed.