66 |
67 | # PiStable-Protocol
68 | PiStable-Protocol is the foundational codebase for the PiStable project, designed to integrate Pi Coin from the Pi Network as a stablecoin pegged to $314.159. This repository includes smart contracts, algorithms for maintaining price stability, governance mechanisms, and interoperability features, enabling seamless transactions and interactions within the global financial ecosystem. Join us in revolutionizing the way digital currencies are utilized and adopted!
69 |
70 | # PiStable Protocol
71 |
72 | ## Overview
73 |
74 | **PiStable** is an advanced decentralized finance (DeFi) protocol that integrates Pi Coin from the Pi Network as a stablecoin pegged to the value of $314.159. This project aims to create a robust financial instrument that enhances the usability and stability of Pi Coin within the global financial ecosystem.
75 |
76 | ## Features
77 |
78 | - **Stablecoin Mechanism**: Algorithmic price stabilization to maintain the peg.
79 | - **Decentralized Governance**: Community-driven decision-making through governance contracts.
80 | - **Interoperability**: Seamless integration with existing DeFi platforms.
81 | - **Security Protocols**: Advanced encryption and multi-layered security measures.
82 | - **User -Friendly Interface**: Intuitive front-end application for easy access.
83 | - **Analytics and Monitoring**: Real-time analytics for user interactions and performance metrics.
84 |
85 | ## Getting Started
86 |
87 | ### Prerequisites
88 |
89 | - Node.js (v14 or higher)
90 | - npm (Node Package Manager)
91 | - A compatible Ethereum wallet (e.g., MetaMask)
92 |
93 | ### Installation
94 |
95 | 1. Clone the repository:
96 | ```bash
97 | 1 git clone https://github.com/KOSASIH/PiStable-Protocol.git
98 | 2 cd PiStable-Protocol
99 | ```
100 |
101 | 2. Install dependencies:
102 |
103 | ```bash
104 | 1 npm install
105 | ```
106 |
107 | 3. Set up environment variables:
108 |
109 | - Create a .env file in the root directory and add your configuration:
110 |
111 | ```plaintext
112 | 1 NETWORK=mainnet
113 | 2 INFURA_PROJECT_ID=your_infura_project_id
114 | 3 PRIVATE_KEY=your_wallet_private_key
115 | ```
116 |
117 | 4. Build the project:
118 |
119 | ```bash
120 | 1 npm run build
121 | ```
122 |
123 | ### Start the application:
124 |
125 | ```bash
126 | 1 npm start
127 | ```
128 |
129 | ### Running Tests
130 | To run the test suite, use the following command:
131 |
132 | ```bash
133 | 1 npm test
134 | ```
135 |
136 | ### Contributing
137 | We welcome contributions! Please read our [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to contribute to the project.
138 |
139 | ## License
140 | This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
141 |
142 |
--------------------------------------------------------------------------------
/analytics/dashboard/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Analytics Dashboard
9 |
10 |
11 |
12 |
Analytics Dashboard
13 |
14 |
Performance Metrics
15 |
16 |
17 |
18 |
User Events
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/analytics/dashboard/script.js:
--------------------------------------------------------------------------------
1 | // analytics/dashboard/script.js
2 |
3 | // Function to fetch and display metrics
4 | const fetchMetrics = async () => {
5 | try {
6 | const response = await fetch('/api/metrics'); // Fetch metrics from the API
7 | if (!response.ok) {
8 | throw new Error('Network response was not ok');
9 | }
10 | const metricsData = await response.json();
11 | displayMetrics(metricsData);
12 | } catch (error) {
13 | console.error('Error fetching metrics:', error);
14 | }
15 | };
16 |
17 | // Function to display metrics in the dashboard
18 | const displayMetrics = (metricsData) => {
19 | const metricsList = document.getElementById('metrics-list');
20 | metricsList.innerHTML = ''; // Clear existing metrics
21 |
22 | metricsData.forEach(metric => {
23 | const li = document.createElement('li');
24 | li.textContent = `Metric: ${metric.name}, Value: ${metric.value}`;
25 | metricsList.appendChild(li);
26 | });
27 | };
28 |
29 | // Function to fetch and display user events
30 | const fetchUser Events = async () => {
31 | try {
32 | const response = await fetch('/api/events'); // Fetch user events from the API
33 | if (!response.ok) {
34 | throw new Error('Network response was not ok');
35 | }
36 | const eventsData = await response.json();
37 | displayUser Events(eventsData);
38 | } catch (error) {
39 | console.error('Error fetching user events:', error);
40 | }
41 | };
42 |
43 | // Function to display user events in the dashboard
44 | const displayUser Events = (eventsData) => {
45 | const eventsList = document.getElementById('events-list');
46 | eventsList.innerHTML = ''; // Clear existing events
47 |
48 | eventsData.forEach(event => {
49 | const li = document.createElement('li');
50 | li.textContent = `Event: ${event.name}, Properties: ${JSON.stringify(event.properties)}`;
51 | eventsList.appendChild(li);
52 | });
53 | };
54 |
55 | // Initial fetch calls to populate the dashboard
56 | fetchMetrics();
57 | fetchUser Events();
58 |
--------------------------------------------------------------------------------
/analytics/dashboard/styles.css:
--------------------------------------------------------------------------------
1 | /* analytics/dashboard/styles.css */
2 |
3 | body {
4 | font-family: Arial, sans-serif;
5 | background-color: #f4f4f4;
6 | margin: 0;
7 | padding: 20px;
8 | }
9 |
10 | .dashboard {
11 | max-width: 800px;
12 | margin: auto;
13 | background: white;
14 | padding: 20px;
15 | border-radius: 8px;
16 | box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
17 | }
18 |
19 | h1 {
20 | text-align: center;
21 | }
22 |
23 | h2 {
24 | color: #333;
25 | }
26 |
27 | ul {
28 | list-style-type: none;
29 | padding: 0;
30 | }
31 |
32 | li {
33 | padding: 10px;
34 | border-bottom: 1px solid #ddd;
35 | }
36 |
--------------------------------------------------------------------------------
/analytics/event-tracking.js:
--------------------------------------------------------------------------------
1 | // analytics/event-tracking.js
2 |
3 | // Initialize analytics service (e.g., Google Analytics, Mixpanel)
4 | const analyticsService = {
5 | trackEvent: (eventName, properties) => {
6 | // Example: Sending event data to Google Analytics
7 | if (window.ga) {
8 | window.ga('send', 'event', eventName, properties);
9 | } else {
10 | // Fallback for local testing or other services
11 | console.log(`Event tracked: ${eventName}`, properties);
12 | }
13 | }
14 | };
15 |
16 | // Track user interactions
17 | export const trackUser Interaction = (eventName, properties = {}) => {
18 | analyticsService.trackEvent(eventName, properties);
19 | };
20 |
21 | // Example usage
22 | // trackUser Interaction('Button Click', { buttonId: 'stakeButton' });
23 |
--------------------------------------------------------------------------------
/analytics/metrics-collection.js:
--------------------------------------------------------------------------------
1 | // analytics/metrics-collection.js
2 |
3 | const metrics = {
4 | startTime: null,
5 | endTime: null,
6 | pageLoadTime: null,
7 |
8 | startTracking: () => {
9 | metrics.startTime = performance.now();
10 | },
11 |
12 | endTracking: () => {
13 | metrics.endTime = performance.now();
14 | metrics.pageLoadTime = metrics.endTime - metrics.startTime;
15 | metrics.reportMetrics();
16 | },
17 |
18 | reportMetrics: () => {
19 | // Send metrics to a monitoring service (e.g., New Relic, Datadog)
20 | console.log(`Page Load Time: ${metrics.pageLoadTime} ms`);
21 | // Example: Send to an API endpoint
22 | fetch('/api/metrics', {
23 | method: 'POST',
24 | headers: {
25 | 'Content-Type': 'application/json'
26 | },
27 | body: JSON.stringify({ pageLoadTime: metrics.pageLoadTime })
28 | });
29 | }
30 | };
31 |
32 | // Example usage
33 | // metrics.startTracking();
34 | // window.onload = metrics.endTracking;
35 |
--------------------------------------------------------------------------------
/backend/api/auth.js:
--------------------------------------------------------------------------------
1 | // backend/api/auth.js
2 | const express = require('express');
3 | const router = express.Router();
4 | const authService = require('../services/authService');
5 |
6 | // Register a new user
7 | router.post('/register', async (req, res) => {
8 | try {
9 | const user = await authService.register(req.body);
10 | res.status(201).json(user);
11 | } catch (error) {
12 | res.status(400).json({ error: error.message });
13 | }
14 | });
15 |
16 | // Login a user
17 | router.post('/login', async (req, res) => {
18 | try {
19 | const token = await authService.login(req.body);
20 | res.status(200).json({ token });
21 | } catch (error) {
22 | res.status(401).json({ error: error.message });
23 | }
24 | });
25 |
26 | module.exports = router;
27 |
--------------------------------------------------------------------------------
/backend/database/models/User.js:
--------------------------------------------------------------------------------
1 | // backend/database/models/User.js
2 | const mongoose = require('mongoose');
3 |
4 | const userSchema = new mongoose.Schema({
5 | username: { type: String, required: true, unique: true },
6 | password: { type: String, required: true },
7 | email: { type: String, required: true, unique: true },
8 | });
9 |
10 | module.exports = mongoose.model('User', userSchema);
11 |
--------------------------------------------------------------------------------
/backend/jobs/proposalJob.js:
--------------------------------------------------------------------------------
1 | // backend/jobs/proposalJob.js
2 | const Proposal = require('../database/models/Proposal');
3 |
4 | const processProposals = async () => {
5 | const proposals = await Proposal.find({ status: 'pending' });
6 | // Logic to process proposals
7 | proposals.forEach(proposal => {
8 | // Process each proposal
9 | });
10 | };
11 |
12 | module.exports = { processProposals };
13 |
--------------------------------------------------------------------------------
/backend/middleware/loggerMiddleware.js:
--------------------------------------------------------------------------------
1 | // backend/middleware/loggerMiddleware.js
2 | const loggerMiddleware = (req, res, next) => {
3 | console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
4 | next();
5 | };
6 |
7 | module.exports = loggerMiddleware;
8 |
--------------------------------------------------------------------------------
/backend/server.js:
--------------------------------------------------------------------------------
1 | // backend/server.js
2 | const express = require('express');
3 | const mongoose = require('mongoose');
4 | const bodyParser = require('body-parser');
5 | const cors = require('cors');
6 | const authRoutes = require('./api/auth');
7 | const governanceRoutes = require('./api/governance');
8 | const stakingRoutes = require('./api/staking');
9 | const liquidityRoutes = require('./api/liquidity');
10 | const loggerMiddleware = require('./middleware/loggerMiddleware');
11 |
12 | const app = express();
13 | const PORT = process.env.PORT || 5000;
14 |
15 | // Middleware
16 | app.use(cors());
17 | app.use(bodyParser.json());
18 | app.use(loggerMiddleware);
19 |
20 | // Database connection
21 | mongoose.connect('mongodb://localhost:27017/pistable', {
22 | useNewUrlParser: true,
23 | useUnifiedTopology: true,
24 | })
25 | .then(() => console.log('MongoDB connected'))
26 | .catch(err => console.error('MongoDB connection error:', err));
27 |
28 | // API routes
29 | app.use('/api/auth', authRoutes);
30 | app.use('/api/governance', governanceRoutes);
31 | app.use('/api/staking', stakingRoutes);
32 | app.use('/api/liquidity', liquidityRoutes);
33 |
34 | // Start server
35 | app.listen(PORT, () => {
36 | console.log(`Server is running on http://localhost:${PORT}`);
37 | });
38 |
--------------------------------------------------------------------------------
/backend/services/authService.js:
--------------------------------------------------------------------------------
1 | // backend/services/authService.js
2 | const User = require('../database/models/User');
3 | const bcrypt = require('bcrypt');
4 | const jwt = require('jsonwebtoken');
5 |
6 | const register = async ({ username, password, email }) => {
7 | const hashedPassword = await bcrypt.hash(password, 10);
8 | const user = new User({ username, password: hashedPassword, email });
9 | await user.save();
10 | return user;
11 | };
12 |
13 | const login = async ({ username, password }) => {
14 | const user = await User.findOne({ username });
15 | if (!user) throw new Error('User not found');
16 |
17 | const isMatch = await bcrypt.compare(password, user.password);
18 | if (!isMatch) throw new Error('Invalid credentials');
19 |
20 | const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
21 | return token;
22 | };
23 |
24 | module.exports = { register, login };
25 |
--------------------------------------------------------------------------------
/config/.env:
--------------------------------------------------------------------------------
1 | # Database Configuration
2 | DB_HOST=localhost
3 | DB_PORT=27017
4 | DB_NAME=pistable
5 |
6 | # JWT Secret
7 | JWT_SECRET=your_jwt_secret_key
8 |
9 | # API Keys
10 | INFURA_PROJECT_ID=your_infura_project_id
11 | ALCHEMY_API_KEY=your_alchemy_api_key
12 |
13 | # Logging Level
14 | LOG_LEVEL=info
15 |
16 | # Email Configuration
17 | EMAIL_SERVICE=gmail
18 | EMAIL_USER=your_email@gmail.com
19 | EMAIL_PASS=your_email_password
20 |
21 | # Frontend URL
22 | FRONTEND_URL=http://localhost:3000
23 |
--------------------------------------------------------------------------------
/config/logging-config.json:
--------------------------------------------------------------------------------
1 | {
2 | "logging": {
3 | "level": "info",
4 | "transports": [
5 | {
6 | "type": "console",
7 | "options": {
8 | "format": "combined"
9 | }
10 | },
11 | {
12 | "type": "file",
13 | "options": {
14 | "filename": "logs/app.log",
15 | "level": "error",
16 | "maxSize": "20m",
17 | "maxFiles": "14d"
18 | }
19 | },
20 | {
21 | "type": "http",
22 | "options": {
23 | "host": "logs.example.com",
24 | "path": "/log",
25 | "level": "warn"
26 | }
27 | }
28 | ]
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/config/network-config.json:
--------------------------------------------------------------------------------
1 | {
2 | "networks": {
3 | "development": {
4 | "url": "http://127.0.0.1:8545",
5 | "chainId": 1337,
6 | "explorer": "http://localhost:3000",
7 | "gasPrice": "20000000000"
8 | },
9 | "rinkeby": {
10 | "url": "https://rinkeby.infura.io/v3/YOUR_INFURA_PROJECT_ID",
11 | "chainId": 4,
12 | "explorer": "https://rinkeby.etherscan.io",
13 | "gasPrice": "20000000000"
14 | },
15 | "mainnet": {
16 | "url": "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID",
17 | "chainId": 1,
18 | "explorer": "https://etherscan.io",
19 | "gasPrice": "100000000000"
20 | },
21 | "polygon": {
22 | "url": "https://polygon-rpc.com",
23 | "chainId": 137,
24 | "explorer": "https://polygonscan.com",
25 | "gasPrice": "30000000000"
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/config/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "app": {
3 | "name": "PiStable Protocol",
4 | "version": "1.0.0",
5 | "description": "A decentralized finance platform for stablecoin management."
6 | },
7 | "features": {
8 | "enableGovernance": true,
9 | "enableStaking": true,
10 | "enableLiquidity": true,
11 | "enableNotifications": true
12 | },
13 | "security": {
14 | "passwordMinLength": 12,
15 | "enableTwoFactorAuth": true,
16 | "maxLoginAttempts": 5,
17 | "lockoutDuration": 30
18 | },
19 | "api": {
20 | "rateLimit": {
21 | "windowMs": 15 * 60 * 1000, // 15 minutes
22 | "max": 100 // limit each IP to 100 requests per windowMs
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/contracts/CollateralManager.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
5 | import "@openzeppelin/contracts/access/Ownable.sol";
6 |
7 | contract CollateralManager is Ownable {
8 | IERC20 public collateralToken;
9 | uint256 public totalCollateral;
10 | uint256 public collateralizationRatio = 150; // 150%
11 |
12 | mapping(address => uint256) public collateralBalances;
13 |
14 | event CollateralDeposited(address indexed user, uint256 amount);
15 | event CollateralWithdrawn(address indexed user, uint256 amount);
16 | event CollateralizationRatioUpdated(uint256 newRatio);
17 |
18 | constructor(IERC20 _collateralToken) {
19 | collateralToken = _collateralToken;
20 | }
21 |
22 | function depositCollateral(uint256 amount ) external {
23 | require(amount > 0, "Amount must be greater than zero");
24 | collateralToken.transferFrom(msg.sender, address(this), amount);
25 | collateralBalances[msg.sender] += amount;
26 | totalCollateral += amount;
27 |
28 | emit CollateralDeposited(msg.sender, amount);
29 | }
30 |
31 | function withdrawCollateral(uint256 amount) external {
32 | require(collateralBalances[msg.sender] >= amount, "Insufficient collateral");
33 | require((totalCollateral - amount) * 100 / totalCollateral >= collateralizationRatio, "Withdrawal would breach collateralization ratio");
34 |
35 | collateralBalances[msg.sender] -= amount;
36 | totalCollateral -= amount;
37 | collateralToken.transfer(msg.sender, amount);
38 |
39 | emit CollateralWithdrawn(msg.sender, amount);
40 | }
41 |
42 | function updateCollateralizationRatio(uint256 newRatio) external onlyOwner {
43 | require(newRatio > 0, "Ratio must be greater than zero");
44 | collateralizationRatio = newRatio;
45 | emit CollateralizationRatioUpdated(newRatio);
46 | }
47 |
48 | function getCollateralBalance(address user) external view returns (uint256) {
49 | return collateralBalances[user];
50 | }
51 |
52 | function getTotalCollateral() external view returns (uint256) {
53 | return totalCollateral;
54 | }
55 |
56 | function getCollateralizationRatio() external view returns (uint256) {
57 | return collateralizationRatio;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/contracts/Escrow.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@openzeppelin/contracts/access/Ownable.sol";
5 |
6 | contract Escrow is Ownable {
7 | enum State { AWAITING_PAYMENT, AWAITING_DELIVERY, COMPLETE, DISPUTED }
8 |
9 | struct EscrowTransaction {
10 | address buyer;
11 | address seller;
12 | uint256 amount;
13 | State state;
14 | }
15 |
16 | mapping(uint256 => EscrowTransaction) public escrows;
17 | uint256 public escrowCount;
18 |
19 | event EscrowCreated(uint256 indexed escrowId, address indexed buyer, address indexed seller, uint256 amount);
20 | event PaymentReleased(uint256 indexed escrowId);
21 | event DisputeResolved(uint256 indexed escrowId, bool buyerWins);
22 |
23 | modifier onlyBuyer(uint256 escrowId) {
24 | require(msg.sender == escrows[escrowId].buyer, "Only buyer can call this function");
25 | _;
26 | }
27 |
28 | modifier onlySeller(uint256 escrowId) {
29 | require(msg.sender == escrows[escrowId].seller, "Only seller can call this function");
30 | _;
31 | }
32 |
33 | modifier inState(uint256 escrowId, State expectedState) {
34 | require(escrows[escrowId].state == expectedState, "Invalid state for this operation");
35 | _;
36 | }
37 |
38 | function createEscrow(address seller) external payable {
39 | require(msg.value > 0, "Amount must be greater than zero");
40 |
41 | escrowCount++;
42 | escrows[escrowCount] = EscrowTransaction({
43 | buyer: msg.sender,
44 | seller: seller,
45 | amount: msg.value,
46 | state: State.AWAITING_DELIVERY
47 | });
48 |
49 | emit EscrowCreated(escrowCount, msg.sender, seller, msg.value);
50 | }
51 |
52 | function confirmDelivery(uint256 escrowId) external onlySeller(escrowId) inState(escrowId, State.AWAITING_DELIVERY) {
53 | EscrowTransaction storage escrow = escrows[escrowId];
54 | escrow.state = State.COMPLETE;
55 |
56 | payable(escrow.seller).transfer(escrow.amount);
57 | emit PaymentReleased(escrowId);
58 | }
59 |
60 | function dispute(uint256 escrowId) external onlyBuyer(escrowId) inState(escrowId, State.AWAITING_DELIVERY) {
61 | escrows[escrowId].state = State.DISPUTED;
62 | }
63 |
64 | function resolveDispute(uint256 escrowId, bool buyerWins) external onlyOwner inState(escrowId, State.DISPUTED) {
65 | EscrowTransaction storage escrow = escrows[escrowId];
66 | escrow.state = State.COMPLETE;
67 |
68 | if (buyerWins) {
69 | payable(escrow.buyer).transfer(escrow.amount);
70 | } else {
71 | payable(escrow.seller).transfer(escrow.amount);
72 | }
73 |
74 | emit DisputeResolved(escrowId, buyerWins);
75 | ```solidity
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/contracts/Governance.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
5 | import "@openzeppelin/contracts/access/Ownable.sol";
6 |
7 | contract Governance is Ownable {
8 | IERC20 public token;
9 |
10 | struct Proposal {
11 | string description;
12 | uint256 voteCount;
13 | mapping(address => bool) voters;
14 | bool executed;
15 | }
16 |
17 | Proposal[] public proposals;
18 |
19 | event ProposalCreated(uint256 proposalId, string description);
20 | event Voted(uint256 proposalId, address voter);
21 | event ProposalExecuted(uint256 proposalId);
22 |
23 | constructor(IERC20 _token) {
24 | token = _token;
25 | }
26 |
27 | function createProposal(string memory description) external onlyOwner {
28 | proposals.push();
29 | Proposal storage newProposal = proposals[proposals.length - 1];
30 | newProposal.description = description;
31 | emit ProposalCreated(proposals.length - 1, description);
32 | }
33 |
34 | function vote(uint256 proposalId) external {
35 | Proposal storage proposal = proposals[proposalId];
36 | require(!proposal.voters[msg.sender], "Already voted");
37 | require(token.balanceOf(msg.sender) > 0, "No voting power");
38 |
39 | proposal.voters[msg.sender] = true;
40 | proposal.voteCount += token.balanceOf(msg.sender);
41 | emit Voted(proposalId, msg.sender);
42 | }
43 |
44 | function executeProposal(uint256 proposalId) external onlyOwner {
45 | Proposal storage proposal = proposals[proposalId];
46 | require(!proposal.executed, "Proposal already executed");
47 | require(proposal.voteCount > (token.totalSupply() / 2), "Not enough votes");
48 |
49 | // Execute the proposal logic here (e.g., change parameters)
50 | proposal.executed = true;
51 | emit ProposalExecuted(proposalId);
52 | }
53 |
54 | function getProposalCount() external view returns (uint256) {
55 | return proposals.length;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/contracts/LiquidityPool.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
5 | import "@openzeppelin/contracts/access/Ownable.sol";
6 |
7 | contract LiquidityPool is Ownable {
8 | IERC20 public tokenA;
9 | IERC20 public tokenB;
10 | uint256 public totalLiquidity;
11 |
12 | struct Liquidity {
13 | uint256 amountA;
14 | uint256 amountB;
15 | }
16 |
17 | mapping(address => Liquidity) public liquidityProviders;
18 |
19 | event LiquidityAdded(address indexed provider, uint256 amountA, uint256 amountB);
20 | event LiquidityRemoved(address indexed provider, uint256 amountA, uint256 amountB);
21 |
22 | constructor(IERC20 _tokenA, IERC20 _tokenB) {
23 | tokenA = _tokenA;
24 | tokenB = _tokenB;
25 | }
26 |
27 | function addLiquidity(uint256 amountA, uint256 amountB) external {
28 | require(amountA > 0 && amountB > 0, "Amounts must be greater than zero");
29 |
30 | tokenA.transferFrom(msg.sender, address(this), amountA);
31 | token B.transferFrom(msg.sender, address(this), amountB);
32 |
33 | Liquidity storage providerLiquidity = liquidityProviders[msg.sender];
34 | providerLiquidity.amountA += amountA;
35 | providerLiquidity.amountB += amountB;
36 | totalLiquidity += amountA + amountB;
37 |
38 | emit LiquidityAdded(msg.sender, amountA, amountB);
39 | }
40 |
41 | function removeLiquidity(uint256 amountA, uint256 amountB) external {
42 | Liquidity storage providerLiquidity = liquidityProviders[msg.sender];
43 | require(providerLiquidity.amountA >= amountA && providerLiquidity.amountB >= amountB, "Insufficient liquidity");
44 |
45 | providerLiquidity.amountA -= amountA;
46 | providerLiquidity.amountB -= amountB;
47 | totalLiquidity -= amountA + amountB;
48 |
49 | tokenA.transfer(msg.sender, amountA);
50 | tokenB.transfer(msg.sender, amountB);
51 |
52 | emit LiquidityRemoved(msg.sender, amountA, amountB);
53 | }
54 |
55 | function getLiquidity(address provider) external view returns (uint256 amountA, uint256 amountB) {
56 | Liquidity storage providerLiquidity = liquidityProviders[provider];
57 | return (providerLiquidity.amountA, providerLiquidity.amountB);
58 | }
59 |
60 | function getTotalLiquidity() external view returns (uint256) {
61 | return totalLiquidity;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/contracts/MultiSigWallet.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@openzeppelin/contracts/access/Ownable.sol";
5 |
6 | contract MultiSigWallet is Ownable {
7 | event Deposit(address indexed sender, uint256 amount);
8 | event SubmitTransaction(address indexed owner, uint256 indexed txIndex);
9 | event ConfirmTransaction(address indexed owner, uint256 indexed txIndex);
10 | event ExecuteTransaction(address indexed owner, uint256 indexed txIndex);
11 | event RevokeConfirmation(address indexed owner, uint256 indexed txIndex);
12 |
13 | struct Transaction {
14 | address to;
15 | uint256 value;
16 | bool executed;
17 | uint256 confirmations;
18 | mapping(address => bool) isConfirmed;
19 | }
20 |
21 | address[] public owners;
22 | mapping(address => bool) public isOwner;
23 | Transaction[] public transactions;
24 | uint256 public requiredConfirmations;
25 |
26 | modifier onlyOwner() {
27 | require(isOwner[msg.sender], "Not an owner");
28 | _;
29 | }
30 |
31 | modifier txExists(uint256 txIndex) {
32 | require(txIndex < transactions.length, "Transaction does not exist");
33 | _;
34 | }
35 |
36 | modifier notExecuted(uint256 txIndex) {
37 | require(!transactions[txIndex].executed, "Transaction already executed");
38 | _;
39 | }
40 |
41 | constructor(address[] memory _owners, uint256 _requiredConfirmations) {
42 | require(_owners.length > 0, "Owners required");
43 | require(_requiredConfirmations > 0 && _requiredConfirmations <= _owners.length, "Invalid number of required confirmations");
44 |
45 | for (uint256 i = 0; i < _owners.length; i++) {
46 | address owner = _owners[i];
47 | require(owner != address(0), "Invalid owner");
48 | require(!isOwner[owner], "Owner not unique");
49 | isOwner[owner] = true;
50 | owners.push(owner);
51 | }
52 | requiredConfirmations = _requiredConfirmations;
53 | }
54 |
55 | receive() external payable {
56 | emit Deposit(msg.sender, msg.value);
57 | }
58 |
59 | function submitTransaction(address to, uint256 value) external onlyOwner {
60 | uint256 txIndex = transactions.length;
61 | transactions.push(Transaction({
62 | to: to,
63 | value: value,
64 | executed: false,
65 | confirmations: 0
66 | }));
67 | emit SubmitTransaction(msg.sender, txIndex);
68 | }
69 |
70 | function confirmTransaction(uint256 txIndex) external onlyOwner txExists(txIndex) notExecuted(txIndex) {
71 | Transaction storage transaction = transactions[txIndex];
72 | require(!transaction.isConfirmed[msg.sender], "Transaction already confirmed");
73 |
74 | transaction.isConfirmed[msg.sender] = true;
75 | transaction.confirmations += 1;
76 | emit ConfirmTransaction(msg.sender, txIndex);
77 |
78 | if (transaction.confirmations >= requiredConfirmations) {
79 | executeTransaction(txIndex);
80 | }
81 | }
82 |
83 | function executeTransaction(uint256 txIndex) internal txExists(txIndex) notExecuted(txIndex) {
84 | Transaction storage transaction = transactions[txIndex];
85 | require(transaction.confirmations >= requiredConfirmations, "Not enough confirmations");
86 |
87 | transaction.executed = true;
88 | (bool success, ) = transaction.to.call{value: transaction.value}("");
89 | require(success, "Transaction failed");
90 | emit ExecuteTransaction(msg.sender, txIndex);
91 | }
92 |
93 | function revokeConfirmation(uint256 txIndex) external onlyOwner txExists(txIndex) notExecuted(txIndex) {
94 | Transaction storage transaction = transactions[txIndex];
95 | require(transaction.isConfirmed[msg.sender], "Transaction not confirmed");
96 |
97 | transaction.isConfirmed[msg.sender] = false;
98 | transaction.confirmations -= 1;
99 | emit RevokeConfirmation(msg.sender, txIndex);
100 | }
101 |
102 | function getTransactionCount() external view returns (uint256) {
103 | return transactions.length;
104 | }
105 |
106 | function getTransaction(uint256 txIndex) external view returns (address, uint256, bool, uint256) {
107 | Transaction storage transaction = transactions[txIndex];
108 | return (transaction.to, transaction.value, transaction.executed, transaction.confirmations);
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/contracts/PiStable.rs:
--------------------------------------------------------------------------------
1 | #![no_std]
2 | use soroban_sdk::{contractimpl, symbol, vec, Env, Symbol, Vec, Address};
3 |
4 | pub struct PiStable;
5 |
6 | #[contractimpl]
7 | impl PiStable {
8 | const STABLE_COIN_VALUE: u128 = 31415900; // Pegged value in cents ($314,159)
9 | const TOTAL_SUPPLY: u128 = 100_000_000_000; // Total supply of 100 billion tokens
10 |
11 | pub fn initialize(env: Env) {
12 | // Mint total supply to the contract owner
13 | let owner: Address = env.current_contract_address();
14 | env.storage().persistent().set(&symbol!("total_supply"), &0); // Initialize total supply to 0
15 | env.storage().persistent().set(&symbol!("owner"), &owner);
16 | }
17 |
18 | pub fn buy_stable_coins(env: Env, amount: u128) {
19 | let owner: Address = env.storage().persistent().get(&symbol!("owner")).unwrap();
20 | let total_supply: u128 = env.storage().persistent().get(&symbol!("total_supply")).unwrap();
21 |
22 | // Calculate the amount of stablecoins to mint
23 | let stablecoins_to_mint = (amount * Self::STABLE_COIN_VALUE) / 1_000_000_000_000_000_000; // Convert to wei
24 |
25 | // Ensure we do not exceed total supply
26 | assert!(total_supply + stablecoins_to_mint <= Self::TOTAL_SUPPLY, "Exceeds total supply");
27 |
28 | // Mint stablecoins (this is a placeholder for actual minting logic)
29 | env.storage().persistent().set(&symbol!("total_supply"), &(total_supply + stablecoins_to_mint));
30 | }
31 |
32 | pub fn get_stable_coin_value() -> u128 {
33 | Self::STABLE_COIN_VALUE
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/contracts/PiStable.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
5 | import "@openzeppelin/contracts/access/Ownable.sol";
6 |
7 | contract PiStable is ERC20, Ownable {
8 | // The value of the stablecoin in USD (pegged to $314.159)
9 | uint256 public constant STABLE_COIN_VALUE = 314159000000000000000; // 314.159 in wei (1e18 = 1 token)
10 | uint256 public constant TOTAL_SUPPLY = 100000000000 * (10 ** decimals()); // 100 billion tokens
11 |
12 | // Event to emit when the value is updated
13 | event ValueUpdated(uint256 newValue);
14 |
15 | constructor() ERC20("PiStable", "PST") {
16 | _mint(msg.sender, TOTAL_SUPPLY); // Mint total supply to the owner
17 | }
18 |
19 | // Function to get the current value of the stablecoin
20 | function getStableCoinValue() external pure returns (uint256) {
21 | return STABLE_COIN_VALUE;
22 | }
23 |
24 | // Function to buy stablecoins
25 | function buyStableCoins() external payable {
26 | require(msg.value > 0, "Send ETH to buy stablecoins");
27 | uint256 amountToMint = (msg.value * STABLE_COIN_VALUE) / 1 ether; // Calculate amount based on the stablecoin value
28 | _mint(msg.sender, amountToMint);
29 | }
30 |
31 | // Function to withdraw ETH from the contract
32 | function withdraw(uint256 amount) external onlyOwner {
33 | payable(owner()).transfer(amount);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/contracts/PriceOracle.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@openzeppelin/contracts/access/Ownable.sol";
5 |
6 | contract PriceOracle is Ownable {
7 | mapping(address => uint256) public prices; // Token address to price mapping
8 | address[] public priceProviders; // List of authorized price providers
9 |
10 | event PriceUpdated(address indexed token, uint256 price);
11 |
12 | modifier onlyPriceProvider() {
13 | require(isPriceProvider(msg.sender), "Not an authorized price provider");
14 | _;
15 | }
16 |
17 | constructor(address[] memory _priceProviders) {
18 | priceProviders = _priceProviders;
19 | }
20 |
21 | function isPriceProvider(address provider) public view returns (bool) {
22 | for (uint256 i = 0; i < priceProviders.length; i++) {
23 | if (priceProviders[i] == provider) {
24 | return true;
25 | }
26 | }
27 | return false;
28 | }
29 |
30 | function updatePrice(address token, uint256 price) external onlyPriceProvider {
31 | prices[token] = price;
32 | emit PriceUpdated(token, price);
33 | }
34 |
35 | function getPrice(address token) external view returns (uint256) {
36 | return prices[token];
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/contracts/Staking.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
5 | import "@openzeppelin/contracts/access/Ownable.sol";
6 |
7 | contract Staking is Ownable {
8 | IERC20 public stakingToken;
9 | uint256 public totalStaked;
10 | uint256 public rewardRate; // Reward rate per block
11 |
12 | struct Stake {
13 | uint256 amount;
14 | uint256 startTime;
15 | uint256 rewards;
16 | }
17 |
18 | mapping(address => Stake) public stakes;
19 |
20 | event Staked(address indexed user, uint256 amount);
21 | event Unstaked(address indexed user, uint256 amount, uint256 rewards);
22 |
23 | constructor(IERC20 _stakingToken, uint256 _rewardRate) {
24 | stakingToken = _stakingToken;
25 | rewardRate = _rewardRate;
26 | }
27 |
28 | function stake(uint256 amount) external {
29 | require(amount > 0, "Amount must be greater than zero");
30 | stakingToken.transferFrom(msg.sender, address(this), amount);
31 |
32 | Stake storage userStake = stakes[msg.sender];
33 | userStake.amount += amount;
34 | userStake.startTime = block.timestamp;
35 |
36 | totalStaked += amount;
37 | emit Staked(msg.sender, amount);
38 | }
39 |
40 | function unstake() external {
41 | Stake storage userStake = stakes[msg.sender];
42 | require(userStake.amount > 0, "No staked amount");
43 |
44 | uint256 rewards = calculateRewards(msg.sender);
45 | stakingToken.transfer(msg.sender, userStake.amount);
46 | userStake.amount = 0;
47 | userStake.rewards += rewards;
48 |
49 | emit Unstaked(msg.sender, userStake.amount, rewards);
50 | }
51 |
52 | function calculateRewards(address user) public view returns (uint256) {
53 | Stake storage userStake = stakes[user];
54 | uint256 duration = block.timestamp - userStake.startTime;
55 | return (userStake.amount * rewardRate * duration) / 1e18; // Adjust for precision
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/contracts/interfaces/IGovernance.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | interface IGovernance {
5 | event ProposalCreated(uint256 proposalId, string description);
6 | event Voted(uint256 proposalId, address indexed voter);
7 | event ProposalExecuted(uint256 proposalId);
8 |
9 | function createProposal(string calldata description) external;
10 | function vote(uint256 proposalId) external;
11 | function executeProposal(uint256 proposalId) external;
12 | function getProposalCount() external view returns (uint256);
13 | function getProposal(uint256 proposalId) external view returns (string memory description, uint256 voteCount, bool executed);
14 | }
15 |
--------------------------------------------------------------------------------
/contracts/interfaces/ILiquidityPool.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | interface ILiquidityPool {
5 | event LiquidityAdded(address indexed provider, uint256 amountA, uint256 amountB);
6 | event LiquidityRemoved(address indexed provider, uint256 amountA, uint256 amountB);
7 |
8 | function addLiquidity(uint256 amountA, uint256 amountB) external;
9 | function removeLiquidity(uint256 amountA, uint256 amountB) external;
10 | function getLiquidity(address provider) external view returns (uint256 amountA, uint256 amountB);
11 | function getTotalLiquidity() external view returns (uint256);
12 | }
13 |
--------------------------------------------------------------------------------
/contracts/interfaces/IPriceOracle.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | interface IPriceOracle {
5 | event PriceUpdated(address indexed token, uint256 price);
6 |
7 | function updatePrice(address token, uint256 price) external;
8 | function getPrice(address token) external view returns (uint256);
9 | function isPriceProvider(address provider) external view returns (bool);
10 | }
11 |
--------------------------------------------------------------------------------
/contracts/interfaces/IStaking.sol:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: MIT
2 | pragma solidity ^0.8.0;
3 |
4 | interface IStaking {
5 | event Staked(address indexed user, uint256 amount);
6 | event Unstaked(address indexed user, uint256 amount, uint256 rewards);
7 |
8 | function stake(uint256 amount) external;
9 | function unstake() external;
10 | function calculateRewards(address user) external view returns (uint256);
11 | function getStakedAmount(address user) external view returns (uint256);
12 | }
13 |
--------------------------------------------------------------------------------
/docs/API.md:
--------------------------------------------------------------------------------
1 | # API Documentation
2 |
3 | ## Base URL
4 |
5 | 'http://localhost:5000/api'
6 |
7 |
8 | ## Authentication
9 | ### Register User
10 | - **POST** `/auth/register`
11 | - **Request Body**:
12 | ```json
13 | {
14 | "username": "string",
15 | "password": "string",
16 | "email": "string"
17 | }
18 | ```
19 | - **Response**: 201 Created
20 |
21 | ### Login User
22 | - **POST** `/auth/login`
23 | - **Request Body**:
24 | ```json
25 | {
26 | "username": "string",
27 | "password": "string"
28 | }
29 | ```
30 | - **Response**: 200 OK
31 | ```json
32 | {
33 | "token": "string"
34 | }
35 | ```
36 |
37 | ## Governance
38 | ### Create Proposal
39 | - **POST** `/governance/proposals`
40 | - **Headers**: `Authorization: Bearer `
41 | - **Request Body**:
42 | ```json
43 | {
44 | "title": "string",
45 | "description": "string"
46 | }
47 | ```
48 | - **Response**: 201 Created
49 |
50 | ### Get Proposals
51 | - **GET** `/governance/proposals`
52 | - **Response**: 200 OK
53 | ```json
54 | [
55 | {
56 | "id": "string",
57 | "title": "string",
58 | "description": "string",
59 | "voteCount": "number"
60 | }
61 | ]
62 | ```
63 |
64 | ## Staking
65 | ### Stake Tokens
66 | - **POST** `/staking/stake`
67 | - **Headers**: `Authorization: Bearer `
68 | - **Request Body**:
69 | ```json
70 | {
71 | "amount": "number"
72 | }
73 | ```
74 | - **Response**: 200 OK
75 |
--------------------------------------------------------------------------------
/docs/architecture.md:
--------------------------------------------------------------------------------
1 | # System Architecture Overview
2 |
3 | The PiStable Protocol is designed to facilitate stablecoin management and decentralized finance services. The architecture includes:
4 |
5 | ## 1. Smart Contracts
6 | - **PiStable Contract**: Manages stablecoin issuance and burning.
7 | - **Governance Contract**: Enables community governance through proposals and voting.
8 | - **Staking Contract**: Allows users to stake tokens for rewards.
9 | - **Liquidity Pool Contract**: Facilitates liquidity provision and trading.
10 |
11 | ## 2. Backend Services
12 | - **RESTful API**: Provides endpoints for frontend interaction, user authentication, and data retrieval.
13 | - **Database**: Stores user data, governance proposals, and transaction history.
14 |
15 | ## 3. Frontend Application
16 | - **React Application**: User interface for governance, staking, and liquidity management.
17 |
18 | ## 4. Security
19 | - **Audits**: Regular security audits of smart contracts and backend services.
20 | - **Best Practices**: Implementation of security best practices to protect user data and funds.
21 |
22 | ## 5. Deployment
23 | - **Ethereum Network**: The protocol is deployed on the Ethereum blockchain, utilizing smart contracts for core functionalities.
24 |
--------------------------------------------------------------------------------
/docs/code_structure.md:
--------------------------------------------------------------------------------
1 | PiStable-Protocol/
2 | │
3 | ├── contracts/ # Smart contracts directory
4 | │ ├── PiStable.sol # Main stablecoin contract
5 | │ ├── Governance.sol # Governance contract for decentralized decision-making
6 | │ ├── CollateralManager.sol # Contract for managing collateralization
7 | │ ├── PriceOracle.sol # Price oracle for external price feeds
8 | │ ├── Staking.sol # Staking contract for incentivizing users
9 | │ ├── LiquidityPool.sol # Contract for managing liquidity pools
10 | │ ├── MultiSigWallet.sol # Multi-signature wallet for governance
11 | │ ├── Escrow.sol # Escrow contract for secure transactions
12 | │ └── interfaces/ # Interfaces for contracts
13 | │ ├── IPriceOracle.sol
14 | │ ├── IGovernance.sol
15 | │ ├── ILiquidityPool.sol
16 | │ └── IStaking.sol
17 | │
18 | ├── scripts/ # Deployment and utility scripts
19 | │ ├── deploy.js # Script for deploying contracts
20 | │ ├── interact.js # Script for interacting with deployed contracts
21 | │ ├── migrate.js # Migration script for upgrading contracts
22 | │ └── utils/ # Utility functions
23 | │ ├── helpers.js
24 | │ ├── constants.js
25 | │ └── validators.js # Input validation functions
26 | │
27 | ├── src/ # Front-end application source code
28 | │ ├── components/ # React components
29 | │ ├── pages/ # Application pages
30 | │ ├── services/ # API and blockchain interaction services
31 | │ ├── hooks/ # Custom React hooks for state management
32 | │ ├── styles/ # CSS/SCSS styles
33 | │ ├── context/ # Context API for global state management
34 | │ └── App.js # Main application file
35 | │
36 | ├── backend/ # Back-end services
37 | │ ├── api/ # RESTful API endpoints
38 | │ ├── database/ # Database models and migrations
39 | │ ├── services/ # Business logic and services
40 | │ ├── middleware/ # Middleware for authentication and logging
41 | │ ├── jobs/ # Background jobs for processing tasks
42 | │ └── server.js # Main server file
43 | │
44 | ├── tests/ # Test directory
45 | │ ├── contracts/ # Smart contract tests
46 | │ ├── integration/ # Integration tests for front-end and back-end
47 | │ ├── unit/ # Unit tests for individual components/services
48 | │ └── e2e/ # End-to-end tests for the entire application
49 | │
50 | ├── docs/ # Documentation
51 | │ ├── architecture.md # System architecture overview
52 | │ ├── API.md # API documentation
53 | │ ├── governance.md # Governance model details
54 | │ ├── user-guide.md # User guide for the platform
55 | │ ├── developer-guide.md # Developer onboarding and contribution guide
56 | │ └── security.md # Security practices and guidelines
57 | │
58 | ├── config/ # Configuration files
59 | │ ├── network-config.json # Network configurations for deployment
60 | │ ├── .env # Environment variables
61 | │ ├── settings.json # Application settings
62 | │ └── logging-config.json # Logging configuration
63 | │
64 | ├── analytics/ # Analytics and monitoring services
65 | │ ├── event-tracking.js # Event tracking for user interactions
66 | │ ├── metrics-collection.js # Metrics collection for performance monitoring
67 | │ └── dashboard/ # Dashboard for visualizing analytics
68 | │
69 | ├── security/ # Security-related files
70 | │ ├── audits/ # Security audit reports
71 | │ ├── vulnerability-scans/ # Results from vulnerability scans
72 | │ └── best-practices.md # Security best practices documentation
73 | │
74 | ├── scripts/ # Automation scripts
75 | │ ├── build.sh # Build script for the application
76 | │ ├── test.sh # Test script for running tests
77 | │ ├── deploy.sh # Deployment script for the entire system
78 | │ └── backup.sh # Backup script for database and contracts
79 | │
80 | ├── .gitignore # Git ignore file
81 | ├── README.md # Project overview and setup instructions
82 | └── package.json # Node.js package file for dependencies
83 |
--------------------------------------------------------------------------------
/docs/developer-guide.md:
--------------------------------------------------------------------------------
1 | # Developer Guide
2 |
3 | Welcome to the PiStable Protocol development community! This guide will help you get started with contributing to the project.
4 |
5 | ## 1. Setting Up Your Development Environment
6 | - **Clone the Repository**:
7 | ```bash
8 | git clone https://github.com/KOSASIH/PiStable-Protocol.git
9 | cd PiStable-Protocol
10 | ```
11 | - **Install Dependencies**:
12 | ```bash
13 | npm install
14 | ```
15 | - **Set Up Environment Variables**: Create a `.env` file in the root directory and configure your environment variables as needed.
16 |
17 | ## 2. Running the Application
18 | - **Start the Backend**:
19 | ```bash
20 | npm run start:backend
21 | ```
22 | - **Start the Frontend**:
23 | ```bash
24 | npm run start:frontend
25 | ```
26 |
27 | ## 3. Writing Tests
28 | - Follow the structure outlined in the tests directory to write unit, integration, and end-to-end tests.
29 | - Use `jest` for unit tests and `supertest` for API tests.
30 |
31 | ## 4. Contributing
32 | - **Fork the Repository**: Create a fork of the repository on GitHub.
33 | - **Create a Branch**:
34 | ```bash
35 | git checkout -b feature/your-feature-name
36 | ```
37 | - **Make Your Changes**: Implement your feature or fix the bug.
38 | - **Submit a Pull Request**: Push your changes and submit a pull request for review.
39 |
40 | ## 5. Code of Conduct
41 | - Please adhere to our code of conduct while contributing to ensure a welcoming environment for all developers.
42 |
43 | ### Conclusion
44 | We appreciate your interest in contributing to the PiStable Protocol. Together, we can build a robust DeFi platform!
45 |
46 |
--------------------------------------------------------------------------------
/docs/governance.md:
--------------------------------------------------------------------------------
1 | # Governance Model
2 |
3 | The governance model empowers the community to make decisions regarding the protocol's future. Key features include:
4 |
5 | ## 1. Proposal Creation
6 | - Users can create proposals by providing a title and description.
7 | - Proposals can cover protocol changes, new features, or funding requests.
8 |
9 | ## 2. Voting
10 | - Users vote on proposals using their staked tokens.
11 | - Each token represents one vote, allowing "Yes" or "No" votes.
12 |
13 | ## 3. Execution
14 | - Proposals with majority votes are executed automatically by the governance contract.
15 | - The execution process is transparent and recorded on the blockchain.
16 |
17 | ## 4. Community Engagement
18 | - Regular community meetings and discussions encourage participation and feedback.
19 |
--------------------------------------------------------------------------------
/docs/security.md:
--------------------------------------------------------------------------------
1 | # Security Practices
2 |
3 | Ensuring the security of the PiStable Protocol is a top priority. This document outlines best practices and guidelines for maintaining security.
4 |
5 | ## 1. Smart Contract Security
6 | - **Audits**: Regularly audit smart contracts by third-party security firms.
7 | - **Testing**: Write comprehensive tests for all smart contracts to cover edge cases.
8 |
9 | ## 2. User Data Protection
10 | - **Encryption**: Use encryption for sensitive user data stored in the database.
11 | - **Authentication**: Implement strong authentication mechanisms, including two-factor authentication (2FA).
12 |
13 | ## 3. Incident Response
14 | - **Monitoring**: Continuously monitor the system for suspicious activities.
15 | - **Response Plan**: Have an incident response plan in place to address potential security breaches.
16 |
17 | ## 4. Community Awareness
18 | - **Education**: Educate users about common security threats, such as phishing attacks.
19 | - **Reporting**: Encourage users to report any security vulnerabilities they discover.
20 |
21 | ### Conclusion
22 | By following these security practices, we can help protect the PiStable Protocol and its users from potential threats. Thank you for your commitment to security!
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/docs/user-guide.md:
--------------------------------------------------------------------------------
1 | # User Guide
2 |
3 | Welcome to the PiStable Protocol! This guide will help you navigate the platform and utilize its features.
4 |
5 | ## Getting Started
6 |
7 | 1. **Creating an Account**
8 | - Visit the registration page and fill in your details (username, password, email).
9 | - Confirm your account via the email link.
10 |
11 | 2. **Logging In**
12 | - Go to the login page and enter your credentials.
13 | - Upon successful login, you will be redirected to your dashboard.
14 |
15 | 3. **Using the Platform**
16 | - **Staking**: Navigate to the staking section to stake your tokens and earn rewards. Enter the amount you wish to stake and confirm the transaction.
17 | - **Governance**: Participate in governance by creating or voting on proposals. Check the governance section for active proposals and cast your vote.
18 | - **Liquidity**: Provide liquidity by depositing tokens into the liquidity pool. This can be done through the liquidity management interface.
19 |
20 | 4. **Managing Your Account**
21 | - Access your profile settings to update your information or change your password.
22 | - View your transaction history and staking rewards in the account dashboard.
23 |
24 | 5. **Support**
25 | - If you encounter any issues, visit the support section for FAQs or contact our support team for assistance.
26 |
27 | ### Conclusion
28 | The PiStable Protocol aims to provide a seamless experience for users in the DeFi space. We encourage you to explore the platform and participate in the community.
29 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "PiStable-Protocol",
3 | "version": "1.0.0",
4 | "description": "A decentralized finance protocol integrating Pi Coin as a stablecoin pegged to $314.159.",
5 | "main": "src/index.js",
6 | "scripts": {
7 | "start": "node backend/server.js",
8 | "build": "webpack --mode production",
9 | "test": "jest --coverage",
10 | "deploy": "node scripts/deploy.js",
11 | "migrate": "node scripts/migrate.js"
12 | },
13 | "keywords": [
14 | "DeFi",
15 | "stablecoin",
16 | "PiCoin",
17 | "blockchain",
18 | "cryptocurrency"
19 | ],
20 | "author": "KOSASIH",
21 | "license": "MIT",
22 | "dependencies": {
23 | "express": "^4.17.1",
24 | "dotenv": "^10.0.0",
25 | "web3": "^1.5.0",
26 | "mongoose": "^5.10.9",
27 | "cors": "^2.8.5",
28 | "axios": "^0.21.1",
29 | "jsonwebtoken": "^8.5.1"
30 | },
31 | "devDependencies": {
32 | "jest": "^26.6.0",
33 | "webpack": "^5.11.0",
34 | "webpack-cli": "^4.3.0",
35 | "babel-loader": "^8.2.2",
36 | "eslint": "^7.14.0",
37 | " "eslint-config-airbnb": "^18.2.1"
38 | },
39 | "engines": {
40 | "node": ">=14.0.0"
41 | },
42 | "repository": {
43 | "type": "git",
44 | "url": "https://github.com/yourusername/PiStable-Protocol.git"
45 | },
46 | "bugs": {
47 | "url": "https://github.com/yourusername/PiStable-Protocol/issues"
48 | },
49 | "homepage": "https://github.com/yourusername/PiStable-Protocol#readme"
50 | }
51 |
--------------------------------------------------------------------------------
/scripts/backup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Backup Script for PiStable Protocol
4 |
5 | echo "Starting the backup process..."
6 |
7 | # Define backup directory
8 | BACKUP_DIR="./backups"
9 | mkdir -p "$BACKUP_DIR"
10 |
11 | # Backup the database
12 | echo "Backing up the database..."
13 | mongodump --uri="mongodb://localhost:27017/pistable" --out="$BACKUP_DIR/db_backup_$(date +%Y%m%d_%H%M%S)"
14 |
15 | # Backup smart contracts
16 | echo "Backing up smart contracts..."
17 | cp -r ./backend/contracts "$BACKUP_DIR/contracts_backup_$(date +%Y%m%d_%H%M%S)"
18 |
19 | echo "Backup process completed successfully!"
20 |
--------------------------------------------------------------------------------
/scripts/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Build Script for PiStable Protocol
4 |
5 | echo "Starting the build process..."
6 |
7 | # Navigate to the frontend directory and build the React app
8 | cd frontend || exit
9 | echo "Building the frontend application..."
10 | npm install
11 | npm run build
12 |
13 | # Navigate to the backend directory and build the backend
14 | cd ../backend || exit
15 | echo "Building the backend application..."
16 | npm install
17 |
18 | echo "Build process completed successfully!"
19 |
--------------------------------------------------------------------------------
/scripts/deploy.js:
--------------------------------------------------------------------------------
1 | // scripts/deploy.js
2 | const { ethers } = require("hardhat");
3 |
4 | async function main() {
5 | // Get the contract factories
6 | const PiStable = await ethers.getContractFactory("PiStable");
7 | const Governance = await ethers.getContractFactory("Governance");
8 | const CollateralManager = await ethers.getContractFactory("CollateralManager");
9 | const PriceOracle = await ethers.getContractFactory("PriceOracle");
10 | const Staking = await ethers.getContractFactory("Staking");
11 | const LiquidityPool = await ethers.getContractFactory("LiquidityPool");
12 | const MultiSigWallet = await ethers.getContractFactory("MultiSigWallet");
13 | const Escrow = await ethers.getContractFactory("Escrow");
14 |
15 | // Deploy contracts
16 | const piStable = await PiStable.deploy();
17 | await piStable.deployed();
18 | console.log("PiStable deployed to:", piStable.address);
19 |
20 | const governance = await Governance.deploy(piStable.address);
21 | await governance.deployed();
22 | console.log("Governance deployed to:", governance.address);
23 |
24 | const collateralManager = await CollateralManager.deploy(piStable.address);
25 | await collateralManager.deployed();
26 | console.log("CollateralManager deployed to:", collateralManager.address);
27 |
28 | const priceOracle = await PriceOracle.deploy([/* initial price providers */]);
29 | await priceOracle.deployed();
30 | console.log("PriceOracle deployed to:", priceOracle.address);
31 |
32 | const staking = await Staking.deploy(piStable.address, ethers.utils.parseUnits("1", 18)); // Example reward rate
33 | await staking.deployed();
34 | console.log("Staking deployed to:", staking.address);
35 |
36 | const liquidityPool = await LiquidityPool.deploy(/* tokenA, tokenB addresses */);
37 | await liquidityPool.deployed();
38 | console.log("LiquidityPool deployed to:", liquidityPool.address);
39 |
40 | const multiSigWallet = await MultiSigWallet.deploy([/* owner addresses */], 2); // Example required confirmations
41 | await multiSigWallet.deployed();
42 | console.log("MultiSigWallet deployed to:", multiSigWallet.address);
43 |
44 | const escrow = await Escrow.deploy();
45 | await escrow.deployed();
46 | console.log("Escrow deployed to:", escrow.address);
47 | }
48 |
49 | main()
50 | .then(() => process.exit(0))
51 | .catch((error) => {
52 | console.error(error);
53 | process.exit(1);
54 | });
55 |
--------------------------------------------------------------------------------
/scripts/deploy.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Deployment Script for PiStable Protocol
4 |
5 | echo "Starting the deployment process..."
6 |
7 | # Set environment variables
8 | export NODE_ENV=production
9 |
10 | # Deploy the backend
11 | cd backend || exit
12 | echo "Deploying the backend application..."
13 | npm run deploy
14 |
15 | # Deploy the frontend
16 | cd ../frontend || exit
17 | echo "Deploying the frontend application..."
18 | npm run deploy
19 |
20 | # Notify completion
21 | echo "Deployment process completed successfully!"
22 |
--------------------------------------------------------------------------------
/scripts/interact.js:
--------------------------------------------------------------------------------
1 | // scripts/interact.js
2 | const { ethers } = require("hardhat");
3 |
4 | async function main() {
5 | const [signer] = await ethers.getSigners();
6 |
7 | // Replace with the deployed contract addresses
8 | const piStableAddress = "0xYourPiStableAddress";
9 | const governanceAddress = "0xYourGovernanceAddress";
10 | const stakingAddress = "0xYourStakingAddress";
11 | const liquidityPoolAddress = "0xYourLiquidityPoolAddress";
12 |
13 | const PiStable = await ethers.getContractAt("PiStable", piStableAddress);
14 | const Governance = await ethers.getContractAt("Governance", governanceAddress);
15 | const Staking = await ethers.getContractAt("Staking", stakingAddress);
16 | const LiquidityPool = await ethers.getContractAt("LiquidityPool", liquidityPoolAddress);
17 |
18 | // Example: Stake tokens
19 | const stakeAmount = ethers.utils.parseUnits("100", 18); // 100 tokens
20 | await PiStable.approve(stakingAddress, stakeAmount);
21 | await Staking.stake(stakeAmount);
22 | console.log("Staked 100 tokens");
23 |
24 | // Example: Create a governance proposal
25 | const proposalDescription = "Change the reward rate for staking";
26 | await Governance.createProposal(proposalDescription);
27 | console.log("Created governance proposal:", proposalDescription);
28 |
29 | // Example: Add liquidity
30 | const amountA = ethers.utils.parseUnits("50", 18); // 50 tokens of token A
31 | const amountB = ethers.utils.parseUnits("50", 18); // 50 tokens of token B
32 | await PiStable.approve(liquidityPoolAddress, amountA);
33 | await PiStable.approve(liquidityPoolAddress, amountB);
34 | await LiquidityPool.addLiquidity(amountA, amountB);
35 | console.log("Added liquidity to the pool");
36 | }
37 |
38 | main()
39 | .then(() => process.exit(0))
40 | .catch((error) => {
41 | console.error(error);
42 | process.exit(1);
43 | });
44 |
--------------------------------------------------------------------------------
/scripts/migrate.js:
--------------------------------------------------------------------------------
1 | // scripts/migrate.js
2 | const { ethers } = require("hardhat");
3 |
4 | async function main() {
5 | const [deployer] = await ethers.getSigners();
6 |
7 | // Replace with the deployed contract addresses
8 | const oldContractAddress = "0xYourOldContractAddress";
9 | const NewContract = await ethers.getContractFactory("NewContract");
10 |
11 | // Deploy the new contract
12 | const newContract = await NewContract.deploy();
13 | await newContract.deployed();
14 | console.log("NewContract deployed to:", newContract.address);
15 |
16 | // Migrate state from the old contract to the new contract
17 | const oldContract = await ethers.getContractAt("OldContract", oldContractAddress);
18 | const stateData = await oldContract.getStateData(); // Example function to get state data
19 |
20 | await newContract.setStateData(stateData); // Example function to set state data
21 | console.log("Migrated state data from old contract to new contract");
22 |
23 | // Optionally, you can disable the old contract or transfer ownership
24 | await oldContract.disable(); // Example function to disable the old contract
25 | console.log("Old contract disabled");
26 | }
27 |
28 | main()
29 | .then(() => process.exit(0))
30 | .catch((error) => {
31 | console.error(error);
32 | process.exit(1);
33 | });
34 |
--------------------------------------------------------------------------------
/scripts/test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Test Script for PiStable Protocol
4 |
5 | echo "Starting the test process..."
6 |
7 | # Navigate to the backend directory and run tests
8 | cd backend || exit
9 | echo "Running backend tests..."
10 | npm test
11 |
12 | # Navigate to the frontend directory and run tests
13 | cd ../frontend || exit
14 | echo "Running frontend tests..."
15 | npm test
16 |
17 | echo "Test process completed successfully!"
18 |
--------------------------------------------------------------------------------
/scripts/utils/constants.js:
--------------------------------------------------------------------------------
1 | // scripts/utils/constants.js
2 |
3 | const TOKEN_DECIMALS = 18;
4 |
5 | const ADDRESSES = {
6 | PI_STABLE: "0xYourPiStableAddress",
7 | GOVERNANCE: "0xYourGovernanceAddress",
8 | COLLATERAL_MANAGER: "0xYourCollateralManagerAddress",
9 | PRICE_ORACLE: "0xYourPriceOracleAddress",
10 | STAKING: "0xYourStakingAddress",
11 | LIQUIDITY_POOL: "0xYourLiquidityPoolAddress",
12 | MULTI_SIG_WALLET: "0xYourMultiSigWalletAddress",
13 | ESCROW: "0xYourEscrowAddress",
14 | };
15 |
16 | const REWARD_RATE = "1"; // Example reward rate for staking
17 |
18 | module.exports = {
19 | TOKEN_DECIMALS,
20 | ADDRESSES,
21 | REWARD_RATE,
22 | };
23 |
--------------------------------------------------------------------------------
/scripts/utils/helpers.js:
--------------------------------------------------------------------------------
1 | // scripts/utils/helpers.js
2 |
3 | const { ethers } = require("hardhat");
4 |
5 | /**
6 | * Converts a number to a BigNumber with the specified decimals.
7 | * @param {number|string} value - The value to convert.
8 | * @param {number} decimals - The number of decimals.
9 | * @returns {BigNumber} - The converted BigNumber.
10 | */
11 | function toBigNumber(value, decimals) {
12 | return ethers.utils.parseUnits(value.toString(), decimals);
13 | }
14 |
15 | /**
16 | * Waits for a transaction to be mined and returns the receipt.
17 | * @param {Promise} tx - The transaction promise.
18 | * @returns {Promise} - The transaction receipt.
19 | */
20 | async function waitForTransaction(tx) {
21 | const receipt = await tx.wait();
22 | return receipt;
23 | }
24 |
25 | /**
26 | * Logs the details of a transaction.
27 | * @param {TransactionReceipt} receipt - The transaction receipt.
28 | */
29 | function logTransaction(receipt) {
30 | console.log(`Transaction Hash: ${receipt.transactionHash}`);
31 | console.log(`Block Number: ${receipt.blockNumber}`);
32 | console.log(`Gas Used: ${receipt.gasUsed.toString()}`);
33 | }
34 |
35 | module.exports = {
36 | toBigNumber,
37 | waitForTransaction,
38 | logTransaction,
39 | };
40 |
--------------------------------------------------------------------------------
/scripts/utils/validators.js:
--------------------------------------------------------------------------------
1 | // scripts/utils/validators.js
2 |
3 | /**
4 | * Validates that a given address is a valid Ethereum address.
5 | * @param {string} address - The address to validate.
6 | * @throws Will throw an error if the address is invalid.
7 | */
8 | function validateAddress(address) {
9 | if (!ethers.utils.isAddress(address)) {
10 | throw new Error(`Invalid address: ${address}`);
11 | }
12 | }
13 |
14 | /**
15 | * Validates that a given amount is a positive number.
16 | * @param {number|string} amount - The amount to validate.
17 | * @throws Will throw an error if the amount is not positive.
18 | */
19 | function validatePositiveAmount(amount) {
20 | if (typeof amount !== "number" && typeof amount !== "string") {
21 | throw new Error(`Invalid amount: ${amount}`);
22 | }
23 | if (parseFloat(amount) <= 0) {
24 | throw new Error(`Amount must be greater than zero: ${amount}`);
25 | }
26 | }
27 |
28 | /**
29 | * Validates that a given string is not empty.
30 | * @param {string} str - The string to validate.
31 | * @throws Will throw an error if the string is empty.
32 | */
33 | function validateNonEmptyString(str) {
34 | if (typeof str !== "string" || str.trim() === "") {
35 | throw new Error(`String cannot be empty: ${str}`);
36 | }
37 | }
38 |
39 | module.exports = {
40 | validateAddress,
41 | validatePositiveAmount,
42 | validateNonEmptyString,
43 | };
44 |
--------------------------------------------------------------------------------
/security/audits/audit-report-2023.md:
--------------------------------------------------------------------------------
1 | # Security Audit Report - 2023
2 |
3 | **Project**: PiStable Protocol
4 | **Audit Date**: January 15, 2023
5 | **Auditor**: Secure Audits Inc.
6 | **Audit Type**: Comprehensive Smart Contract Audit
7 |
8 | ## Summary
9 | The PiStable Protocol underwent a comprehensive security audit to identify vulnerabilities and ensure the integrity of the smart contracts. The audit covered the following contracts:
10 | - PiStable Contract
11 | - Governance Contract
12 | - Staking Contract
13 |
14 | ## Findings
15 | ### Critical Issues
16 | 1. **Reentrancy Vulnerability**: Identified in the Staking Contract during withdrawal functions.
17 | - **Recommendation**: Implement checks-effects-interactions pattern.
18 |
19 | ### High Issues
20 | 1. **Gas Limit Issues**: Certain functions may exceed gas limits under heavy load.
21 | - **Recommendation**: Optimize functions to reduce gas consumption.
22 |
23 | ### Medium Issues
24 | 1. **Access Control**: Some functions lack proper access control checks.
25 | - **Recommendation**: Implement role-based access control.
26 |
27 | ### Low Issues
28 | 1. **Code Comments**: Lack of comments in complex functions.
29 | - **Recommendation**: Add comments for better code readability.
30 |
31 | ## Conclusion
32 | The audit identified several issues, but none were deemed critical enough to warrant immediate action. The team is encouraged to address the identified issues in future iterations.
33 |
34 | **Auditor Signature**:
35 | *Secure Audits Inc.*
36 |
--------------------------------------------------------------------------------
/security/audits/audit-report-2024.md:
--------------------------------------------------------------------------------
1 | # Security Audit Report - 2024
2 |
3 | **Project**: PiStable Protocol
4 | **Audit Date**: January 10, 2024
5 | **Auditor**: Secure Audits Inc.
6 | **Audit Type**: Comprehensive Smart Contract Audit
7 |
8 | ## Summary
9 | The PiStable Protocol underwent a comprehensive security audit to identify vulnerabilities and ensure the integrity of the smart contracts. The audit covered the following contracts:
10 | - PiStable Contract
11 | - Governance Contract
12 | - Staking Contract
13 |
14 | ## Findings
15 | ### Critical Issues
16 | 1. **Reentrancy Vulnerability**: Identified in the Staking Contract during withdrawal functions.
17 | - **Recommendation**: Implement checks-effects-interactions pattern.
18 |
19 | ### High Issues
20 | 1. **Gas Limit Issues**: Certain functions may exceed gas limits under heavy load.
21 | - **Recommendation**: Optimize functions to reduce gas consumption.
22 |
23 | ### Medium Issues
24 | 1. **Access Control**: Some functions lack proper access control checks.
25 | - **Recommendation**: Implement role-based access control.
26 |
27 | ### Low Issues
28 | 1. **Code Comments**: Lack of comments in complex functions.
29 | - **Recommendation**: Add comments for better code readability.
30 |
31 | ## Conclusion
32 | The audit identified several issues, but none were deemed critical enough to warrant immediate action. The team is encouraged to address the identified issues in future iterations.
33 |
34 | **Auditor Signature**:
35 | *Secure Audits Inc.*
36 |
--------------------------------------------------------------------------------
/security/best-practices.md:
--------------------------------------------------------------------------------
1 | # Security Best Practices for PiStable Protocol
2 |
3 | ## Introduction
4 | This document outlines the best practices for ensuring the security of the PiStable Protocol. Following these guidelines will help mitigate risks and enhance the overall security posture of the project.
5 |
6 | ## Best Practices
7 |
8 | ### 1. Code Review
9 | - Conduct regular code reviews to identify potential vulnerabilities.
10 | - Use automated tools to assist in the review process.
11 |
12 | ### 2. Testing
13 | - Implement comprehensive unit and integration tests.
14 | - Use fuzz testing to uncover edge cases and vulnerabilities.
15 |
16 | ### 3. Access Control
17 | - Implement role-based access control (RBAC) to restrict access to sensitive functions.
18 | - Regularly review and update access permissions.
19 |
20 | ### 4. Smart Contract Patterns
21 | - Use established design patterns such as checks-effects-interactions to prevent reentrancy attacks.
22 | - Avoid using `delegatecall` unless absolutely necessary.
23 |
24 | ### 5. Documentation
25 | - Maintain clear and comprehensive documentation for all contracts and functions.
26 | - Include comments in complex code sections for better understanding.
27 |
28 | ### 6. Regular Audits
29 | - Schedule regular security audits by third-party firms.
30 | - Address any findings promptly and thoroughly.
31 |
32 | ### 7. Incident Response
33 | - Develop an incident response plan to address potential security breaches.
34 | - Conduct drills to ensure the team is prepared for real incidents.
35 |
36 | ## Conclusion
37 | By adhering to these best practices, the PiStable Protocol can significantly reduce its risk exposure and enhance its security framework. Continuous improvement and vigilance are key to maintaining a secure environment.
38 |
--------------------------------------------------------------------------------
/security/vulnerability-scans/scan-report-2023.json:
--------------------------------------------------------------------------------
1 | {
2 | "scanDate": "2023-12-01",
3 | "project": "PiStable Protocol",
4 | "scannedBy": "VulnScanner Pro",
5 | "vulnerabilities": [
6 | {
7 | "id": "VULN-2023-001",
8 | "description": "Reentrancy vulnerability in Staking Contract",
9 | "severity": "Critical",
10 | "recommendation": "Implement checks-effects-interactions pattern."
11 | },
12 | {
13 | "id": "VULN-2023-002",
14 | "description": "Gas limit issues in multiple functions",
15 | "severity": "High",
16 | "recommendation": "Optimize functions to reduce gas consumption."
17 | },
18 | {
19 | "id": "VULN-2023-003",
20 | "description": "Access control issues in Governance Contract",
21 | "severity": "Medium",
22 | "recommendation": "Implement role-based access control."
23 | },
24 | {
25 | "id": "VULN-2023-004",
26 | "description": "Lack of comments in complex functions",
27 | "severity": "Low",
28 | "recommendation": "Add comments for better code readability."
29 | }
30 | ]
31 | }
32 |
--------------------------------------------------------------------------------
/security/vulnerability-scans/scan-report-2024.json:
--------------------------------------------------------------------------------
1 | {
2 | "scanDate": "2024-12-01",
3 | "project": "PiStable Protocol",
4 | "scannedBy": "VulnScanner Pro",
5 | "vulnerabilities": [
6 | {
7 | "id": "VULN-2024-001",
8 | "description": "Reentrancy vulnerability in Staking Contract",
9 | "severity": "Critical",
10 | "recommendation": "Implement checks-effects-interactions pattern."
11 | },
12 | {
13 | "id": "VULN-2024-002",
14 | "description": "Gas limit issues in multiple functions",
15 | "severity": "High",
16 | "recommendation": "Optimize functions to reduce gas consumption."
17 | },
18 | {
19 | "id": "VULN-2024-003",
20 | "description": "Access control issues in Governance Contract",
21 | "severity": "Medium",
22 | "recommendation": "Implement role-based access control."
23 | },
24 | {
25 | "id": "VULN-2024-004",
26 | "description": "Lack of comments in complex functions",
27 | "severity": "Low",
28 | "recommendation": "Add comments for better code readability."
29 | }
30 | ]
31 | }
32 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | // src/App.js
2 | import React from 'react';
3 | import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
4 | import { AppProvider } from './context/AppContext';
5 | import Home from './pages/Home';
6 | import Governance from './pages/Governance';
7 | import Staking from './pages/Staking';
8 | import Liquidity from './pages/Liquidity';
9 | import Header from './components/Header';
10 | import Footer from './components/Footer';
11 | import './styles/App.css';
12 |
13 | function App() {
14 | return (
15 |
16 |
17 |
18 |