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

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.

主站蜘蛛池模板: 荔波县| 慈溪市| 榆中县| 牡丹江市| 霍邱县| 化隆| 衡阳市| 南昌市| 莎车县| 木兰县| 鄂托克旗| 石狮市| 蓝山县| 灌阳县| 开远市| 会泽县| 新和县| 西和县| 广灵县| 南木林县| 酒泉市| 雷州市| 西吉县| 遵义县| 报价| 会宁县| 兴山县| 聂拉木县| 玉林市| 边坝县| 上饶县| 手机| 靖州| 永修县| 宜州市| 夏津县| 清远市| 南雄市| 曲麻莱县| 宁陵县| 武定县|