June 16, 2020
This article is a part of a series called Corporate Governance on Blockchain.
Part 1 of the series outlines the potential applications of blockchain in corporate governance. It also provides an overview of the technical architecture of the shareholder voting solution to be implemented in this series and walks through how to set up your project to follow this series. Read part 1 here.
In this article, we will write a shareholder voting smart contract using Solidity.
Here is the overview of the idea we want to capture in the smart contract. We will write a function to:
We will assume that each 'Annual General Meeting (AGM)', the annual meeting where shareholders vote on agendas to make key decisions for the company, will be different, so a different smart contract would be developed for each one.
Assuming that you've set up your project, you can find `Dapp.sol`
Let's start by defining what our candidate will look like. For sake of simplicity, let's assume it will have an id, name and, voteCount.
Now, let's define the addCandidate function. This function's job is to create a candidate listing on the blockchain. Instead of a candidate, you can also vote on agendas. The choice is yours.
The initial voteCount for each candidate will be zero.
We want to invoke the addCandidate function as soon as the smart contract is deployed, so we will call it from the Constructor() function.
The next step would be to fetch all candidates. There are two approaches you could choose from:
Note 1: Since getCandidates() is NOT called from within the smart contract but will be called from the outside, we will use external keyword here.
Note 2: getCandidates() is a read only function. Reading from the blockchain is free. So we use the keyword view here.
Finally we need to add voting logic in our smart contract. Let's call this function vote. Since this function will be called from outside of the smart contract, we will use external keyword here. We will NOT use view keyword because this function writes your vote to the blockchain and writing to the blockchain is not free.
At the end, your smart contract should look like this-
In this article, we explored the various approaches to writing a resource-efficient smart contract. We also covered the important keywords (external, view) to understand and use properly when developing a smart contract. In part 3, we’ll outline how to connect your smart contract to a UI to make it simple for shareholders to interact with the smart contract functions we’ve written here.
Start building with DappStarter.