-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
74 lines (68 loc) · 2.87 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// require('dotenv').config();
const fs = require("fs")
const express = require('express')
const app = express()
const routes = require('./routes')
const Web3 = require('web3');
const {Client} = require("pg")
const client = new Client({
user: process.env.PG_USERNAME,
host: 'localhost',
database: 'voting_app_db',
password: process.env.PG_PASSWORD,
port: 5432,
})
// const mongodb = require('mongodb').MongoClient
const bodyParser = require('body-parser')
const votersJson = require("./voters.json")
app.use(bodyParser.json());
client.connect()
client.query('SELECT NOW()')
let accountValues = []
let web3;
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
}
var bytecode = fs.readFileSync('./Voting_sol_Ballot.bin').toString()
var abi = JSON.parse(fs.readFileSync('./Voting_sol_Ballot.abi').toString())
const listOfCandidates = ['George W. Bush', 'Barack Obama', 'Joe Biden']
const votingContract = new web3.eth.Contract(abi);
function readAndSaveJson(voterHexValues) {
client
.query("TRUNCATE TABLE voters", (err, res) => {
for (let i = 0; i < votersJson.length; i++) {
let insertQuery = "INSERT INTO voters (name, surname, id_number, password, hexvalue) VALUES(" + "'" + votersJson[i].name + "'" + "," + "'" + votersJson[i].surname + "'" + "," + "'" + votersJson[i].id_number + "'" + "," + "'" + votersJson[i].password +"'" + "," + "'" + voterHexValues[i+1] + "'" + ")"
client
.query(insertQuery)
.then(() => console.log("Voter saved"))
.catch(e => console.log(e.toString().substr(0, 100)))
}
})
}
(async function () {
const accounts = await web3.eth.getAccounts();
let candidates = new Map();
for (let i = 0; i < listOfCandidates.length; i++) {
candidates[web3.utils.asciiToHex(listOfCandidates[i])] = listOfCandidates[i]
}
readAndSaveJson(accounts)
votingContract.deploy({
data: bytecode,
arguments: [listOfCandidates.map(name => web3.utils.asciiToHex(name)),
[accounts[1], accounts[2], accounts[3], accounts[4], accounts[5], accounts[6], accounts[7]],
"1622371495", "1622371495"]
}).send({
from: accounts[0],
gas: 5500000,
gasPrice: web3.utils.toWei('0.00000000000001', 'ether')
}).then((newContractInstance) => {
votingContract.options.address = newContractInstance.options.address
console.log("Contract address: " + newContractInstance.options.address)
})
routes(app, candidates, votingContract, listOfCandidates, client)
app.listen(process.env.PORT || 8082, () => {
console.log('listening on port ' + (process.env.PORT || 8082));
})
})();