1. Variable Declaration and Common Data Types#
Except for special types like address, Solidity's variables and data types are similar to those in common programming languages, as described below:
- Enumeration
When Solidity needs to define a set of constants, it can be achieved by defining an enumeration using the enum keyword. The example code below defines an enumeration for colors, which includes red, yellow, and green, with values of 0, 1, and 2 respectively.
- Struct
Structs are defined using the Struct keyword. The following example defines a struct named Player, which contains two properties: address (addr) and amount (amount), where address is of type address and amount is an integer. The specific code is as follows:
- Functions
The syntax for defining functions in Solidity is as follows:
Here, refers to the parameters and their types. The keywords {internal|external} specify the calling method of the function, where internal refers to internal calls that can directly use data in the context; external implements external message calls to the contract, with internal as the default. [pure|constant|view|payable] are four keywords used to specify function attributes. The pure keyword comes from functional programming, indicating that this function body is a pure function that cannot call other functions; the constant keyword defines a constant but is no longer used after Solidity version 0.4.17; the view keyword indicates that this function is read-only and cannot modify state; if a function needs to perform monetary operations, it must include the payable keyword. [returns()] is used to specify the return type of the function.
5. Comments#
The syntax for comments in Solidity is the same as in JavaScript, using "//" for single-line comments and "/" and "/" for multi-line comments.
// This is a single-line comment
/*
This is
a multi-line comment
*/
6. File Structure#
For the Solidity language, in addition to understanding the basic syntax mentioned above, it is also necessary to understand the file structure of Solidity. Solidity files generally have a .sol file extension. In a .sol file, the first line is the version declaration, as different versions support different features, so the file needs to specify the version number. The syntax is as follows:
pragma solidity ^0.4.0;
The above line indicates that this .sol file needs to run on versions after 0.4.0, where the "^" symbol indicates that versions 0.5.0 and later are not supported.
The above is a brief introduction to Solidity syntax; for detailed content, please refer to the official Solidity tutorial, which will not be elaborated here.
: The official tutorial address for the Solidity language is http://solidity.readthedocs.io/en/develop/types.html.
Smart Contract Development#
After understanding the basic syntax of Solidity, you can start developing smart contracts. To develop smart contracts using Solidity, you need to install a compiler. For readers who are just starting to learn the Solidity language, it is recommended to use the online IDE editor - Remix. You can use it by entering http://remix.ethereum.org in your browser, without the need for local installation.
1. Using the Remix Compiler#
The Remix interface is mainly divided into four parts. The left side is the file browsing area, where you can create new files, open local files, update code to GitHub, and browse all open files; the upper middle part is where you edit code, with syntax highlighting and automatic syntax checking, where yellow indicates warnings and suggestions, and red indicates syntax errors; the lower part is an interactive terminal interface used to query transaction details and debug smart contracts; the right side is the function panel used to compile, run, and test smart contracts, as shown in Figure 5-21.
Remix has powerful features, and this book will not elaborate further. Interested readers can visit the official Remix website at https://remix.readthedocs.io/en/latest for more information. Next, we will directly use the Remix compiler to develop a smart contract.
After opening Remix, the default display is an example of a voting smart contract written in Solidity, which has a lot of code and will not be explained here. We will create a new file named Hello.sol. Click the "+" button in the upper left corner, enter the file name "Hello.sol", and click the "OK" button to save it, as shown in the figure.
In the newly created file, declare the compiler version as after 0.4.0 in the first line, then define a smart contract named "helloBlockchain", which only contains one function renderHello that returns the string "Hello Blockchain", as shown in the figure.
After completing the code, select the compiler version 0.4.25+ in the right function panel to compile, as shown in the figure. Upon successful compilation, it will print the name of the smart contract "Hello Blockchain".
Next, click the "Run" tab, select the local test environment as the running environment, choose the "helloBlockchain" smart contract, and then click the "Deploy" button to deploy this smart contract, as shown in Figure 5-25.
Remix has three running modes, as described below.
● JavaScript VM: This mode simulates a blockchain in the browser, and contracts execute in this simulated sandbox. Refreshing the page will clear all data without any persistence, and there is no injected Web3 object.
● Injected Provider: Connects to a source that contains an injected Web3 object, and will automatically switch to this mode in the Mist browser or browsers with MetaMask installed.
● Web3 Provider: Connects to a remote node, requiring the source's URL address and port, such as geth, ganache, etc., which contains the Web3 object.
Here, we choose the Injected Provider mode (the Provider in the figure is the Web3 object, i.e., Injected Web3).
Deploying a smart contract writes it to Ethereum, and all write operations on Ethereum consume Ether, so this operation will consume Ether. In the pop-up window, click the "Confirm" button to confirm the payment, as shown in the figure.
At this point, the smart contract has been deployed to the local test environment. After the smart contract is successfully deployed, you can see the successfully deployed smart contract and the callable function renderHello in the lower right corner of the Remix main interface. Clicking on renderHello will call and execute the function, and you can see the output result as the string "Hello Blockchain", as shown in the figure.
Finally, let's summarize the smart contract development process, as shown in the flowchart.
-
Create a new .sol file and implement the functionality of the smart contract, which outputs "Hello Blockchain".
-
Use the compiler to compile the code.
-
If there are no errors in the code, the compiler will generate a binary file from the compilation results.
-
Deploy the successfully compiled smart contract to the blockchain system.
-
After successful deployment, it will return the address of the smart contract and the Application Binary Interface (ABI) for interacting with the smart contract.
-
Call the smart contract using the address and ABI.
Truffle Framework#
Once you have mastered the basic syntax of Solidity and the smart contract development process, you can further learn about the DApp development framework Truffle.
Truffle is a development framework for the Solidity language based on Ethereum. Truffle itself is based on JavaScript, and its goal is to make DApp development simpler. It has the following features.
● Built-in management of smart contract compilation, linking, deployment, and binary files.
● Support for automated testing of smart contracts.
● Scriptable and extensible deployment and release framework.
● Management of deployment network environment functionality.
● Package management using EthPM or npm, following the ERC190 standard.
● Interactive console for direct communication with contracts (you can verify contracts in the command line after writing them).
● The smart contract build process can be customized according to needs.
● Support for executing external scripts in the Truffle environment.
Installing Truffle and Common Commands#
Truffle can be installed using the package management tool npm, with the installation command as follows:
$ npm install -g truffle
After installation, enter the truffle command to see its usage, as shown in Figure 5-29. Below are descriptions of several main Truffle commands.
- Initialize Truffle Project - truffle init
To initialize a Truffle project, simply enter truffle init to create an empty project. Create a folder called first-DApp, enter the folder, and execute truffle init, as shown in the figure.
Truffle will automatically generate an empty project structure. The newly generated Truffle project includes several folders and configuration files, where the contracts folder is used to store smart contracts; the migrations folder is used to implement the deployment of smart contracts; the test folder is used to store contract test files; truffle.js is the default configuration file; truffle-config.js is the default configuration file for Windows to prevent filename conflicts with the truffle command. The structure of a Truffle project is as follows:
- Compile Command - truffle compile
Executing the truffle compile command will compile the smart contract files. Upon successful compilation, new smart contract binary files will be generated in the build folder of the current directory, as shown in Figure 5-32.
- Deploy Command - truffle deploy
Before deploying the smart contract, you need to modify the configuration file. The smart contract development test environment used in this chapter is Ganache, which listens on the local port 7545, so you need to modify the truffle.js file to connect to the local port 7545, as shown in the figure.
Once the modifications are complete, you can deploy the smart contract by entering the command "truffle deploy" in the terminal.
- Test Command - truffle test
Executing the truffle test command will run all test cases in the test folder. This command will automatically recognize files with extensions .js, .es, .es6, .jsx, and .sol, while files with other extensions will be ignored.
- Terminal Command - truffle console
Executing the truffle console command will open an interactive terminal interface, making it easy to call and debug smart contracts.
- Download Template Command - truffle unbox[box-name]
After installation, enter the truffle command to see its usage, as shown in Figure 5-29. Below are descriptions of several main Truffle commands.
- Initialize Truffle Project - truffle init
To initialize a Truffle project, simply enter truffle init to create an empty project. Create a folder called first-DApp, enter the folder, and execute truffle init, as shown in Figure 5-30.
Truffle will automatically generate an empty project structure. The newly generated Truffle project includes several folders and configuration files, where the contracts folder is used to store smart contracts; the migrations folder is used to implement the deployment of smart contracts; the test folder is used to store contract test files; truffle.js is the default configuration file; truffle-config.js is the default configuration file for Windows to prevent filename conflicts with the truffle command. The structure of a Truffle project is as follows.
Another very useful command in Truffle is truffle unbox[box-name], which is used to download templates, where box-name is the actual name of the template to be downloaded. The next section will detail the use of templates.
To use this drizzle template, you first need to install the Truffle and Ganache environments, which have already been installed. Next, simply execute the command truffle unbox drizzle to download this template.
Thus, the foundational knowledge for DApp development has been introduced, and the preparatory work is complete. Now we can begin the actual development of DApps.