用solidity写一个众筹系统要求众筹得到的钱可以被追踪
时间: 2023-11-26 12:06:07 浏览: 63
好的,以下是一个简单的用Solidity编写的众筹合约,其中可以追踪众筹得到的钱:
```
pragma solidity ^0.8.0;
contract Crowdfunding {
address public owner;
uint public goal;
uint public raisedAmount;
mapping(address => uint) public contributions;
bool public goalReached;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
constructor(uint _goal) {
owner = msg.sender;
goal = _goal;
}
function contribute() public payable {
require(!goalReached);
contributions[msg.sender] += msg.value;
raisedAmount += msg.value;
emit FundTransfer(msg.sender, msg.value, true);
}
function checkGoalReached() public {
require(msg.sender == owner);
if (raisedAmount >= goal) {
goalReached = true;
emit GoalReached(owner, raisedAmount);
}
}
function withdraw() public {
require(goalReached);
require(msg.sender == owner);
uint amount = address(this).balance;
(bool success,) = owner.call{value: amount}("");
require(success, "Transfer failed.");
emit FundTransfer(owner, amount, false);
}
}
```
在这个合约中,有一个`raisedAmount`变量用于记录众筹得到的总金额,`contributions`映射用于记录每个人的贡献。当众筹成功达成目标时,可以通过`checkGoalReached`函数发出`GoalReached`事件,通知所有人。此时,只有合约的创建者可以通过`withdraw`函数取回筹款。