如何阅读一个简单的 Solidity 智能合约?
Swipe sideways to see all of it.
Solidity 简介
Solidity 是一种用于编写智能合约的高级语言。1 它使用花括号,并且被设计为在 EVM 上运行。1 它借鉴了 C++、Python 和 JavaScript 的一些思想。1
合约
下面是 Solidity 官方文档中的第一个示例。它被称为 SimpleStorage。2
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.9.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
逐行解读
第 1 行:许可证。 第一行说明,该代码以 GPL 3.0 许可证共享。2 当发布代码成为常规做法时,机器可读的许可证标签就很重要。2
第 2 行:版本。 pragma 是给编译器的指令。这一行说明,该代码适用于 Solidity 0.4.16 或更新版本,但低于 0.9.0。2 这样可以防止未来的编译器版本(它可能使代码的行为发生变化)去编译它。2
第 4 行:合约。 contract SimpleStorage 开始定义合约。在 Solidity 中,合约是位于同一个地址上的代码(它的函数)和数据(它的状态)。2
第 5 行:保存的数字。 uint storedData; 创建了一个名为 storedData 的状态变量。2 uint 表示 256 位的“无符号整数”:一个从零开始、不能低于零的整数。2,3 可以把它想象成数据库中的一个格子。2 状态变量会永久保存在区块链上。4 在有人设置它之前,它的值是 0,这是 uint 的默认值。5
第 7 至 9 行:set。 set 函数接收一个名为 x 的数字,并将其保存到 storedData 中。2 它被标记为 public,因此它是合约接口的一部分,可以从外部调用。6 人们通过发送交易来运行合约的函数,而交易需要支付 gas。7,8
第 11 至 13 行:get。 get 函数返回保存的数字。2 它被标记为 view,意思是承诺不改变合约的状态。6 这类函数通常被称为“getter”。4
它让人们做什么
这个合约让任何人都可以保存一个数字,世界上任何人都能读取它。2 任何人都可以再次调用 set 来覆盖这个数字。旧的数字仍会保存在区块链的历史记录中。2
为了防止陌生人修改某个值,合约需要访问规则。2 ethereum.org 的自动售货机示例使用了一行 require,使得只有所有者才能为售货机补货。7 require 检查在函数开始时运行,只有满足条件,函数才会继续执行。9
- Solidity documentation (home page). Solidity documentation, The Solidity Authors.
- Introduction to Smart Contracts (the SimpleStorage example and the EVM overview). Solidity documentation, The Solidity Authors.
- Types: integers. Solidity documentation, The Solidity Authors.
- Anatomy of smart contracts. ethereum.org developer docs, page updated 12 June 2026.
- Expressions and control structures: scoping and declarations. Solidity documentation, The Solidity Authors.
- Contracts: function visibility and view functions. Solidity documentation, The Solidity Authors.
- Introduction to smart contracts. ethereum.org developer docs, page updated 25 February 2026.
- Gas and fees. ethereum.org developer docs, page updated 24 June 2026.
- Smart contract security. ethereum.org developer docs, page updated 7 October 2026.
本内容为基于上述公开来源的通识教育,不构成财务、法律、税务或投资建议。提及某家公司、某个项目或某个监管机构,并不代表任何形式的认可或背书。 最后核对于2026年10月22日。 条款与免责声明.