智能合约技术 以太坊采用了Solidity作为智能合约语言,Solidity 是一门为实现智能合约而创建的高级编程语言,能在允许以太坊程序的节点上运行。该语言吸收了C++、JavaScript的一些特性,例如它是静态类型语言,支持继承、库等。
简单的示例:
// 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;
}
}
源文件中可以包含任意多个 合约定义 、导入源文件指令 、 版本标识 指令、 结构体 、 枚举 和 函数 定义.
SPDX许可标识
SPDX:The Software Package Data Exchange
// SPDX-License-Identifier: MIT
// SPDX-License-Identifier: UNLICENSED
版本标识
pragma solidity ^0.8.4;
或者 pragma solidity >=0.4.16 <0.9.0;
ABI Coder Pragma
Solidity 0.7.4 之前:pragma experimental ABIEncoderV2
Solidity 0.7.4 之后:pragma abicoder v2
导入文件
import "filename";
示例:
import "./helper.sol";
注释
// This is a single-line comment.
/*
This is a
multi-line comment.
*/
状态变量
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.0 <0.9.0;
contract SimpleStorage {
uint storedData; // State variable
// ...
}
函数
/ SPDX-License-Identifier: GPL-3.0
pragma solidity >0.7.0 <0.9.0;
contract TinyAuction {
function Mybid() public payable { // 定义函数
// ...
}
}
// Helper function defined outside of a contract
function helper(uint x) pure returns (uint) {
return x * 2;
}
函数修饰器
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.22 <0.9.0;
contract Purchase {
address public seller;
modifier onlySeller() { // Modifier
require(
msg.sender == seller,
"Only seller can call this."
);
_;
}
function abort() public view onlySeller { // Modifier usage
// ...
}
}
事件
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.21 <0.9.0;
contract SimpleAuction {
event HighestBidIncreased(address bidder, uint amount); // Event
function bid() public payable {
// ...
emit HighestBidIncreased(msg.sender, msg.value); // Triggering event
}
}
异常处理
使用revert
或者require
(推荐)
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
/// Not enough funds for transfer. Requested `requested`,
/// but only `available` available.
error NotEnoughFunds(uint requested, uint available);
contract Token {
mapping(address => uint) balances;
function transfer(address to, uint amount) public {
uint balance = balances[msg.sender];
if (balance < amount)
revert NotEnoughFunds(amount, balance);
balances[msg.sender] -= amount;
balances[to] += amount;
// ...
}
function transfer2(address to, uint amount) public {
uint balance = balances[msg.sender];
require(balance > amount," balance must be greater than amount");
balances[msg.sender] -= amount;
balances[to] += amount;
// ...
}
}
结构
pragma solidity >=0.4.0 <0.9.0;
contract Ballot {
struct Voter { // 结构体
uint weight;
bool voted;
address delegate;
uint vote;
}
}
枚举
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.25 <0.9.0;
contract Purchase {
enum State { Created, Locked } // Enum
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。