官术网_书友最值得收藏!

File structure

We'll use the 0.5.0 version of Solidity for all the examples in this book. A smart contract in Solidity always starts with the version that is used in the file to ensure that the contract is not compatible with newer versions that could break the contract because of newly added functionalities.

Let's look at the structure of a contract in Solidity using the following steps:

  1. You define the version at the beginning of the file with the pragma statement:
pragma solidity 0.5.0;
  1. Then you can start writing your contracts. All statements in Solidity must end with a semicolon (;) to be valid. After defining the version used in the file, you have to create the contracts, as shown here:
pragma solidity 0.5.0;
contract Example {}
  1. You can define multiple contracts in one single file:
pragma solidity 0.5.0;
contract Example {}
contract Another {}
contract Token {}
contract ICO {}
  1. Inside the contract, you'll have state variables, functions, modifiers, and a single constructor. I'll explain later how they are used in detail:
pragma solidity 0.5.0;
contract Example {
uint256 counter;
modifier onlyOwner {}
constructor() {}
function doSomething() {}
}
  1. The variables that are defined directly in the contract, meaning that they are outside functions, are called state variables. These are special variables that store their value even after executing the contract. Think of them as special permanent variables that you can always read and modify:
pragma solidity 0.5.0;
contract Example {
uint256 myStateVariable;
string myOtherStateVariable;
function example(){
uint256 thisIsNotAStateVariable;
}
}

As you can see, they are outside functions but inside the contract, and they are defined at the top of the file, right when the contract begins. As I said, they keep their value forever, even after making changes to your contract. So, if your myStateVariable has a value of 5, you'll be able to read the value of that variable days or months after it has been modified, as long as you don't modify it.

They store their value directly on the blockchain storage, not in memory. In-memory variables, as you'll learn later, lose their value and are reset after the contract execution.

Finally, Solidity files use the .sol extension, for instance, example.sol. You will learn how to deploy them with the Remix IDE and Truffle in Chapter 3, Mastering Smart Contracts, and Chapter 9, Decentralized Exchanged Workflow.

主站蜘蛛池模板: 于都县| 隆昌县| 宁都县| 古浪县| 新野县| 新绛县| 孟州市| 承德市| 河南省| 积石山| 哈密市| 卫辉市| 眉山市| 扎囊县| 阿克| 洞头县| 化州市| 成安县| 讷河市| 呼玛县| 潍坊市| 穆棱市| 吉林市| 萝北县| 满城县| 时尚| 淳安县| 绍兴县| 朔州市| 伊吾县| 宜州市| 浦东新区| 襄汾县| 芮城县| 区。| 邹城市| 濮阳县| 刚察县| 汨罗市| 克什克腾旗| 南平市|