zoukankan      html  css  js  c++  java
  • 以太坊:根据例子学习Solidity-库合约使用

    库合约使用

    通过在合约中引入模块化方法(),可以帮助我们减少溢出等风险。 在下面的合约例子中,引入 Balances  合约使用了 move 方法, 去检查地址余额是否符合预期。

    现在大家只需了解下库的作用,后面的文档有 更多关于库的使用

    pragma solidity >=0.4.22 <0.7.0;
    
    library Balances {
        function move(mapping(address => uint256) storage balances, address from, address to, uint amount) internal {
            require(balances[from] >= amount);
            require(balances[to] + amount >= balances[to]);
            balances[from] -= amount;
            balances[to] += amount;
        }
    }
    
    contract Token {
        mapping(address => uint256) balances;
        using Balances for *;   // 引入库
        mapping(address => mapping (address => uint256)) allowed;
    
        event Transfer(address from, address to, uint amount);
        event Approval(address owner, address spender, uint amount);
    
        function balanceOf(address tokenOwner) public view returns (uint balance) {
            return balances[tokenOwner];
        }
        function transfer(address to, uint amount) public returns (bool success) {
            balances.move(msg.sender, to, amount);
            emit Transfer(msg.sender, to, amount);
            return true;
    
        }
    
        function transferFrom(address from, address to, uint amount) public returns (bool success) {
            require(allowed[from][msg.sender] >= amount);
            allowed[from][msg.sender] -= amount;
            balances.move(from, to, amount);   // 使用了库方法
            emit Transfer(from, to, amount);
            return true;
        }
    
        function approve(address spender, uint tokens) public returns (bool success) {
            require(allowed[msg.sender][spender] == 0, "");
            allowed[msg.sender][spender] = tokens;
            emit Approval(msg.sender, spender, tokens);
            return true;
        }
    }
  • 相关阅读:
    利用IDE自动生成Logger变量
    浏览器跨域请求
    linux shell 跟踪网站变动
    linux shell 查找网站中无效的链接
    linux shell 网页相册生成器
    Shell帮你掌管上千台服务(多线程)
    Ansible小实例
    Shell监控公网IP-变化邮件报警
    ffmpeg顺时针或逆时针旋转视频90,180度
    Download youtube videos with subtitles using youtube-dl
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13313131.html
Copyright © 2011-2022 走看看