【區塊鏈】以太坊DApp開發

機器環境

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

Github地址


效果


初始化專案

  • 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 <http://truffleframework.com/docs/advanced/configuration>
// 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