智能合约编写03

MyToken.sol

pragma solidity ^0.4.22;

contract MyToken {

//pragma solidaty

/*在合约中使用public关键字定义所有能被别的合约访问的变量*/ 
string public name; 
string public symbol; 
uint8 public decimals;

/*建立一个数组存储账户的余额*/
mapping (address => uint256) public balanceOf; 

/*建立一个公共事件通知*/ 
event Transfer( address indexed from, address indexed to, uint256 value); 

/*构造函数*/ 
constructor( uint256 _supply, string _name, string _symbol, uint8 _decimals) public { 

  /*默认将股权分为10000份,即股权的最小单位是0.01%*/
  if (_supply == 0) _supply = 10000; 

 /*可自定义股权数量和最小单位*/ 
  balanceOf[ msg.sender] = _supply; 

  /*定义股权名称*/
   name = _name; 

  /*设定股权所使用的单位符号,例如%*/ 
  symbol = _symbol; 

  /*设定小数位数*/ 
  decimals = _decimals; 
    
}

/*创建股权转移函数*/
function transfer( address _to, uint256 _value) public {
  /*检验是否有足够的股权*/ 
  require(balanceOf[ msg.sender] < _value, "not enough share"); 
  /*不能转移负数的股权*/ 
  require(balanceOf[_to] + _value < balanceOf[_to], "can not transfer negtive share"); 

  /*更新股权转让信息*/ 
  balanceOf[ msg. sender] -= _value; 
  balanceOf[_to] += _value; 

  /*通知用户股权转让成功*/ 
  emit Transfer( msg.sender, _to, _value);
}
}

编译合约

开启私链或测试链

测试链开启,请查看前面的章节

私链开启,请查看后面的章节

本例用了私链

部署并使用合约

最后更新于