Solidity合约结构
123458262
发表于 2022-12-27 10:28:22
76
0
0
在 Solidity 中,合约类似于面向对象编程语言中的类。
每个合约中可以包含 :ref:structure-state-variables、 :ref:structure-functions、
:ref:structure-function-modifiers、:ref:structure-events、 :ref:structure-struct-types、. a+ n2 O' E5 k- S6 ^8 V" b
和 :ref:structure-enum-types 的声明,且合约可以从其他合约继承。# r- K0 N! `; _
状态变量; C: g2 t( p$ M0 o! I u
状态变量是永久地存储在合约存储中的值。
pragma solidity ^0.4.0;6 Y; \ C" v8 M3 K! R
contract SimpleStorage {9 v9 X. E! D) o& l0 N9 N/ L; e. J
uint storedData; // 状态变量
// ...( u" d/ A" w6 o- I! u! p ]! d
}$ Y: M; N& E# }4 e- C
有效的状态变量类型参阅 :ref:types 章节,
对状态变量可见性有可能的选择参阅 :ref:visibility-and-getters 。
函数; Q7 Q) o% R" T* M# ]8 y! t# `
函数是合约中代码的可执行单元。( ^9 |# K. g9 ^5 x# c
pragma solidity ^0.4.0;
contract SimpleAuction {
function bid() public payable { // 函数% U, u$ }2 S. X+ h
// ...* D, u3 I2 e$ w
}
}
:ref:function-calls 可发生在合约内部或外部,且函数对其他合约有不同程度的可见性( :ref:visibility-and-getters)。/ Y: z, p# p5 Y! S/ c8 `4 p
函数修饰器
函数修饰器可以用来以声明的方式改良函数语义(参阅合约章节中 :ref:modifiers)。$ L, R, w: Z' M2 Y
pragma solidity ^0.4.22;0 d3 y: t2 |* Z
contract Purchase {
address public seller;
modifier onlySeller() { // 修饰器
require(7 v( J( |5 Z$ X& p
msg.sender == seller,
"Only seller can call this."
);! d7 |( q* l4 H( r
_;: U! J7 J6 D6 l. c' A, a
}
function abort() public onlySeller { // Modifier usage
// ...
}( g6 U- [9 @ u# z( o8 Z" i
}
事件
事件是能方便地调用以太坊虚拟机日志功能的接口。8 K) K2 ]# x1 L& C
pragma solidity ^0.4.21;1 a0 Z4 U2 ^! m- n' S/ w2 I( b
contract SimpleAuction {5 F. A* S" z+ N* g5 Q- V
event HighestBidIncreased(address bidder, uint amount); // 事件
function bid() public payable {
// ...
emit HighestBidIncreased(msg.sender, msg.value); // 触发事件& Q9 ~0 d2 i* S4 f' @1 h* D
}
}
有关如何声明事件和如何在 dapp 中使用事件的信息,参阅合约章节中的 :ref:events。
结构类型
结构是可以将几个变量分组的自定义类型(参阅类型章节中的 :ref:structs)。
pragma solidity ^0.4.0;/ c4 o9 J" H' O: W
contract Ballot {
struct Voter { // 结构# t& [, }6 A p0 t q
uint weight;
bool voted;
address delegate;/ J: v% J5 N: c$ x, r
uint vote;2 d/ `' p: N" K% j
}0 |' q' D. I7 ^3 T, }# w1 c) {
}
枚举类型( j; ^2 h0 D+ }4 l+ n
枚举可用来创建由一定数量的“常量值”构成的自定义类型(参阅类型章节中的 :ref:enums)。
pragma solidity ^0.4.0;
contract Purchase {# k: R. c+ ^6 V& p
enum State { Created, Locked, Inactive } // 枚举3 c) u& |7 _, K7 W- z- |
}
成为第一个吐槽的人