I am relatively new to Solidity. I am following a tutorial and came up with the following contract:

contract Election {
  struct Candidate {
    uint id;
    string name;
    uint voteCount;

  mapping (uint => Candidate) public candidates;
  // keep a counter to track the number of candidates
  uint public candidatesCount;

  constructor () public {
    addCandidate("Candidate 1");
    addCandidate("Candidate 2");

  function addCandidate (string memory _name) private {
    candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);


I am using Truffle for development. Now, once the contract is deployed locally, I am running these on the truffle console:

> Election.deployed().then(instance => app = instance)
> app.candidates(1).then(res => candidate1 = res)

So basically I am getting an instance of a Candidate from candidates to candidate1. Now, when I am assigning the voteCount property of candidate1 from the console like this:

> candidate1.voteCount = 100 

To my surprise the voteCount is actually set to 100. I assumed the properties of a struct to be private. I tried adding the private access modifier to the struct properties but it is throwing errors.

What is the valid/correct way to add access modifiers to the struct so that the voteCount property cannot be set without a setter?


You're not changing anything in the contract state. You're setting candidate1 to be an instance of the contract in the JavaScript sense. This is in the client. You can set arbitrary properties and retrieve set values. That activity won't affect the contract state storage in any way.

Indeed, even after you set that, you should see the contract was unaffected with.

candidate1.candidatesCount().then(function(response) { console.log(response.toString(10); });

I expect it should print 2.

Instead of modifying the contract abstraction Truffle gave you, you should be using it to inspect the contract.

If you wanted to change the contract state then you would send a transaction to your addCandidate() function. If you're using truffle:

candidate1.addCandidate(arguments).then(... This will return a transaction hash and you have to wait until it mines, then you'll see the test returns count of 3. I think you should call your contract abstration elections (not candidate1) to reflect that it is a JavaScript representation of the deployed Elections contract.

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.