{"size": 4120, "ext": "js", "max_stars_repo_path": "deployContract.js", "max_stars_repo_name": "mcwebdev/Blockchain-Election-DAPP", "max_stars_repo_stars_event_min_datetime": "2020-03-19T15:27:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T10:25:48.000Z", "max_issues_repo_path": "deployContract.js", "max_issues_repo_name": "mcwebdev/Blockchain-Election-DAPP", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deployContract.js", "max_forks_repo_name": "mcwebdev/Blockchain-Election-DAPP", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.219858156, "max_line_length": 97, "alphanum_fraction": 0.6839805825}
/**
 * This script will deploy sample Voting contract to Ethereum TestRPC.
 *
 * Before executing this script, run Ethereum TestRPC from the console:
 *     > .\node_modules\.bin\testrpc (Windows)
 *     $ ./node_modules/.bin/testrpc (*nix)
 *
 * @see https://github.com/ZitRos/edu-ethereum-contract-deployment-example
 */

const Web3 = require("web3");
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
const fs = require("fs");
const solc = require("solc");

const contractToCompile = "Voting"; // .sol (in local directory)
const listOfCandidates = ["Nick", "Edward", "John"];
const contractDetailsOutputFile = `${ __dirname }/client/votingContractData.js`;

let contractAccount; // will be assigned later

// Let's see the list of available accounts first.
console.log(`Listing available accounts...`);
web3.eth.getAccounts().then((accountsList) => {

	console.log(`Available accounts (${ accountsList.length }):\r\n${ accountsList.join("\r\n") }`);
	contractAccount = accountsList[0];
	console.log(`We will deploy contract from account ${ contractAccount }`);

	compile(contractToCompile);

});

function compile (contractName) {

	console.log(`Compiling ${ contractName }.sol...`);

	const contractCode = fs.readFileSync(`${ contractName }.sol`).toString();
	const compiledCode = solc.compile(contractCode);
	const abiDefinition = JSON.parse(compiledCode.contracts[`:${ contractName }`].interface);
	const contract = new web3.eth.Contract(abiDefinition);
	// abiDefinition and contract address are the only things we need to interact with the contract,
	// and we will save them to a file later.

	deploy(contractName, contract, compiledCode, abiDefinition);

}

function deploy (contractName, contract, compiledCode, abiDefinition) {

	console.log(`Preparing ${ contractName } contract to be deployed...`);

	const preparedContract = contract.deploy({
		data: compiledCode.contracts[`:${ contractName }`].bytecode,
		gas: 4700000,
		arguments: [
			// first argument: array of names (which we need to convert to HEX)
			listOfCandidates.map(name => web3.utils.asciiToHex(name))
		]
	}, (err) => err && console.error(err));

	preparedContract.estimateGas().then((gas) => {

		console.log(`Gas estimation for deploying this contract: ${ gas }`);

		preparedContract.send({
			from: contractAccount,
			gas: gas + 100000
		}).then((deployedContract) => {

			console.log(
				`Contract successfully deployed, contract address: ${ 
				deployedContract.options.address }`
			);

			fs.writeFile( // save contract info to a file to access contract data from the client
				contractDetailsOutputFile,
				`window.contractAddress="${ deployedContract.options.address }";\n`
				+ `window.contractABI=${ JSON.stringify(abiDefinition) };\n`
				+ `window.candidates=${ JSON.stringify(listOfCandidates) };\n`
				+ `window.testAccount="${ contractAccount }";`,
				() => interactionTest(deployedContract)
			);

		});

	});

}

function interactionTest (contract) {

	// Check -> Vote -> Check -> Vote -> Check! (Should be 2 votes)
	checkVotes(() =>
	voteFor(listOfCandidates[0], () =>
	checkVotes(() =>
	voteFor(listOfCandidates[0], () =>
	checkVotes(() =>
		console.log("Done. Now open /client/index.html and see contract in action!"
	))))));

	function checkVotes (next) {

		console.log(`Let's see how many votes are received for ${ listOfCandidates[0] }...`);

		contract.methods["totalVotesFor"](
			web3.utils.asciiToHex(listOfCandidates[0])
		).call().then((votes) => {

			console.log(
				`${ listOfCandidates[0] } has got ${ votes } vote${ votes === 1 ? "" : "s" }!`
			);

			next();

		});

	}

	function voteFor (candidate, next) {

		console.log(`Let's vote for ${ candidate } as ${ contractAccount }...`);

		contract.methods["voteForCandidate"](
			web3.utils.asciiToHex(candidate) // again, convert candidate name to HEX
		).send({
			from: contractAccount // let the contract holder vote
		}).then((tx) => {

			console.log(
				`Successfully voted for ${ candidate }. Gas used: ${ tx.gasUsed 
				} Transaction hash: ${ tx.transactionHash }`
			);

			next();

		});

	}

}