You are on page 1of 41

3.4.

4 Structs in Solidity

TCE Online Course - Blockchain 1


Session Outcomes

 Use structures for writing simple contracts in solidity

Click icon to add picture

TCE Online Course – Blockchain 2


Introduction to Structures

• A way to create user defined data types


• Group of elements with different data types – A record
• Syntax
struct <structure_name> {
<data type> variable_1;
<data type> variable_2;
}
• To define the variable of structure data type, structure name is used.
• For accessing any element of the structure, dot operator is used

TCE Online Course – Blockchain 3


A simple contract to demonstrate the use of structures
pragma solidity ^0.5.0; // Defining a function to set values for the fields for structure
function set_stud_detail() public {
// Creating a contract s1 = Stud("Siddharth","22CS030",2);
contract test { }

// Declaring a structure
struct Stud { // Defining function to print details
string name; function stud_info()public view returns (string memory, string memory,
string regno; Click icon to uint) {
add picture
uint dept;
return(s2.name, s2.regno, s2.dept);
} }

// Declaring a structure object // Defining function to print stud details


Stud s1; function get_details() public view returns (string memory, string memory,
uint) {
// Assigning values to the fields for the structure object return (s1.name, s1.regno, s1.dept);
Stud s2= Stud(“RAJ","22IT020 ",1); }
}

TCE Online Course – Blockchain 4


Structures - Output

TCE Online Course – Blockchain 5


A simple contract to demonstrate the use of array of structures
pragma solidity ^0.6.8; arr.push(s1);
pragma experimental ABIEncoderV2; }
contract DynamicArray{
// Declaring state variable // Function to get data of dynamic array
struct Stud { function getData() public view returns(Stud[] memory)
string name; {
string regno; return
Click icon to add arr;
picture
uint dept; }
}
Stud[] arr; // Function to return length of dynamic array
Stud s1; function getLength() public view returns (uint)
{
// Function to add data in dynamic array return arr.length;
function addData(string memory s, string memory r, uint }
d) public
{
s1=Stud(s,r,d); }

TCE Online Course – Blockchain 6


Array of Structures - Output

TCE Online Course – Blockchain 7


Activity Time

• Write a smart contract to design a structure by name BOOK

with three attributes. Write functions


Click icon to add picture
to add and display the
details of book.

TCE Online Course – Blockchain 8


Click icon to add picture

TCE Online Course – Blockchain 9


Mapping
• Similar to a hash table or dictionary in other programming languages
• Key – Value pair
• Mapping is a reference type as arrays and structs.
mapping(Key => Value) <access specifier> <name>
Where,
Key − can be any built-in types. No reference type or complex objects are
allowed.
Value− can be any type.
• Associate the unique Ethereum address with the associated value type.
TCE Online Course – Blockchain 10
A simple contract to demonstrate the use of Mapping
pragma solidity ^0.5.0;

contract AddtoAccount {
mapping(address => uint) public balances;
Click icon to add picture

function credit(address a, uint newBalance) public {


balances[a] = balances[a] + newBalance;
}
}

TCE Online Course – Blockchain 11


Mapping - Output

TCE Online Course – Blockchain 12


Enumerated Datatypes
pragma solidity ^0.5.0;   // function to turn off the button
contract Example {   function buttonOff() public {
  // creating an enum     // set the value of button to OFF
  enum Button { OFF, ON }     button = Button.OFF;
  // declaring a variable of type enum Click icon to add
  } picture
  Button button;   // function to get the value of the button
  // function to turn on the button   function getbuttonState() public view returns(Button) {
  function buttonOn() public {     // return the value of button
    // set the value of button to ON     return button;
    button = Button.ON;  }
 } }

TCE Online Course – Blockchain 13


Modifiers
• The modifiers can be used when there is a need to verify the condition
automatically before executing a particular function.
• If the given condition is not satisfied, then the function will not get executed.

Function modifier with an argument:


modifier  modifier_name(unit arg)
{
   // action to be taken
}
Function modifier without argument:
modifier  modifier_name()
{
   // action to be taken
}

TCE Online Course – Blockchain 14


modifier isAdmin
{
require(admin==msg.senderClick
; icon to add picture
_;
}

TCE Online Course – Blockchain 15


contract modifierWithoutArg { {
address admin; require(admin == msg.sender);
struct employee _;
{ }
uint emp_id; employee e;
string emp_name; function enterDetails (uint _empid, string
uint age; memory
Click icon to add picture _empname, uint _empage)
} public isAdmin {
constructor() public e.emp_id = _empid;
{ e.emp_name = _empname;
admin = msg.sender; e.age = _empage;
} }
}
modifier isAdmin

TCE Online Course – Blockchain 16


pragma solidity >=0.4.22 <0.7.0;         if(exp >= 5)
contract modifierWithArg {             _;
            else
  struct employee             revert("Must have a minimum of 5
 { years of experience");
    uint emp_id;   }
    string emp_name;  employee public e;
Click icon to add picture
    uint age;  function enterDetails (uint _empid, string
   } memory _empname, uint _empage) public
   uint ex; isExperienced(ex) {
   function  getexp (uint x)public    e.emp_id = _empid;
  {    e.emp_name = _empname;
  ex=x;    e.age = _empage;
 }  }
    modifier isExperienced(uint exp) }
  {
TCE Online Course – Blockchain 17
Only After
pragma solidity ^0.5.17; function getResult() view public
contract Test { onlyAfter(creationTime + 40) returns (uint,uint)
uint public num1 = 2; {
uint public num2 = 4; uint prod = num1;
uint public creationTime = now; Click icon to add picture
uint sum = num2 ;
  //num1=num1+2;
modifier onlyAfter(uint time) { return (prod, sum);
      require( now >= time, }
         "Function called too early."      ); }
      _;
}

TCE Online Course – Blockchain 18


Pure and View Functions
The view functions are read-only function, which ensures that state variables cannot be modified
after calling them. 
contract Test {
    // Declaring state variables                            
    uint num1 = 2;
    uint num2 = 4; Click icon to add picture
 
   function getResult() public view returns(
     uint product, uint sum){
      product = num1 * num2;
      sum = num1 + num2;
   
   }
}

TCE Online Course – Blockchain 19


Function Overloading
pragma solidity ^0.5.0; returns(uint){
return getSum(1,2,3);
contract Test { }
function getSum(uint a, uint b) public pure returns(uint){ }
return a + b;
}
Click icon to add picture
function getSum(uint a, uint b, uint c) public pure returns(uint){

return a + b + c;
}
function callSumWithTwoArguments() public pure
returns(uint){
return getSum(1,2);
}
function callSumWithThreeArguments() public pure

TCE Online Course – Blockchain 20


Inheritance
pragma solidity ^0.5.0; contract derived is base
{
contract base { function prodpower(uint a, uint x, uint
uint public power; n)public returns (uint,uint)
{
function computepower(uint x, uint n) public return (a*computepower(x,n), power);
returns (uint) { Click icon to add picture
}
power=1; }
for (uint i=1;i<=n; i++)
{
power=power*x;
}
return power; }
}

TCE Online Course – Blockchain 21


Abstract Contracts
pragma solidity ^0.5.0; returns (uint){
contract abs{ return (l*b/2);
function area(uint l, uint b) public pure }
returns (uint){} }
}

contract rec{ Click icon to add picture


function area(uint l, uint b) public pure
returns (uint){
return (l*b);
}
}

contract tri{
function area(uint l, uint b) public pure

TCE Online Course – Blockchain 22


Click icon to add picture

TCE Online Course – Blockchain 23


Application Development Using Solidity
pragma solidity ^0.4.0;         voters[chairperson].weight =         Voter storage sender =
contract Ballot { 2; voters[msg.sender];
  struct Voter {         proposals.length =         if (sender.voted || toProposal
        uint weight; _numProposals; >= proposals.length) return;
        bool voted;   }         sender.voted = true;
        uint8 vote; }     function register(address         sender.vote = toProposal;
    struct Proposal { Click icon
toVoter) public { to add picture     
        uint voteCount; }         if (msg.sender != chairperson proposals[toProposal].voteCount
    address chairperson; || voters[toVoter].voted) return; += sender.weight;
    mapping(address => Voter)         voters[toVoter].weight = 1;   }
voters;         voters[toVoter].voted = false;
    Proposal[] proposals;   }     }
   constructor(uint8 }
_numProposals) public {      function vote(uint8 toProposal)
        chairperson = msg.sender; public {

TCE Online Course – Blockchain 24


Application Development Using Solidity
function winningProposal() public constant returns (uint8 _winningProposal) {
        uint256 winningVoteCount = 0;
        for (uint8 prop = 0; prop < proposals.length; prop++)
            if (proposals[prop].voteCount > winningVoteCount) {
                winningVoteCount = proposals[prop].voteCount;
Click icon to add picture
                _winningProposal = prop;
      }

TCE Online Course – Blockchain 25


Application Development Using Solidity
pragma solidity ^0.4.0;
contract Ballot {
    struct Voter {     Proposal[] proposals;     /// Give $(toVoter) the right to
        uint weight;         uint startTime;   vote on this ballot.
        bool voted;     /// Create a new ballot with $     /// May only be called by $
        uint8 vote; (_numProposals) different (chairperson).
  } proposals.Click icon to add picture     function register(address
    struct Proposal {     function Ballot(uint8 toVoter) public {
        uint voteCount; _numProposals) public  {         if (stage != Stage.Reg) {return;}
  }         chairperson = msg.sender;         if (msg.sender != chairperson
    enum Stage {Init,Reg, Vote,         voters[chairperson].weight = || voters[toVoter].voted) return;
Done} 2; // weight is 2 for testing         voters[toVoter].weight = 1;
    Stage public stage = Stage.Init; purposes         voters[toVoter].voted = false;
           proposals.length =         if (now > (startTime+ 10
    address chairperson; _numProposals; seconds)) {stage = Stage.Vote;
    mapping(address => Voter)         stage = Stage.Reg; startTime = now;}        
public voters;         startTime = now;   }
TCE Online Course – Blockchain
  } 26
Application Development Using Solidity
  /// Give a single vote to proposal $(toProposal).  }
    function vote(uint8 toProposal) public  {   function winningProposal() public constant returns
        if (stage != Stage.Vote) {return;} (uint8 _winningProposal) {
        Voter storage sender = voters[msg.sender];        if(stage != Stage.Done) {return;}
        if (sender.voted || toProposal >=         uint256 winningVoteCount = 0;
proposals.length) return;         for (uint8 prop = 0; prop < proposals.length;
        sender.voted = true; Click icon to add picture
prop++)
        sender.vote = toProposal;               if (proposals[prop].voteCount >
        proposals[toProposal].voteCount += winningVoteCount) {
sender.weight;                 winningVoteCount =
        if (now > (startTime+ 10 seconds)) {stage = proposals[prop].voteCount;
Stage.Done;}        
                _winningProposal = prop;    }       
    
    }

TCE Online Course – Blockchain 27


Application Development -2

Problem Statement:
Consider the problem of Chinese auction or penny social. We will refer to it as simple “Auction.” It is a
conventional approach used for fundraising for a cause. The organizers collect items to be auctioned off for
raising funds. Before the auction, the items for auctions are received and arranged each with a bowl to place
Click icon to add picture
the bid. A chairperson is a special person among the organizers. She/he heads the effort and is the only person
who can determine the winner by random drawing at the end of the auction. A set of bidders buy sheets of
tickets with their money. The bidder’s sheet has a stub that identifies the bidder’s number, and tokens bought.
The bidders examine the items to bid, place the one or more tickets in the bowl in front of the items they desire
to bid for until all the tickets are used. After the auction period ends the chairperson, collects the bowls,
randomly selects a ticket from each item’s bowl to determine the winning bidder for that item. The item is
transferred to the winning bidder. Total money collected is the fund raised by the penny social auction.

TCE Online Course – Blockchain 28


Assumptions

Fixed number of bidders, initialized to 4. All 4 need to self-register. Funds transfer from bidder is
automatically done and is not in the scope of this application.
Fixed number of items to be auctioned off, initialized to 3.
Click iconNtoisadd
Items auctioned are indexed from 0..N-1 where thepicture
number of items for auction. N is 2.
Each bidder buys just 1 sheet of tickets or tokens; each sheet has only 5 tokens.
Assume simple number for the serial numbers for the sheet of tickets: 0,1,2,3. Here we show the tokens
of bidder 0 and 1.
0 0 0 0 0
1 1 1 1 1
. . . . .
n-1 n-1 n-1 n-1 n-1

TCE Online Course – Blockchain 29


Constructor that initializes the owner,
register that allows (decentralized person) to register online to get the tokens and start bidding,
bid function that lets a person bid, and
finally revealWinner, to randomly choose the winner for the item auctioned
Click icon to add picture

TCE Online Course – Blockchain 30


Click icon to add picture

TCE Online Course – Blockchain 31


pragma solidity ^0.4.17; contract Auction {  
  mapping(address => Person) tokenDetails; //address
struct Item { to person
uint itemId; // id of the item Person [4] bidders;//Array containing 4 person
uint[] itemTokens; //tokens bid in favor of the item objects
  Click icon to  add picture
} Item [3] public items;//Array containing 3 item
  objects
struct Person { address[3] public winners;//Array for address of
uint remainingTokens; // tokens remaining with winners address
bidder public beneficiary;//owner of the smart contract
uint personId; // it serves as tokenId as well uint bidderCount=0;//counter
address addr;//address of the bidder  

TCE Online Course – Blockchain 32


function Auction() public payable{ items[0] =
//constructor Item({itemId:0,itemTokens:emptyArray});

//Part 1 Task 1. Initialize beneficiary with //Part 1 Task 2. Initialize two items with at
address of smart contract’s owner Click icon toindex 1 and 2.
add picture
//Hint. In the constructor,"msg.sender" is the // ** Start code here. 2 lines approximately.
address of the owner. **/ items[1] =
// ** Start code here. 1 line approximately. items[2] =
**/ //** End code here**/
}
//** End code here. **/ uint[] memory  

emptyArray;

TCE Online Course – Blockchain 33


function Auction() public Item({itemId:1,itemTokens:e
payable{ mptyArray});
beneficiary = msg.sender;Click icon to items[2]
add picture
=
uint[] memory emptyArray; Item({itemId:2,itemTokens:e
items[0] = mptyArray});
Item({itemId:0,itemTokens:e }}
mptyArray});  

items[1] =

TCE Online Course – Blockchain 34


function register() public payable{ **/

bidders[bidderCount].personId = //** End code here. **


bidderCount; bidders[bidderCount].remainingTokens =
Click icon to5;
add// only 5 tokens
picture
//Part 1 Task 3. Initialize the address of the tokenDetails[msg.sender]=bidders[bidderCo
bidder unt]; bidderCount++;
/*Hint. Here the bidders[bidderCount].addr }
should be initialized with address of the function
registrant.*/ }
 

// ** Start code here. 1 line approximately.

TCE Online Course – Blockchain 35


function register() public payable{ } 
bidders[bidderCount].personId =
bidderCount;
Click icon to add picture
bidders[bidderCount].addr = msg.sender;
bidders[bidderCount].remainingTokens = 5;
tokenDetails[msg.sender]=bidders[bidderCo
unt];
bidderCount++;

TCE Online Course – Blockchain 36


function register() public payable{ } 
bidders[bidderCount].personId =
bidderCount;
Click icon to add picture
bidders[bidderCount].addr = msg.sender;
bidders[bidderCount].remainingTokens = 5;
tokenDetails[msg.sender]=bidders[bidderCo
unt];
bidderCount++;

TCE Online Course – Blockchain 37


function bid(uint _itemId, uint _count) public  // ** Start code here. 2 lines approximately. **/
payable{
tokens bid
Part 1 Task 4. Implement the three conditions
below. bidders[tokenDetails[msg.sender].personId].remain
ingTokens=
◦ If the number of tokens remaining with the
bidder is <count of tokens bid, revert tokenDetails[msg.sender].remainingTokens;
◦ If there are no tokens remaining with the bidder, //updating the same balance in bidders map.
Click icon to add picture
revert. Item storage bidItem = items[_itemId]; for(uint i=0;
◦ If the id of the item for which bid is placed, is i<_count;i++) {
greater than 2, revert.
bidItem.itemTokens.push(tokenDetails[msg.sender]
 Hint: "tokenDetails[msg.sender].remainingTokens" .personId);
gives the details of the number of tokens remaining
}
with the bidder.
}
*/

TCE Online Course – Blockchain 38


function bid(uint _itemId, uint _count) public Item storage bidItem = items[_itemId];
payable{
for(uint i=0; i<_count;i++) {
if (tokenDetails[msg.sender].remainingTokens <
_count) return; bidItem.itemTokens.push(tokenDetails[msg.sender].
personId);
Click icon to add picture
if (_itemId > 2) return;
}
(tokenDetails[msg.sender].remainingTokens -
_count); }

bidders[tokenDetails[msg.sender].personId].remaini
ngTokens=
tokenDetails[msg.sender].remainingTokens;
//updating the same balance in bidders map.

TCE Online Course – Blockchain 39


function revealWinners() public { address of the person obtained above to
winners[id] */
for (uint id = 0; id < 3; id++) {
 // ** Start coding here *** 1 line approximately.
Item storage currentItem=items[id];
if(currentItem.itemTokens.length != 0){ }
// generate random# from block number uint }
randomIndex = (block.number /
 function getPersonDetails(uint id) public constant
Click icon to add picture
currentItem.itemTokens.length)% returns(uint,uint,address){
currentItem.itemTokens.length;
return
uint winnerId = (bidders[id].remainingTokens,bidders[id].personId,bi
currentItem.itemTokens[randomIndex];  dders[id].addr);
/* Part 1 Task 6. Assign the winners. }
Hint." bidders[winnerId] " will give you the person }
object with the winnerId. you need to assign the

TCE Online Course – Blockchain 40


function revealWinners() public returns (uint){ }
for (uint id = 0; id < 3; id++) { function getPersonDetails(uint id) public constant
returns(uint,uint,address){
Item storage currentItem=items[id];
return
if (currentItem.itemTokens.length != 0){
(bidders[id].remainingTokens,bidders[id].personId,bi
uint randomIndex = (block.number / dders[id].addr);
currentItem.itemTokens.length)% Click icon to }add picture
currentItem.itemTokens.length;
}
uint winnerId =
currentItem.itemTokens[randomIndex];
return winnerId;
}
}

TCE Online Course – Blockchain 41

You might also like