Blockchain & Solidity Program Lab Manual
ISBN 9788119221646

Highlights

Notes

  

Prog. 8:: Contract using Structure in Solidity Code

Contract With Structure

1) Open the Ganache

2) Open the Node.js command prompt

3) install the truffle in the directory

5) Open the sublime texteditor

6) Unpack the truffle director into our project

pragma solidity 0.5.16;

//creating the contract contract Contest {

//creating strcture to model the contestant struct Contestant {

uint id; string name;

uint voteCount;

}

//use mapping to get or fetch the contestant details mapping(uint => Contestant) public contestants;

//to save the list of users/accounts who already casted vote mapping(address => bool) public voters;

//add a public state variable to keep track of contestant Count uint public contestantsCount;

event votedEvent (uint indexed _contestantId

);

constructor() public {addContestant(“Tom”); 
addContestant(“Jerry”);

}

//add a function to add contestant

function addContestant (string memory _name) private {contestantsCount ++;

contestants[contestantsCount] = Contestant(contestantsCount, _name, 0);

}

function vote (uint _contestantId) public 
{

//restricting the person who already casted the vote require(!voters[msg.sender]);

//require that the vote is casted to a valid contestant require(_contestantId > 0 && _contestantId <= contestantsCount);

//increase the contestant vote count contestants[_contestantId].voteCount ++;

//set the voter’s voted status to true voters[msg.sender] = true;

//trigger the vote event

emit votedEvent(_contestantId);

}

}

7) Compile the contract

8) Deployment of Contract over Ganache using command line

10) Accessing Contestant Attribute Data values using web2.js interface to get accounts information of the node