Solidity合约结构
123458262
发表于 2022-12-27 10:28:22
99
0
0
% V' }6 E: D0 j+ [) `. q- r8 H
在 Solidity 中,合约类似于面向对象编程语言中的类。
每个合约中可以包含 :ref:structure-state-variables、 :ref:structure-functions、
:ref:structure-function-modifiers、:ref:structure-events、 :ref:structure-struct-types、6 T, C! |4 `+ H* Y4 y4 _( d
和 :ref:structure-enum-types 的声明,且合约可以从其他合约继承。
状态变量4 w# U4 y, u2 v! f/ O$ ~( B+ p
状态变量是永久地存储在合约存储中的值。- R1 s: { ^# U
pragma solidity ^0.4.0;: H/ K" ?) V) D1 |* H+ ~! ^
contract SimpleStorage {
uint storedData; // 状态变量
// ...1 T; j. C/ ~4 B6 F: P o
}
有效的状态变量类型参阅 :ref:types 章节,
对状态变量可见性有可能的选择参阅 :ref:visibility-and-getters 。% H( o0 B, i* S6 V; i
函数
函数是合约中代码的可执行单元。
pragma solidity ^0.4.0;% `4 C5 ?8 {# W
contract SimpleAuction {( M/ g0 {) O6 y6 I1 y' Q ~
function bid() public payable { // 函数
// ...+ ^. J3 V+ ~. x x) ^
}$ O# D$ r" G4 ]0 J' a
}2 U9 ], r9 ]# g- H6 Y# E9 {- w
:ref:function-calls 可发生在合约内部或外部,且函数对其他合约有不同程度的可见性( :ref:visibility-and-getters)。" W" N ^ e w1 ^% ~: q
函数修饰器
函数修饰器可以用来以声明的方式改良函数语义(参阅合约章节中 :ref:modifiers)。3 N. }# R0 [* x
pragma solidity ^0.4.22;
contract Purchase {3 m% e1 }- k/ n& b% z
address public seller;
modifier onlySeller() { // 修饰器8 [5 P2 T/ I7 ^$ K
require(/ U" K5 j3 B/ N1 L9 o" P
msg.sender == seller,: v& u. q# P3 z" C+ j4 F4 V5 |' [
"Only seller can call this."7 D: m- [2 M4 O s0 D
);
_;7 E2 o; u/ ]9 h" y
}
7 y6 B( K$ n, x$ d$ q s! j1 ?$ W
function abort() public onlySeller { // Modifier usage+ P4 r( w5 ^" x8 c9 b. `
// ...$ f N+ t. C) `! t4 { {6 l
}
}
事件
事件是能方便地调用以太坊虚拟机日志功能的接口。
pragma solidity ^0.4.21;1 c! U# A) j; }
contract SimpleAuction {2 ?* ?; H1 _1 e9 H% Z0 s
event HighestBidIncreased(address bidder, uint amount); // 事件) k# U( t' Y2 w0 N4 J: Y& `
function bid() public payable {6 e* {) [: W4 L0 P: w
// ...
emit HighestBidIncreased(msg.sender, msg.value); // 触发事件
}
}
有关如何声明事件和如何在 dapp 中使用事件的信息,参阅合约章节中的 :ref:events。
结构类型6 r5 g T6 v2 v9 H
结构是可以将几个变量分组的自定义类型(参阅类型章节中的 :ref:structs)。' q; [1 j9 ?# Q: [
pragma solidity ^0.4.0;. C9 V D9 K1 F$ X% |, M/ z% Z
contract Ballot {6 n# e, e# ]; C2 ^8 l" ?
struct Voter { // 结构
uint weight;
bool voted;9 I) C* q5 V$ L' K y/ n; J7 f
address delegate;
uint vote;
}3 U% o' v0 R' r6 x1 Y+ E; f: ^2 x
}; t0 ]6 u* b2 T9 \, ]- F3 ~7 F3 K( `- {
枚举类型
枚举可用来创建由一定数量的“常量值”构成的自定义类型(参阅类型章节中的 :ref:enums)。 z5 p# j2 i, o2 }0 V
pragma solidity ^0.4.0;, Q% H( t: S& }: N
contract Purchase {' }4 c1 ]* R g1 \9 U3 z+ x1 z
enum State { Created, Locked, Inactive } // 枚举6 x% ~& m6 Q$ K! M# }! x
}
成为第一个吐槽的人