Solidity Introduction and Development Environment
Learning Objectives
- Understand the essence and core characteristics of smart contracts
- Master the operating principles of contracts on Ethereum (Transaction + EVM)
- Recognize Solidity language features and development toolchain
- Write and deploy the first smart contract
Prerequisites
- Understand basic blockchain concepts (blocks, transactions, consensus)
- Understand the Ethereum account model (EOA and contract accounts)
- Basic programming experience (any language is acceptable)
I. Fundamental Nature of Smart Contracts
1.1 Essentially a Contract
The English term for smart contract is Smart Contract, with the emphasis on Contract. It is not merely a piece of program, but rather a digital expression of trust relationships across organizations and individuals.
Traditional contracts rely on legal systems and intermediaries to ensure execution, while smart contracts rely on blockchain networks and code logic to ensure execution—Code is Law.
1.2 Development Process: Formation, Amendment, Termination of Contracts
The lifecycle of a smart contract can be analogized to traditional contracts:
| Phase | Traditional Contract | Smart Contract |
|---|---|---|
| Formation | Drafting, signing contract | Writing, deploying contract (deploy) |
| Amendment | Signing supplementary agreement | Deploying new version contract (Proxy Pattern) |
| Termination | Terminating contract | Calling selfdestruct or deactivating logic |
1.3 Immutability and Open Source
Once a smart contract is deployed on the blockchain, its code cannot be modified—this is immutability. This means:
- Thorough testing and auditing must be performed before deployment
- Modifying logic can only be done by deploying a new contract or using a Proxy Pattern
- Contract code is usually open-source verified on block explorers like Etherscan, allowing anyone to read and audit it
1.4 DeFi Illustrates Commercial Contracts, DAO Illustrates Social Contracts
The application scenarios of smart contracts perfectly demonstrate their 'contractual' nature:
- DeFi (Decentralized Finance): The digitalization of financial contracts such as lending, trading, and insurance, reflecting commercial contract relationships. Examples include Uniswap's trading contracts and Aave's lending contracts.
- DAO (Decentralized Autonomous Organization): The digitalization of organizational rules such as voting, governance, and proposals, reflecting social contract relationships. An example is MakerDAO's governance contract.
II. Contract Operating Principles
2.1 Dual Role of Nodes
Each node in the Ethereum network undertakes two core responsibilities:
- One side processes transactions: receiving, validating, and broadcasting transactions
- One side runs the EVM (Ethereum Virtual Machine): executing contract code and updating state
2.2 Sequential Execution, No Concurrency
This is key to understanding smart contracts:
- Block sequential generation: Blocks are generated sequentially at fixed time intervals
- Transaction sequential execution: Transactions within a block are executed one by one in a fixed order
- No concurrent access: No multi-threading, no race conditions
This is fundamentally different from traditional backend development—you don't need to consider concurrency control issues like locks or semaphores, but it also means performance is limited by the chain's throughput.
2.3 Transaction Triggers EVM Execution
Contract execution is always triggered by a Transaction, and understanding the structure of a Transaction is crucial:
| Field | Description |
|---|---|
| from | Sender address (EOA account) |
| to | Target address (contract address, or empty to deploy a new contract) |
| value | Amount of ETH transferred (in wei) |
| calldata | Call data (function selector + parameter encoding) |
Key Understanding: Behind contract execution are Transactions and the EVM. Each time a contract function is called, it is essentially sending a transaction, which the EVM parses the calldata and executes the corresponding function logic. Read operations (view/pure functions) do not require sending a transaction and can be executed directly on a local node.
III. Introduction to Solidity Language
Solidity is the mainstream development language for Ethereum smart contracts, with the following characteristics:
- Strongly typed: All variables must declare a type, and type safety is checked at compile time
- Object-oriented: Supports contract inheritance, interfaces, and abstract contracts
- Multiple inheritance: A contract can inherit from multiple parent contracts simultaneously (using C3 linearization to solve the diamond problem)
- C++-like syntax: Brace syntax, semicolon termination, friendly to developers with C/C++/Java/JavaScript experience
- Designed for EVM: Compiles to EVM bytecode, runs on the Ethereum Virtual Machine
IV. Development Environment and Toolchain
4.1 solc Compiler
solc is the official Solidity compiler, which compiles .sol source files into EVM bytecode and ABI (Application Binary Interface).
# 安装(macOS)
brew install solidity
# 编译合约
solc --bin --abi MyContract.sol
4.2 Remix IDE
Remix is the most suitable smart contract development tool for beginners:
- Online version: Use directly in the browser, no installation required
- Desktop version: Remix Desktop, provides offline development capabilities
- Built-in compiler, deployment tool, debugger
- Supports connecting to MetaMask for deployment to real networks
It is recommended to use Remix during the introductory phase, and then migrate to a framework for subsequent project development.
4.3 Development Frameworks
| Framework | Language | Features |
|---|---|---|
| Hardhat | JavaScript/TypeScript | Currently mainstream, rich plugin ecosystem, built-in Hardhat Network |
| Truffle | JavaScript | Veteran framework, mature community, gradually being replaced by Hardhat |
| Foundry | Solidity | Write tests in Solidity, extremely fast compilation speed |
4.4 SDK (Frontend Interaction Libraries)
| Library | Features |
|---|---|
| ethers.js | Lightweight, modular, currently recommended as the first choice |
| web3.js | Veteran library, rich API, large community |
| viem | TypeScript-first, excellent performance, emerging choice |
V. First Contract: NumberStorage
Below, we will write the simplest smart contract to implement number storage and retrieval:
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.2 <0.9.0;
contract NumberStorage {
uint public x;
function setX(uint px) public {
x = px;
}
function getX() public view returns(uint) {
return x;
}
function add(uint a, uint b) private pure returns(uint) {
return a + b;
}
}
Code Line-by-Line Analysis
Line 1: License Declaration
// SPDX-License-Identifier: MIT
SPDX (Software Package Data Exchange) license identifier, declaring the open-source protocol of the code. Starting from Solidity 0.6.8, the compiler will issue a warning for files missing this declaration. Common values include MIT, GPL-3.0, UNLICENSED (not open source).
Line 2: Version Declaration
pragma solidity >=0.8.2 <0.9.0;
Specifies the compiler version range. pragma is a compiler directive that tells the compiler to compile this file only if the version meets the conditions.
Line 4: Contract Definition
contract NumberStorage {
The contract keyword defines a contract, similar to a class in object-oriented languages.
Line 5: State Variable
uint public x;
uint is an unsigned integer type (equivalent to uint256), and public automatically generates a getter function with the same name. State variables are stored on the blockchain and are the contract's persistent data.
Lines 7-9: Write Function
function setX(uint px) public {
x = px;
}
public means it can be called externally and internally. Modifying state variables requires sending a transaction (consuming Gas).
Lines 11-13: Read Function
function getX() public view returns(uint) {
return x;
}
view means it only reads state, not modifies it. Calling a view function does not consume Gas (executed locally).
Lines 15-17: Pure Calculation Function
function add(uint a, uint b) private pure returns(uint) {
return a + b;
}
private: Callable only within the contractpure: Neither reads nor modifies state, a purely computational function
VI. Source File Structure
The standard structure of a Solidity source file:
// 1. 许可证声明
// SPDX-License-Identifier: MIT
// 2. 版本声明
pragma solidity ^0.8.0;
// 3. import 语句(如有)
import "./OtherContract.sol";
// 4. 合约定义
contract MyContract {
// ...
}
VII. Versioning Issues
7.1 Semantic Versioning
Solidity follows semantic versioning: MAJOR.MINOR.PATCH
- MAJOR: Incompatible major changes
- MINOR: Backward-compatible feature additions
- PATCH: Backward-compatible bug fixes
7.2 Version Declaration Syntax
pragma solidity ^0.8.0; // >=0.8.0 且 <0.9.0
pragma solidity >=0.8.2 <0.9.0; // 精确范围
pragma solidity 0.8.20; // 仅限指定版本
7.3 Important Version Changes
| Version | Important Changes |
|---|---|
| 0.8.0 | Integer overflow defaults to throwing an exception (SafeMath no longer needed) |
| 0.8.0 | ABIEncoderV2 becomes the default encoder |
| 0.5.0 | Function visibility must be explicitly declared (no longer defaults to public) |
| 0.6.0 | fallback and receive replace anonymous fallback functions |
Pay special attention to the integer overflow change in 0.8.0: In versions below 0.8.0, the result of
uint8(255) + 1is0(modulo operation), which was the root cause of many security vulnerabilities. Starting from 0.8.0, an exception is thrown by default, greatly enhancing security.
VIII. Basic Contract Structure
A complete contract may include the following elements:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyContract {
// 1. 状态变量 - 永久存储在区块链上
uint public count;
address public owner;
// 2. 事件 - 用于记录日志,前端可以监听
event CountChanged(uint newCount);
// 3. 修饰符 - 函数执行的前置条件检查
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
// 4. 构造函数 - 合约部署时执行一次
constructor() {
owner = msg.sender;
}
// 5. 函数 - 合约的行为逻辑
function increment() public onlyOwner {
count += 1;
emit CountChanged(count);
}
}
| Element | Description |
|---|---|
| State Variables | Persistent data of the contract, stored on-chain |
| Functions | Contract behavior, can read or modify state |
| Modifiers | Reusable pre/post-condition check logic for functions |
| Events | On-chain logs, convenient for frontend listening and indexing |
| Constructor | Executed once upon deployment, used for initialization |
Summary
In this section, we learned that the essence of smart contracts is a digitized contractual relationship, understood the Transaction + EVM execution model, recognized the Solidity language and development toolchain, and wrote our first smart contract. In the next section, we will delve into Solidity's value type system.
This article is the 3rd of 12 in the Web3 Blockchain series.
主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/7486
