006Immutable
//SPDX-License-Identifier:MIT
pragma solidity ^0.8.13;
contract Immutable{
// immutable修饰的变量可以在声名时不去进行赋值,之后构造器中(constructor)进行赋值,但是赋值后便不能再修改
address public immutable MY_ADDRESS;
uint public immutable MY_UINT;
constructor(uint _myUint){
MY_ADDRESS = msg.sender;
MY_UINT = _myUint;
}
}
007Read&Write2State
//SPDX-License-Identifier:MIT
pragma solidity ^0.8.13;
// 写入和读取变量的方法
// 写入和修改变量是会有花费的
// 但是读取变量是免费的
contract SimpleStorage {
uint public num;
function set(uint _num) public{
num = _num;
}
function get() public view returns(uint){
return num;
}
}
008Ether&Wei
//SPDX-License-Identifier:MIT
pragma solidity ^0.8.13;
contract EtherUnits{
// 1eth = 10**18 wei,wei是以太坊上的最小单位
uint public onewei = 1 wei;
// 1wei == 1
bool public isOneWei = 1 wei == 1;
uint public oneEther = 1 ether;
// 1ether = 10^18
bool public isOneEther = oneEther == 1e18; //1e18 = 10**18
}
009Gas&GasPrice
//SPDX-License-Identifier:MIT
pragma solidity ^0.8.13;
// 一笔交易你需要支付多少ether呢?
// 你将会支付 (gas消耗量)*(gas的单价)
// // 1. gas代表着一种计算单元
// // 2. gas消耗量 是指在一笔交易中所使用的所有的gas的总量
// // 3. gas的单价 是指你愿意为每个gas支付多少Ether
// 拥有更改Gas单价的交易,会更优先的被涵盖到链中
// 不支付gas的交易会被退还
// Gas Limit
// 还有两个关于你能消耗的gas的数量上限
// 1. gas limit:你愿意为订单支付的gas的最大数量,由你定义
// 2. block gas limit:块中能被允许的gas的最大数量,由网络定义
contract Gas{
uint public i = 0;
// 这个死循环最后会消耗所有的gas
// 然后导致交易失败
function forever() public {
while (true) {
i += 1;
}
}
}
010IfElse
//SPDX-License-Identifier:MIT
pragma solidity ^0.8.13;
contract ifelse{
function foo(uint myuint) public pure returns(uint){
if(myuint < 10){
return 1;
}else if(myuint == 10){
return 0;
}else{
return 2;
}
}
function ternary(uint _myuint) public pure returns(uint){
return _myuint == 10?1:0;
}
}