此範例為群眾募資的合約設計,發起人可以設定目標集資金額、募資時間,發起合約時,投資人可以觸發投資function,將投資金額放進合約中,直到發起人意識到募資時間已經結束,觸發核定目標function,並針對募資狀況,發送募資成功訊息到blockchain,並將總募資金額傳給發起人;如果募資失敗,觸發失敗event,並將投資金額還給投資人。
pragma solidity^0.4.25;
contract CrowFunding{
address public Host;
uint256 public TotalInvestor;
uint256 public TargetAmount;
uint256 public CurrentAmount;
uint256 public deadline;
bool public ended;
mapping (uint256 => Investor) public investors;
event Fund(address indexed _investor,uint256 _investAmount);
event Fail(uint256 _numOfInvestor,uint256 _totaltAmount);
event Success(uint256 _deadline,uint256 _numOfInvestor,uint256 _totalAmount);
struct Investor{
address addr;
uint256 amount;
}
modifier onlyOwner(){
require(msg.sender == Host,"You are not Host");
_;
}
//輸入募資時間和目標金額
constructor(uint256 _targetAmount, uint256 _duration) public{
TargetAmount = _targetAmount;
deadline = now + _duration;
}
function fund() public payable{
require(!ended,"Funding been ended");
TotalInvestor++;
CurrentAmount += msg.value;
investors[TotalInvestor] = Investor(msg.sender,msg.value);
emit Fund(msg.sender,msg.value);
}
//檢查募資進度
function checkGoal() public onlyOwner{
require(!ended,"Funding been ended");
require(now >= deadline);
if(CurrentAmount >= TargetAmount){
Host.transfer(address(this).balance);
ended = true;
emit Success(deadline,TotalInvestor,CurrentAmount);
}else{
ended = true;
emit Fail(TotalInvestor,CurrentAmount);
for(uint i = 0; i <= TotalInvestor ; i++){
investors[i].addr.transfer(investors[i].amount);
}
}
}
}
(待補)