Implementing a Decentralized Finance (DeFi) Application with Web3.js

Decentralized Finance (DeFi) applications leverage blockchain technology to provide financial services without intermediaries. In this guide, we will outline the steps to create a simple DeFi lending application using Web3.js and Solidity.

1. Prerequisites

Before you begin, ensure you have the following:

  • Node.js and npm installed on your machine
  • A local Ethereum node or access to a test network (e.g., Ganache)
  • Basic understanding of Solidity and JavaScript

2. Set Up Your Project

Create a new project directory and initialize it:

mkdir defi-app
cd defi-app
npm init -y

3. Install Web3.js

Install the Web3.js library using npm:

npm install web3

4. Create the Smart Contract

For this example, we will create a simple lending platform smart contract. Below is the Solidity code for the contract:

pragma solidity ^0.8.0;
contract LendingPlatform {
mapping(address => uint) public balances;
mapping(address => uint) public depositTimestamps;
uint public interestRate = 1; // 1% interest rate per day
function deposit() public payable {
balances[msg.sender] += msg.value;
depositTimestamps[msg.sender] = block.timestamp;
}
function withdraw() public {
uint depositTimestamp = depositTimestamps[msg.sender];
uint depositAmount = balances[msg.sender];
require(depositAmount > 0, `No deposit to withdraw`);
uint elapsedTime = (block.timestamp - depositTimestamp) / 1 days;
uint interest = (depositAmount * interestRate * elapsedTime) / 100;
balances[msg.sender] = 0;
depositTimestamps[msg.sender] = 0;
payable(msg.sender).transfer(depositAmount + interest);
}
}

Deploy this contract using Remix IDE or Truffle to your local Ethereum node or a test network.

5. Create the Frontend

Create an index.html file in your project directory:

<!DOCTYPE html>
<html lang=`en`>
<head>
<meta charset=`UTF-8`>
<meta name=`viewport` content=`width=device-width, initial-scale=1.0`>
<title>DeFi Lending App</title>
<script src=`https://cdn.jsdelivr.net/npm/web3/dist/web3.min.js`></script>
<script src=`app.js`></script>
</head>
<body>
<h1>DeFi Lending Platform</h1>
<input type=`text` id=`depositAmount` placeholder=`Deposit Amount (ETH)`>
<button id=`depositButton`>Deposit</button>
<button id=`withdrawButton`>Withdraw</button>
<p id=`statusMessage`></p>
</body>
</html>

6. Create the JavaScript File

Create an app.js file in your project directory:

const Web3 = require('web3');
// Connect to your local Ethereum node or test network
const web3 = new Web3('http://localhost:8545'); // Change to your node URL
// Replace with your deployed contract address
const contractAddress = '0xYourContractAddress';
// ABI of the LendingPlatform contract
const contractABI = [
{
`inputs`: [],
`name`: `deposit`,
`outputs`: [],
`stateMutability`: `payable`,
`type`: `function`
},
{
`inputs`: [],
`name`: `withdraw`,
`outputs`: [],
`stateMutability`: `nonpayable`,
`type`: `function`
}
];
// Create contract instance
const lendingPlatform = new web3.eth.Contract(contractABI, contractAddress);
// Function to deposit Ether
async function deposit() {
const accounts = await web3.eth.getAccounts();
const amount = web3.utils.toWei(document.getElementById('depositAmount').value, 'ether');
await lendingPlatform.methods.deposit().send({ from: accounts[0], value: amount });
document.getElementById(' statusMessage').innerText = 'Deposit successful!';
}
// Function to withdraw Ether
async function withdraw() {
const accounts = await web3.eth.getAccounts();
await lendingPlatform.methods.withdraw().send({ from: accounts[0] });
document.getElementById('statusMessage').innerText = 'Withdrawal successful!';
}
// Add event listeners
document.getElementById('depositButton').addEventListener('click', deposit);
document.getElementById('withdrawButton').addEventListener('click', withdraw);

7. Run Your DeFi Application

To run your DeFi application, you can use a simple HTTP server. If you have Python installed, you can run:

python -m http.server 8000

Then, open your browser and navigate to http://localhost:8000 to interact with your DeFi application.

8. Conclusion

By following these steps, you can create a simple decentralized finance application using Web3.js. This DeFi application allows users to deposit and withdraw Ether while earning interest, showcasing the potential of decentralized financial services.