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

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.

主站蜘蛛池模板: 无为县| 广元市| 剑河县| 日土县| 上饶市| 镇赉县| 工布江达县| 台湾省| 万安县| 黔西县| 志丹县| 商河县| 从江县| 岑巩县| 三亚市| 积石山| 正蓝旗| 沈阳市| 嵊泗县| 吉林省| 应用必备| 辽源市| 琼中| 清水县| 商水县| 来宾市| 普兰店市| 神池县| 山丹县| 延津县| 平谷区| 宁强县| 万源市| 惠州市| 广东省| 微山县| 长白| 阳城县| 霍州市| 右玉县| 台南县|