講了那麼多天的 ERC20 ,相信大家都膩了XD那我們就換個口味,來舉個切身的例子作為 smart contract 的範例吧!
這個範例原本是我的朋友 polarjack 所撰寫的,本次拿來改成範例。
本日合約:
pragma solidity ^0.4.25;
import "browser/SafeMath.sol";
contract MiningShare {
using SafeMath for uint;
// 召集人
address private owner = 0x0;
// 召集人設定募資時間
uint private closeBlock = 0;
// 投資者:
// 1. 投資金額
mapping(address => uint) private usersNTD;
// 2. 提領金額
mapping(address => uint) private usersWithdraw;
// 記錄參數:
// 1. 總投資金額
uint private totalNTD = 0;
// 2. 總提領金額
uint private totalWithdraw = 0;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyShareHolders() {
require(usersNTD[msg.sender] != 0);
_;
}
// 在募資結束之前
modifier beforeCloseBlock() {
require(block.number <= closeBlock);
_;
}
modifier afterCloseBlock() {
require(block.number > closeBlock);
_;
}
// 召集人功能
constructor() public {
owner = msg.sender;
closeBlock = block.number+2000;
}
function CapitalIncrease(address account, uint NTD) public onlyOwner beforeCloseBlock {
usersNTD[account] = usersNTD[account].add(NTD);
totalNTD = totalNTD.add(NTD);
}
function CapitalDecrease(address account, uint NTD) public onlyOwner beforeCloseBlock {
usersNTD[account] = usersNTD[account].sub(NTD);
totalNTD = totalNTD.sub(NTD);
}
function MyTotalNTD() public constant onlyShareHolders returns (uint) {
return usersNTD[msg.sender];
}
function MyTotalWithdraw() public constant onlyShareHolders afterCloseBlock returns (uint) {
return usersWithdraw[msg.sender];
}
function TotalMined() public constant onlyShareHolders afterCloseBlock returns (uint) {
return totalWithdraw.add(address(this).balance);
}
function Withdraw() public onlyShareHolders afterCloseBlock {
uint totalMined = totalWithdraw.add(address(this).balance);
// totalMined * hisNTD / totalNTD - userWithdraw;
uint userCanWithdraw = totalMined.mul(
usersNTD[msg.sender].div(totalNTD)).sub(
usersWithdraw[msg.sender]);
usersWithdraw[msg.sender].add(userCanWithdraw);
totalWithdraw.add(userCanWithdraw);
msg.sender.transfer(userCanWithdraw);
}
}
本日影片:
https://youtu.be/XjarXxdpDpQ
Smart Contract 實戰教學播放清單:
https://www.youtube.com/playlist?list=PLHmOMPRfmOxSJcrlwyandWYiuP9ZAMYoF