在众筹项目中,对出资金额进行排序
pragma solidity ^0.6.0;
contract Financing {
// 出资人
struct Donor {
uint amount;//融资金额
address addr;//地址
uint time;//融资时间
}
// 融资发起人
struct Sponsor {
uint amount; // 当前已融资金额
uint max_amount;//需要融资金额
string name;//名称
address addr;//地址
uint start_time;//发起时间
uint end_time;//结束时间
uint financing_num;//融资地址数
mapping(uint => Donor) map;//融资人
}
// 发起人自增id
uint public sponsorId;
// 发起人信息
mapping(uint => Sponsor) public sponsorMap;
// 已完成的融资
mapping(uint => bool) public finishMap;
//管理员
address admin;
// 扣点 5%
uint public deduction = 20;
// 净收入
uint public profit = 0;
constructor(address admin_) public {
admin = admin_;
}
// 提取净收入
function extractProfit_() public {
admin.call{value : profit}('');
}
// 发起融资项目
function createFinancing(uint amount_, string memory name_, uint end) public {
// 最少融资时常1天
if (end - now < 86400) {
end = now + 86400;
}
sponsorId ++;
sponsorMap[sponsorId] = Sponsor(0, amount_, name_, msg.sender, now, end, 0);
}
//uint[] public value;
// 给项目融资
function donate(uint sponsorId_) public payable {
// 判断是否结束
require(!isEnd(sponsorId_), 'Financing completed');
// 判断支付的钱是否小于0
require(msg.value > 0, 'donate amount is 0');
// 找出融资的发起人
Sponsor storage sponsor_ = sponsorMap[sponsorId_];
// 判断有没有发起时间,没有的话表示没有这个项目
require(sponsor_.addr != address(0), 'notfund fundraising');
sponsor_.financing_num ++;
sponsor_.amount += msg.value;
//value.push(msg.value);
// 设置当前的融资信息,key为当前融资的个数
sponsor_.map[sponsor_.financing_num] = Donor(msg.value, msg.sender, now);
}
/*function paixu() public {
uint len=value.length;
for(uint i=0;i<len;i++){
for(uint j=0;j<len-1-i;j++){
if(value[j]>value[j+1]){
uint temp=value[j+1];
value[j+1]=value[j];
value[j]=temp;
}
}
}
}*/
// 定义事件
event TakeOut(string name, address addr, uint start_time, uint end_time, uint financing_num, uint amount);
// 结束并取出
function endAndTakeOut(uint sponsorId_) public {
require(!finishMap[sponsorId_], 'the financing is end');
Sponsor storage sponsor_ = sponsorMap[sponsorId_];
// 判断当前id是不是你的
require(msg.sender == sponsor_.addr, 'Illegal withdrawal');
// 结束当前项目
finishMap[sponsorId_] = true;
// 取出前扣点扣点
uint lixi = sponsor_.amount*deduction/100;
// 已融资金额大于0,转给发起融资地址
if (sponsor_.amount > 0) {
// 收取扣点
profit = sponsor_.amount-lixi;
// 发给募资发起人
sponsor_.addr.call{value : lixi}('');
}
// 执行成功发事件
emit TakeOut(sponsor_.name, sponsor_.addr, sponsor_.start_time, sponsor_.end_time, sponsor_.financing_num, lixi);
}
// 判断是否结束
function isEnd(uint sponsorId_) public view returns(bool){
Sponsor storage sponsor_ = sponsorMap[sponsorId_];
return finishMap[sponsorId_] || sponsor_.end_time < now;
}
}