【区块链】以太坊智能合约第三方库--OpenZeppelin

简介

OpenZeppelin提供了许多可继承重用的智能合约模块,方便我们构造出更健壮的智能合约


安装

  • npm install --save openzeppelin-solidity

常用的模块

  • token模块:里面已有ERC20,ERC721,ERC827的接口
  • math模块:提供安全的运算方法,防止上溢,下溢
  • ownership模块:提供判断所有者的一些方法,如onlyOwner

示例

  • ERC20代币实现
pragma solidity ^0.4.23;

import "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol";

contract MyToken is StandardToken {

  string public constant name = "MyToken"; // 合约名称
  string public constant symbol = "N25"; // 代币名称
  uint8 public constant decimals = 18; // 代币精确度

  uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(decimals));

  /**
   * @dev 合约所有者拥有所有的代币
   */
  constructor() public {
    totalSupply_ = INITIAL_SUPPLY;
    balances[msg.sender] = INITIAL_SUPPLY;
    emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
  }
}
  • ERC721代币实现
pragma solidity ^0.4.21;

import 'zeppelin-solidity/contracts/token/ERC721/ERC721Token.sol';

contract RoboHashToken is ERC721Token("RoboHashToken", "RHT") {

    mapping(uint256 => string) internal tokenIdToName;
    mapping(string => uint256) internal nameToTokenId;

    function create(string name) public {
        require(nameToTokenId[name] == 0);
        uint256 tokenId = allTokens.length + 1;
        _mint(msg.sender, tokenId);
        tokenIdToName[tokenId] = name;
        nameToTokenId[name] = tokenId;
    }

    function getTokenName(uint256 tokenId) view public returns (string) {
        return tokenIdToName[tokenId];
    }

    function getTokenId(string name) view public returns (uint) {
        return nameToTokenId[name];
    }
}

你可能感兴趣的:(区块链)