• 使用Mapping实现的以太坊智能合约的代码


    • Step 1: 创建一个基础合约
    pragma solidity ^0.4.7;
    
    contract Coin {
        address public minter;
        mapping (address => uint) public balances;
    }
    

    这里我们定义了一个address 作为key, uint做为value的hashTable balances; 我们还定义了一个address的变量minter;

    • Step 2: 添加一个构造函数Coin()
        function Coin() {
            minter = msg.sender;
        }
    

    这里的代码minter = msg.sender; 代表创建这个合约的账户地址,被赋值给变量minter.

    • Step 3: 添加一个挖矿合约
        function mint(address receiver, uint amount) {
            if (msg.sender != minter) throw;
            balances[receiver] += amount;
        }
      

    这里的核心代码在于,如果调用这个方法的账户,不是minter, 也就是创建合约的账户的话,这个mint()将无法被执行。 只有是创建合约的账户,也就是minter 才可以执行它

    • Step 4: 添加一个function send() 也就是从A转移X代币到B账户。代码如下:
        function send(address receiver, uint amount) {
            if (balances[msg.sender] < amount) return;
            balances[msg.sender] -= amount;
            balances[receiver] += amount;
        }
      

    这个非常简单的转移货币的代码,也就是说msg.sender减少一定代币,接受者receiver增加一定代币

    • Step 5: 定义一个事件 Sent()
        event Sent(address from, address to, uint amount);
      
        function send(address receiver, uint amount) {
            if (balances[msg.sender] < amount) return;
            balances[msg.sender] -= amount;
            balances[receiver] += amount;
            Sent(msg.sender, receiver, amount);
        }
      
    完整代码如下:
    pragma solidity ^0.4.7;
    
    contract Coin {
        address public minter;
        mapping (address => uint) public balances;
    
        event Sent(address from, address to, uint amount);
    
        function Coin() {
            minter = msg.sender;
        }
    
        function mint(address receiver, uint amount) {
            if (msg.sender != minter) throw;
            balances[receiver] += amount;
        }
    
        function send(address receiver, uint amount) {
            if (balances[msg.sender] < amount) return;
            balances[msg.sender] -= amount;
            balances[receiver] += amount;
            Sent(msg.sender, receiver, amount);
        }
    }
  • 相关阅读:
    建造者(Builder)模式
    模板方法模式(Tempalte Method Pattern)
    NIO Socket编程实例
    Java NIO概述
    转:Java中的Clone()方法详解
    调停者(Mediator)模式
    门面(Facade)模式
    struts2中方法拦截器(Interceptor)的中的excludeMethods与includeMethods的理解
    Struts2默认拦截器配置
    struts2的json-default和struts-default的区别
  • 原文地址:https://www.cnblogs.com/ceet/p/8600530.html
Copyright © 2020-2023  润新知