存储合约示例
浏览 196 | 评论 0 | 字数 1504
硝基苯
2023年06月02日
  • 存储示例

    该实例做了一个简单的存储,但是新的存储会覆盖之前的存储
    注意:view 是 Solidity 中的关键字,用于标识一个函数不会修改合约的状态,只读取合约的数据并返回结果。因此,调用一个 view 函数不会在区块链上创建交易,也不会消耗 Gas 费用。

    // SPDX-License-Identifier: GPL-3.0
    pragma solidity >=0.4.16 <0.9.0;
    //允许0.4.16到0.9.0版本的solidity编辑器编译
    
    contract SimpleStorage {
    //contract定义了一个合约
    
        uint storedData;
    //定义了一个256位无符号的整形变量storedData
    
        function set(uint x) public {
    //定义了set方法可以用于存储用户所传入的storedData
            storedData = x;
        }
    
        function get() public view returns (uint) {
            return storedData;
    //读取storedData
    //要访问当前合约的一个成员(如状态变量),通常不需要添加 this. 前缀, 只需要通过它的名字直接访问它
        }
    }
    

    铸币示例

    
    pragma solidity ^0.4.21;
    contract Coin {
        // 关键字“public”让这些变量可以从外部读取
        address public minter;//定义了一个address类型的minter
        mapping (address => uint) public balances;//定义了一个哈希表类型的balance,通过address进行查询的哈希表
        // 轻客户端可以通过事件针对变化作出高效的反应
        event Sent(address from, address to, uint amount);//声明了一个Sent的事件
        // 这是构造函数,只有当合约创建时运行
        function Coin()  {
            minter = msg.sender;//发送者地址给到minter
        }
           //用于铸币,创建者可以给任意用户发币
        function mint(address receiver, uint amount) public {
            if (msg.sender != minter) return;
            balances[receiver] += amount;
        }
           //相互之间的转账
        function send(address receiver, uint amount) public {
            if (balances[msg.sender] < amount) return;
            balances[msg.sender] -= amount;
            balances[receiver] += amount;
            emit Sent(msg.sender, receiver, amount);
        }
    }
    本文作者:硝基苯
    本文链接:https://www.c6sec.com/index.php/archives/836/
    最后修改时间:2023-06-02 17:06:42
    本站未注明转载的文章均为原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!
    评论已关闭
    评论列表
    暂无评论