【区块链】以太坊DApp开发

机器环境

  • win10
  • nodev8.9.4
  • npm install -g truffle
  • npm install -g ganache-cli

Github地址

  • https://github.com/ns2250225/eth-one-words

效果

【区块链】以太坊DApp开发_第1张图片

初始化项目

  • mkdir eth-one-words
  • cd eth-one-words
  • truffle init
  • npm init

编写智能合约

  • contracts/BlogSystem.sol
pragma solidity ^0.4.4;

contract BlogSystem {

    // 每次点赞的奖励
    uint256 public readPrice = 0.001 ether;

    // 每次发布句子的价格
    uint256 public publishPrice = 0.001 ether;

    // 合约拥有者的地址
    address owner;

    // 发布句子事件
    event PublishArticle(address sender, string title);

    // 点赞句子事件
    event ReadArticle(address sender);

    // 存放每个作者的奖励,用于提现
    mapping (address => uint) pendingWithdrawals;

    // 存放address到title的映射
    mapping (address => string) titleOf;

    // 存放title到address的映射
    mapping (string => address) authorAddress;


    // 函数装饰器--合约拥有者权限
    modifier onlyOwner() {
        require(owner == msg.sender);
        _;
    }

    // 合约构造函数
    function BlogSystem() {
        owner = msg.sender;
    }

    // 发布句子函数
    function Publish(string _title) payable {
        require(msg.value >= publishPrice);

        // 存放句子与作者地址的映射
        authorAddress[_title] = msg.sender;
        titleOf[msg.sender] = _title;

        // 触发发布句子事件
        PublishArticle(msg.sender, _title);
    }

    // 点赞句子函数
    function Read(string _title) payable {
        require(msg.value >= readPrice);

        // 金句作者获得奖励
        address _author = authorAddress[_title];
        pendingWithdrawals[_author] += readPrice;

        // 触发句子点赞事件
        ReadArticle(msg.sender);
    }


    // 查看合约余额
    function contractBalance() constant returns(uint) {
        return this.balance;
    }


    // 提现奖励
    function withdraw() payable {
        uint amount = pendingWithdrawals[msg.sender];
        pendingWithdrawals[msg.sender] = 0;
        msg.sender.transfer(amount);
    }

    // 查看作者累计奖励
    function balanceOf(address user) constant returns(uint) {
        return pendingWithdrawals[user];
    }

    // 设置发布金句价格
    function setPublishPrice(uint _publishPrice) onlyOwner {
        publishPrice = _publishPrice;
    }

    // 设置点赞金句奖励
    function setReadPrice(uint _readPrice) onlyOwner {
        readPrice = _readPrice;
    }

}

编写迁移脚本

  • migrations/2_deploy_contracts.js
var BlogSystem = artifacts.require('./BlogSystem');

module.exports = (deployer) => {
    deployer.deploy(BlogSystem);
}

配置truffle.js文件

module.exports = {
  // See 
  // to customize your Truffle configuration!
  networks: {  
    development: {  
      host: "localhost",  
      port: 8545,  
      network_id: "*"  
    }  
  }  
};

启动ganache-cli

  • ganache-cli

迁移合约

  • truffle migrate

启动前端

  • npm install && npm run dev

设置MetaMask

  • 导入ganache-cli生成的key
  • 设置网络为localhost:8545

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