π DeFiPlex is a comprehensive decentralized finance (DeFi) platform built on the Polygon blockchain, a Layer 2 scaling solution for Polygon. It aims to facilitate a wide array of decentralized financial activities, making it accessible and efficient for users across the globe. Whether users are looking to stake their assets to earn rewards, participate in decentralized lending and borrowing markets, or engage in community-driven governance decisions, DeFiPlex provides a seamless and secure environment.
π Powered by smart contracts, DeFiPlex ensures unparalleled transparency by executing transactions in a trustless manner, thereby eliminating the need for intermediaries. Security is paramount, with robust protocols and audits in place to safeguard user funds and maintain the integrity of the platform.
For comprehensive information about this project, check out this Medium article.
-
π Staking: Users can stake their tokens in DeFiPlex to earn rewards, securing the network and earning passive income based on their stake amount and duration.
-
π° Reward Distribution: DeFiPlex distributes rewards to users who stake their tokens. Rewards are calculated based on the staked amount and duration, available for periodic claiming.
-
πΈ Lending and Borrowing: The platform allows users to lend and borrow assets directly, earning interest by lending assets or paying interest to borrow assets, thereby creating a decentralized money market.
-
π³οΈ Governance: DeFiPlex incorporates a robust decentralized governance framework empowering token holders to actively participate in decision-making, including loan approval processes. The community votes on key proposals related to loan approvals, ensuring transparent and democratic decision-making reflecting the collective interests of platform users.
-
π Staking Contract: Manages token deposits, tracks user balances, calculates staking rewards, and facilitates reward claims.
-
π Lending Pool Contract: Enables lending and borrowing functionalities, manages loan requests, and ensures loan repayment mechanisms.
-
π Governance Token (FlexTokenERC20Contract): Implements the governance token used for voting and decision-making within the platform.
-
π Governance Contract (DefiFlexGovernanceContract): Facilitates governance processes by managing proposals and ensuring transparent voting mechanisms. It requires a minimum threshold of votes over a specified voting period for loan approvals, ensuring community consensus.
Complete UML diagram of decentralized application design.
The DeFiPlex governance system plays a crucial role in loan approval processes. Here are its key components:
-
Proposal Creation: π Users can create loan proposals detailing loan conditions, terms, and collateral requirements.
-
Voting: π³οΈ Token holders participate in governance by voting on submitted loan proposals. Each token represents one vote, encouraging active participation and stakeholder engagement.
-
Threshold Requirements: π Loan proposals must meet a minimum threshold of votes during a specified voting period to be approved. This ensures robust community backing and consensus before final approval.
-
Execution: π Once a loan proposal meets the voting requirements, it is automatically executed via smart contracts. This includes disbursing loan funds and implementing agreed-upon terms.
-
π Auditing: All smart contracts undergo rigorous audits conducted by reputable security firms to ensure robustness and protection against vulnerabilities.
-
π Access Control: Critical parameters such as reward rates are securely controlled, with restricted access limited to authorized entities only.
-
π§ͺ Testing: Comprehensive testing is conducted on testnets prior to mainnet deployment to validate contract functionality and security measures.
DeFiPlex is committed to providing a secure and versatile platform for decentralized financial activities. By leveraging smart contracts and the Polygon blockchain, DeFiPlex offers a transparent and efficient way to engage in staking, lending, borrowing, and governance processes.
DeFiPlex leverages a robust technology stack to ensure scalability, security, and efficiency across its decentralized finance platform:
-
π οΈ Polygon Blockchain: DeFiPlex is built on the Polygon blockchain, benefiting from its high throughput, low transaction fees, and interoperability with Polygon.
-
π» Solidity: Smart contracts in DeFiPlex are written in Solidity, the predominant programming language for Polygon-compatible blockchains, ensuring compatibility and reliability.
-
π¦ OpenZeppelin: OpenZeppelin's library is extensively used for secure and standardized smart contract components. It provides tested and audited implementations of ERC standards and contract functionalities, enhancing security and reliability.
-
βοΈ Hardhat: Hardhat serves as the development environment for DeFiPlex, facilitating tasks such as compiling, testing, and deploying smart contracts. It supports a wide range of plugins and tools essential for robust contract development and deployment.
Polygon provides a scalable and Polygon-compatible platform that enhances transaction speeds and reduces costs compared to the Polygon mainnet. DeFiPlex leverages Polygonβs Layer 2 solutions to ensure fast transaction finality and a seamless user experience.
Solidity is the programming language of choice for developing smart contracts on Polygon and compatible blockchains. It enables developers to write secure and efficient contracts, ensuring compatibility with the broader Polygon ecosystem and facilitating seamless integration with decentralized applications (dApps).
OpenZeppelin is a library of reusable and secure smart contract components widely adopted within the blockchain community. DeFiPlex utilizes OpenZeppelin's tested implementations of ERC standards and contract functionalities to enhance security and mitigate potential vulnerabilities.
Hardhat is a popular development environment tailored for Polygon smart contract development. It offers built-in support for tasks such as compiling, testing, debugging, and deploying smart contracts, streamlining the development lifecycle and ensuring the reliability of deployed contracts.
The technology stack behind DeFiPlex underscores its commitment to delivering a secure, scalable, and efficient decentralized finance platform. By leveraging Polygon's blockchain, Solidity smart contracts, OpenZeppelin's library, and the Hardhat development environment, DeFiPlex ensures robustness, security, and interoperability while offering a seamless user experience for staking, lending, borrowing, and governance activities.
The DeFiPlex Staking Contract allows users to stake multiple ERC20 tokens and earn rewards over time.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IDeFiPlexStakingContract.sol";
/**
* @title DeFiPlex Staking Contract
* @dev A contract that allows users to stake multiple ERC20 tokens and earn rewards over time.
*/
contract DeFiPlexStakingContract is Ownable, IDeFiPlexStakingContract {
using SafeERC20 for IERC20;
// Contract implementation
}
- Stake Tokens: Users can stake ERC20 tokens into the contract to earn rewards based on predefined rates.
- Withdraw Tokens: Users can withdraw their staked tokens at any time, which updates their earned rewards.
- Claim Rewards: Users can claim accumulated rewards periodically for each staked token.
- Manage Reward Rates: Admins can set and update reward rates for each staking token.
- Authorization Mechanism: Provides functionality to authorize specific addresses for token transfers.
StakingTokenAdded(_stakingTokenAddress, _rewardRate)
: Fired when a new staking token is successfully added.Staked(user, amount)
: Indicates when a user stakes tokens into the contract.Withdrawn(user, amount)
: Indicates when a user withdraws tokens from the contract.RewardClaimed(user, amount)
: Fired when a user claims their accumulated rewards.
The contract includes mechanisms for secure staking and rewards distribution, ensuring transparency and integrity through blockchain technology.
This contract manages lending and borrowing functionalities within the DeFiPlex platform. It allows users to request loans, approve loans, and repay loans. Additionally, it handles collateral management and penalties for late repayments.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IDeFiPlexLendingPoolContract.sol";
import "./IDeFiPlexGovernanceContract.sol";
import "./IDeFiPlexStakingContract.sol";
/**
* @title DeFiPlexLendingPoolContract
* @dev This contract handles the lending and borrowing functionalities within the DeFiPlex platform.
* It allows users to request loans, approve loans, and repay loans. Additionally, it manages collateral and penalties for late repayment.
*/
contract DeFiPlexLendingPoolContract is Ownable, IDeFiPlexLendingPoolContract {
using SafeERC20 for IERC20;
// Contract implementation
}
-
Request Loan (
requestLoan
) π:- Allows users to request a new loan by specifying the borrow token, amount, collateral token, collateral amount, interest rate, and duration.
- Validates input parameters to ensure they meet specified requirements.
-
Approve Loan (
approveLoan
) β :- Enables the contract owner to approve a loan after verifying collateral availability and governance approval.
- Transfers collateral from the borrower to the contract, secures it, and transfers borrowed tokens to the borrower.
- Records approval and sets penalty start time based on loan duration.
-
Repay Loan (
repayLoan
) β°:- Allows borrowers to repay their loans, including interest and any applicable late repayment penalties.
- Validates borrower identity, loan collateralization status, repayment timing, and calculates repayment amounts including penalties.
-
Set Penalty Rate (
setPenaltyRate
)β οΈ :- Allows the contract owner to set the penalty rate for late loan repayments.
-
Loan Information (
getLoan
,getLoanCount
,getBorrowerLoans
) π:- Provides functions to retrieve loan details, total loan count, and borrower-specific loan indices for transparency and auditing purposes.
- Ownable: Provides ownership control functionalities.
- SafeERC20: Safely handles ERC20 token transfers to prevent common vulnerabilities.
- IDeFiPlexLendingPoolContract: Interface for external interactions related to lending pools.
- IDeFiPlexGovernanceContract: Interface for governance-related operations.
- IDeFiPlexStakingContract: Interface for staking-related operations.
This contract manages governance proposals for the DeFiPlex platform. It facilitates the creation, voting, and execution of proposals related to loans within the ecosystem.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./DeFiPlexGovernanceTokenContract.sol";
import "./IDeFiPlexGovernanceContract.sol";
/**
* @title DeFiPlexGovernanceContract
* @dev This contract manages governance proposals for DeFiPlex platform.
*/
contract DeFiPlexGovernanceContract is Ownable, IDeFiPlexGovernanceContract {
// Contract implementation
}
-
Propose Loan Request (
proposeLoanRequest
) π:- Allows any address to propose a new loan request.
- Initiates a voting period during which token holders can vote on the proposal.
-
Vote on Proposal (
vote
) π³οΈ:- Enables token holders to vote either in favor of or against a loan proposal.
- Votes are weighted by the token balance held by the voter.
-
Check Proposal Approval Status (
checkProposalApprovalStatus
) β :- Determines whether a loan proposal has met the criteria for approval.
- Conditions include surpassing the minimum required votes and having no votes against the proposal.
-
Adjust Voting Parameters (
setMinimumVotesRequired
,setVotingPeriod
) βοΈ:- Allows the contract owner to set the minimum votes required for proposal approval and adjust the duration of the voting period.
-
Get Proposal Details (
getProposalDetails
) π:- Provides access to detailed information about a specific loan proposal, including its initiator, voting period, and current voting status.
- Ownable: Manages ownership and access control over contract functionalities.
- DeFiPlexGovernanceTokenContract: Interface to interact with the governance token for voting rights.
- IDeFiPlexGovernanceContract: Interface defining the standard functions for governance contracts.
First, clone the repository:
git clone https://github.com/sergio11/defiplex_blockchain.git
cd defiplex_blockchain
Install the necessary dependencies:
npm install
Deploying the DeFiPlex smart contracts is a straightforward process using Hardhat Ignition*. This tool simplifies the deployment process, allowing you to deploy your contracts with ease and confidence. Below is a step-by-step guide to deploying the DeFiPlex contracts to your specified network.
Use the following command to deploy the contracts to the specified network (in this case, Polygon amoy):
npx hardhat ignition deploy ignition/modules/DefiPlex.js --network amoy
Deploying your DeFiPlex contracts with Hardhat Ignition ensures a smooth, efficient, and error-free process, paving the way for a robust and transparent DeFi system.
β Confirm deploy to network amoy (80002)? ... yes
Hardhat Ignition π
Resuming existing deployment from .\ignition\deployments\chain-80002
Deploying [ DeFiPlex ]
Batch #1
Executed DeFiPlex#DeFiPlexLendingPoolContract
[ DeFiPlex ] successfully deployed π
Deployed Addresses
DeFiPlex#DeFiPlexGovernanceTokenContract - 0x8A53E585c5c19b78b03d215a978BAa74f81EE08B
DeFiPlex#PlexTokenERC20Contract - 0xe75457AeFa4D367DFc5495112a60178A8e2A0243
DeFiPlex#DeFiPlexGovernanceContract - 0xbD3a29C9C39E13D4307a9E153468481f63dD606e
DeFiPlex#DeFiPlexStakingContract - 0x7a820E12b5C357f63984dBf9a7b3d17bE1114857
DeFiPlex#DeFiPlexLendingPoolContract - 0xB1D55F4Dfc46905f43A424656584351445956009
Testing is a critical part of the development process for ensuring that our smart contracts function correctly and securely. The DeFiPlex project includes comprehensive test suites for all the contracts. These tests cover a wide range of scenarios to ensure robustness and reliability.
To run the tests, use the following command:
npx hardhat test
This command will execute all the test scripts located in the test directory, and you should see output similar to the following:
DeFiPlexGovernanceContract
β Should deploy the contract correctly
β Should allow setting minimum votes required
β Should allow setting voting period
β Should propose a loan request
β Should vote on a proposal
β Should not approve a proposal if criteria are not met
β Should approve a proposal if criteria are met
β Should not approve a proposal if there are votes against it
β Should revert on trying to vote on non-existent proposal (38ms)
β Should revert on trying to propose with same ID
β Should revert when user tries to vote again
β Should revert when user tries to vote outside voting period
β Should retrieve correct details of a loan proposal
DeFiPlexLendingPoolContract
Loan Requests
β Should allow users to request a loan
β Should revert if loan amount is zero
β Should revert if interest rate is zero
β Should revert if collateral amount is zero
β Should revert if duration is zero
Loan Queries
β Should return borrower loans correctly
β Should revert if no loans found for borrower
β Should return loan details correctly
β Should revert if loan index is out of bounds
Loan Approval
β Should be rejected because insufficient borrow token amount in lending pool
β Should be rejected because borrower does not have enough collateral tokens
β Should be rejected because collateral already collected
β Should be rejected because the loan proposal has not been approved by governance
β Should be approved successfully
Loan Repayment
β Should be rejected because the loan duration not expired yet
β Should be repay successfuly
β Should be rejected because loan is already repaid
β Should be rejected because Only the borrower can repay the loan
β Should be repay successfuly penalty (45ms)
DeFiPlexStakingContract
β Should set the right owner
Adding Staking Tokens
β Should allow the owner to add staking tokens
β Should not allow non-owners to add staking tokens
β Should not allow adding the same staking token more than once
β Should revert when adding a staking token with a reward rate of zero
β Should correctly store staking token info after adding
β Should emit StakingTokenAdded event when a new staking token is added
β Should revert if trying to add a staking token with a non-contract address
β Should not allow adding staking tokens with extremely high reward rates
Staking Tokens
β Should allow users to stake tokens
β Should not allow staking zero tokens
β Should allow multiple users to stake tokens
β Should not allow staking more tokens than available
β Should allow stake and withdraw tokens
β Should revert if user tries to withdraw more than staked
β Should revert if contract has insufficient funds for withdrawal
Withdrawing Tokens
β Should allow users to withdraw all staked tokens
β Should not allow withdrawing more tokens than staked
β Should allow withdrawing tokens and update rewards
β Should allow withdrawing tokens and update rewards 2
Claiming Rewards
β Should allow users to claim rewards
β Should update user reward after claiming
β Should not allow claiming zero rewards
β Should not affect staked balance after claiming rewards
β Should revert if user tries to claim rewards with no staked tokens
β Should revert if user tries to claim rewards with no rewards available
Setting Reward Rate
β Should allow the owner to set the reward rate
β Should not allow non-owners to set the reward rate
Getting Information
β Should return the correct total supply
β Should return the correct balance of user
β Should return the correct earned rewards
β Should return the correct total rewards accumulated
PlexTokenERC20Contract
Deployment
β Should set the right owner
β Should assign the initial supply to the owner
Minting
β Should allow the owner to mint tokens
β Should not allow non-owners to mint tokens
Burning
β Should allow users to burn their tokens
MultiTransfer
β Should allow the owner to transfer tokens to multiple addresses
β Should not allow non-owners to execute multiTransfer
β Should revert if arrays length mismatch
72 passing (9s)
You can also use ganache to carry out the tests, for this it is only necessary to use the network option
npx hardhat --network ganache test
Tests provide comprehensive coverage of all DeFiPlex smart contract functionalities, ensuring thorough validation of every aspect of the platform's lending, borrowing, and governance mechanisms. These tests simulate various scenarios, including edge cases and typical user interactions, to verify the robustness, security, and compliance of the smart contracts with the intended DeFiPlex platform specifications. By rigorously testing each function, from loan requests to governance proposals, developers ensure early identification and resolution of potential bugs, vulnerabilities, and unintended behaviors. This approach enhances the overall reliability and trustworthiness of DeFiPlex, fostering confidence among users and stakeholders in the platform's operational integrity.