跳转至主要内容
Change page

详解智能合约

上次修改时间: @zhangyuenet(opens in a new tab), 2024年4月1日

智能合约是一种在以太坊某个地址上运行的程序。 它们是由数据和函数组成的,可以在收到交易时执行。 以下概述一个智能合约的组成。

前提条件

确保你已经先阅读了智能合约。 本文档假设你已经熟悉某种编程语言,例如 JavaScript 或 Python。

数据

任何合约数据必须分配到一个位置:要么是存储,要么是内存。 在智能合约中修改存储消耗很大,因此你需要考虑数据在哪里存取。

存储

持久性数据被称之为存储,由状态变量表示。 这些值被永久地存储在区块链上。 你需要声明一个类型,以便于合约在编译时可以跟踪它在区块链上需要多少存储。

1// Solidity example
2contract SimpleStorage {
3 uint storedData; // State variable
4 // ...
5}
复制
1# Vyper example
2storedData: int128
复制

如果用过面向对象编程语言,应该会熟悉大多数类型。 但如果是刚接触以太坊开发,则会发现 address 是一个新类型。

一个 address 类型可以容纳一个以太坊地址,相当于 20 个字节或 160 位。 它以十六进制的形式返回,前导是 0x。

其它类型包括:

  • 布尔
  • 整数(integer)
  • 定点数(fixed point numbers)
  • 固定大小的字节数组(fixed-size byte arrays)
  • 动态大小的字节数组(dynamically-sized byte arrays)
  • 有理数和整数常量(Rational and integer literals)
  • 字符常量(String literals)
  • 十六进制常量(Hexadecimal literals)
  • 枚举(Enums)

了解更多信息,请参阅文档:

内存

仅在合约函数执行期间存储的值被称为内存变量。 由于这些变量不是永久地存储在区块链上,所以它们的使用成本要低得多。

Solidity 文档(opens in a new tab)中了解更多关于以太坊虚拟机如何存储数据(存储、内存和栈)。

环境变量

除了在自己合约上定义的变量之外,还有一些特殊的全局变量。 它们主要用于提供有关区块链或当前交易的信息。

示例:

属性状态变量描述
block.timestampuint256当前区块的时间戳
msg.sender地址消息的发送者(当前调用)

函数

用最简单的术语来说,函数可以获得信息或设置信息,以响应传入的交易。

有两种函数调用方式:

  • internal – 不会创建以太坊虚拟机调用
    • Internal 函数和状态变量只能在内部访问(只能在合约内部或者从其继承的合约内部访问)。
  • external – 会创建以太坊虚拟机调用
    • External 函数是合约接口的一部分,这意味着他可以被其它合约和交易调用。 一个 external 函数 f 不可以被内部调用(即 f() 不行,但 this.f() 可以)。

它们可以是 publicprivate

  • public 函数可以在合约内部调用或者通过消息在合约外部调用
  • private 函数仅在其被定义的合约内部可见,并且在该合约的派生合约中不可见。

函数和状态变量都可以被定义为 public 或 private

下面是更新合约上一个状态变量的函数:

1// Solidity example
2function update_name(string value) public {
3 dapp_name = value;
4}
复制
  • string 类型的参数 value 传入函数 update_name
  • 函数声明为 public,意味着任何人都能访问它
  • 函数没有被声明为 view,因此它可以修改合约状态

视图函数

这些函数保证不会修改合约数据的状态。 常见的示例是 "getter" 函数 - 例如,它可以用于接收用户的余额。

1// Solidity 示例
2function balanceOf(address _owner) public view returns (uint256 _balance) {
3 return ownerPizzaCount[_owner];
4}
复制
1dappName: public(string)
2
3@view
4@public
5def readName() -> string:
6 return dappName
复制

这些操作被视为修改状态:

  1. 写入状态变量。
  2. 正在导出事件(opens in a new tab)
  3. 创建其它合约(opens in a new tab)
  4. 使用 selfdestruct
  5. 通过调用发送 ether。
  6. 调用任何未标记为 viewpure 的函数。
  7. 使用底层调用。
  8. 使用包含某些操作码的内联程序组。

构造函数

constructor 函数只在首次部署合约时执行一次。 与许多基于类的编程语言中的 constructor 函数类似,这些函数常将状态变量初始化到指定的值。

1// Solidity 示例
2// 初始化合约数据,设置 `owner`为合约的创建者。
3constructor() public {
4 // 所有智能合约依赖外部交易来触发其函数。
5 // `msg` 是一个全局变量,包含了给定交易的相关数据,
6 // 例如发送者的地址和交易中包含的 ETH 数量。
7 // 了解更多:https://solidity.readthedocs.io/en/v0.5.10/units-and-global-variables.html#block-and-transaction-properties
8 owner = msg.sender;
9}
显示全部
复制
1# Vyper 示例
2
3@external
4def __init__(_beneficiary: address, _bidding_time: uint256):
5 self.beneficiary = _beneficiary
6 self.auctionStart = block.timestamp
7 self.auctionEnd = self.auctionStart + _bidding_time
复制

内置函数

除了自己在合约中定义的变量和函数外,还有一些特殊的内置函数。 最明显的例子是:

  • address.send() – Solidity
  • send(address) – Vyper

这使合约可以发送以太币给其它帐户。

编写函数

你的函数需要:

  • 参数变量及其类型(如果它接受参数)
  • 声明为 internal/external
  • 声明为 pure/view/payable
  • 返回类型(如果它返回值)
1pragma solidity >=0.4.0 <=0.6.0;
2
3contract ExampleDapp {
4 string dapp_name; // state variable
5
6 // Called when the contract is deployed and initializes the value
7 constructor() public {
8 dapp_name = "My Example dapp";
9 }
10
11 // Get Function
12 function read_name() public view returns(string) {
13 return dapp_name;
14 }
15
16 // Set Function
17 function update_name(string value) public {
18 dapp_name = value;
19 }
20}
显示全部
复制

一个完整的合约可能就是这样。 在这里,constructor 函数为 dapp_name 变量提供了初始化值。

事件和日志

事件可以让你通过前端或其它订阅应用与你的智能合约通信。 当交易被挖矿执行时,智能合约可以触发事件并且将日志写入区块链,然后前端可以进行处理。

附带注解的示例

这是一些用 Solidity 写的例子。 如果希望运行这些代码,你可以在 Remix(opens in a new tab) 中调试。

Hello world

1// Specifies the version of Solidity, using semantic versioning.
2// 了解更多:https://solidity.readthedocs.io/en/v0.5.10/layout-of-source-files.html#pragma
3pragma solidity ^0.5.10;
4
5// 定义合约名称 `HelloWorld`。
6// 一个合约是函数和数据(其状态)的集合。
7// 一旦部署,合约就会留在以太坊区块链的一个特定地址上。
8// 了解更多: https://solidity.readthedocs.io/en/v0.5.10/structure-of-a-contract.html
9contract HelloWorld {
10
11 // 定义`string`类型变量 `message`
12 // 状态变量是其值永久存储在合约存储中的变量。
13 // 关键字 `public` 使得可以从合约外部访问。
14 // 并创建了一个其它合约或客户端可以调用访问该值的函数。
15 string public message;
16
17 // 类似于很多基于类的面向对象语言,
18 // 构造函数是仅在合约创建时执行的特殊函数。
19 // 构造器用于初始化合约的数据。
20 // 了解更多:https://solidity.readthedocs.io/en/v0.5.10/contracts.html#constructors
21 constructor(string memory initMessage) public {
22 // 接受一个字符变量 `initMessage`
23 // 并为合约的存储变量`message` 赋值
24 message = initMessage;
25 }
26
27 // 一个 public 函数接受字符参数并更新存储变量 `message`
28 function update(string memory newMessage) public {
29 message = newMessage;
30 }
31}
显示全部
复制

代币

1pragma solidity ^0.5.10;
2
3contract Token {
4 // 一个 `address` 类比于邮件地址 - 它用来识别以太坊的一个帐户。
5 // 地址可以代表一个智能合约或一个外部(用户)帐户。
6 // 了解更多:https://solidity.readthedocs.io/en/v0.5.10/types.html#address
7 address public owner;
8
9 // `mapping` 是一个哈希表数据结构。
10 // 此 `mapping` 将一个无符号整数(代币余额)分配给地址(代币持有者)。
11 // 了解更多: https://solidity.readthedocs.io/en/v0.5.10/types.html#mapping-types
12 mapping (address => uint) public balances;
13
14 // 事件允许在区块链上记录活动。
15 // 以太坊客户端可以监听事件,以便对合约状态更改作出反应。
16 // 了解更多: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#events
17 event Transfer(address from, address to, uint amount);
18
19 // 初始化合约数据,设置 `owner`为合约创建者的地址。
20 constructor() public {
21 // 所有智能合约依赖外部交易来触发其函数。
22 // `msg` 是一个全局变量,包含了给定交易的相关数据,
23 // 例如发送者的地址和包含在交易中的 ETH 数量。
24 // 了解更多:https://solidity.readthedocs.io/en/v0.5.10/units-and-global-variables.html#block-and-transaction-properties
25 owner = msg.sender;
26 }
27
28 // 创建一些新代币并发送给一个地址。
29 function mint(address receiver, uint amount) public {
30 // `require` 是一个用于强制执行某些条件的控制结构。
31 // 如果 `require` 的条件为 `false`,则异常被触发,
32 // 所有在当前调用中对状态的更改将被还原。
33 // 学习更多: https://solidity.readthedocs.io/en/v0.5.10/control-structures.html#error-handling-assert-require-revert-and-exceptions
34
35 // 只有合约创建人可以调用这个函数
36 require(msg.sender == owner, "You are not the owner.");
37
38 // 强制执行代币的最大数量
39 require(amount < 1e60, "Maximum issuance exceeded");
40
41 // 将 "收款人"的余额增加"金额"
42 balances[receiver] += amount;
43 }
44
45 // 从任何调用者那里发送一定数量的代币到一个地址。
46 function transfer(address receiver, uint amount) public {
47 // 发送者必须有足够数量的代币用于发送
48 require(amount <= balances[msg.sender], "Insufficient balance.");
49
50 // 调整两个帐户的余额
51 balances[msg.sender] -= amount;
52 balances[receiver] += amount;
53
54 // 触发之前定义的事件。
55 emit Transfer(msg.sender, receiver, amount);
56 }
57}
显示全部
复制

唯一的数字资产

1pragma solidity ^0.5.10;
2
3// 从其它文件向当前合约中导入符号。
4// 本例使用一系列来自 OpenZeppelin 的辅助合约。
5// 了解更多:https://solidity.readthedocs.io/en/v0.5.10/layout-of-source-files.html#importing-other-source-files
6
7import "../node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol";
8import "../node_modules/@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
9import "../node_modules/@openzeppelin/contracts/introspection/ERC165.sol";
10import "../node_modules/@openzeppelin/contracts/math/SafeMath.sol";
11
12// `is` 关键字用于从其它外部合约继承函数和关键字。
13// 本例中,`CryptoPizza` 继承 `IERC721` 和 `ERC165` 合约。
14// 了解更多:https://solidity.readthedocs.io/en/v0.5.10/contracts.html#inheritance
15contract CryptoPizza is IERC721, ERC165 {
16 // 使用 OpenZeppelin's SafeMath 库来安全执行算数操作。
17 // 了解更多:https://docs.openzeppelin.com/contracts/2.x/api/math#SafeMath
18 using SafeMath for uint256;
19
20 // Solidity 语言中的常量状态变量与其他语言类似。
21 // 但是必须用一个表达式为常量赋值,而这个表达式本身必须在编译时是一个常量。
22 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#constant-state-variables
23 uint256 constant dnaDigits = 10;
24 uint256 constant dnaModulus = 10 ** dnaDigits;
25 bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
26
27 // Struct types let you define your own type
28 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/types.html#structs
29 struct Pizza {
30 string name;
31 uint256 dna;
32 }
33
34 // Creates an empty array of Pizza structs
35 Pizza[] public pizzas;
36
37 // Mapping from pizza ID to its owner's address
38 mapping(uint256 => address) public pizzaToOwner;
39
40 // Mapping from owner's address to number of owned token
41 mapping(address => uint256) public ownerPizzaCount;
42
43 // Mapping from token ID to approved address
44 mapping(uint256 => address) pizzaApprovals;
45
46 // You can nest mappings, this example maps owner to operator approvals
47 mapping(address => mapping(address => bool)) private operatorApprovals;
48
49 // Internal function to create a random Pizza from string (name) and DNA
50 function _createPizza(string memory _name, uint256 _dna)
51 // The `internal` keyword means this function is only visible
52 // within this contract and contracts that derive this contract
53 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#visibility-and-getters
54 internal
55 // `isUnique` is a function modifier that checks if the pizza already exists
56 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/structure-of-a-contract.html#function-modifiers
57 isUnique(_name, _dna)
58 {
59 // Adds Pizza to array of Pizzas and get id
60 uint256 id = SafeMath.sub(pizzas.push(Pizza(_name, _dna)), 1);
61
62 // Checks that Pizza owner is the same as current user
63 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/control-structures.html#error-handling-assert-require-revert-and-exceptions
64
65 // note that address(0) is the zero address,
66 // indicating that pizza[id] is not yet allocated to a particular user.
67
68 assert(pizzaToOwner[id] == address(0));
69
70 // Maps the Pizza to the owner
71 pizzaToOwner[id] = msg.sender;
72 ownerPizzaCount[msg.sender] = SafeMath.add(
73 ownerPizzaCount[msg.sender],
74 1
75 );
76 }
77
78 // Creates a random Pizza from string (name)
79 function createRandomPizza(string memory _name) public {
80 uint256 randDna = generateRandomDna(_name, msg.sender);
81 _createPizza(_name, randDna);
82 }
83
84 // Generates random DNA from string (name) and address of the owner (creator)
85 function generateRandomDna(string memory _str, address _owner)
86 public
87 // Functions marked as `pure` promise not to read from or modify the state
88 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#pure-functions
89 pure
90 returns (uint256)
91 {
92 // Generates random uint from string (name) + address (owner)
93 uint256 rand = uint256(keccak256(abi.encodePacked(_str))) +
94 uint256(_owner);
95 rand = rand % dnaModulus;
96 return rand;
97 }
98
99 // Returns array of Pizzas found by owner
100 function getPizzasByOwner(address _owner)
101 public
102 // Functions marked as `view` promise not to modify state
103 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#view-functions
104 view
105 returns (uint256[] memory)
106 {
107 // Uses the `memory` storage location to store values only for the
108 // lifecycle of this function call.
109 // 了解更多:https://solidity.readthedocs.io/en/v0.5.10/introduction-to-smart-contracts.html#storage-memory-and-the-stack
110 uint256[] memory result = new uint256[](ownerPizzaCount[_owner]);
111 uint256 counter = 0;
112 for (uint256 i = 0; i < pizzas.length; i++) {
113 if (pizzaToOwner[i] == _owner) {
114 result[counter] = i;
115 counter++;
116 }
117 }
118 return result;
119 }
120
121 // 转移 Pizza 和归属关系到其它地址
122 function transferFrom(address _from, address _to, uint256 _pizzaId) public {
123 require(_from != address(0) && _to != address(0), "Invalid address.");
124 require(_exists(_pizzaId), "Pizza does not exist.");
125 require(_from != _to, "Cannot transfer to the same address.");
126 require(_isApprovedOrOwner(msg.sender, _pizzaId), "Address is not approved.");
127
128 ownerPizzaCount[_to] = SafeMath.add(ownerPizzaCount[_to], 1);
129 ownerPizzaCount[_from] = SafeMath.sub(ownerPizzaCount[_from], 1);
130 pizzaToOwner[_pizzaId] = _to;
131
132 // 触发继承自 IERC721 合约中定义的事件。
133 emit Transfer(_from, _to, _pizzaId);
134 _clearApproval(_to, _pizzaId);
135 }
136
137 /**
138 * 安全转账给定代币 ID 的所有权到其它地址
139 * 如果目标地址是一个合约,则该合约必须实现 `onERC721Received`函数,
140 * 该函数调用了安全转账并且返回一个 magic value。
141 * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`;
142 * 否则,转账被回退。
143 */
144 function safeTransferFrom(address from, address to, uint256 pizzaId)
145 public
146 {
147 // solium-disable-next-line arg-overflow
148 this.safeTransferFrom(from, to, pizzaId, "");
149 }
150
151 /**
152 * 安全转账给定代币 ID 所有权到其它地址
153 * 如果目标地址是一个合约,则该合约必须实现 `onERC721Received` 函数,
154 * 该函数调用安全转账并返回一个 magic value
155 * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`;
156 * 否则,转账被回退。
157 */
158 function safeTransferFrom(
159 address from,
160 address to,
161 uint256 pizzaId,
162 bytes memory _data
163 ) public {
164 this.transferFrom(from, to, pizzaId);
165 require(_checkOnERC721Received(from, to, pizzaId, _data), "Must implement onERC721Received.");
166 }
167
168 /**
169 * Internal function to invoke `onERC721Received` on a target address
170 * The call is not executed if the target address is not a contract
171 */
172 function _checkOnERC721Received(
173 address from,
174 address to,
175 uint256 pizzaId,
176 bytes memory _data
177 ) internal returns (bool) {
178 if (!isContract(to)) {
179 return true;
180 }
181
182 bytes4 retval = IERC721Receiver(to).onERC721Received(
183 msg.sender,
184 from,
185 pizzaId,
186 _data
187 );
188 return (retval == _ERC721_RECEIVED);
189 }
190
191 // Burns a Pizza - destroys Token completely
192 // The `external` function modifier means this function is
193 // part of the contract interface and other contracts can call it
194 function burn(uint256 _pizzaId) external {
195 require(msg.sender != address(0), "Invalid address.");
196 require(_exists(_pizzaId), "Pizza does not exist.");
197 require(_isApprovedOrOwner(msg.sender, _pizzaId), "Address is not approved.");
198
199 ownerPizzaCount[msg.sender] = SafeMath.sub(
200 ownerPizzaCount[msg.sender],
201 1
202 );
203 pizzaToOwner[_pizzaId] = address(0);
204 }
205
206 // Returns count of Pizzas by address
207 function balanceOf(address _owner) public view returns (uint256 _balance) {
208 return ownerPizzaCount[_owner];
209 }
210
211 // Returns owner of the Pizza found by id
212 function ownerOf(uint256 _pizzaId) public view returns (address _owner) {
213 address owner = pizzaToOwner[_pizzaId];
214 require(owner != address(0), "Invalid Pizza ID.");
215 return owner;
216 }
217
218 // Approves other address to transfer ownership of Pizza
219 function approve(address _to, uint256 _pizzaId) public {
220 require(msg.sender == pizzaToOwner[_pizzaId], "Must be the Pizza owner.");
221 pizzaApprovals[_pizzaId] = _to;
222 emit Approval(msg.sender, _to, _pizzaId);
223 }
224
225 // Returns approved address for specific Pizza
226 function getApproved(uint256 _pizzaId)
227 public
228 view
229 returns (address operator)
230 {
231 require(_exists(_pizzaId), "Pizza does not exist.");
232 return pizzaApprovals[_pizzaId];
233 }
234
235 /**
236 * Private function to clear current approval of a given token ID
237 * Reverts if the given address is not indeed the owner of the token
238 */
239 function _clearApproval(address owner, uint256 _pizzaId) private {
240 require(pizzaToOwner[_pizzaId] == owner, "Must be pizza owner.");
241 require(_exists(_pizzaId), "Pizza does not exist.");
242 if (pizzaApprovals[_pizzaId] != address(0)) {
243 pizzaApprovals[_pizzaId] = address(0);
244 }
245 }
246
247 /*
248 * Sets or unsets the approval of a given operator
249 * An operator is allowed to transfer all tokens of the sender on their behalf
250 */
251 function setApprovalForAll(address to, bool approved) public {
252 require(to != msg.sender, "Cannot approve own address");
253 operatorApprovals[msg.sender][to] = approved;
254 emit ApprovalForAll(msg.sender, to, approved);
255 }
256
257 // Tells whether an operator is approved by a given owner
258 function isApprovedForAll(address owner, address operator)
259 public
260 view
261 returns (bool)
262 {
263 return operatorApprovals[owner][operator];
264 }
265
266 // Takes ownership of Pizza - only for approved users
267 function takeOwnership(uint256 _pizzaId) public {
268 require(_isApprovedOrOwner(msg.sender, _pizzaId), "Address is not approved.");
269 address owner = this.ownerOf(_pizzaId);
270 this.transferFrom(owner, msg.sender, _pizzaId);
271 }
272
273 // Checks if Pizza exists
274 function _exists(uint256 pizzaId) internal view returns (bool) {
275 address owner = pizzaToOwner[pizzaId];
276 return owner != address(0);
277 }
278
279 // Checks if address is owner or is approved to transfer Pizza
280 function _isApprovedOrOwner(address spender, uint256 pizzaId)
281 internal
282 view
283 returns (bool)
284 {
285 address owner = pizzaToOwner[pizzaId];
286 // Disable solium check because of
287 // https://github.com/duaraghav8/Solium/issues/175
288 // solium-disable-next-line operator-whitespace
289 return (spender == owner ||
290 this.getApproved(pizzaId) == spender ||
291 this.isApprovedForAll(owner, spender));
292 }
293
294 // Check if Pizza is unique and doesn't exist yet
295 modifier isUnique(string memory _name, uint256 _dna) {
296 bool result = true;
297 for (uint256 i = 0; i < pizzas.length; i++) {
298 if (
299 keccak256(abi.encodePacked(pizzas[i].name)) ==
300 keccak256(abi.encodePacked(_name)) &&
301 pizzas[i].dna == _dna
302 ) {
303 result = false;
304 }
305 }
306 require(result, "Pizza with such name already exists.");
307 _;
308 }
309
310 // Returns whether the target address is a contract
311 function isContract(address account) internal view returns (bool) {
312 uint256 size;
313 // Currently there is no better way to check if there is a contract in an address
314 // than to check the size of the code at that address.
315 // See https://ethereum.stackexchange.com/a/14016/36603
316 // for more details about how this works.
317 // TODO Check this again before the Serenity release, because all addresses will be
318 // contracts then.
319 // solium-disable-next-line security/no-inline-assembly
320 assembly {
321 size := extcodesize(account)
322 }
323 return size > 0;
324 }
325}
显示全部
复制

延伸阅读

查阅 Solidity 和 Vyper 文档,以获得关于智能合约的更完整概述:

本文对你有帮助吗?