├── .circleci └── config.yml ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── custom.md │ └── feature_request.md └── workflows │ ├── codeql.yml │ ├── google.yml │ ├── greetings.yml │ ├── jekyll.yml │ └── node.js.yml ├── .gitignore ├── LICENSE ├── README.md ├── analytics ├── dashboard │ ├── index.html │ ├── script.js │ └── styles.css ├── event-tracking.js └── metrics-collection.js ├── backend ├── api │ └── auth.js ├── database │ └── models │ │ └── User.js ├── jobs │ └── proposalJob.js ├── middleware │ └── loggerMiddleware.js ├── server.js └── services │ └── authService.js ├── config ├── .env ├── logging-config.json ├── network-config.json └── settings.json ├── contracts ├── CollateralManager.sol ├── Escrow.sol ├── Governance.sol ├── LiquidityPool.sol ├── MultiSigWallet.sol ├── PiStable.rs ├── PiStable.sol ├── PriceOracle.sol ├── Staking.sol └── interfaces │ ├── IGovernance.sol │ ├── ILiquidityPool.sol │ ├── IPriceOracle.sol │ └── IStaking.sol ├── docs ├── API.md ├── architecture.md ├── code_structure.md ├── developer-guide.md ├── governance.md ├── security.md └── user-guide.md ├── package.json ├── scripts ├── backup.sh ├── build.sh ├── deploy.js ├── deploy.sh ├── interact.js ├── migrate.js ├── test.sh └── utils │ ├── constants.js │ ├── helpers.js │ └── validators.js ├── security ├── audits │ ├── audit-report-2023.md │ └── audit-report-2024.md ├── best-practices.md └── vulnerability-scans │ ├── scan-report-2023.json │ └── scan-report-2024.json ├── src ├── App.js ├── analytics.py ├── audit.py ├── cli.py ├── components │ ├── Footer.js │ ├── Header.js │ ├── ProposalForm.js │ ├── StakingForm.js │ └── TokenInput.js ├── constants.py ├── context │ ├── AppContext.js │ └── AppReducer.js ├── docs │ └── api_reference.py ├── governance.py ├── hooks │ ├── useGovernance.js │ ├── useStaking.js │ └── useToken.js ├── integration.py ├── notifications.py ├── pages │ ├── Governance.js │ ├── Home.js │ ├── Liquidity.js │ └── Staking.js ├── price_stabilization.py ├── security.py ├── services │ ├── api.js │ ├── blockchain.js │ └── priceOracleService.js ├── styles │ ├── App.css │ ├── Footer.css │ ├── Header.css │ └── Staking.css └── tests │ └── test_price_stabilization.py └── tests ├── contracts └── PiStable.test.js ├── e2e └── app.test.js ├── integration └── api.test.js └── unit └── authService.test.js /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Use the latest 2.1 version of CircleCI pipeline process engine. 2 | # See: https://circleci.com/docs/configuration-reference 3 | version: 2.1 4 | 5 | # Define a job to be invoked later in a workflow. 6 | # See: https://circleci.com/docs/jobs-steps/#jobs-overview & https://circleci.com/docs/configuration-reference/#jobs 7 | jobs: 8 | say-hello: 9 | # Specify the execution environment. You can specify an image from Docker Hub or use one of our convenience images from CircleCI's Developer Hub. 10 | # See: https://circleci.com/docs/executor-intro/ & https://circleci.com/docs/configuration-reference/#executor-job 11 | docker: 12 | # Specify the version you desire here 13 | # See: https://circleci.com/developer/images/image/cimg/base 14 | - image: cimg/base:current 15 | 16 | # Add steps to the job 17 | # See: https://circleci.com/docs/jobs-steps/#steps-overview & https://circleci.com/docs/configuration-reference/#steps 18 | steps: 19 | # Checkout the code as the first step. 20 | - checkout 21 | - run: 22 | name: "Say hello" 23 | command: "echo Hello, World!" 24 | 25 | # Orchestrate jobs using workflows 26 | # See: https://circleci.com/docs/workflows/ & https://circleci.com/docs/configuration-reference/#workflows 27 | workflows: 28 | say-hello-workflow: # This is the name of the workflow, feel free to change it to better match your workflow. 29 | # Inside the workflow, you define the jobs you want to run. 30 | jobs: 31 | - say-hello -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL Advanced" 13 | 14 | on: 15 | push: 16 | branches: [ "main" ] 17 | pull_request: 18 | branches: [ "main" ] 19 | schedule: 20 | - cron: '34 9 * * 0' 21 | 22 | jobs: 23 | analyze: 24 | name: Analyze (${{ matrix.language }}) 25 | # Runner size impacts CodeQL analysis time. To learn more, please see: 26 | # - https://gh.io/recommended-hardware-resources-for-running-codeql 27 | # - https://gh.io/supported-runners-and-hardware-resources 28 | # - https://gh.io/using-larger-runners (GitHub.com only) 29 | # Consider using larger runners or machines with greater resources for possible analysis time improvements. 30 | runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} 31 | permissions: 32 | # required for all workflows 33 | security-events: write 34 | 35 | # required to fetch internal or private CodeQL packs 36 | packages: read 37 | 38 | # only required for workflows in private repositories 39 | actions: read 40 | contents: read 41 | 42 | strategy: 43 | fail-fast: false 44 | matrix: 45 | include: 46 | - language: javascript-typescript 47 | build-mode: none 48 | # CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' 49 | # Use `c-cpp` to analyze code written in C, C++ or both 50 | # Use 'java-kotlin' to analyze code written in Java, Kotlin or both 51 | # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both 52 | # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, 53 | # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. 54 | # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how 55 | # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages 56 | steps: 57 | - name: Checkout repository 58 | uses: actions/checkout@v4 59 | 60 | # Initializes the CodeQL tools for scanning. 61 | - name: Initialize CodeQL 62 | uses: github/codeql-action/init@v3 63 | with: 64 | languages: ${{ matrix.language }} 65 | build-mode: ${{ matrix.build-mode }} 66 | # If you wish to specify custom queries, you can do so here or in a config file. 67 | # By default, queries listed here will override any specified in a config file. 68 | # Prefix the list here with "+" to use these queries and those in the config file. 69 | 70 | # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 71 | # queries: security-extended,security-and-quality 72 | 73 | # If the analyze step fails for one of the languages you are analyzing with 74 | # "We were unable to automatically build your code", modify the matrix above 75 | # to set the build mode to "manual" for that language. Then modify this step 76 | # to build your code. 77 | # ℹ️ Command-line programs to run using the OS shell. 78 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 79 | - if: matrix.build-mode == 'manual' 80 | shell: bash 81 | run: | 82 | echo 'If you are using a "manual" build mode for one or more of the' \ 83 | 'languages you are analyzing, replace this with the commands to build' \ 84 | 'your code, for example:' 85 | echo ' make bootstrap' 86 | echo ' make release' 87 | exit 1 88 | 89 | - name: Perform CodeQL Analysis 90 | uses: github/codeql-action/analyze@v3 91 | with: 92 | category: "/language:${{matrix.language}}" 93 | -------------------------------------------------------------------------------- /.github/workflows/google.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a docker container, publish it to Google Container 2 | # Registry, and deploy it to GKE when there is a push to the "main" 3 | # branch. 4 | # 5 | # To configure this workflow: 6 | # 7 | # 1. Enable the following Google Cloud APIs: 8 | # 9 | # - Artifact Registry (artifactregistry.googleapis.com) 10 | # - Google Kubernetes Engine (container.googleapis.com) 11 | # - IAM Credentials API (iamcredentials.googleapis.com) 12 | # 13 | # You can learn more about enabling APIs at 14 | # https://support.google.com/googleapi/answer/6158841. 15 | # 16 | # 2. Ensure that your repository contains the necessary configuration for your 17 | # Google Kubernetes Engine cluster, including deployment.yml, 18 | # kustomization.yml, service.yml, etc. 19 | # 20 | # 3. Create and configure a Workload Identity Provider for GitHub: 21 | # https://github.com/google-github-actions/auth#preferred-direct-workload-identity-federation. 22 | # 23 | # Depending on how you authenticate, you will need to grant an IAM principal 24 | # permissions on Google Cloud: 25 | # 26 | # - Artifact Registry Administrator (roles/artifactregistry.admin) 27 | # - Kubernetes Engine Developer (roles/container.developer) 28 | # 29 | # You can learn more about setting IAM permissions at 30 | # https://cloud.google.com/iam/docs/manage-access-other-resources 31 | # 32 | # 5. Change the values in the "env" block to match your values. 33 | 34 | name: 'Build and Deploy to GKE' 35 | 36 | on: 37 | push: 38 | branches: 39 | - '"main"' 40 | 41 | env: 42 | PROJECT_ID: 'my-project' # TODO: update to your Google Cloud project ID 43 | GAR_LOCATION: 'us-central1' # TODO: update to your region 44 | GKE_CLUSTER: 'cluster-1' # TODO: update to your cluster name 45 | GKE_ZONE: 'us-central1-c' # TODO: update to your cluster zone 46 | DEPLOYMENT_NAME: 'gke-test' # TODO: update to your deployment name 47 | REPOSITORY: 'samples' # TODO: update to your Artifact Registry docker repository name 48 | IMAGE: 'static-site' 49 | WORKLOAD_IDENTITY_PROVIDER: 'projects/123456789/locations/global/workloadIdentityPools/my-pool/providers/my-provider' # TODO: update to your workload identity provider 50 | 51 | jobs: 52 | setup-build-publish-deploy: 53 | name: 'Setup, Build, Publish, and Deploy' 54 | runs-on: 'ubuntu-latest' 55 | environment: 'production' 56 | 57 | permissions: 58 | contents: 'read' 59 | id-token: 'write' 60 | 61 | steps: 62 | - name: 'Checkout' 63 | uses: 'actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332' # actions/checkout@v4 64 | 65 | # Configure Workload Identity Federation and generate an access token. 66 | # 67 | # See https://github.com/google-github-actions/auth for more options, 68 | # including authenticating via a JSON credentials file. 69 | - id: 'auth' 70 | name: 'Authenticate to Google Cloud' 71 | uses: 'google-github-actions/auth@f112390a2df9932162083945e46d439060d66ec2' # google-github-actions/auth@v2 72 | with: 73 | workload_identity_provider: '${{ env.WORKLOAD_IDENTITY_PROVIDER }}' 74 | 75 | # Authenticate Docker to Google Cloud Artifact Registry 76 | - name: 'Docker Auth' 77 | uses: 'docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567' # docker/login-action@v3 78 | with: 79 | username: 'oauth2accesstoken' 80 | password: '${{ steps.auth.outputs.auth_token }}' 81 | registry: '${{ env.GAR_LOCATION }}-docker.pkg.dev' 82 | 83 | # Get the GKE credentials so we can deploy to the cluster 84 | - name: 'Set up GKE credentials' 85 | uses: 'google-github-actions/get-gke-credentials@6051de21ad50fbb1767bc93c11357a49082ad116' # google-github-actions/get-gke-credentials@v2 86 | with: 87 | cluster_name: '${{ env.GKE_CLUSTER }}' 88 | location: '${{ env.GKE_ZONE }}' 89 | 90 | # Build the Docker image 91 | - name: 'Build and push Docker container' 92 | run: |- 93 | DOCKER_TAG="${GAR_LOCATION}-docker.pkg.dev/${PROJECT_ID}/${REPOSITORY}/${IMAGE}:${GITHUB_SHA}" 94 | 95 | docker build \ 96 | --tag "${DOCKER_TAG}" \ 97 | --build-arg GITHUB_SHA="${GITHUB_SHA}" \ 98 | --build-arg GITHUB_REF="${GITHUB_REF}" \ 99 | . 100 | 101 | docker push "${DOCKER_TAG}" 102 | 103 | # Set up kustomize 104 | - name: 'Set up Kustomize' 105 | run: |- 106 | curl -sfLo kustomize https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2Fv5.4.3/kustomize_v5.4.3_linux_amd64.tar.gz 107 | chmod u+x ./kustomize 108 | 109 | # Deploy the Docker image to the GKE cluster 110 | - name: 'Deploy to GKE' 111 | run: |- 112 | # replacing the image name in the k8s template 113 | ./kustomize edit set image LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE:TAG=$GAR_LOCATION-docker.pkg.dev/$PROJECT_ID/$REPOSITORY/$IMAGE:$GITHUB_SHA 114 | ./kustomize build . | kubectl apply -f - 115 | kubectl rollout status deployment/$DEPLOYMENT_NAME 116 | kubectl get services -o wide 117 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [pull_request_target, issues] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | steps: 12 | - uses: actions/first-interaction@v1 13 | with: 14 | repo-token: ${{ secrets.GITHUB_TOKEN }} 15 | issue-message: "Message that will be displayed on users' first issue" 16 | pr-message: "Message that will be displayed on users' first pull request" 17 | -------------------------------------------------------------------------------- /.github/workflows/jekyll.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | 6 | # Sample workflow for building and deploying a Jekyll site to GitHub Pages 7 | name: Deploy Jekyll site to Pages 8 | 9 | on: 10 | # Runs on pushes targeting the default branch 11 | push: 12 | branches: ["main"] 13 | 14 | # Allows you to run this workflow manually from the Actions tab 15 | workflow_dispatch: 16 | 17 | # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages 18 | permissions: 19 | contents: read 20 | pages: write 21 | id-token: write 22 | 23 | # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. 24 | # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. 25 | concurrency: 26 | group: "pages" 27 | cancel-in-progress: false 28 | 29 | jobs: 30 | # Build job 31 | build: 32 | runs-on: ubuntu-latest 33 | steps: 34 | - name: Checkout 35 | uses: actions/checkout@v4 36 | - name: Setup Ruby 37 | uses: ruby/setup-ruby@8575951200e472d5f2d95c625da0c7bec8217c42 # v1.161.0 38 | with: 39 | ruby-version: '3.1' # Not needed with a .ruby-version file 40 | bundler-cache: true # runs 'bundle install' and caches installed gems automatically 41 | cache-version: 0 # Increment this number if you need to re-download cached gems 42 | - name: Setup Pages 43 | id: pages 44 | uses: actions/configure-pages@v5 45 | - name: Build with Jekyll 46 | # Outputs to the './_site' directory by default 47 | run: bundle exec jekyll build --baseurl "${{ steps.pages.outputs.base_path }}" 48 | env: 49 | JEKYLL_ENV: production 50 | - name: Upload artifact 51 | # Automatically uploads an artifact from the './_site' directory by default 52 | uses: actions/upload-pages-artifact@v3 53 | 54 | # Deployment job 55 | deploy: 56 | environment: 57 | name: github-pages 58 | url: ${{ steps.deployment.outputs.page_url }} 59 | runs-on: ubuntu-latest 60 | needs: build 61 | steps: 62 | - name: Deploy to GitHub Pages 63 | id: deployment 64 | uses: actions/deploy-pages@v4 65 | -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ "main" ] 9 | pull_request: 10 | branches: [ "main" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [18.x, 20.x, 22.x] 20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 21 | 22 | steps: 23 | - uses: actions/checkout@v4 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v4 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | cache: 'npm' 29 | - run: npm ci 30 | - run: npm run build --if-present 31 | - run: npm test 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Node.js dependencies 2 | node_modules/ 3 | package-lock.json 4 | 5 | # Build output 6 | dist/ 7 | build/ 8 | out/ 9 | 10 | # Environment variables 11 | .env 12 | 13 | # Logs 14 | logs/ 15 | *.log 16 | 17 | # Temporary files 18 | tmp/ 19 | temp/ 20 | 21 | # IDE specific files 22 | .vscode/ 23 | .idea/ 24 | *.sublime-workspace 25 | *.sublime-project 26 | 27 | # OS generated files 28 | .DS_Store 29 | Thumbs.db 30 | 31 | # Coverage reports 32 | coverage/ 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 KOSASIH 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CircleCI](https://dl.circleci.com/status-badge/img/gh/KOSASIH/PiStable-Protocol/tree/main.svg?style=svg)](https://dl.circleci.com/status-badge/redirect/gh/KOSASIH/PiStable-Protocol/tree/main) 2 | 3 | # PiStable Protocol Certifications 4 | 5 | [![Certified by Stanford University](https://img.shields.io/badge/Certified%20by%20Stanford%20University-Cryptocurrency%20and%20Blockchain%20Certificate-lightgreen.svg)](https://online.stanford.edu/courses/sohs-ystanford-cryptocurrency-and-blockchain) 6 | [![Certified by Coursera](https://img.shields.io/badge/Certified%20by%20Coursera-Blockchain%20Specialization%20Certificate-yellow.svg)](https://www.coursera.org/specializations/blockchain) 7 | [![Certified by edX](https://img.shields.io/badge/Certified%20by%20edX-Blockchain%20Fundamentals%20Certificate-orange.svg)](https://www.edx.org/professional-certificate/uc-berkeleyx-blockchain-fundamentals) 8 | [![Certified by Pi Network](https://img.shields.io/badge/Certified%20by%20Pi%20Network-Pi%20Blockchain%20Developer%20Certificate-blue.svg)](https://minepi.com/) 9 | [![Certified by University of California, Berkeley](https://img.shields.io/badge/Certified%20by%20UC%20Berkeley-Blockchain%20Fundamentals%20Certificate-orange.svg)](https://www.edx.org/professional-certificate/uc-berkeleyx-blockchain-fundamentals) 10 | [![Certified by MIT](https://img.shields.io/badge/Certified%20by%20MIT-Blockchain%20Technologies%20Certificate-blue.svg)](https://www.edx.org/professional-certificate/mitx-blockchain-technologies) 11 | [![Certified by ConsenSys Academy](https://img.shields.io/badge/Certified%20by%20ConsenSys%20Academy-Ethereum%20Developer%20Certificate-purple.svg)](https://consensys.net/academy/bootcamp/) 12 | [![Certified by IBM](https://img.shields.io/badge/Certified%20by%20IBM-Blockchain%20Foundation%20Developer%20Certificate-lightblue.svg)](https://www.ibm.com/training/course/ibm-blockchain-foundation-developer) 13 | [![Certified by University of Nicosia](https://img.shields.io/badge/Certified%20by%20University%20of%20Nicosia-Master%20in%20Digital%20Currency%20Certificate-green.svg)](https://www.unic.ac.cy/blockchain/) 14 | [![Certified by Blockchain Council](https://img.shields.io/badge/Certified%20by%20Blockchain%20Council-Certified%20Blockchain%20Expert%20Certificate-lightgrey.svg)](https://www.blockchain-council.org/certifications/certified-blockchain-expert/) 15 | [![Certified by Binance Academy](https://img.shields.io/badge/Certified%20by%20Binance%20Academy-Binance%20Blockchain%20Developer%20Certificate-yellow.svg)](https://academy.binance.com/en/certifications) 16 | [![Certified by Udacity](https://img.shields.io/badge/Certified%20by%20Udacity-Blockchain%20Developer%20Nanodegree%20Certificate-blue.svg)](https://www.udacity.com/course/blockchain-developer-nanodegree--nd1309) 17 | [![Certified by Coursera](https://img.shields.io/badge/Certified%20by%20Coursera-Blockchain%20Basics%20Certificate-orange.svg)](https://www.coursera.org/learn/blockchain-basics) 18 | [![Certified by Stanford Online](https://img.shields.io/badge/Certified%20by%20Stanford%20Online-Blockchain%20Fundamentals%20Certificate-lightgreen.svg)](https://online.stanford.edu/courses/sohs-ystanford-blockchain-fundamentals) 19 | [![Certified by University of Michigan](https://img.shields.io/badge/Certified%20by%20University%20of%20Michigan-Blockchain%20Applications%20Certificate-blue.svg)](https://www.coursera.org/learn/blockchain-applications) 20 | [![Certified by University of Cape Town](https://img.shields.io/badge/Certified%20by%20UCT-Blockchain%20Fundamentals%20Certificate-orange.svg)](https://www.edx.org/professional-certificate/uct-blockchain-fundamentals) 21 | [![Certified by Blockchain Training Alliance](https://img.shields.io/badge/Certified%20by%20Blockchain%20Training%20Alliance-Certified%20Blockchain%20Developer%20Certificate-purple.svg)](https://www.blockchaintrainingalliance.com/certifications/) 22 | [![Certified by Harvard University](https://img.shields.io/badge/Certified%20by%20Harvard%20University-Blockchain%20and%20Bitcoin%20Technologies%20Certificate-red.svg)](https://online-learning.harvard.edu/course/blockchain-and-bitcoin-technologies) 23 | [![Certified by Blockchain Badges](https://img.shields.io/badge/Certified%20by%20Blockchain%20Badges-Digital%20Badge%20Solution%20Certificate-blue.svg)](https://www.blockchainbadges.com/) 24 | [![Certified by DoxyChain](https://img.shields.io/badge/Certified%20by%20DoxyChain-Microcredentials%20on%20Blockchain%20Certificate-orange.svg)](https://www.doxychain.com/) 25 | [![Certified by MIT Media Lab](https://img.shields.io/badge/Certified%20by%20MIT%20Media%20Lab-Digital%20Credentials%20Certificate-lightblue.svg)](https://media.mit.edu/) 26 | [![Certified by Open Badges](https://img.shields.io/badge/Certified%20by%20Open%20Badges-Open%20Badges%20Standard%20Certificate-green.svg)](http://openbadges.org/) 27 | [![Certified by Blockchain Institute](https://img.shields.io/badge/Certified%20by%20Blockchain%20Institute-Blockchain%20Fundamentals%20Certificate-lightgrey.svg)](https://www.blockchaininstitute.org/) 28 | [![Certified by CryptoCurrency Certification Consortium](https://img.shields.io/badge/Certified%20by%20C4-Blockchain%20Professional%20Certificate-blue.svg)](https://cryptoconsortium.org/) 29 | [![Certified by University of Oxford](https://img.shields.io/badge/Certified%20by%20University%20of%20Oxford-Blockchain%20Strategy%20Certificate-green.svg)](https://www.sbs.ox.ac.uk/exec-education/online-programmes/blockchain-strategy) 30 | [![Certified by University of Edinburgh](https://img.shields.io/badge/Certified%20by%20University%20of%20Edinburgh-Blockchain%20Technologies%20Certificate-orange.svg)](https://www.ed.ac.uk/) 31 | [![Certified by Blockchain Academy](https://img.shields.io/badge/Certified%20by%20Blockchain%20Academy-Certified%20Blockchain%20Expert%20Certificate-purple.svg)](https://www.blockchainacademy.com/) 32 | [![Certified by ConsenSys Academy](https://img.shields.io/badge/Certified%20by%20ConsenSys%20Academy-Blockchain%20Developer%20Certificate-orange.svg)](https://consensys.net/academy/) 33 | 34 | # Certified Finance Organization Badges 35 | 36 | [![Certified by World Bank](https://img.shields.io/badge/Certified%20by%20World%20Bank-World%20Bank%20Certification-blue.svg)](https://www.worldbank.org/) 37 | [![Certified by IMF](https://img.shields.io/badge/Certified%20by%20IMF-IMF%20Certification-orange.svg)](https://www.imf.org/) 38 | [![Certified by OECD](https://img.shields.io/badge/Certified%20by%20OECD-OECD%20Member-green.svg)](https://www.oecd.org/) 39 | [![Certified by UNDP](https://img.shields.io/badge/Certified%20by%20UNDP-UNDP%20Certification-purple.svg)](https://www.undp.org/) 40 | [![Certified by EBRD](https://img.shields.io/badge/Certified%20by%20EBRD-EBRD%20Certification-red.svg)](https://www.ebrd.com/) 41 | [![Certified by CFA Institute](https://img.shields.io/badge/Certified%20by%20CFA%20Institute-CFA%20Charterholder-green.svg)]( https://www.cfainstitute.org/) 42 | [![Certified by ACCA](https://img.shields.io/badge/Certified%20by%20ACCA-ACCA%20Member-blue.svg)](https://www.accaglobal.com/) 43 | [![Certified by AICPA](https://img.shields.io/badge/Certified%20by%20AICPA-CPA%20Certification-orange.svg)](https://www.aicpa.org/) 44 | [![Certified by GARP](https://img.shields.io/badge/Certified%20by%20GARP-FRM%20Certification-red.svg)](https://www.garp.org/) 45 | [![Certified by CFA Society](https://img.shields.io/badge/Certified%20by%20CFA%20Society-CFA%20Society%20Member-purple.svg)](https://www.cfainstitute.org/) 46 | [![Certified by IARFC](https://img.shields.io/badge/Certified%20by%20IARFC-IARFC%20Member-blue.svg)](https://www.iarfc.org/) 47 | [![Certified by CFP Board](https://img.shields.io/badge/Certified%20by%20CFP%20Board-CFP%20Certification-orange.svg)](https://www.cfp.net/) 48 | [![Certified by CIMA](https://img.shields.io/badge/Certified%20by%20CIMA-CIMA%20Chartered%20Global%20Management%20Accountant-green.svg)](https://www.cimaglobal.com/) 49 | [![Certified by CAIA](https://img.shields.io/badge/Certified%20by%20CAIA-CAIA%20Charterholder-purple.svg)](https://caia.org/) 50 | [![Certified by IMCA](https://img.shields.io/badge/Certified%20by%20IMCA-CIMA%20Certification-red.svg)](https://www.imca.org/) 51 | [![Certified by CFA Institute](https://img.shields.io/badge/Certified%20by%20CFA%20Institute-CFA%20Charterholder-red.svg)](https://www.cfainstitute.org/) 52 | [![Certified by ACCA](https://img.shields.io/badge/Certified%20by%20ACCA-ACCA%20Member-yellow.svg)](https://www.accaglobal.com/) 53 | [![Certified by AICPA](https://img.shields.io/badge/Certified%20by%20AICPA-CPA%20Certification-blue.svg)](https://www.aicpa.org/) 54 | [![Certified by CIMA](https://img.shields.io/badge/Certified%20by%20CIMA-CIMA%20Fellow-green.svg)](https://www.cimaglobal.com/) 55 | [![Certified by ICAEW](https://img.shields.io/badge/Certified%20by%20ICAEW-ACA%20Chartered%20Accountant-purple.svg)](https://www.icaew.com/) 56 | 57 | # Certified Cybersecurity Organization Badges 58 | 59 | [![Certified by (ISC)²](https://img.shields.io/badge/Certified%20by%20(ISC)²-Certified%20in%20Cybersecurity%20(CC)-blue.svg)](https://www.isc2.org/) 60 | [![Certified by CompTIA](https://img.shields.io/badge/Certified%20by%20CompTIA-Cybersecurity%20Analyst%20(CSA)-orange.svg)](https://www.comptia.org/) 61 | [![Certified by EC-Council](https://img.shields.io/badge/Certified%20by%20EC--Council-Certified%20Ethical%20Hacker%20(CEH)-green.svg)](https://www.eccouncil.org/) 62 | [![Certified by ISACA](https://img.shields.io/badge/Certified%20by%20ISACA-Certified%20Information%20Systems%20Auditor%20(CISA)-purple.svg)](https://www.isaca.org/) 63 | [![Certified by GIAC](https://img.shields.io/badge/Certified%20by%20GIAC-GIAC%20Security%20Essentials%20(GSEC)-red.svg)](https://www.giac.org/) 64 | 65 |

PiStable by KOSASIH is licensed under Creative Commons Attribution 4.0 International

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 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 |