9. Voting Contract
In this tutorial, we're going to deploy a contract that allows users to vote on multiple proposals that a voting administrator controls.
Open the starter code for this tutorial in the Flow Playground:
https://play.onflow.org/d120f0a7-d411-4243-bc59-5125a84f99b3
The tutorial will be asking you to take various actions to interact with this code.
Instructions that require you to take action are always included in a callout box like this one. These highlighted actions are all that you need to do to get your code running, but reading the rest is necessary to understand the language's design.
With the advent of blockchain technology and smart contracts, it has become popular to try to create decentralized voting mechanisms that allow large groups of users to vote completely on chain. This tutorial will provide a trivial example for how this might be achieved by using a resource-oriented programming model.
We'll take you through these steps to get comfortable with the Voting contract.
- Deploy the contract to account
0x01
- Create proposals for users to vote on
- Use a transaction with multiple signers to directly transfer the
Ballot
resource to another account. - Record and cast your vote in the central Voting contract
- Read the results of the vote
Before proceeding with this tutorial, we highly recommend following the instructions in Getting Started and Hello, World! to learn how to use the Playground tools and to learn the fundamentals of Cadence.
A Voting Contract in Cadence
In this contract, a Ballot is represented as a resource.
An administrator can give Ballots to other accounts, then those accounts mark which proposals they vote for and submit the Ballot to the central smart contract to have their votes recorded.
Using a resource type is logical for this application, because if a user wants to delegate their vote, they can send that Ballot to another account, and the use case of voting ballots benefits from the uniqueness and existence guarantees inherent to resources.
Deploy the Contract
Time to deploy the contract we'll be working with:
- Open Contract 1 - the
ApprovalVoting
contract. - In the bottom right deployment modal, press the arrow to expand and make sure account
0x01
is selected as the signer. - Click the Deploy button to deploy it to account
0x01
The deployed contract should have the following contents:
This contract implements a simple voting mechanism where an Administrator
can initialize a vote with an array of proposals to vote on by using the initializeProposals
function.
_15// function to initialize all the proposals for the voting_15pub fun initializeProposals(_ proposals: [String]) {_15 pre {_15 ApprovalVoting.proposals.length == 0: "Proposals can only be initialized once"_15 proposals.length > 0: "Cannot initialize with no proposals"_15 }_15 ApprovalVoting.proposals = proposals_15_15 // Set each tally of votes to zero_15 var i = 0_15 while i < proposals.length {_15 ApprovalVoting.votes[i] = 0_15 i = i + 1_15 }_15}
Then they can give Ballot
resources to other accounts. The other accounts can record their votes on their Ballot
resource by calling the vote
function.
_10pub fun vote(proposal: Int) {_10 pre {_10 self.proposals[proposal] != nil: "Cannot vote for a proposal that doesn't exist"_10 }_10 self.choices[proposal] = true_10}
After a user has voted, they submit their vote to the central smart contract by calling the cast
function, which records the votes in the Ballot
and destroys the used Ballot
.
_15// A user moves their ballot to this function in the contract where_15// its votes are tallied and the ballot is destroyed_15pub fun cast(ballot: @Ballot) {_15 var index = 0_15 // look through the ballot_15 while index < self.proposals.length {_15 if ballot.choices[index]! {_15 // tally the vote if it is approved_15 self.votes[index] = self.votes[index]! + 1_15 }_15 index = index + 1;_15 }_15 // Destroy the ballot because it has been tallied_15 destroy ballot_15}
When the voting time ends, the administrator can read the tallies for each proposal to see if a proposal has received the right number of votes.
Perform Voting
Performing the common actions in this voting contract only takes three types of transactions.
- Initialize Proposals
- Send
Ballot
to a voter - Cast Vote
We have a transaction for each step that we provide for you. With the ApprovalVoting
contract to account 0x01
:
- Open Transaction 1 which should have
Transaction1.cdc
- Submit the transaction with account
0x01
selected as the only signer.
This transaction allows the Administrator
of the contract to create new proposals for voting and save them to the smart contract. They do this by calling the initializeProposals
function on their stored Administrator
resource, giving it two new proposals to vote on.
We use the post
block to ensure that there were two proposals created, like we wished for.
Next, the Administrator
needs to hand out Ballot
s to the voters. There isn't an easy deposit
function this time for them to send a Ballot
to another account, so how would they do it?
This is where multi-signed transactions can come in handy!
Selecting multiple Accounts as Signers
A transaction has access to the private account objects of every account that signed it, so if both the admin and the voter sign a transaction, the admin can directly move a Ballot
resource object to the other account's storage.
In the Flow playground, you can select multiple accounts to sign a transaction to be able to access the private account objects of both accounts.
To select multiple signers, you first need to include two arguments in the prepare
block of your transaction:
prepare(acct1: AuthAccount, acct2: AuthAccount)
The playground will give you an error if the number of selected signers is different than the number of arguments to the prepare block. The playground also maps the accounts you select as signers to the arguments in the order that you select them. The first account you select will be the first argument, and the second account you select is the second argument.
- Open Transaction 2 which should have
Transaction2.cdc
. - Select account
0x01
as a signer first, then also select account0x02
. - Submit the transaction by clicking the
Send
button
This transaction has two signers as prepare
parameters, so it is able to access both of their private AuthAccount
objects, and therefore their private account storage.
Because of this, we can perform a direct transfer of the Ballot
by creating it with the admin's issueBallot
function and then directly store it in the voter's storage by using the save
function.
Account 0x02
should now have a Ballot
resource object in its account storage. You can confirm this by selecting 0x02
from the lower-left sidebar and seeing Ballot
resource listed under the Storage
field.
Casting a Vote
Now that account 0x02
has a Ballot
in their storage, they can cast their vote. To do this, they will call the vote
method on their stored resource, then cast that Ballot
by passing it to the cast
function in the main smart contract.
- Open Transaction 3 which should contain
Transaction3.cdc
. - Select account
0x02
as the only transaction signer. - Click the
send
button to submit the transaction.
In this transaction, the user votes for one of the proposals, and then moves their Ballot back to the smart contract via the cast()
method where the vote is tallied.
Reading the result of the vote
At any time, anyone could read the current tally of votes by directly reading the fields of the contract. You can use a script to do that, since it does not need to modify storage.
- Open a Script 1 which should contain the code below.
- Click the
execute
button to run the script.
You should see something like this print:
_10"Number of Votes for Proposal 1:"_10"Longer Shot Clock"_100_10"Number of Votes for Proposal 2:"_10"Trampolines instead of hardwood floors"_101
This shows that one vote was cast for proposal 1 and no votes were cast for proposal 2.
Other Voting possibilities
This contract was a very simple example of voting in Cadence. It clearly couldn't be used for a real-world voting situation, but hopefully you can see what kind of features could be added to it to ensure practicality and security.