header-langage
简体中文
English
Tiếng Việt
Scan to Download the APP
Partnered With:

Simple Introduction to Solidity|Lecture 8: Constructors and Decorators

Read this article in 5 Minutes
This article will introduce the constructors and modifiers in solidity, and give an Ownable contract that controls contract permissions.
Original title: " A minimalist introduction to Solidity: 8. Constructors and decorators "
Original author: 0xAA


I am learning solidity again recently, Consolidate the details, and write an "Introduction to Solidity Minimalist" for beginners (programmers can find another tutorial), and update 1-3 lectures every week.


All codes are open source on github: github.com/AmazingAng/WTFSolidity


This lecture , we will use the example of contract authority control (Ownable) to introduce the constructor (constructor) and unique modifier (modifier) in solidity language.


Constructor


The constructor (constructor) is a special function, each A contract can be defined and run automatically once when the contract is deployed. It can be used to initialize some parameters of the contract, such as initializing the owner address of the contract:



Modifier


The modifier is The solidity-specific syntax, similar to the decorator in object-oriented programming, declares the characteristics of functions and reduces code redundancy. It's like Iron Man's smart armor, and functions that wear it will have certain behaviors. The main usage scenario of modifier is to check before running functions, such as addresses, variables, balances, etc.


Iron Man modifier


We define a modifier called onlyOwner:



  The function with the onlyOwner modifier can only be called by the owner address, such as the following example:


< /p>


We defined a changeOwner function, running it can change the contract owner, but due to the existence of the onlyOwner modifier, only the original owner can call, and others will report an error. This is also the most commonly used method of controlling smart contract permissions.


Ownable standard implementation of OppenZepplin:  https://github.com/OpenZeppelin/openzeppelin-contracts/blob /master/contracts/access/Ownable.sol


Summary


In this lecture, we introduced the constructors and modifiers in solidity, and gave a control contract authority Ownable contract.


Original link


Welcome to join the official BlockBeats community:

Telegram Subscription Group: https://t.me/theblockbeats

Telegram Discussion Group: https://t.me/BlockBeats_App

Official Twitter Account: https://twitter.com/BlockBeatsAsia

举报 Correction/Report
Choose Library
Add Library
Cancel
Finish
Add Library
Visible to myself only
Public
Save
Correction/Report
Submit