solidity 合约文件结构
合约文件:
- 版本申明
- 合约主体:
- 状态变量
- 函数
- 结构类型
- 事件
- 函数修改器
- 代码注释
例子:
pragma solidity ^0.4.0;
import "";
contract Test {
//状态变量
uint a;
function setA(uint x) public {
a = x;
// 调用事件
emit Set_A(x)
}
// 定义事件
event Set_A(uint a);
// 定义结构类型
struct Pos {
int lat;
int lng;
}
//函数修改器
modifier owner () {
}
}
整型 —int/uint
int 是有符号的整型,而uint是无符号的整型 uint8 表示无符号的8位整型。
整型的运算符:
- 比较运算符: <= , < , == , != ,>= , >
- 位运算:& , | ,^(异或) , ~(位取反)
- 算数运算: + , - , 一元运算 ,…(其中 ** 表示取幂,>> 表示又移两位)
pragma solidity ^0.4.0;
contract Test {
uint a;
uint256 b = 20;
uint256 c = 30;
function testadd() public returns (int) {
if(b>c){
return b + c
} else if(b == c){
return b * c
} else {
return b >> 2;
//结果是5 b>> 2 表示 20 / 2^2
}
}
}
常量 contant
- 有理数和整形常量
- 字符串常量
- 十六进制常量
- 地址常量
uint是指只支持固定的位数的变量,而constant 是支持任意精度的,所以有时候会运用到常量
并且常量的运算是不会有溢出的
pragma solidity ^0.4.0;
contract Test {
function testLiterals() public constant returns (uint){
return 1; // 这个 1 就是一个常量
// return 1 + 1;
// return 1.0 + 1e10; 有理数的常量
}
function testStringLiterals() public constant returns(string){
return "abc"; //字符串常量会被转换成一个字节数组或者是字符串数组
}
function testHexLiterals() public constant returns(bytes2,bytes1,bytes1){
// 十六进制常量返回的是一个字节数组,十六进制常量是以hex开头的
bytes2 a = hex"abcd";
return (a,a[0],a[1]); // "0xabcd","0xab","0xcd"
}
}
contant 表示不会修改状态变量的常量,新版本也可以使用 view
是一种数据类型,比如数字 1 和 1.000 就是常量
字符串常量:就是字符串
地址类型
表示一个账户的地址(20字节)
地址类型成员包括: 获取账户余额:`balance` ,转移账户余额:` transfer(金额数目)`
pragma solidity ^0.4.16;
contract AddrTest {
//当表示一个方法可以接受以太币时需要在函数声明的时候加上 payable
function deposit() public payable {
}
function getBalance() public constant returns (uint) {
return this.balance;
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7Xr2b3Ie-1572335194921)(.\img\1.png)]
实现转账功能
pragma solidity ^0.4.16;
contract AddrTest {
//当表示一个方法可以接受以太币时需要在函数声明的时候加上 payable
function deposit() public payable {
}
function getBalance() public constant returns (uint) {
return this.balance;
}
function transferEther(address towho) public {
//10 表示转10个单位的币种
towho.transfer(10)
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3lbMlMlh-1572335194922)(.\img\2.png)]
再来看一段代码:
pragma solidity ^0.4.4;
contract Test {
address public _owner;
uint public _number;
function Test() {
_owner = this;
_number = 100;
}
function msgSenderAddress() constant returns (address) {
return msg.sender;
}
function setNumberAdd1() {
_number = _number + 5;
}
function setNumberAdd2() {
if (_owner