Full Stack Hello World Voting Ethereum Dapp Tutorial — Part 3

Mahesh Murthy
Feb 14, 2017 · 5 min read
/* When the contract is deployed on the blockchain, we will 
initialize the total number of tokens for sale, cost per token and
all the candidates
function Voting(uint tokens, uint pricePerToken, bytes32[] candidateNames) public {
candidateList = candidateNames;
totalTokens = tokens;
balanceTokens = tokens;
tokenPrice = pricePerToken;
deployer.deploy(Voting, 1000, web3.toWei('0.1', 'ether'), ['Rama', 'Nick', 'Jose']);// 1000 is the total number of tokens for sale and the price of each token is set to 0.1 ether.
// We will revisit this section again later in this tutorial.
/* This function is used to purchase the tokens. Note the keyword 
'payable' below. By just adding that one keyword to a function,
your contract can now accept Ether from anyone who calls this
function. Accepting money can not get any easier than this!
function buy() payable public returns (uint) {
uint tokensToBuy = msg.value / tokenPrice;
if (tokensToBuy > balanceTokens) throw;
voterInfo[msg.sender].voterAddress = msg.sender;
voterInfo[msg.sender].tokensBought += tokensToBuy;
balanceTokens -= tokensToBuy;
return tokensToBuy;
truffle(development)> Voting.deployed().then(function(contract) {contract.buy({value: web3.toWei('1', 'ether'), from: web3.eth.accounts[1]})})
var Voting = artifacts.require("./Voting.sol");
module.exports = function(deployer) {
deployer.deploy(Voting, 1000, web3.toWei('0.1', 'ether'), ['Rama', 'Nick', 'Jose']);
maheshmurthy|~/dev/ethereum_voting_dapp/chapter3$ truffle migrateUsing network 'development'.Compiling Migrations.sol...
Compiling Voting.sol...
Writing artifacts to ./build/contracts
Running migration: 1_initial_migration.jsDeploying Migrations...Migrations: 0xc9249947010675b8a3b1defb12334148f7f59010Saving successful migration to network...Saving artifacts...Running migration: 2_deploy_contracts.jsDeploying Voting...Voting: 0x795d6d1f7cf467f27e48181da5f1ebd5bbd0a8dfSaving successful migration to network...Saving artifacts...

Thanks to Raine Revere

Mahesh Murthy

Written by

Techie, Foodie, Traveler, Founder www.zastrin.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade