How To Code Ethereum Election Smart Contract – Live Coding


– Now, for the coding demo,
I will actually walk you guys through a contract to do a
simple election, so in order to do this, you guys can
follow along if you want to. Basically, you just need
to open up a web browser and go to Remix.ethereum.org or you can just Google
Remix ethereum in Google, and that should take you to a
web page that looks like this, so Remix is basically an online ID or integrative development environment, and it’s really nice,
it’s a really cool tool, really great for just testing
out smart contract quickly and good for hack-a-thons or even good for personal projects. And I will definitely
share all the documents and all the slides and
all the code with you guys at the end, so don’t worry if you feel like you can’t follow along
and you can’t catch up, you can just follow along if you want to, or if you don’t want to,
you can just lay back and just watch me code
and as I explain it. So, basically, on the left hand side here, we have this file browser,
so basically if this is the first time you’ve
come to Remix.ethereum.org, Remix will create a
file called ballot.sol, S-O-L for solidity, it basically creates a default
smart contract for you, so you can just delete that file and just create a new file by
clicking this add icon here and giving it a name, and
that will create a new file. In my case, I just gave the name election, and that’s basically
it, so I can hide this, and there’s some other
things on the right side and then at the console at the bottom that I will get into later,
so yeah, let me just zoom in, make this bigger for you
guys, so you can see. Okay, so here, basically,
the first thing I’m gonna do is this thing called pragma
solidity, so basically, what this does is basically
tells that the compile of which version of
solidity we want to use. Here, we’re using 0.4.21, okay, you can ignore this wording for now, it doesn’t matter, so we’re
gonna create a contract called election, so contract
is like a class, like I said, imagine in class election
or contract election, so in this election, we
have basically a candidate, so we want to encapsulate this candidate into a struct; a struct
is similar to, you know, if you’ve done any C
programming language before, struct is similar to a class,
it basically just contains a bunch of data and has no
message, so for the candidate, we basically have a string
for the name of the candidate and we also want to assign an integer to count how many votes the candidate has, and we also wanna create
a struct for a voter. So, for our election, for example, we want to basically make sure that only authorized individual can vote. So, for example, you’d
be doing an election for a vice president of your company, then you’ll wanna make
sure the only people who are authorized which are employees of the company can vote, right? And also, we wanna make sure the voter, we wanna keep track whether
or not they have voted, so we don’t want people
to vote more than once ’cause then that wouldn’t
be a fair election, and we also want to keep track
of who they’re voting for, so we use an onsite to
keep track of the vote because what we’re gonna do
is we assign each candidate based on your number; we’ll
have a candidate number zero, a candidate number one,
candidate number two, and this vote will
basically keep track of oh, I voted for candidate number one. Okay, and basically also we
want to keep an address type, we wanna make it public,
and we wanna keep the owner, so the owner basically is
the owner of this contract so what that means is that
once I created the code, I must deploy my program
onto the block chain, so that every node in the ethereum network will have a copy of my program, so to deploy the contract, a user account that contains some ether must be the one that deploys this contract, so
whoever deploys this contract is the owner of the
contract, and basically, notice that the type of the
owner is an address type, address is basically
like I mentioned before, is like a Bitcoin wallet address
or ethereum wallet address, it’s basically a sequence of
random letters and numbers, and so the owner basically
is a user account, has some ether, and it can
deploy the smart contract. I will show you in a
second how that would work when we deploy the contract,
so let’s just finish writing the remainder of our code, and so we wanna keep track of the owner. We also wanna keep track of
what this election’s about, right, so we give this election
a name, so for example, vice president of xyz,
where xyz is your company or the presidential
election of USA for example. Also, we wanna keep track of, basically using a mapping data structure, so a mapping data structure is
basically like a dictionary. It’s basically like a key value store, so where here basically we have a mapping where the key is an address and we wanna keep track of the voter which is a struct that we created here, so basically what this mapping, this type, we wanna be public and it’s basically, um, we’re keeping track of the voters. So, the public key word is similar to traditional programming languages, they’re visibility modifiers on our, basically, these are, the owner, election name, and voter
that I’ve declared, these are basically called state variables because they are the state that
is stored in the blockchain, so these are the data of my program, and these data are the ones
that are gonna be stored in every single loading ethereum
network in the blockchain, so they’re called state variables, so basically these state
variables, we make it public, so that anyone in the world
can actually read their value, right, and they can also
modify as well, but we will see how we can control who
can modify it in a sec. And also we want to create
an array of candidate types, so the candidate type is
struct that we’ve created and we’re creating an
array of candidate types, and we’re also making this public and we’re giving it this name, candidates, so we wanna keep an array of candidates, and we also wanna keep track
of the total votes we receive so far for our election, like,
say that 100 people voted so far, for example, right? Okay, so next, now we are done with the state variable
decoration of our contract, now let’s create some methods. So, the first method we’re gonna create or function we’re gonna create is basically called the constructor, and the constructor’s
name must match the name on the contract, that’s
how the solidity detects that this is the constructor function, so in this constructor,
we’re gonna paste in the name of our election, and we want
to make this public as well, so then we can deploy it, so basically, when we construct or thing
we wanna set our owner, right, so the constructor gets executed when the contract is deployed, so we basically wanna set
this to message.sender, so you might be wondering, well, where does this message
object come from, right? So, in solidity, there’s a
bunch of global variables that’s made available to
you, and message is one of these global variable for example, and it just comes default in solidity, so making it easier for you
to write a program, right? So, message.sender basically says is, it’s basically the address
of the user account that deployed this contract,
so we set whoever deployed it to the owner state
variable of our contract, and the other thing is we
want to set our election, whoops, election name, right,
the name of the election to the parameter that’s
passing through the parameter of the constructor, so it’s
usually a conventional necessity to mark all parameters inputs to function with the underscore. It’s just a convention, it will work if you don’t have the underscore there, but it’s just a convention,
you can follow it if you want, but it is recommended that you do so. Let’s create our next
function for our contract. So, the next function we
wanna create is basically have a way to add a new
candidate to our election. Let me follow the convention
here, and basically, this is gonna be public as well,
um, let me just scroll down best so you guys can see,
so we only want the owner of this contract which is
basically, you can think about it like the admin or the organizer who’s running this election to basically add a new candidate. We don’t want anyone
just come and be like, declare themself as a candidate,
then this election will be, you know, it wouldn’t work, right? So, solidity has a cool thing
basically called modifiers. I’ll show you what that means, so you can use a keyword modifier. Think of it kinda like a
function, except it’s not exactly like a function, it’s like a modifier, so it has a name and a mess of parameters. And inside this function
what we’re gonna do is basically, we’re gonna
require the message.sender, so the message.sender is the person that’s calling the function to equal to our owner state variable
that we saved, right? So, okay, so basically,
the required state, I-R-E, okay, I spelled that wrong,
okay, so require statement is basically a, it’s kinda like a cert, if you’ve done any other
programming language, it was a cert, solidity
also has a cert as well, but require is usually use
to check input conditions, so the input condition in
this case is the parameter that has passed into the add candidate, so to use a modifier, all we had to do is add this modifier name to our function, so when this function add
candidate gets involved, since we added this modifier,
this actually will execute, right, then you will check
that the message sender equals the owner, and then after this, we’re gonna put an underscore
and then a semicolon, so what does this underscore,
semicolon mean, right? So, this underscore
represents the remaining body of our functions, so the rest of the code inside our add candidate function, so basically this modifier says, we’re gonna execute
this required statement, and, if the conditions are satisfied, then we’ll execute the rest of the body of our add candidate function. You can also use modifier
as a post-condition check, so if you cut this to the
beginning of the require, then the modifier will execute the body of your function first and then execute the post-condition check, so if your smart contract’s
doing some state manipulation, and you can use a cert to
check the internal logic of your program, making sure
that states are consistent after the function execute. But, in this case we wanted
to be a pre-condition check, so we put the underscore afterwards, after the require statement,
so in order to add a candidate, it’s fairly simple, right, so we have this candidate array. We’re basically gonna
basically push a new candidate into this array, so
basically what we’re gonna do is create a new candidate struct, right, we basically create a new
candidate struct with this, uh, by calling candidate, and
then we’re gonna passing all the fields of the
candidate, so the candidate has a name which is already given inside of the parameter of the function, and then basically the
next thing, their vote, is basically gonna be
zero to start with, right, when we add a new candidate,
they don’t have any votes yet. Okay, so the next
function we want to write is basically we want to
authorize a voter, right, we want to authorize someone to vote. Actually, before we do
that, let’s add a function to get the number of
candidates in our function as a helper method to see how
many candidates are there. So, we want it to be public, and we also wanna add this view modifier
and returns onsite integer, so this is how you
declare that your function is gonna return something
is with a returns with a S and then the bracket and the
type that you’re gonna return. So, this view is basically
same thing as constant, constant is now kind of
deprecated, in solidity, and prefers view instead,
so what that means is that your function, this
function doesn’t actually change any of this state variables
that we already declared before in our contract, so that means is that it’s not changing
the state of our program, so that means that all the database doesn’t need to be updated, right, because we’re not updating the state, you’re basically reading the
state from the blockchain, right, so in ethereum, reading
the state of the blockchain is actually free, it
doesn’t cost any money, anyone can go and read it, which is great, so, okay, so basically, for those of you who don’t know what this
website is, this website is called Remix, just
Google Remix.ethereum and you’ll be taken to Remix.ethereum.org, okay, so we wanna get into
the number of candidates. This is fairly easy as well, right, we just wanna return the
size of our candidate array, so we can do this by the
ninth field of the candidates which is provided in
all arrays in solidity, so that’s fairly simple, so the next thing we want to do is authorize a voter, authorize if we can
spell correctly (laughs). So, authorize, so we wanna
authorize a person, right, a person is basically an
address, a user account has an address, and we only
want the owner of this election to do so, so we want this
to be public as well, and then basically what we’re gonna do is basically in our voters, the mapping, we’re basically gonna use this key to retrieve a voter object. You might be asking, okay, we never actually
initialized this dictionary, we never added anything into it, right? So, what is this voter
object that I am retrieving? So, in solidity actually what it does, basically, for mapping,
it basically imagines that all the possible keys are there and it just creates an
empty voter, basically, everything initialized to
zero, um, you can think of it that way, but it doesn’t
actually go and do that because that would be like
infinite amount of addresses, but when we do this we actually
just retrieving basically an empty voter object
with all the fields inside to set to their default, so
this would be false, false, and this would be zero, essentially, so voters, okay so voter is the person, and then we basically want to
change the authorized field within the voter struct
to basically to be true, so that’s pretty much it
for this function as well. So, now we have all this
function, this, now right, the actual function to vote, right? So, we want to vote,
right, so vote index, um. It’s public as well, so
as I mentioned before, when we want our vote, a
voter will basically say they wanna vote for candidate number zero, candidate number one,
candidate number two, so basically this vote index will be used to index into this candidate’s array to retrieve the candidate, so
basically what we’re gonna do, we wanna make sure that
this person is authorized to vote, right, so we
wanna basically make sure that we retrieve the message.sender, so message.sender is the person
who’s calling the function and is an address type,
and we can use this address into our vote, the mapping
to retrieve the voter, and if this voter basically, um… Okay, first, we wanna make
sure they haven’t voted yet, right, so we wanna make sure
the voted field is false, so that’s why we do the not
operator in front of it, and then the next thing we
also wanna do is voters, message.sender, the
authorized field is equal to true as well, so we can just basically, we don’t need to expressly
say this equal to true, basically whatever is
inside the require condition must valuate to true,
and since this authorize is already a bool, we
just check that as true. So, once we check the input conditions, then we wanna basically say
that this guy has voted, so that he can not vote
again, so we basically say that this message sender.vote, we will check who they voted for, so in this case, the vote
index, the candidate number, and also we wanna make
sure that the voted field is now equal to true, so if
they call this function again, the first condition would not pass, and they cannot change the
state of our smart contract. So, now we can keep track of
that and then we also want to actually update the candidate, right, the candidate’s vote count has increased, so candidates, we use the vote
index to get the candidate, and we basically increment
the vote count by one. And then, also the total
votes also incremented by one as well to keep track
of how many votes are there. And one other thing you
could do in solidity is called an event, but I
don’t get into too much detail about events, so we’ll just
keep it as this for now. So, we’ll write one more
function, called end to end our election, so
this is also owner only, only the owner of the
organization or the admin running the election can end the election, so basically this is gonna be
more or less pretty simple, we basically gonna call self destruct, and basically what self destruct does is just destroys this contract so then no further state changes or anyone can call any methods. Basically, we’re saying
this contract is done, we’re done with this
application essentially. And if this contract
were to have any ethers, ethereum inside of it,
by passing the owner into the self destruct,
basically any remaining ether will be sent to the owner,
so that’s pretty much it for the code, now let’s
actually take our code for a spin, right, so basically,
on the right pane here, we have bunch of tabs here,
basically the first one is compile, so compile
like I mentioned before is solidity’s high-level
language, it gets compiled down into bite codes, you can
click the details tab that will tell you basically
the bite codes and everything. These are the bite
codes push, all of these are ethereum bite codes
and there’s more detail about your contract you can
look at, but what we’re gonna do is go to the run tab and
actually take our smart contract for a spin, so here
basically, the JavaScript VM, there’s three different
environments you can run, so the JavaScript VM,
basically what it does is inside the browser window
itself, inside the JavaScript, basically what it’s gonna do is mimic the ethereum blockchain. It’s gonna create this little
test etherum blockchain, and it’s gonna mine
everything instantaneously; it’s not really connected
to the ethereum network, it’s just always inside
the browser’s hand box. That’s what the JavaScript VM is is basically the fastest
way to test your contract. Injected Web3 is say if you have Metamask, if you don’t know,
Metamask is a Chrome plugin that basically manages, it’s like a ethereum wallet essentially, and you can inject the Web3
wallet, and if you select that, it will connect your
Metamask account directly and then you can actually
deploy your contract onto the test net or the
main net, and then you will have to pay real ether if
you do the main net obviously through Metamask, and Web3
Provider is basically, if you have a local
instance of a guest node, so if you download it,
like, if you run a full node for example or even like a, something like a test blockchain, like, something like Ganache
locally on your computer, then you can use Web3 Provider to connect to your local instance of
ethereum, and if you do that, you can specify the local
host and the port number that your thing is running
at, but for this example, yeah, why not, let’s
use the Web3 Provider, so let me actually launch
the Ganache test blockchain, I’ll show you guys what
that would look like, so Ganache is basically a
tool that you can download if you just Google Ganache
ethereum you will find it, so basically this is
like a test blockchain that’s running locally on your computer, so this, you have a bunch of counts, you have basically a count
with a bunch of addresses, and they all have 100 ether, don’t worry, it’s not real ether; it’s
connected to the test net or the real net, it’s
basically a local blockchain running locally on your computer, and it’s only for testing. And you can see the block is,
right now this block is zero, this genesis block that
has no transactions, so this is what Ganache is,
I’ll put this in the background. This is basically running on port 7545. If you’re following along,
if you don’t have Ganache, just select the JavaScript
VM which is the same thing, the way you interact is
exactly the same thing. Just select the first
option and now, to run it, let’s run an election, right, let’s say, who’s the best NBA player ever, right, and when you create,
basically what happens is you see the count, I
selected the first account, you had 100 ether before,
now it has 99.9999 something, so basically that is the account owner that deployed the smart contract, right? And the smart contract
now has an address, right, so if I bring back the
Ganache instance here, now you see that there’s
actually a new transaction. It’s from this account address which is, matches the one in basically here and also in Remix, automatically
pick up the account number from your Ganache instance
which is pretty cool, so now you have this
transaction, and this basically has created a smart contract,
contract creation basically, that tells you, and then
now we have one extra block in our blockchain, ‘kay,
let me put this away. So, now we create a smart contract, now the owner of the contract, this guy, so let’s now add some, let’s
say Kobe Bryant, right, he’s pretty good, obviously
we got Michael Jordan, right, and then let’s add, you know,
just one more, Lebron James. I’m a basketball fan by the
way, so just so you know. So, now we added a bunch of candidates. Now if I actually go
select one of the accounts, oh actually, the owner can
also vote as well, right, so we can authorize ourself,
the owner of the contract to vote, right, and let’s
say we wanted to vote for, okay, let’s just test it out, right. You see these red buttons
and the purple blue-ish buttons here, the red ones
basically are all the functions that will modify the
state of your program, so they will basically be
stored in the blockchain, and all the blue purple ones
are basically read only, so they read the blockchain,
so one thing I forgot to mention is all these
state variables was public. For example, owner, what they
do is they actually create a function, a getter
function called owner, matches the state variable
name that you can use to basically get the
owner of the contract, so the owner of the contract
is the first account as we’ve seen before, right? 67 something blah blah blah. Also, this console here, if I show you, every time you create a
transaction, you can actually look at the detail of every transaction, so this first transaction is
the constructive function, and you if you look at
the detail, it’ll tell you how much gas and transaction
costs and the path to the transaction and all the data used to create the smart contract, right? And that’s what basically
the console is good for if you’re, you know, doing some debugging, looking at more details, so now, okay, so we can get the number of
candidates which is three ’cause we added Michael Jordan,
Kobe Bryant, Lebron James, and basically by now,
nobody has voted, right? And we can even get the first candidate by indexing number zero,
and the name is Kobe Bryant. He has zero votes right now. Now, let’s actually
vote for someone, right? Let’s vote for, say,
Michael Jordan, right, which is candidate number
one, which is the second guy we added, so now if you come here and get candidate Michael
Jordan, now we see the vote count is one and the total vote
count is also one now, right. Now let’s actually vote with
some other user account. Let’s go with a second
account which is second user, but we need to authorize this
guy, so we need to go back to the first account and
then authorize this guy. When you’re authorizing, make sure you’re adding the quotation mark which is basically saying this
account address is a string, so we’re gonna authorize
the second guy here. Let’s also authorize the third guy. Let’s authorize a bunch of
them, so we can, you know, vote with them, ‘kay,
authorize the third guy, and the fourth guy, let’s
copy his address as well, so this little handy tool
lets you copy the address, so I’m also going to authorize
this guy to vote as well, so the third, second,
third, and fourth accounts are all authorized, now
let’s come and vote, right? Let’s say this guy likes
Kobe Bryant better, so he’s gonna vote for
Kobe, and if we go back to get the thing for Kobe, we
can see that his vote count has also incremented to
one, and let’s see this guy also likes Michael Jordan, he’s gonna vote for Michael Jordan, and the
last guy, he likes Labron James, so he’s gonna vote for Labron, right? So, now the total votes should be four. So, that’s kinda like the
smart contract, how it works and how you can, like, play with it, but since we’re kinda limited on time, I’m gonna show you how you
can actually build a front end that basically you can get
these, basically these results, right, say, how do you build
a smart contract front end? So, right now, I basically
have a local instances of basically local webserver
running locally on my computer, and I have some JavaScript
html code that uses Web3 to talk to my smart contract, right? So, now I see who’s the
best NBA player ever? And we have Kobe Bryant, Michael
Jordan, and Lebron James, right, and Michael Jordan has
50% of the vote right now. And now let’s say I
come back and vote for, authorize this last account to vote and have him vote as well,
and let’s say that this guy, the last guy is also
gonna, he’s gonna vote for Michael Jordan as well,
so we don’t have a tie. So, if we come back to
this and refresh our page, we can actually see how
Michael Jordan’s vote has now become 60% and Kobe
and Labron is 20% each, so I don’t have the time to
show you the code for this, but definitely if you
take our online courses, ethereum will definitely
show you how you do this, so this is like a simple page,
like a status page to show, like, the progress of the election. You can definitely build
a more complicated web app that allows say a user to login, and then if they’re
authorized, then they can vote on the front end, so from
the user end prospective, they’re just using a traditional web app, and they, you know, the user
experience is the same, right, and it’s really in the back end you get all the added benefits of security and all the privacy and all of
these things on the back end, so that is pretty much it for example for the smart contract example and the front end, what
it would look like. And, you know, if you wanna learn how to build the front end,
definitely take our courses.

Add a Comment

Your email address will not be published. Required fields are marked *