diff --git a/.DS_Store b/.DS_Store
new file mode 100644
index 0000000..346f103
Binary files /dev/null and b/.DS_Store differ
diff --git a/.gitlab/.DS_Store b/.gitlab/.DS_Store
new file mode 100644
index 0000000..e9d44c0
Binary files /dev/null and b/.gitlab/.DS_Store differ
diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md
deleted file mode 100644
index 2255a19..0000000
--- a/DOCUMENTATION.md
+++ /dev/null
@@ -1,359 +0,0 @@
-# Agora Blockchain
-
-> This document covers the technical aspect of **Agora Blockchain**, which will help in understanding the APIs, integrations, frontend, backend, and designs of the project. Please have a look at the README.md file for contribution and installation guidelines.
-
-## Table of Contents
-
-[TOC]
-
-## Prerequisites
-
-- Basic familarity with [Git](https://git-scm.com/), [NodeJS](https://nodejs.org/en) and [npm](https://www.npmjs.com/).
-- Basic familarity with [ReactJS](https://reactjs.org/), [React context APIs](https://reactjs.org/docs/context.html) and [Drizzle](https://www.trufflesuite.com/drizzle), if working on frontend part.
-- Basic familiarity with Blockchain, [Solidity](https://docs.soliditylang.org/en/v0.8.6/) and [Truffle](https://www.trufflesuite.com/truffle), if working on blockchain part.
-
-## Requirements
-
-- [NodeJS](https://nodejs.org/en) >= 10.16 and [npm](https://www.npmjs.com/) >= 5.6 installed.
-- [Git](https://git-scm.com/) installed in the system.
-- [Truffle](https://www.trufflesuite.com/truffle), which can be installed globally with `npm install -g truffle`
-- [Metamask](https://metamask.io) extension added to the browser.
-
-> Please get familiar with the technologies mentioned in the pre-requisites, for a better understanding of the documentation ahead.
-
-## About Agora Blockchain
-
-**Agora** is a library of voting algorithms like `Moore's`, `Oklahoma` etc. Some of these voting algorithms are already implemented by **AOSSIE** in a centralized manner using Scala as their backend. Our vision is to take these algorithms on a decentralized platform, so that, crucial votes of the voters could not be tampered with by the admins, hackers, or anyone with access to the database. Blockchain technology would make the ballots immutable and hence more secure.
-
-### Versions
-
-#### [v1.0](https://gitlab.com/aossie/agora-blockchain/-/tree/gsoc-2021)
-
-In **Google Summer of Code 2021**, we have implemented the first version i.e. **v1.0** with the following features implemented -
-
-- User registration using their public address
-- Creating custom elections
-- Voting in elections
-- Real-time vote counts
-- Results of elections
-- Currently we are having only `General` voting algorithm
-
-## Project Structure
-
-**Agora Blockchain** project is organized into two components - **Frontend** and **Backend**. We have followed the `client-server` model of development, in which `client` and `server` folders are independent of each other, with separate `package.json` and `node_modules`. An Independent and stand-alone model would ensure that developers working on the blockchain part would not end up installing unnecessary client-side dependencies and vice-versa.
-
-**Backend** component deals with the business logic of the project. These logics are implemented using EVM-based smart contracts. Here we are using the Solidity programming language.
-
-**Frontend** component deals with the UI/UX development and integration of deployed smart contracts with the frontend. Here we are using ReactJS and React Context APIs. Trufflesuite's Drizzle will be used for connecting our frontend with blockchain.
-
-Though these components can be developed independently, we need the build files of the backend in the frontend. While deploying or migrating Solidity code, it generates certain build files in `JSON` format which contains the [ABI](), network information, and other necessary details. To use these files in the frontend, we will save these to the `client/src/blockchainBuild` folder.
-
-We will learn more about these components in the documentation ahead.
-
-> This is not a tutorial for **Solidity**, **React**, or **Drizzle**. Readers should be familiar with the mentioned **prerequisites** to understand this documentation.
-
-## Backend
-
-Our backend is implemented using Truffle framework and solidity language. The implementation code is present in `server` directory. The directory description is:
-
-- `contracts` contains all the smart contracts for the blockchain
-- `migrations` contains code for migrating the contracts on the chain
-- `test` contains unit tests for each of the smart contract files.
-
-### About contracts
-
-In the contacts directory we have a `MainContract.sol` file, which is reponsible for creation of users. It contains a mapping `Users` which holds addresses of all the contracts which creates a user. The user has functions to create an election and perform operations.
-
-Then we have a `User.sol` file, which is responsible for creation of an election by a particular user. It contains a mapping `Elections` which contains address of all the election contract, that a particular user creates.
-
-The last contract is `Election.sol`, which is responsible for initializing an election. It contains all the details of the election, and functions for calculating results of an election.
-
-## About tests
-
-The `test` folder in the `server` directory is used to implement tests for every smart contracts written. In each of the test files, most of the functions of contract are being tested, to ensure expected behaviour from the functions.
-
-Every test file has a `contract` function in which all the test cases are written. This function receives 10 acoounts from `Ganache` each with 100 test ethers. By default, all the transactions take place from 1st account ie. accounts[0].
-
-```javascript=
-contract("mainContract", function (accounts) {
- const owner = accounts[0];
- const user1 = accounts[1];
- const user2 = accounts[2];
-})
-```
-
-The tests uses `Mocha` and `Chai` framework. It is expected from future contributors to implement tests for every new feature being added in the contract. The coverage of tests can be obtained using `test coverage` module, whose usage is documented in README.md
-
-## Frontend
-
-Our frontend is implemented using ReactJS and React context APIs. We make API calls to the blockchain network using the Drizzle library. All these calls are implemented in the `client/src/drizzle` folder.
-
-### About Drizzle
-
-**Drizzle** is a collection of libraries to make blockchain integration easier and hassle-free. It also helps to keep the function calls in cached form, which keeps the data fresh. Without Drizzle we had to initialize **web3**, make instances of deployed contracts, and had to manage them throughout the component tree.
-
-We are using Drizzle's `@drizzle/store` and `@drizzle/react-plugin` libraries (see `client/src/index.js`).
-
-```javascript=
-import { Drizzle } from "@drizzle/store";
-import { DrizzleContext } from '@drizzle/react-plugin';
-```
-
-Drizzle requires a `DrizzleOption` object, in which we define what contracts we want to add by default, events, web3 provider, etc. Currently, we are just adding `MainContract` to the drizzle as a default contract, as this is the only contract which we will be deployed to the network. (see `client/src/drizzle/drizzleOptions.js`).
-```javascript=
-import MainContract from "../blockchainBuild/MainContract.json";
-
-const drizzleOptions = {
- contracts: [MainContract]
-}
-
-export default drizzleOptions;
-```
-
-Using this **DrizzleOption** we instantiate a drizzle object, which contains all the necessary information of the deployed contract. We extract important variables from this object using the `DrizzleContext`, which will be shown in the subsequent paragraphs.
-
-```javascript
-const drizzle = new Drizzle(drizzleOptions);
-```
-
-### Screens and Components
-
-In the frontend, we are having the following screens and components -
-
-- Authentication page `/auth`
-- Dashboard `/dashboard`
- - Create election modal
- - Delete election modal
-- Election `election?contractAddress=0x0ab...`
- - Cast vote modal
- - Add candidate modal
- - Candidate detail modal
- - Timer
-
-### Context providers and consumers
-
-We are having the following user-defined and installed context providers in our project. All of these are present in the `client/src/index.js` file -
-
-```javascript=
-const drizzle = new Drizzle(drizzleOptions);
-
-ReactDOM.render(
-
-
-
-
-
-
-
-
- ,
- document.getElementById('root')
-);
-```
-
-**DrizzleContext** - It is an installed context provider from the `@drizzle/react-plugin` library and is used for extracting Drizzle variables like deployed contracts, drizzle state, web3 information, etc. from the `Drizzle` object passed in the `DrizzleContext.Provider` component.
-
-
-
-The extracted context variables can be accessed by their children components using the following line of code.
-
-```javascript
-const { drizzle } = useContext(DrizzleContext.Context);
-```
-
-**ContractProvider** - User-defined context provider, present at `client/src/drizzle/drizzleContracts.js`, to make available runtime deployed contracts to the Drizzle like `Election` and `User` contract, which are not present while starting the application. This component keeps track of all the contracts with which the user interacts within a particular session.
-
-```javascript=
-useEffect(() => {
- contracts.forEach(({contractName, contractAddress, contractType}) => {
- if(!checkContractExist({contractName, contractAddress})) {
- let web3Contract;
- switch (contractType) {
- case USER_CONTRACT:
- web3Contract = new drizzle.web3.eth.Contract(UserContract.abi, contractAddress);
- break;
- case ELECTION_CONTRACT:
- web3Contract = new drizzle.web3.eth.Contract(ElectionContract.abi, contractAddress);
- break;
- default: console.log("Contract type not given");
- }
- drizzle.addContract({ contractName, web3Contract });
- }
- });
-}, [contracts.length]);
-```
-
-In the above code snippet, `contracts` is an array of all the contracts with their `name`, `address` and `type` (Election or User type). For adding contracts to Drizzle, we need its `web3` instance, using the following line of code.
-
-```javascript
-web3Contract = new drizzle.web3.eth.Contract(UserContract.abi, contractAddress);
-```
-
-`User` or `Election` ABI will be required, depending upon which type of contract we are deploying. Once the web3 instance is ready, we can add the contract to drizzle, using the below code.
-
-```javascript
-drizzle.addContract({ contractName, web3Contract });
-```
-
-This `useEffect()` hook is called whenever there is a new contract, as identified by a change in `contracts.length` in its dependency array. New contracts are added in the `contracts` array by calling the `pushNewContracts()` function. This function is called when all the elections are loaded, or a new election is created by the user, or when the user signs in.
-
-```javascript=
-const pushNewContracts = (contractName, contractAddress, contractType) => {
- let newContract = {
- contractName,
- contractAddress,
- contractType
- };
- setContracts(oldContracts => (
- !isAvailable(oldContracts, contractName, contractAddress)
- ?
- [...oldContracts, newContract]
- :
- oldContracts
- ));
-}
-```
-
-**CallProvider** - This context (`client/src/drizzle/calls.js`) manages the drizzle contract calls and provides contract methods according to the ABI, cached method calls, account address, etc. to the consumer. Since there are 3 types of contracts viz. `MainContract`, `User` and `Election`, we divide this provider into 3 function components, and these are - `MainContractCall`, `UserCall`, `ElectionCall`. Each of these functions manages and returns methods, subscribers, and identifiers related to each added contract. Following values are provided by this context provider.
-
-```javascript=
-return (
-
- {children}
-
-);
-```
-
-Here, `MainContract`, `UserContract` and `CurrentElection` variables are objects obtained from their respective functional components (like `UserContract` is obtained from `UserCall.js`). Using these objects we can make general contract calls. See the below code snippet.
-
-```javascript
-CurrentElection.vote(2).send({ from: account });
-```
-
-`CurrentElection` is an object of the `Election` contract which we are viewing. `vote` is a function defined in the `Election` smart contract. We use this line to call the `vote` function with argument `2` (`send` is used to initiate a transaction).
-
-```javascript
-UserContract.userInfo().call();
-```
-
-Similarly, we can make a non-transaction, view-type contract call by using the above snippet.
-
-But, how do we access these context variables? Since these are provided by the **CallProvider**, only its children can access these variables through the `useContext()` hook, as shown below.
-
-```javascript
-import { useCallContext } from "../../drizzle/calls";
-
-const { MainContract, userInfo, account } = useCallContext();
-```
-
-### Let's briefly discuss these context variables
-
-**MainContract** - Object to manage general `call` and `send` contract calls for the deployed `MainContract`. See `ABI` for method details.
-
-**MainSubscriber** - Object to manage cached method calls of the `MainContract`.
-
-**UserContract** - Same as `MainContract`
-
-**UserSubscriber** - Same as `MainSubscriber`
-
-**userInfo** - Information about user signed in. It is an object with the following structure.
-```javascript
-{
- id: Number,
- name: String,
- publicAddress: String,
- contractAddress: String
-}
-```
-
-**electionDetails** - Array of details of elections created by the user signed in. Each element in the array is an object, with the following structure.
-```javascript
-id: Number,
-name: String,
-description: String,
-algorithm: String,
-sdate: Number,
-edate: Number,
-voterCount: Number,
-electionOrganiser: String,
-contractAddress: String
-```
-
-**getCurrentElection** - A function to add Election contract according to contract address to Drizzle. Takes `contractAddress` as argument.
-
-**CurrentElection** - An object with `Election` smart contract as its type, and is used for making `call` and `send` calls to the contract.
-
-**currentElectionDetails** - Same as `electionDetails`, but it is not an array, instead is an object with `electionDetails` of the current election only.
-
-**initialized** - A boolean typed variable to denote whether the drizzle variables, states, store are ready or not. Calling these drizzle variables before they are ready, can throw errors, hence the `initialized` variable is used.
-
-**isRegistered** - It is an integer array of length 2, where 0th index represents whether the user is registered or not (0 for not registered and 1 for registered) and 1th index represents the `userId` of the registered user.
-
-**account** - Public address of the active and connected account on the Metamask wallet.
-
-## Deployments
-
-In this project, we separately deploy **backend** (blockchain) and **frontend** (ReactJS). We choose **[Avalanche](https://www.avax.network/)** or any **EVM** based test network for deploying our smart contracts. Whereas, we deploy our frontend on **[Heroku](https://heroku.com)**.
-
-### Deploying backend
-To migrate our smart contracts to the blockchain, we need 2 things - **RPC node** connected to the network and **an account** with few funds in it to cover the deployment cost. **Avalanche** provides RPC node, and since we are deploying on test network (**Avalanche's Fuji**), we can get free test tokens from their **Faucet**.
-
-**Steps to deploy backend**
-
-- Move to `server` directory.
-- Compile your smart contracts if modified using `truffle compile`
-- Make a `.env` file (`.` is necessary) with the following content
-
-```bash
-MNEMONIC=""
-```
-
-- Now make a new wallet (or use your existing) [here](https://wallet.avax.network) and save the mnemonic in the `.env` file, against the `MNEMONIC` variable, inside the quotes.
-- Visit the [faucet](https://faucet.avax-test.network/) and request some test `AVAX` in your account, by putting your public address in the input field.
-- Now deploy smart contracts using the command
-
-```bash
-truffle migrate --network fuji --reset
-```
-
-- After successful execution of this command, the contracts will be deployed on the network.
-
-### Deploying frontend
-
-We use **Heroku's** cloud service to deploy our frontend. So, to deploy, you need - **an account on Heroku**.
-
-**Steps to deploy frontend**
-
-- Open Heroku dashboard and create a new application by giving it any name of your choice.
-- Install Heroku CLI on your system.
-- Login to your Heroku CLI using the `heroku login` command
-- Now add this newly created application's repo as the remote URL for your `git` using the below command.
-
-```bash
-git remote add heroku https://git.heroku.com/.git
-```
-
-- Push the `main` or `develop` or any other branch, to your app's repository, using
-
-```bash
-git push heroku :main
-```
-
-This last command will initiate the deployment, and after successful deployment, you can see your application at `https://.herokuapp.com`
-
-> **Find this document incomplete?** Make a Pull Request!
diff --git a/README.md b/README.md
index cd02b7e..99b562a 100644
--- a/README.md
+++ b/README.md
@@ -1,143 +1,147 @@
# Agora Blockchain
-# Agora Blockchain
-
-## Prerequisites (only for contributing)
+## Introduction
-- Basic familarity with [Git](https://git-scm.com/), [NodeJS](https://nodejs.org/en) and [npm](https://www.npmjs.com/).
-- Basic familarity with [ReactJS](https://reactjs.org/), [React context APIs](https://reactjs.org/docs/context.html), if working on frontend part.
-- Basic familarity with Blockchain, [Solidity](https://docs.soliditylang.org/en/v0.8.6/) and [Hardhat](https://hardhat.org/), if working on blockchain part.
+Agora is a library of voting algorithms like `Moore's`, `Oklahoma` , `Borda` , `IRV` etc. Some of these voting algorithms are already implemented by AOSSIE in a centralized manner using Scala as their backend. Our vision is to take these algorithms on a decentralized platform, so that, crucial votes of the voters could not be tampered with by admins, hackers, or anyone with access to the database. Blockchain technology would make the ballots immutable and hence more secure.
-## Requirements
+## Tech Stack
-- [NodeJS](https://nodejs.org/en) >= 10.16 and [npm](https://www.npmjs.com/) >= 5.6 installed.
-- [Git](https://git-scm.com/) installed in the system.
-- [Hardhat](https://hardhat.org/), which can be installed globally with `npm install --save-dev hardhat`
-- [Metamask](https://metamask.io) extension added to the browser.
+- ### Backend
-## Development Guide
+ - [Solidity](https://docs.soliditylang.org/en/v0.8.24/): A programming language used for developing smart contracts on the Ethereum ecosystem.
+ - [Hardhat](https://hardhat.org/): A development environment for testing, deploying, and managing smart contracts.
+ - [ChainLink](https://docs.chain.link/ccip): Facilitates cross-chain interoperability within the ecosystem.
+ - [EIPs](https://eips.ethereum.org/): Utilized for implementing the latest Ethereum Improvement Proposals.
+ - [OpenZeppelin](https://www.openzeppelin.com/): Provides a collection of well-audited, secure smart contracts that are easy to integrate and use.
-**Clone the repository**
-
-```bash
-git clone https://gitlab.com/aossie/agora-blockchain/
-```
-
-**Switch to develop branch**
-
-```bash
-git checkout develop
-```
+- ### Client
-The frontend code is inside the `client` directory, whereas the smart contracts (solidity) is present inside `server` folder. You may proceed to `client` folder if you are here for enhancing frontend part of the Agora Blockchain. Else you can proceed to `server` folder for enhancing the efficiency or introducing new features in the blockchain part of the Agora.
+ - [Next.js](https://nextjs.org/): A React framework used for developing the frontend of the application.
+ - [Node.js](https://nodejs.org/en/) (v10.16 or later): A JavaScript runtime required for server-side development.
+ - [MetaMask](https://metamask.io): A browser extension for managing Ethereum accounts and interacting with the blockchain.
+ - [Vercel](https://vercel.com/) - The platform used for deploying the Next.js frontend, offering seamless deployment and hosting with serverless functions.
+ - [Wagmi](https://wagmi.sh/): A set of React hooks for working with Ethereum contracts.
+ - [TailwindCSS](https://tailwindcss.com/): A utility-first CSS framework for efficient styling.
+ - [zustand](https://zustand.docs.pmnd.rs/getting-started/introduction): A state management library for React, used for managing global state in the Next.js application.
-> Whatever dependencies you need for frontend should be saved in their local `package.json` and not in the global one. This would ensure that a developer who only want to contribute to blockchain code, should not install unneccessary frontend dependencies and vice-versa.
+Here's a refined version of the development guide:
-## Setting up client side
+## Development Guide
-Frontend code is present inside the `client` folder. Thus, the dependencies required for frontend are listed in the local `package.json` of `client` folder. You can install only the client-side dependencies using the following command.
+### Running Locally
-**Install client-side dependencies**
+**Clone the Repository**:
```bash
-npm run install-client --force
+git clone https://github.com/AOSSIE-Org/Agora-Blockchain
```
-or
+## Backend
-```bash
-cd client
-npm install
-```
+1. **Navigate to the Blockchain Directory**:
-**Start frontend**
+ ```bash
+ cd blockchain
+ ```
-For development purpose we will run this command to start our client react app.
+2. **Install Dependencies**:
-```bash
-npm run client
-```
+ ```bash
+ npm install
+ ```
-or
+3. **Test the Contracts**:
-```bash
-cd client
-npm start
-```
+ ```bash
+ npx hardhat test
+ ```
-**Build production for client**
+4. **Create an `.env.local` file** with the following environment variables:
-> Only required while deploying frontend to some hosting services like AWS, Heroku, GCP etc.
+ ```bash
+ PRIVATE_KEY=
+ RPC_URL_SEPOLIA=
+ RPC_URL_FUJI=
+ ETHERSCAN_KEY=
+ ```
-This will create production build folder inside the `client` directory with the minified code of frontend. The production build will be served using `server.js` file inside the `client` folder.
+5. **Compile & Deploy Contracts**:
+ ```bash
+ npx hardhat ignition deploy ./ignition/modules/ --network --verify
+ ```
-```
-npm run build
-```
+## Frontend
-Deploying the repository to **Heroku** would automatically serve production build of the client side. This is because, **Heroku** uses `npm run build` for deploying our application. Once the `build` is complete, it uses the `npm start` command. In the `package.json` file of root directory, you can see `node client/server.js` command against `start` script. This will serve the minified files from `build` direcotry.
+1. **Navigate to the Client Directory**:
-## Setting up Hardhat
+ ```bash
+ cd client
+ ```
-Smart contracts or blockchain codes and necessary config files for developing, testing and deploying them are present inside `server` directory. Inside the `server` folder, there is `contracts` directory which stores **Agora Blockchain**'s business logic i.e. the smart contracts. `migrations` folder contains files for migrating smart contracts to the blockchain network. Go through these smart contracts and start contributing.
+2. **Install Dependencies**:
-**About smart contracts**
+ ```bash
+ npm install
+ ```
-We use Hardhat for editing, compiling, debugging and deploying your smart contracts and dApps, all of which work together to create a complete development environment. Compiled smart contracts or build files are then stored inside the `/artifacts/contracts` directory. You need to copy the required files to the frontend after compiling.
+3. **Run the Application**:
-**Install server-side dependencies**
+ ```bash
+ npm run dev
+ ```
-```bash
-npm run install-server
-```
+4. **Create an `.env.local` file** with the following environment variables:
-or
+ ```bash
+ NEXT_PUBLIC_PINATA_JWT=
+ ```
-```bash
-cd server
-npm install
-```
+5. **Visit the Live App at**:
+ **[localhost](http://localhost:3000/)**
-> Now move inside `server` folder for the next steps.
+## About smart contracts
-**Compiling smart contracts**
+The architecture of your Election Factory contract is designed to facilitate the creation and management of elections on the blockchain, incorporating cross-chain voting capabilities through Chainlink's Cross-Chain Interoperability Protocol (CCIP). Below is a detailed explanation:
-If we have altered the code within our Solidity files (.sol) or made new ones or just want generate build files for the client, we need to run `npx hardhat compile` in the terminal. Compiled files are generated inside `/artifacts/contracts/File_name/`.
+### Overview
-```bash
-npx hardhat compile
-```
+The `ElectionFactory` contract serves as the core component of the election creation and management system. It is responsible for generating new election instances, handling cross-chain voting, and maintaining a record of active elections. The contract leverages several other contracts and libraries to achieve its functionality, including the `Election`, `BallotGenerator`, and `ResultCalculator` contracts, as well as Chainlink's CCIP components.
-**Create a .env file**
+- ### Key Features:
-For deploying smart contracts on a blockchain network we need two things: A node connected to the network through which we will make RPC calls and an account with few coins, to cover the cost of deployment. [Infura](https://infura.io/) provides us the node for Ethereum network. So register there and put the Infura's API key inside of the `.env` file, like shown below.
+ - Election Creation: Utilizes a clonable election template (electionGenerator) to efficiently create new election contracts.
+ - Ballot and Result Handling: Generates ballots using the BallotGenerator contract and calculates election results with a dedicated ResultCalculator contract.
+ - Cross-Chain Voting: Implements Chainlink's Cross-Chain Interoperability Protocol (CCIP) to allow voting from multiple blockchain networks.
-```bash
-MNEMONIC=""
-KEY=""
-```
+- ### Efficiency and Security:
-Also save your wallet's mnemonic phrase against the MNEMONIC in .env file, and don't forget to fund the account corresponding to that mnemonic. There are several faucets available to fund your account with test tokens.
+ - Clonable Contracts: Reduces deployment costs and resource usage by cloning a pre-deployed election template.
+ - Owner Management: Ensures only the election creator can delete or modify their election, providing security and control.
+ - Whitelisted Cross-Chain Communication: Only allows approved contracts to send votes across chains, preventing unauthorized access.
-> Never share or commit your `.env` file. It contains your credentials like `mnemonics` and `API` key. Therefore, it is advised to add `.env` to your `.gitignore` file.
+## Deployed Instances
-**Deploying smart contracts**
+- **Election Factory**: [Sepolia Testnet](https://sepolia.etherscan.io/address/0x64c720eBD5227bba57a5E8282893e71087cCcBb8#code)
+- **CCIP Contract**: [FUJI Testnet](https://testnet.snowtrace.io//address/0xf267f0603672E791779E52B153BD9A39C9928767#code)
+- **Frontend**: [Live URL](https://agora-blockchain.vercel.app/)
-You can deploy the smart contracts in the localhost network following these steps:
+## How to Contribute
-- Start a local node
-
-```bash
-npx hardhat node
-```
-
-- Open a new terminal and deploy the smart contract in the localhost network.
-
-
-```bash
-npx hardhat run --network localhost scripts/deploy.js
-```
+1. **Create an Issue**: For any feature requests, bugs, security concerns, or other issues, please create an issue in the repository and wait to be assigned before proceeding.
+2. **Branch Management**: Always create a new branch on your forked repository to commit your changes.
+3. **Pull Request Descriptions**: When submitting a pull request (PR), provide a detailed explanation in the description, outlining all changes and the reasons behind them.
+4. **Community Engagement**: Post your issues and PR updates on the Agora-Blockchain [Discord channel](https://discord.gg/HrJ6eKJ28a) for visibility and discussion.
-The above line will print the contract addresses which are deployed, mentioned in `deploy.js`.
+## Additional Points to Remember
-Replace the contract addresses printed in the terminal with the contract addresses hard coded in the frontend files.
+1. **Testing and Code Quality**: Ensure all changes are thoroughly tested, and avoid introducing code smells.
+2. **Small Changes**: If a frontend change involves fewer than 20 lines of code or if you are making documentation updates, you may directly create a PR without prior assignment.
+3. **Assignment Requirement**: Do not submit unassigned PRs; they will be closed without review.
+4. **Avoiding Overlap**: Before starting work, check existing issues and PRs to avoid duplicating efforts or conflicting changes.
+5. **Open Review Period**: A new issue or PR will remain open for one week to allow other contributors to review and suggest improvements.
+6. **Mentor Notification**: If your PR is left unattended for more than 1-2 weeks, depending on the contribution size, feel free to tag the mentors of Agora-Blockchain to get their attention.
+7. **Completion Timeline**: An issue is expected to be completed within 5-30 days, depending on its complexity. If not completed within this timeframe, it may be reassigned to another contributor.
+8. **Progress Updates**: If your work on an issue is taking longer than expected, ensure you provide regular updates in the issue’s or PR's comments to keep everyone informed.
+9. **Working on Blockchain Components**:
+ - **Error Interface Changes**: If modifying an interface for errors, ensure the corresponding error is added to `client/app/helper/ErrorMessage.ts`.
+ - **Contract ABI Updates**: For changes to `ElectionFactory`, `Election`, or `CCIPSender` contracts, manually update the ABI files in `client/abi/artifacts/` (do not configure Hardhat to generate these paths automatically in the client directory).
diff --git a/anonymousVoting/.DS_Store b/anonymousVoting/.DS_Store
new file mode 100644
index 0000000..363e3a8
Binary files /dev/null and b/anonymousVoting/.DS_Store differ
diff --git a/blockchain/.DS_Store b/blockchain/.DS_Store
new file mode 100644
index 0000000..b3a56f1
Binary files /dev/null and b/blockchain/.DS_Store differ
diff --git a/chatbot/.DS_Store b/chatbot/.DS_Store
new file mode 100644
index 0000000..1471208
Binary files /dev/null and b/chatbot/.DS_Store differ
diff --git a/chatbot/Procfile b/chatbot/Procfile
new file mode 100644
index 0000000..2e35818
--- /dev/null
+++ b/chatbot/Procfile
@@ -0,0 +1 @@
+web: python app.py
diff --git a/chatbot/README.md b/chatbot/README.md
index f2bb2ab..4b03b33 100644
--- a/chatbot/README.md
+++ b/chatbot/README.md
@@ -1,49 +1,63 @@
## Installation
### Create an environment using venv
+
```console
-$ cd chat-bot
+$ cd chatbot
$ python3 -m venv venv
```
### Activate it
+
Mac / Linux:
+
```console
. venv/bin/activate
```
+
Windows:
+
```console
venv\Scripts\activate
```
+
### Install PyTorch and dependencies
For Installation of PyTorch see [official website](https://pytorch.org/).
You also need `nltk`:
- ```console
+
+```console
pip install nltk flask_cors numpy torch flask
- ```
+```
If you get an error during the first run, you also need to install `nltk.tokenize.punkt`:
Run this once in your terminal:
- ```console
+
+```console
$ python
>>> import nltk
->>> nltk.download('punkt')
+>>> nltk.download('punkt_tab')
```
## Usage
+
Run
+
```console
python train.py
```
+
This will dump `data.pth` file. And then run
+
```console
python app.py
```
## Customize
+
Have a look at [intents.json](intents.json). You can customize it according to your own use case. Just define a new `tag`, possible `patterns`, and possible `responses` for the chat bot. You have to re-run the training whenever this file is modified.
+
```console
{
"intents": [
diff --git a/chatbot/app.py b/chatbot/app.py
index 236c500..7227e6b 100644
--- a/chatbot/app.py
+++ b/chatbot/app.py
@@ -1,11 +1,35 @@
import random
import json
-from flask import Flask, request, jsonify
-
import torch
-from model import NeuralNet
-from nltk_utils import bag_of_words, tokenize
-from flask_cors import CORS
+import torch.nn as nn
+from flask import Flask, request, jsonify
+from flask_cors import CORS
+from os.path import dirname, abspath, join
+
+# Define a simple tokenizer and stemmer
+def tokenize(sentence):
+ return sentence.split() # Tokenize by splitting on spaces
+
+def stem(word):
+ return word.lower() # Simple stemming by converting to lowercase
+
+def bag_of_words(tokenized_sentence, words):
+ bag = [1 if stem(word) in [stem(w) for w in tokenized_sentence] else 0 for word in words]
+ return torch.tensor(bag, dtype=torch.float32)
+
+class NeuralNet(nn.Module):
+ def __init__(self, input_size, hidden_size, num_classes):
+ super(NeuralNet, self).__init__()
+ self.l1 = nn.Linear(input_size, hidden_size)
+ self.l2 = nn.Linear(hidden_size, hidden_size)
+ self.l3 = nn.Linear(hidden_size, num_classes)
+ self.relu = nn.ReLU()
+
+ def forward(self, x):
+ x = self.relu(self.l1(x))
+ x = self.relu(self.l2(x))
+ x = self.l3(x)
+ return x
app = Flask(__name__)
CORS(app)
@@ -15,7 +39,7 @@
intents = json.load(json_data)
FILE = "data.pth"
-data = torch.load(FILE)
+data = torch.load(FILE,weights_only=True)
input_size = data["input_size"]
hidden_size = data["hidden_size"]
@@ -26,34 +50,34 @@
model = NeuralNet(input_size, hidden_size, output_size).to(device)
model.load_state_dict(model_state)
-model.eval()
+model.eval()
bot_name = "Agora"
@app.route('/api/chat', methods=['POST'])
def chat():
try:
- data = request.get_json()
- user_message = data['message']
+ request_data = request.get_json()
+ user_message = request_data.get('message', '')
- # Your existing chatbot logic
+ # Tokenize and process the message
sentence = tokenize(user_message)
- X = bag_of_words(sentence, all_words)
- X = X.reshape(1, X.shape[0])
- X = torch.from_numpy(X).to(device)
+ X = bag_of_words(sentence, data['all_words']).unsqueeze(0).to(device)
+ # Make prediction
output = model(X)
_, predicted = torch.max(output, dim=1)
+ tag = data['tags'][predicted.item()]
+ prob = torch.softmax(output, dim=1)[0][predicted.item()]
- tag = tags[predicted.item()]
-
- probs = torch.softmax(output, dim=1)
- prob = probs[0][predicted.item()]
-
+ # Determine response
if prob.item() > 0.75:
for intent in intents['intents']:
if tag == intent["tag"]:
bot_response = random.choice(intent['responses'])
+ break
+ else:
+ bot_response = "I do not understand..."
else:
bot_response = "I do not understand..."
@@ -63,4 +87,4 @@ def chat():
return jsonify({"error": str(e)})
if __name__ == '__main__':
- app.run(debug=True)
+ app.run(host="0.0.0.0", port=5000,debug=True)
diff --git a/chatbot/data.pth b/chatbot/data.pth
index e2b6835..da687f8 100644
Binary files a/chatbot/data.pth and b/chatbot/data.pth differ
diff --git a/chatbot/intents.json b/chatbot/intents.json
index 702dab3..e55d26e 100644
--- a/chatbot/intents.json
+++ b/chatbot/intents.json
@@ -371,21 +371,6 @@
"What did the buffalo say when his son left for college? Bison."
]
},
- {
- "tag": "erc2535_intro",
- "patterns": [
- "What is ERC-2535?",
- "What is erc2535",
- "What is diamond Structure",
- "Explain the ERC-2535 Diamond Standard",
- "Tell me about ERC-2535",
- "Give me an overview of ERC-2535"
- ],
- "responses": [
- "ERC-2535 is a standard for implementing fungible and non-fungible tokens within a single contract, known as the Diamond Standard. It provides a flexible and efficient way to create complex token ecosystems on the Ethereum blockchain.",
- "ERC-2535, also known as the Diamond Standard, is a token standard on the Ethereum blockchain that allows for the creation of composite, or multifunctional, tokens. It enables the implementation of both fungible and non-fungible tokens in a single contract."
- ]
- },
{
"tag": "diamond_structure",
"patterns": [
@@ -401,163 +386,6 @@
"ERC-2535 Diamond Standard employs a modular structure where different functionalities are separated into 'facets.' These facets can be added or removed, providing flexibility and upgradability to the token contract. Each facet represents a specific feature or behavior."
]
},
- {
- "tag": "diamond_facets",
- "patterns": [
- "What are facets in ERC-2535?",
- "Explain ERC-2535 facets",
- "Tell me about the roles of facets in ERC-2535",
- "How do facets work in ERC-2535?"
- ],
- "responses": [
- "Facets in ERC-2535 are individual modules or components that represent specific features or behaviors of a token. Examples include transferability, minting, and burning. Facets can be added or removed to customize the token's functionality.",
- "In ERC-2535, facets are modular components responsible for specific functionalities like transfer, minting, burning, and more. By using facets, developers can mix and match different features to create tokens with the desired behavior, making the Diamond Standard highly flexible."
- ]
- },
- {
- "tag": "diamond_upgradeability",
- "patterns": [
- "How does ERC-2535 support upgradeability?",
- "Explain upgradeability in ERC-2535",
- "Tell me about the upgradeable features of ERC-2535",
- "Can I upgrade specific features in ERC-2535?"
- ],
- "responses": [
- "ERC-2535 supports upgradeability by allowing facets to be added or removed without modifying the core contract. This enables developers to upgrade specific features or add new functionalities while maintaining the existing state and data of the token contract.",
- "Upgradeability in ERC-2535 is achieved through the ability to add or remove facets. Developers can upgrade specific features or add new functionalities without disrupting the existing state of the token contract. This feature enhances the adaptability of ERC-2535 tokens over time."
- ]
- },
- {
- "tag": "diamond_use_cases",
- "patterns": [
- "What are the use cases for ERC-2535?",
- "Explain the practical applications of ERC-2535",
- "Tell me about projects using ERC-2535",
- "Where can ERC-2535 be applied?"
- ],
- "responses": [
- "ERC-2535 is suitable for projects that require a flexible and upgradable token infrastructure. It's used in applications like decentralized finance (DeFi), gaming, and other tokenized ecosystems where different functionalities are required within a single contract.",
- "ERC-2535 is utilized in projects that demand a versatile token infrastructure. It finds applications in decentralized finance (DeFi), gaming, and other tokenized ecosystems where the need for multiple functionalities within a single contract is essential."
- ]
- },
- {
- "tag": "erc2535_security",
- "patterns": [
- "How secure is ERC-2535?",
- "Tell me about the security of ERC-2535",
- "Is ERC-2535 a secure standard?",
- "What security features does ERC-2535 have?"
- ],
- "responses": [
- "ERC-2535 is designed with security in mind, leveraging the decentralized and tamper-resistant nature of the blockchain. Its modular structure enhances security by allowing for targeted upgrades without compromising the overall integrity of the token contract.",
- "The security of ERC-2535 is a priority, utilizing the inherent security features of blockchain technology. The modular structure and upgradeability contribute to maintaining a robust and secure token standard."
- ]
- },
- {
- "tag": "erc2535_compatibility",
- "patterns": [
- "Is ERC-2535 compatible with other token standards?",
- "Tell me about the compatibility of ERC-2535",
- "Can ERC-2535 tokens work with other standards?",
- "How interoperable is ERC-2535?"
- ],
- "responses": [
- "ERC-2535 is designed to be compatible with existing token standards on the Ethereum blockchain. Its flexible structure allows for seamless integration with other standards, facilitating interoperability within the Ethereum ecosystem.",
- "Compatibility is a key feature of ERC-2535. Its modular design ensures compatibility with other token standards, promoting interoperability and enabling developers to combine features from different standards within a single ERC-2535 contract."
- ]
- },
- {
- "tag": "erc2535_advantages",
- "patterns": [
- "What advantages does ERC-2535 offer?",
- "Explain the benefits of ERC-2535",
- "Tell me why developers choose ERC-2535",
- "Why is ERC-2535 preferred by developers?"
- ],
- "responses": [
- "ERC-2535 offers several advantages, including flexibility, upgradability, and the ability to create complex token ecosystems. Developers choose ERC-2535 for its versatility, making it suitable for a wide range of decentralized applications.",
- "The advantages of ERC-2535 lie in its flexibility and upgradability. Developers choose ERC-2535 for its ability to create multifunctional tokens with ease, providing a comprehensive solution for various decentralized applications."
- ]
- },
- {
- "tag": "erc2535_examples",
- "patterns": [
- "Can you give examples of projects using ERC-2535?",
- "Tell me about real-world applications of ERC-2535",
- "Provide use cases for ERC-2535",
- "Name some projects implementing ERC-2535"
- ],
- "responses": [
- "Several projects in decentralized finance (DeFi), gaming, and tokenized ecosystems leverage ERC-2535. Examples include lending platforms, decentralized exchanges, and innovative gaming experiences built on the Ethereum blockchain.",
- "Real-world applications of ERC-2535 span diverse sectors, with projects in DeFi, gaming, and tokenized ecosystems. Use cases include lending protocols, decentralized exchanges, and groundbreaking gaming applications."
- ]
- },
- {
- "tag": "zkp_intro",
- "patterns": [
- "What is a Zero Knowledge Proof?",
- "Explain Zero Knowledge Proofs",
- "Tell me about ZKPs",
- "How do Zero Knowledge Proofs work?",
- "Give an overview of Zero Knowledge Proofs"
- ],
- "responses": [
- "A Zero Knowledge Proof (ZKP) is a cryptographic method allowing one party to prove the authenticity of a statement to another party without revealing any information about the statement itself. It ensures privacy while providing assurance of truth.",
- "Zero Knowledge Proofs (ZKPs) are cryptographic protocols that enable the verification of information without revealing the actual data. They play a crucial role in maintaining privacy and security in various applications, including digital identity and transactions."
- ]
- },
- {
- "tag": "zkp_properties",
- "patterns": [
- "What are the properties of Zero Knowledge Proofs?",
- "Explain the characteristics of ZKPs",
- "Tell me about the features of Zero Knowledge Proofs",
- "Describe the fundamental properties of ZKPs"
- ],
- "responses": [
- "Zero Knowledge Proofs have three main properties: completeness, soundness, and zero-knowledge. Completeness ensures that a true statement can be proven, soundness ensures false statements cannot be proven, and zero-knowledge ensures that the proof reveals nothing about the statement other than its truth.",
- "The properties of Zero Knowledge Proofs include completeness, soundness, and zero-knowledge. Completeness ensures that a valid statement can be proven, soundness ensures that an invalid statement cannot be proven, and zero-knowledge ensures that the proof leaks no information about the statement."
- ]
- },
- {
- "tag": "zkp_applications",
- "patterns": [
- "What are the applications of Zero Knowledge Proofs?",
- "Tell me how ZKPs are used",
- "Explain the practical uses of Zero Knowledge Proofs",
- "Provide examples of Zero Knowledge Proofs in action"
- ],
- "responses": [
- "Zero Knowledge Proofs are applied in various fields, including authentication, privacy-preserving transactions, and digital identity verification. They enable secure interactions without revealing sensitive information.",
- "The applications of Zero Knowledge Proofs are diverse and include privacy-preserving transactions, authentication, and digital identity verification. ZKPs allow parties to prove the authenticity of information without disclosing the actual data."
- ]
- },
- {
- "tag": "zkp_voting",
- "patterns": [
- "How can Zero Knowledge Proofs be used in voting?",
- "Explain ZKPs in the context of voting",
- "Tell me about Zero Knowledge Proofs and voting",
- "Give examples of ZKPs enhancing voting processes"
- ],
- "responses": [
- "In voting, Zero Knowledge Proofs can be employed to verify age without disclosing the actual birthdate. A voter can prove they are above a certain age without revealing the specific age, thus maintaining privacy while ensuring eligibility.",
- "Zero Knowledge Proofs in voting enable the verification of eligibility without exposing sensitive information. For example, a voter can prove they are of legal age to vote without revealing their actual birthdate, contributing to a privacy-preserving voting process."
- ]
- },
- {
- "tag": "zkp_age_verification",
- "patterns": [
- "How does ZKP verify age during voting?",
- "Explain the process of age verification using ZKP",
- "Tell me about Zero Knowledge Proofs and age verification in voting",
- "Provide details on using ZKPs for age verification in voting"
- ],
- "responses": [
- "In age verification for voting, a voter can use a Zero Knowledge Proof to demonstrate that their age is above a specified threshold without revealing the exact age. This is achieved through a cryptographic protocol that allows the verifier to confirm eligibility without knowing the specific age of the voter.",
- "Zero Knowledge Proofs enable age verification during voting by allowing a voter to prove they meet the age requirement without disclosing their actual age. The cryptographic protocol ensures that the verifier can confirm eligibility without learning any unnecessary details about the voter's age."
- ]
- },
{
"tag": "agora_intro",
"patterns": [
@@ -572,32 +400,6 @@
"Agora Blockchain is a decentralized voting app created by AOSSIE. It utilizes blockchain technology, Zero Knowledge Proofs, and the Diamond Structure to ensure a secure and private voting experience."
]
},
- {
- "tag": "agora_zkp",
- "patterns": [
- "How does Agora Blockchain use Zero Knowledge Proofs?",
- "Explain the role of ZKPs in Agora Blockchain",
- "Tell me about ZKPs in the AOSSIE voting app",
- "How are Zero Knowledge Proofs applied in Agora Blockchain?"
- ],
- "responses": [
- "Agora Blockchain employs Zero Knowledge Proofs (ZKPs) to verify voters' age and credentials without revealing sensitive information. This cryptographic technique ensures privacy while allowing the system to confirm eligibility.",
- "In Agora Blockchain, Zero Knowledge Proofs are used to verify age and credentials securely. This cryptographic technique enables users to prove their eligibility without disclosing unnecessary information, enhancing the privacy of the voting process."
- ]
- },
- {
- "tag": "agora_diamond_structure",
- "patterns": [
- "Explain the Diamond Structure in Agora Blockchain",
- "How is the Diamond Structure used in AOSSIE's voting app?",
- "Tell me about the Diamond Structure in Agora Blockchain",
- "How does Agora Blockchain implement the Diamond Structure?"
- ],
- "responses": [
- "The Diamond Structure in Agora Blockchain refers to the implementation of ERC-2535, allowing for the creation of composite tokens with various functionalities. This structure enhances flexibility and upgradability in the voting app.",
- "Agora Blockchain utilizes the Diamond Structure, implementing ERC-2535, to create composite tokens with multiple functionalities. This modular approach enhances the flexibility and upgradability of the decentralized voting app developed by AOSSIE."
- ]
- },
{
"tag": "agora_voting_algorithms",
"patterns": [
@@ -650,105 +452,6 @@
"The voting app integrates blockchain to create an immutable and decentralized ledger of votes. Each vote is recorded as a block, ensuring transparency and preventing tampering.",
"Blockchain integration in the voting app involves using a decentralized and tamper-resistant ledger to record votes. This ensures the integrity of the voting process and provides a transparent and auditable record of all transactions."
]
- },
- {
- "tag": "transparent_results",
- "patterns": [
- "How does the app ensure transparent election results?",
- "Explain the transparency of election results in the app",
- "Tell me about result transparency in the voting app",
- "What measures are in place for ensuring transparent results in the voting app?"
- ],
- "responses": [
- "The voting app ensures transparent election results by providing a publicly accessible blockchain ledger. Each vote and the overall results are verifiable, promoting trust in the integrity of the election.",
- "Result transparency in the voting app is achieved through a publicly accessible blockchain ledger. Voters can verify their own votes, and the overall election results are tamper-resistant, fostering trust and confidence in the fairness of the election."
- ]
- },
- {
- "tag": "fraud_prevention",
- "patterns": [
- "How does the app prevent fraud in the voting process?",
- "Explain the fraud prevention measures in the voting app",
- "Tell me about security measures against fraud in the voting app",
- "What safeguards are implemented to prevent fraud in the voting app?"
- ],
- "responses": [
- "The voting app prevents fraud by leveraging the immutability of the blockchain. Once a vote is recorded, it cannot be altered, ensuring the integrity of the entire election process.",
- "Fraud prevention in the voting app is ensured through the immutability of the blockchain. Once a vote is recorded, it becomes a permanent and tamper-resistant part of the ledger, safeguarding the integrity of the entire voting process."
- ]
- },
- {
- "tag": "user_experience",
- "patterns": [
- "What is the user experience like in the voting app?",
- "Explain the interface and usability of the app",
- "Tell me about the user-friendly features in the voting app",
- "How user-friendly is the interface of the voting app?"
- ],
- "responses": [
- "The voting app provides a user-friendly interface with intuitive navigation. It ensures a seamless and accessible experience for voters, making the democratic process more inclusive and efficient.",
- "User experience in the voting app is a priority, featuring an intuitive interface and easy navigation. This enhances accessibility and ensures a seamless, user-friendly experience for voters, making the democratic process more inclusive and efficient."
- ]
- },
- {
- "tag": "agora_decentralization",
- "patterns": [
- "How decentralized is Agora Blockchain?",
- "Explain the decentralization features in Agora Blockchain",
- "Tell me about the decentralization of AOSSIE's voting app"
- ],
- "responses": [
- "Agora Blockchain embraces decentralization by leveraging blockchain technology. The distributed nature of the blockchain ensures that no single entity has control, promoting transparency and trust in the voting process.",
- "Decentralization is a core aspect of Agora Blockchain. Utilizing blockchain technology ensures a distributed and decentralized system, preventing any single entity from having undue control. This enhances transparency and trust in the voting process."
- ]
- },
- {
- "tag": "voting_app_features",
- "patterns": [
- "What features does the blockchain voting app offer?",
- "Explain the functionalities of the voting app",
- "Tell me about the capabilities of the blockchain-powered voting app"
- ],
- "responses": [
- "The blockchain voting app offers features such as secure identity verification, transparent result tabulation, and fraud prevention through blockchain's immutability. Its user-friendly interface ensures a positive voting experience.",
- "Functionalities of the blockchain-powered voting app include secure identity verification, transparent result tabulation, and fraud prevention leveraging blockchain's immutability. The user-friendly interface enhances the overall voting experience."
- ]
- },
- {
- "tag": "voting_app_privacy",
- "patterns": [
- "How does the voting app prioritize voter privacy?",
- "Explain the privacy features of the blockchain voting app",
- "Tell me about the privacy measures in the voting app"
- ],
- "responses": [
- "The voting app prioritizes voter privacy by using Zero Knowledge Proofs and secure identity verification. These measures ensure that sensitive information is not disclosed during the voting process, enhancing overall privacy.",
- "Privacy is a priority in the voting app, achieved through the use of Zero Knowledge Proofs and secure identity verification. These measures safeguard sensitive information, ensuring a private and secure voting process."
- ]
- },
- {
- "tag": "voting_app_inclusivity",
- "patterns": [
- "How inclusive is the voting app?",
- "Explain the inclusivity features of the blockchain-powered voting app",
- "Tell me about the efforts to make the voting app inclusive"
- ],
- "responses": [
- "The voting app prioritizes inclusivity with a user-friendly interface and accessible design. Efforts are made to ensure that diverse user demographics can easily participate in the democratic process.",
- "Inclusivity is a focus of the voting app, featuring a user-friendly interface and accessible design. The goal is to enable users from diverse demographics to easily participate in the democratic process."
- ]
- },
- {
- "tag": "voting_app_scalability",
- "patterns": [
- "How scalable is the blockchain-powered voting app?",
- "Explain the scalability features of the voting app",
- "Tell me about the scalability of the blockchain voting app"
- ],
- "responses": [
- "Scalability is a consideration in the design of the voting app. Its architecture allows for efficient scaling to accommodate a growing number of users, ensuring reliability and performance during elections.",
- "The blockchain-powered voting app is designed with scalability in mind. Its architecture enables efficient scaling to handle a growing user base, ensuring reliability and optimal performance during elections."
- ]
}
]
}
diff --git a/chatbot/model.py b/chatbot/model.py
deleted file mode 100644
index 4d6f3b2..0000000
--- a/chatbot/model.py
+++ /dev/null
@@ -1,20 +0,0 @@
-import torch
-import torch.nn as nn
-
-
-class NeuralNet(nn.Module):
- def __init__(self, input_size, hidden_size, num_classes):
- super(NeuralNet, self).__init__()
- self.l1 = nn.Linear(input_size, hidden_size)
- self.l2 = nn.Linear(hidden_size, hidden_size)
- self.l3 = nn.Linear(hidden_size, num_classes)
- self.relu = nn.ReLU()
-
- def forward(self, x):
- out = self.l1(x)
- out = self.relu(out)
- out = self.l2(out)
- out = self.relu(out)
- out = self.l3(out)
- # no activation and no softmax at the end
- return out
\ No newline at end of file
diff --git a/chatbot/nltk_utils.py b/chatbot/nltk_utils.py
deleted file mode 100644
index edbabd1..0000000
--- a/chatbot/nltk_utils.py
+++ /dev/null
@@ -1,43 +0,0 @@
-import numpy as np
-import nltk
-nltk.download('punkt')
-from nltk.stem.porter import PorterStemmer
-stemmer = PorterStemmer()
-
-def tokenize(sentence):
- """
- split sentence into array of words/tokens
- a token can be a word or punctuation character, or number
- """
- return nltk.word_tokenize(sentence)
-
-
-def stem(word):
- """
- stemming = find the root form of the word
- examples:
- words = ["organize", "organizes", "organizing"]
- words = [stem(w) for w in words]
- -> ["organ", "organ", "organ"]
- """
- return stemmer.stem(word.lower())
-
-
-def bag_of_words(tokenized_sentence, words):
- """
- return bag of words array:
- 1 for each known word that exists in the sentence, 0 otherwise
- example:
- sentence = ["hello", "how", "are", "you"]
- words = ["hi", "hello", "I", "you", "bye", "thank", "cool"]
- bog = [ 0 , 1 , 0 , 1 , 0 , 0 , 0]
- """
- # stem each word
- sentence_words = [stem(word) for word in tokenized_sentence]
- # initialize bag with 0 for each word
- bag = np.zeros(len(words), dtype=np.float32)
- for idx, w in enumerate(words):
- if w in sentence_words:
- bag[idx] = 1
-
- return bag
\ No newline at end of file
diff --git a/chatbot/requirements.txt b/chatbot/requirements.txt
new file mode 100644
index 0000000..eec0836
--- /dev/null
+++ b/chatbot/requirements.txt
@@ -0,0 +1,3 @@
+flask
+flask_cors
+torch
\ No newline at end of file
diff --git a/chatbot/train.py b/chatbot/train.py
index deb32d5..5dee63e 100644
--- a/chatbot/train.py
+++ b/chatbot/train.py
@@ -7,8 +7,34 @@
from torch.utils.data import Dataset, DataLoader
import nltk
nltk.download('punkt')
-from nltk_utils import bag_of_words, tokenize, stem
-from model import NeuralNet
+
+
+# Define a simple tokenizer and stemmer
+def tokenize(sentence):
+ return sentence.split() # Tokenize by splitting on spaces
+
+def stem(word):
+ return word.lower() # Simple stemming by converting to lowercase
+
+def bag_of_words(tokenized_sentence, words):
+ bag = [1 if stem(word) in [stem(w) for w in tokenized_sentence] else 0 for word in words]
+ return torch.tensor(bag, dtype=torch.float32)
+
+class NeuralNet(nn.Module):
+ def __init__(self, input_size, hidden_size, num_classes):
+ super(NeuralNet, self).__init__()
+ self.l1 = nn.Linear(input_size, hidden_size)
+ self.l2 = nn.Linear(hidden_size, hidden_size)
+ self.l3 = nn.Linear(hidden_size, num_classes)
+ self.relu = nn.ReLU()
+
+ def forward(self, x):
+ x = self.relu(self.l1(x))
+ x = self.relu(self.l2(x))
+ x = self.l3(x)
+ return x
+
+
with open('intents.json', 'r') as f:
intents = json.load(f)
diff --git a/client/.eslintrc.json b/client/.eslintrc.json
index ea4f299..bffb357 100644
--- a/client/.eslintrc.json
+++ b/client/.eslintrc.json
@@ -1,3 +1,3 @@
{
- "extends":["@babel/plugin-transform-private-property-in-object", "next/core-web-vitals"]
+ "extends": "next/core-web-vitals"
}
diff --git a/client/.gitignore b/client/.gitignore
index fd3dbb5..edc7393 100644
--- a/client/.gitignore
+++ b/client/.gitignore
@@ -9,6 +9,10 @@
# testing
/coverage
+/api/__pycache__/
+api/__pycache__/
+
+
# next.js
/.next/
/out/
@@ -20,6 +24,8 @@
.DS_Store
*.pem
+/venv/
+venv
# debug
npm-debug.log*
yarn-debug.log*
diff --git a/client/app/components/Cards/BallotCards/RankedBallot.tsx b/client/app/components/Cards/BallotCards/RankedBallot.tsx
index 8fc3f39..b5f11c7 100644
--- a/client/app/components/Cards/BallotCards/RankedBallot.tsx
+++ b/client/app/components/Cards/BallotCards/RankedBallot.tsx
@@ -1,19 +1,9 @@
import React, { useState } from "react";
import { Reorder } from "framer-motion";
-import { useAccount, useWriteContract } from "wagmi";
-import {
- CCIP_FUJI_ADDRESS,
- ELECTION_FACTORY_ADDRESS,
- SEPOLIA_CHAIN_SELECTOR,
-} from "@/app/constants";
-import { CCIPSender } from "@/abi/artifacts/CCIPSender";
import { useParams } from "next/navigation";
-import { Election } from "@/abi/artifacts/Election";
-import toast from "react-hot-toast";
-import { ErrorMessage } from "@/app/helpers/ErrorMessage";
import CandidateCard from "../VotingCards/CandidateCard";
-import { useElectionModal } from "@/app/hooks/ElectionModal";
import BallotInfo from "../../Helper/BallotInfo";
+import Vote from "../../Modal/Vote";
const RankedBallot = ({
candidateList,
isVoted,
@@ -23,38 +13,9 @@ const RankedBallot = ({
isVoted: boolean;
isOwner: boolean;
}) => {
- const { setelectionModal } = useElectionModal();
const { id: electionAddress } = useParams<{ id: `0x${string}` }>();
- const { writeContractAsync } = useWriteContract();
- const { chain } = useAccount();
const [preference, setpreference] = useState(candidateList);
- const vote = async () => {
- const preferenceIDs = preference.map(
- (candidate: any) => candidate.candidateID
- );
- try {
- if (chain?.id === 43113) {
- await writeContractAsync({
- address: CCIP_FUJI_ADDRESS,
- abi: CCIPSender,
- functionName: "sendMessage",
- args: [SEPOLIA_CHAIN_SELECTOR, electionAddress, preferenceIDs],
- });
- } else {
- await writeContractAsync({
- address: electionAddress,
- abi: Election,
- functionName: "userVote",
- args: [preferenceIDs],
- });
- }
- toast.success(`Voted Casted `);
- setelectionModal(false);
- } catch (error) {
- console.log("Error", error);
- toast.error(ErrorMessage(error));
- }
- };
+
return (
<>