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 1
- 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.
In this contract, a Ballot is represented as a resource. An administrator can give Ballots to other accounts, then those account 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.
Open Account 0x01
which has the ApprovalVoting
contract.
Click the Deploy button to deploy it to account 0x01
"
1/*2*3* In this example, we want to create a simple approval voting contract4* where a polling place issues ballots to addresses.5*6* The run a vote, the Admin deploys the smart contract,7* then initializes the proposals8* using the initialize_proposals.cdc transaction.9* The array of proposals cannot be modified after it has been initialized.10*11* Then they will give ballots to users by12* using the issue_ballot.cdc transaction.13*14* Every user with a ballot is allowed to approve any number of proposals.15* A user can choose their votes and cast them16* with the cast_vote.cdc transaction.17*18*/1920pub contract ApprovalVoting {2122//list of proposals to be approved23pub var proposals: [String]2425// number of votes per proposal26pub let votes: {Int: Int}2728// This is the resource that is issued to users.29// When a user gets a Ballot object, they call the `vote` function30// to include their votes, and then cast it in the smart contract31// using the `cast` function to have their vote included in the polling32pub resource Ballot {3334// array of all the proposals35pub let proposals: [String]3637// corresponds to an array index in proposals after a vote38pub var choices: {Int: Bool}3940init() {41self.proposals = ApprovalVoting.proposals42self.choices = {}4344// Set each choice to false45var i = 046while i < self.proposals.length {47self.choices[i] = false48i = i + 149}50}5152// modifies the ballot53// to indicate which proposals it is voting for54pub fun vote(proposal: Int) {55pre {56self.proposals[proposal] != nil: "Cannot vote for a proposal that doesn't exist"57}58self.choices[proposal] = true59}60}6162// Resource that the Administrator of the vote controls to63// initialize the proposals and to pass out ballot resources to voters64pub resource Administrator {6566// function to initialize all the proposals for the voting67pub fun initializeProposals(_ proposals: [String]) {68pre {69ApprovalVoting.proposals.length == 0: "Proposals can only be initialized once"70proposals.length > 0: "Cannot initialize with no proposals"71}72ApprovalVoting.proposals = proposals7374// Set each tally of votes to zero75var i = 076while i < proposals.length {77ApprovalVoting.votes[i] = 078i = i + 179}80}8182// The admin calls this function to create a new Ballot83// that can be transferred to another user84pub fun issueBallot(): @Ballot {85return <-create Ballot()86}87}8889// A user moves their ballot to this function in the contract where90// its votes are tallied and the ballot is destroyed91pub fun cast(ballot: @Ballot) {92var index = 093// look through the ballot94while index < self.proposals.length {95if ballot.choices[index]! {96// tally the vote if it is approved97self.votes[index] = self.votes[index]! + 198}99index = index + 1;100}101// Destroy the ballot because it has been tallied102destroy ballot103}104105// initializes the contract by setting the proposals and votes to empty106// and creating a new Admin resource to put in storage107init() {108self.proposals = []109self.votes = {}110111self.account.save<@Administrator>(<-create Administrator(), to: /storage/VotingAdmin)112}113}
This contract implements a simple voting mechanism where an administrator can initialize it with an array of proposals to vote on by using the initializeProposals
function.
1// function to initialize all the proposals for the voting2pub fun initializeProposals(_ proposals: [String]) {3pre {4ApprovalVoting.proposals.length == 0: "Proposals can only be initialized once"5proposals.length > 0: "Cannot initialize with no proposals"6}7ApprovalVoting.proposals = proposals89// Set each tally of votes to zero10var i = 011while i < proposals.length {12ApprovalVoting.votes[i] = 013i = i + 114}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.
1pub fun vote(proposal: Int) {2pre {3self.proposals[proposal] != nil: "Cannot vote for a proposal that doesn't exist"4}5self.choices[proposal] = true6}
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
.
1// A user moves their ballot to this function in the contract where2// its votes are tallied and the ballot is destroyed3pub fun cast(ballot: @Ballot) {4var index = 05// look through the ballot6while index < self.proposals.length {7if ballot.choices[index]! {8// tally the vote if it is approved9self.votes[index] = self.votes[index]! + 110}11index = index + 1;12}13// Destroy the ballot because it has been tallied14destroy ballot15}
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.
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.
"You should have the ApprovalVoting already deployed to account 0x01
.
Open Transaction 1 which should have Transaction1.cdc
Submit the transaction with account 0x01
selected as the only signer.
1import ApprovalVoting from 0x0123// This transaction allows the administrator of the Voting contract4// to create new proposals for voting and save them to the smart contract56transaction {7prepare(admin: AuthAccount) {89// borrow a reference to the admin Resource10let adminRef = admin.borrow<&ApprovalVoting.Administrator>(from: /storage/VotingAdmin)!1112// Call the initializeProposals function13// to create the proposals array as an array of strings14adminRef.initializeProposals(15["Longer Shot Clock", "Trampolines instead of hardwood floors"]16)1718log("Proposals Initialized!")19}2021post {22ApprovalVoting.proposals.length == 223}2425}
This transaction allows the administrator of the Voting 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 Ballots 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 multiple-transaction signers can come in handy!
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 account 0x02
.
Submit the transaction by clicking the Send
button
1import ApprovalVoting from 0x0123// This transaction allows the administrator of the Voting contract4// to create a new ballot and store it in a voter's account5// The voter and the administrator have to both sign the transaction6// so it can access their storage78transaction {9prepare(admin: AuthAccount, voter: AuthAccount) {1011// borrow a reference to the admin Resource12let adminRef = admin.borrow<&ApprovalVoting.Administrator>(from: /storage/VotingAdmin)!1314// create a new Ballot by calling the issueBallot15// function of the admin Reference16let ballot <- adminRef.issueBallot()1718// store that ballot in the voter's account storage19voter.save<@ApprovalVoting.Ballot>(<-ballot, to: /storage/Ballot)2021log("Ballot transferred to voter")22}23}
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 opening the account 2 tab and seeing the Ballot
resource shown in the Resources box.
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.
1import ApprovalVoting from 0x0123// This transaction allows a voter to select the votes they would like to make4// and cast that vote by using the castVote function5// of the ApprovalVoting smart contract67transaction {8prepare(voter: AuthAccount) {910// take the voter's ballot our of storage11let ballot <- voter.load<@ApprovalVoting.Ballot>(from: /storage/Ballot)!1213// Vote on the proposal14ballot.vote(proposal: 1)1516// Cast the vote by submitting it to the smart contract17ApprovalVoting.cast(ballot: <-ballot)1819log("Vote cast and tallied")20}21}
In this transaction, the user votes for one of the proposals, and then moves their Ballot back to the smart contract where the vote is tallied.
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.
1import ApprovalVoting from 0x0123// This script allows anyone to read the tallied votes for each proposal4//56pub fun main() {78// Access the public fields of the contract to log9// the proposal names and vote counts1011log("Number of Votes for Proposal 1:")12log(ApprovalVoting.proposals[0])13log(ApprovalVoting.votes[0])1415log("Number of Votes for Proposal 2:")16log(ApprovalVoting.proposals[1])17log(ApprovalVoting.votes[1])1819}
You should see something like this print:
1"Number of Votes for Proposal 1:"2"Longer Shot Clock"304"Number of Votes for Proposal 2:"5"Trampolines instead of hardwood floors"61
This shows that one vote was cast for proposal 1 and no votes were cast for proposal 2.
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.