Solidity By Example006~010

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值