智能合约技术 以太坊采用了Solidity作为智能合约语言,Solidity 是一门为实现智能合约而创建的高级编程语言,能在允许以太坊程序的节点上运行。该语言吸收了C 、JavaScript的一些特性,例如它是静态类型语言,支持继承、库等。
二. solidity开发讲解
简单的示例:
代码语言: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;
}
}
1. 源文件结构
源文件中可以包含任意多个 合约定义 、导入源文件指令 、 版本标识 指令、 结构体 、 枚举 和 函数 定义.
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
导入文件
代码语言:javascript复制import "filename";
示例:
import "./helper.sol";
注释
代码语言:javascript复制// This is a single-line comment.
/*
This is a
multi-line comment.
*/
2. 合约结构
状态变量
代码语言:javascript复制// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.0 <0.9.0;
contract SimpleStorage {
uint storedData; // State variable
// ...
}
函数
代码语言:javascript复制/ 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;
}
函数修饰器
代码语言:javascript复制// 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
// ...
}
}
事件
代码语言:javascript复制// 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;
// ...
}
}
结构
代码语言:javascript复制pragma solidity >=0.4.0 <0.9.0;
contract Ballot {
struct Voter { // 结构体
uint weight;
bool voted;
address delegate;
uint vote;
}
}
枚举
代码语言:javascript复制// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.25 <0.9.0;
contract Purchase {
enum State { Created, Locked } // Enum
}