机器环境
- 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
编写智能合约
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;
mapping (address => string) titleOf;
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 = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*"
}
}
};
启动ganache-cli
迁移合约
启动前端
npm install && npm run dev
- 导入ganache-cli生成的key
- 设置网络为localhost:8545