solidity学习笔记

编辑器

https://remix.ethereum.org/

view 与 prue

pragma solidity ^0.8.4;
contract Day1{
    string private str="web03";
    function getStr() public view returns(string memory){
        return str;
    }
    function setStr(string memory newStr) public {
        str = newStr;
    }
    function prueTest(string memory str_) public view returns(string memory){
        return str_;
    }
}

bool

pragma solidity ^0.8.4;

contract Day2{
    bool isTrue = false;
    string _str = "yes";
    function getBool() public view returns(bool){
        return isTrue;
    }
    function setBool() public {
        isTrue = !isTrue;
    }
    // 校验字符串是否相等
    function checkBool(string memory str) public view returns(bool) {
        return keccak256(abi.encodePacked(_str)) == keccak256(abi.encodePacked(str));
    }
}

整型 int uint

pragma solidity ^0.8.0;


contract Day3{
    // int num1 = 100;//init256
    // uint num2 = 100;//unit256
    function add(uint num1, uint num2) public view returns(uint sum){
        return num1 + num2;
    }
    function test1() public view returns(uint){
        uint8 n = 255;
        return n + 1;//0 ,十进制255=二进制11111111,加1等于100000000,uint8截取了后8位00000000,所以结果=0
        // 在solidity 0.8版本返回,高版本报错
    }
     function test2() public view returns(uint){
        uint8 n = 0;
        return n - 1;//255,十进制0=二进制00000000的补码=11111111转为二进制为255
        // 在solidity 0.8版本以下返回,高版本报错
    }
    function test3() public view returns(int){
        int n = 9;
        return n/2;//4 自动舍去小数部分,solidity不支持小数计算
    }
    function test4() public view returns(int){
        int n = 10;
        return n/3;//3 自动舍去小数部分,solidity不支持小数计算
    }
}

Solidity 中整型分为有符号 int和无符号uint

从8位开始到256位,每次步长8位
也就是

uint8,uit16,uint24 ... uint256
int8,int16,int24... int256
取值范围
uintX取值范围是 0 - 2^X-1
如uint8取值范围是0 - 2^8-1 = 0到255

固定长度字节数组

pragma solidity ^0.4.0;

contract Day4{
    // 在contract直属内部声明public的变量,系统回自动生成get方法供外部调用取值
    // 一个butes 占 8位,一个字节占2位,声明的bytes是几位就固定为几位
    bytes1 public b1 = 0x1a;
    bytes2 public b2 = 0x1a32;
    // 声明动态数组,有push方法
    bytes public b3 = new bytes(3);//默认 0x000000

    // 获取bytes长度
    function getLength() public view returns(uint){
        // 声明的几位获取的就是几位,且长度不能修改
        // b1.length//1
        return b2.length;//2
    }
    // 如果returns 带上一个变量,那么里面不写retuen也会返回该变量的值
    function setb1(bytes1 b1_) public view returns(bytes1 b1){
        b1 = b1_; 
    }

    // 以下只有低版本solidity支持,高版本不支持,不推荐这样使用

    // 修改b3的值,会消耗gas
    function InitB3(){
        b3.push(0x12);
        b3[0] = 0x11;//0x11000012
    }
    // 设置b3的长度
    function setB3(){
        b3.length = 1;
    }

}

字符串

声明字符串

pragma solidity ^0.6.0;

contract Test {
   string public name = "web03";
   string public url = 'web03.cn';
}

字符串内置转换

pragma solidity ^0.6.0;

contract Test {
	// 可以是双引号 
   bytes public name = "web03";
   // 也可以是单引号
   string url = 'web03.cn';
   
   function nameTostring() public view returns(string memory){
       string memory str = string(name);
       return str;
   }
}

转义字符

\n 开始新的一行
\\ 反斜杠
\’ 单引号
\” 双引号
\b 退格
\f 换页
\r 回车
\t 制表符
\v 垂直制表符
\xNN 表示十六进制值并插入适当的字节。
\uNNNN 表示Unicode值并插入UTF-8序列。

数组

声明数组

uint balance[10];

初始化数组

uint balance[3] = [1, 2, 3];
uint balance[] = [1, 2, 3];

创建内存数组

pragma solidity ^0.6.0;

contract Test {
    function test(uint len) public {
        uint[] memory arr1 = new uint[](7);
        bytes memory arr2 = new bytes(len);
    }
}

数组属性.length
数组方法.push()

枚举(enum)

pragma solidity ^0.6.0;

contract Test {
    // 顺序 0,1,2,3...
    enum COLOR{RED, GREEN, YELLOW, BLACK}
   COLOR color;//默认 0
   function setColor() public{
       color = COLOR.BLACK;//设置3
   }
   function getColor() public view returns(COLOR){
       return color;//3
   }
}

结构体(struct)

pragma solidity ^0.6.0;

contract Test {
    struct User{
        string name;
        uint id;
        address addr;
    }
    User public user;
   function setUser() public{
       user = User("零三", 3, 0x23FCB0E1DDbC821Bd26D5429BA13B7D5c96C0DE0);
   }
   function getUserName() public view returns(string memory){
       return user.name;
   }
}

映射(mapping)

pragma solidity ^0.6.0;

contract Test {
    mapping(address => uint) public countMap;
    // 每次调用count递增
    function updateCount() public{
        countMap[msg.sender] += 1; 
    }
}

单位

以太单位

assert(1 wei == 1);
assert(1 szabo == 1e12);
assert(1 finney == 1e15);
assert(1 ether == 1e18);
assert(2 ether == 2000 fenny);

时间单位

assert(1 seconds == 1);
assert(1 minutes == 60 seconds);
assert(1 hours == 60 minutes);
assert(1 day == 24 hours);
assert(1 week == 7 days);

全局变量

名称返回值类型描述
blockhash(uint blockNumber)bytes32给定区块的哈希值 – 只适用于256最近区块, 不包含当前区块。
block.coinbaseaddress当前区块矿工的地址
block.difficultyuint当前区块的难度
block.gaslimituint当前区块的gaslimit
block.numberuint当前区块的number
block.timestampuint当前区块的时间戳,单位秒
gasleft()uint256剩余 gas
msg.databytes完成 calldata
msg.senderaddress消息发送者 (当前 caller)
msg.sigbytes4calldata的前四个字节 (function identifier)
msg.valueuint当前消息的wei值
nowuint当前块的时间戳,单位秒
tx.gaspriceuint交易的gas价格
tx.originaddress交易的发送方

函数修饰符(modifier)

修饰符定义中出现特殊符号_的地方,用于插入函数体。如果在调用此函数时,满足了修饰符的条件,则执行该函数,否则将抛出异常。

pragma solidity ^0.6.0;

contract Owner {
   address owner;

   constructor() public {
      owner = msg.sender;
   }

   // 定义修饰符 onlyOwner 不带参数
   modifier onlyOwner {
      require(msg.sender == owner);
      _;
   }

   // 定义修饰符 costs 带参数
   modifier costs(uint price) {
      if (msg.value >= price) {
         _;
      }
   }
}

contract Register is Owner {
   mapping (address => bool) public registeredAddresses;
   uint price;

   // 使用修饰符 onlyOwner
   function changePrice(uint _price) public onlyOwner {
      price = _price;
   }
   // 使用修饰符 costs
   function register() public payable costs(price) {
      registeredAddresses[msg.sender] = true;
   }
}

视图(view)函数

不能修改状态变量。
不能触发事件。
不能创建合约。
不能使用selfdestruct。
不能发送以太。
不能调用任何不是视图函数或纯函数的函数
不能使用底层调用
不能使用包含某些操作码的内联程序集。
函数添加view属性,函数不会修改状态不消耗gas,不上链

pragma solidity ^0.6.0;

contract Test {
    uint num = 1;
    function sum(uint n1,uint n2) public view returns(uint){
        return n1 + n2 + num;
    }
}

纯函数(pure)

不能读取状态变量。
不能访问 address(this).balance 或 address.balance
不能访问任何区块、交易、msg等特殊变量(msg.sig 与 msg.data 允许读取)。
不能调用任何不是纯函数的函数。
不能使用包含特定操作码的内联程序集
纯函数不读取不修改状态,可以理解为只能进行内部数据计算的utils工具函数

pragma solidity ^0.6.0;

contract Test {
    function sum(uint n1,uint n2) public pure returns(uint){
        return n1+n2;
    }
}

重载

与大多数语言一样,solidity也支持函数重载

pragma solidity ^0.6.0;

contract Test {
    function sum(uint n1,uint n2) public pure returns(uint){
        return n1 + n2;
    }
    function sum(uint n1,uint n2, uint n3) public pure returns(uint){
        return n1 + n2 + n3;
    }
}

构造函数(constructor)

一个合约只能有一个构造函数。
构造函数在创建合约时执行一次,用于初始化合约状态。
在执行构造函数之后,合约最终代码被部署到区块链。合约最终代码包括公共函数和可通过公共函数访问的代码。构造函数代码或仅由构造函数使用的任何内部方法不包括在最终代码中。
构造函数可以是公共的,也可以是内部的。
内部构造函数将合约标记为抽象合约。
如果没有定义构造函数,则使用默认构造函数。

pragma solidity ^0.6.0;

contract Test {
    uint public price;
   constructor() public{
       price = 1;
   }
}

初始化参数

在发布合约的时候需要传入初始参数

pragma solidity ^0.6.0;

contract Test {
    uint public price;
   constructor(uint price_) public{
       price = price_;
   }
}

数学函数

addmod(uint x, uint y, uint k) returns (uint) 计算(x + y) % k,计算中,以任意精度执行加法,且不限于2^256大小。
mulmod(uint x, uint y, uint k) returns (uint) 计算(x * y) % k,计算中,以任意精度执行乘法,且不限于2^256大小。

求余数

pragma solidity ^0.6.0;

contract Test {
    function sum(uint num,uint remainder) public pure returns(uint){
        return addmod(num, 0, remainder);//等同于 num%remainder
		// return mulmod(num, 1, remainder);//等同于 num%remainder
    }
}

加密函数

keccak256(bytes memory) returns (bytes32) 计算输入的Keccak-256散列。
sha256(bytes memory) returns (bytes32) 计算输入的SHA-256散列。
ripemd160(bytes memory) returns (bytes20) 计算输入的RIPEMD-160散列。
ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address) 从椭圆曲线签名中恢复与公钥相关的地址,或在出错时返回零。函数参数对应于签名的ECDSA值: r – 签名的前32字节; s: 签名的第二个32字节; v: 签名的最后一个字节。这个方法返回一个地址。

pragma solidity ^0.6.0;

contract Test {   
   function callKeccak256() public pure returns(bytes32 result){
      return keccak256("web03");//0xa007794497b240cc062e7e7acbcdc9557dce648386ebeb8357a3e7de5c202164
   }  
}

修饰符权限

internal 只能在合约内部调用,合约外部不行
external 只能在合约外部调用,合约内部不行
public 合约内部,合约外部均可以调用
private 不能够被继承,在合约外部不能被调用,但是在合约内部可以被调用
|

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值