Interacting with an Ethereum Voting Smart-Contract using Pythons web3

Kipling Crossing
2 min readNov 14, 2020
“ETC Wallpaper — Smart Contract” by EthereumClassic is marked with CC0 1.0

In this article, we will use the web3.py python library to demonstrate that anyone can interact with the DigiPol smart-contract in their own way by demonstrating how to get the vote count of a particular ballot.

The DigiPol app uses smart contracts on the Ethereum network to publish ballots, make votes and get voting results. Ethereum is a decentralized cryptocurrency with smart contract capability. This means that the information on the Ethereum blockchain and the smart contract methods may be accessible by the anyone!

Set-up

Before starting, you will need to install web3.py onto your system. You can do this via pip:

pip install web3

You will also need to have an private key and save as an environmental variable. Here we will save it as PRIVATE_KEY. If you don’t have one, you can generate one using a service like MetaMask. Now let’s start coding!

Using web3

From web3.py we will need to import the following:

In order to interact with the DigiPol smart contract, we will need:

  • A private key
  • The testnet endpoint (an ethereum testnet)
  • The smart contract address
  • The smart contract abi (a json file to help define the smart contract methods with web3)

Note, the json file for the abi can be produced from the smart contract repo or you can use one we prepared earlier.

Next, we get the smart contract as a python object:

We then add our private key to web3 via the middleware:

Now we are all set up and can start to interact with smart contract.

Getting the vote count

Each ballot has an associated ‘ballotspec hash’, a unique identifier string for that bill. All of the spec hashes are publicly available. Here we will use an existing one to get the ballot id via the getProposalId smart contract method. Then we can get the ballot (proposal) information using the getProposal method which returns a list of related information.

Finally we can get the vote counts for the ballot. The no votes are in position 3 of the proposalInfo list and the yes votes are in position 4.

Voilà!

Now you can check the votes on the blockchain directly and don’t have to trust the results that are shown in DigiPol app. You should use the DigiPol app though as it’s pretty cool and looks a lot nicer!

Full example

Here is the full script wrapped in a get_votes_from_blochchain function:

--

--

Kipling Crossing

I do many things including: Open-Source, Geo-spatial Data Science, Scientific utility apps, Micro-Python and Writing