Structure & Building Blocks of Smart Contract- Part 2

Harsimran Singh
3 min readFeb 15, 2022

--

In our last article, we have seen how to get start writing smart contracts on remix. So far we have covered contract creation, state variables, functions & events.In this article we are gonna discuss about modifiers, structs ,enums & errors.

Enums- Let’s start with enums. Enums are user-defined type with finite set of values. Enums are explicitly converted to and from integer types. Enum need to have at-least one value and maximum of 256 values.Enums are created using enum keyword followed by name of enum and values enum can have. Let’s create a SkillLevel enum in our contract which will have three values ROOKIE,EXPERIENCED & EXPERT.

Enum

Structs- Structs are user-defined types which can group other types. Struct can have primitive types and other structs as well. Structs are created using structkeyword followed by name of struct and types & name of those types. Let’s define Friend struct in our contract which will have string, int & SkillLevel(enum) types.

Struct

Error- Errors are way of telling user of contract what went wrong in case of failure. Preferred way of using error is with revert statement(will show later in this tutorial). Errors are created using error keyword followed by name of error and values error can have. Let’s define SkillLevelUnknown error in our contract.

Error

Modifier — Modifiers are used to check pre-conditions before running functions body. Execution of program should halt quickly as it costs gas to run piece of code on ethereum blockchain. Modifiers help us to state these in declarative way before running functions code.Modifiers are created using modifier keyword and followed by name of modifier and values modifier can have. Let’s define checkFriendAge modifier in our contract. _; is special syntax which tells to follow the function flow if condition is met.

Modifier

Let’s tie up all the pieces together and create two new functions addFriend & fetchFriendName like below. Compile the code and play around with age & skillLevel value to see how errors and modifiers worked.

--

--