iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 27
1
影片教學

Smart Contract 實戰教學系列 第 27

Example - 挖礦合資

  • 分享至 

  • xImage
  •  

講了那麼多天的 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


上一篇
ERC20 Pausable
下一篇
Example - ERC20 Token Exchange
系列文
Smart Contract 實戰教學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言