Skip to content

Commit

Permalink
Merge pull request #1081 from Xekhai/main
Browse files Browse the repository at this point in the history
Xekhai/Voting_DApp
  • Loading branch information
ChoiceCoin authored Dec 20, 2021
2 parents f4afed1 + 944d1cd commit 8155947
Show file tree
Hide file tree
Showing 53 changed files with 55,225 additions and 0 deletions.
Binary file modified .DS_Store
Binary file not shown.
7 changes: 7 additions & 0 deletions xekhai:Voting_Dapp/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2021 Atakere Kester Williams & Adewumi Isaac Eniola

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (Choice Coin DAO Voting Platform), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
17 changes: 17 additions & 0 deletions xekhai:Voting_Dapp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Pretty Vote

In the *Frontend* Directory, run *npm install*.
Then, run *npm start*


Also in the algosdk node modules package.json


add

"browser": {
"crypto": false
},


after devDependencies...
2 changes: 2 additions & 0 deletions xekhai:Voting_Dapp/backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.env
Empty file.
1 change: 1 addition & 0 deletions xekhai:Voting_Dapp/backend/Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: node index.js
6 changes: 6 additions & 0 deletions xekhai:Voting_Dapp/backend/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const app = require("./src/app");

const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Listening: http://localhost:${port}`);
});
21 changes: 21 additions & 0 deletions xekhai:Voting_Dapp/backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"main": "index.js",
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js"
},
"dependencies": {
"algosdk": "^1.12.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"helmet": "^4.6.0",
"joi": "^17.5.0",
"mongoose": "^6.1.2",
"morgan": "^1.10.0",
"uuid": "^8.3.2"
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}
169 changes: 169 additions & 0 deletions xekhai:Voting_Dapp/backend/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
const express = require("express");
const morgan = require("morgan");
const helmet = require("helmet");
const cors = require("cors");

require("dotenv").config();

const middlewares = require("./middlewares");
const app = express();

const { Election, Candidate } = require("./models");
const { indexerClient, ASSET_ID } = require("./config");

app.use(morgan("dev"));
app.use(helmet());
app.use(cors());
app.use(express.json());

app.get("/", (req, res) => {
res.json({
message: "🦄✨Choice Coin API👋✨🦄",
});
});

app.get("/committed/:address", async (req, res) => {
const candidates = await Candidate.find();
const addresses = candidates.map((el) => el.address);

try {
let txnAmt = 0;

const pastTxn = await indexerClient
.searchForTransactions()
.address(req.params.address)
.addressRole("sender")
.assetID(ASSET_ID)
.txType("axfer")
.do();
const txns = pastTxn["transactions"];

txns.forEach((item) => {
const txn = item["asset-transfer-transaction"];
if (addresses.includes(txn["receiver"])) {
txnAmt += txn["amount"] / 100;
}
});

return res.status(200).json({
status: "success",
message: "Choice committed returned successfully",
data: { amount: txnAmt },
});
} catch (error) {
console.log(error);
return res.status(500).json({
status: "error",
message: "An error occured while fetching data",
});
}
});

// For internal use only
app.post("/elections/create", async (req, res) => {
const auth = req.headers["x-authorization-id"];
// check if header exists
if (!auth) {
return res.status(401).json({
status: "error",
message: "You are not authorized to make this request",
});
}

// check if token passed matches the one stored in the environment variable
if (auth !== process.env.AUTHORIZATION_ID) {
return res.status(401).json({
status: "error",
message: "You are not authorized to make this request",
});
}

const { body: data } = req;

try {
const new_election = await Election.create({});

// create candidates
const { candidates } = data;
for (const candidate of candidates) {
const new_candidate = await Candidate.create({
electionID: new_election._id,
address: candidate.address,
});

new_election.candidates.push(new_candidate._id);
}

await new_election.save();

return res.status(201).json({
status: "success",
message: "Election created successfully!",
data: { electionId: new_election._id },
});
} catch (error) {
console.log(error);
return res.status(500).json({
status: "error",
message: "An error occured while creating the election data",
});
}
});

app.get("/elections", async (req, res) => {
const elections = await Election.find().populate("candidates");

return res.status(200).json({
status: "success",
message: "All elections returned successfully",
data: elections,
});
});

app.get("/results/:id", async (req, res) => {
const election = await Election.findOne({ _id: req.params.id }).populate(
"candidates"
);
if (election) {
const results = {};
for (const candidate of election.candidates) {
// variable to hold the amount of choice sent to the address
let amount = 0;

// get the txn history of the addresss
const txnHistory = await indexerClient
.searchForTransactions()
.address(candidate.address)
.assetID(ASSET_ID)
.addressRole("receiver")
.txType("axfer")
.do();
const txns = await txnHistory["transactions"];

// loop through and update the amount
txns?.forEach((txn) => {
const transaction = txn["asset-transfer-transaction"];
amount += transaction["amount"];
});

results[candidate.address] = amount / 100;
}

return res.status(200).json({
status: "success",
message: "Result for election returned successfully!",
data: results,
});
} else {
return res.status(200).json({
status: "success",
message: "Result for election returned successfully!",
data: [],
});
}
});

app.use(middlewares.notFound);
app.use(middlewares.errorHandler);

module.exports = app;
14 changes: 14 additions & 0 deletions xekhai:Voting_Dapp/backend/src/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const algosdk = require("algosdk");

require("dotenv").config();

const algodToken = { "X-API-Key": process.env.ALGOD_TOKEN };
const indexerServer = process.env.INDEXER_SERVER;
const algodServer = process.env.ALGOD_SERVER;
const algodPort = process.env.ALGOD_PORT;
const ASSET_ID = parseInt(process.env.ASSET_ID);

const algodClient = new algosdk.Algodv2(algodToken, algodServer, algodPort);
const indexerClient = new algosdk.Indexer(algodToken, indexerServer, algodPort);

module.exports = { algodClient, indexerClient, ASSET_ID };
19 changes: 19 additions & 0 deletions xekhai:Voting_Dapp/backend/src/middlewares.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
function notFound(req, res, next) {
res.status(404);
const error = new Error(`🔍 - Not Found - ${req.originalUrl}`);
next(error);
}

function errorHandler(err, req, res, next) {
const statusCode = res.statusCode !== 200 ? res.statusCode : 500;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? "🥞" : err.stack,
});
}

module.exports = {
notFound,
errorHandler,
};
27 changes: 27 additions & 0 deletions xekhai:Voting_Dapp/backend/src/models.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const mongoose = require("mongoose");
const { v4: uuid4 } = require("uuid");

require("dotenv").config();

mongoose
.connect(process.env.MONGO_DB_URI)
.then((message) => console.log(`Mongoose running successfully!`))
.catch((error) => console.log(`An error occured!`));

const { Schema } = mongoose;

// Candidate
const CandidateSchema = new Schema({
electionID: { type: String, ref: "Election" },
address: { type: String, maxlength: 58 },
});
const Candidate = mongoose.model("Candidate", CandidateSchema);

// Election
const ElectionSchema = new Schema({
_id: { type: String, default: uuid4 },
candidates: [{ type: Schema.Types.ObjectId, ref: "Candidate" }],
});
const Election = mongoose.model("Election", ElectionSchema);

module.exports = { Election, Candidate };
Empty file.
Loading

0 comments on commit 8155947

Please sign in to comment.