智能合约技术
以太坊采用了Solidity作为智能合约语言,Solidity 是一门为实现智能合约而创建的高级编程语言,能在允许以太坊程序的节点上运行。该语言吸收了C++、JavaScript的一些特性,例如它是静态类型语言,支持继承、库等。
二. solidity开发讲解
简单的示例:
// 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
}