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

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.

主站蜘蛛池模板: 绥芬河市| 巫山县| 大城县| 嘉峪关市| 连江县| 大冶市| 固安县| SHOW| 三明市| 丁青县| 积石山| 正定县| 浦江县| 杭州市| 敦化市| 奉化市| 普洱| 台东县| 临潭县| 噶尔县| 章丘市| 余姚市| 顺义区| 汉沽区| 沐川县| 安丘市| 盱眙县| 闽侯县| 达尔| 广汉市| 永城市| 苏尼特左旗| 密云县| 肇源县| 谢通门县| 平遥县| 寿光市| 绥阳县| 凭祥市| 中西区| 嘉祥县|