如何寫個眾籌合約

电报nft119發表於2024-02-21

編寫眾籌合約涉及使用 Solidity 語言來定義智慧合約。以下是一個簡單的眾籌合約示例,基於以太坊的 ERC-20 代幣標準。請注意,這只是一個基礎示例,實際應用中可能需要更多的安全性和功能。


```solidity

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;


import "@openzeppelin/contracts/token/ERC20/IERC20.sol";


contract Crowdfunding {

address public owner;

IERC20 public token; // 使用的代幣合約地址

uint256 public goal; // 眾籌目標

uint256 public deadline; // 截止日期

uint256 public raisedAmount; // 已籌集金額

mapping(address => uint256) public contributions; // 參與者的貢獻記錄

bool public fundingGoalReached = false; // 眾籌目標是否達成

bool public crowdsaleClosed = false; // 眾籌是否關閉


event Contribution(address indexed contributor, uint256 amount);

event FundingGoalReached(uint256 amountRaised);

event CrowdsaleClosed();


modifier onlyOwner() {

require(msg.sender == owner, "Only the owner can call this function");

_;

}


modifier notClosed() {

require(!crowdsaleClosed, "Crowdsale is closed");

_;

}


modifier afterDeadline() {

require(block.timestamp >= deadline, "Crowdsale deadline has not passed");

_;

}


constructor(

address _token,

uint256 _goal,

uint256 _durationInMinutes

) {

owner = msg.sender;

token = IERC20(_token);

goal = _goal;

deadline = block.timestamp + _durationInMinutes * 1 minutes;

}


function contribute(uint256 _amount) external notClosed {

require(block.timestamp < deadline, "Crowdsale has ended");

require(raisedAmount + _amount <= goal, "Contribution exceeds the goal");


token.transferFrom(msg.sender, address(this), _amount);

contributions[msg.sender] += _amount;

raisedAmount += _amount;


emit Contribution(msg.sender, _amount);


if (raisedAmount >= goal) {

fundingGoalReached = true;

emit FundingGoalReached(raisedAmount);

}

}


function withdraw() external afterDeadline {

require(fundingGoalReached, "Funding goal not reached");

uint256 amount = contributions[msg.sender];

contributions[msg.sender] = 0;

token.transfer(msg.sender, amount);

}


function closeCrowdsale() external onlyOwner {

require(!crowdsaleClosed, "Crowdsale already closed");

crowdsaleClosed = true;

emit CrowdsaleClosed();

}

}

```


上述合約使用了 OpenZeppelin 的 ERC20 合約庫,確保了在代幣互動方面的安全性。在實際使用中,你需要引入相關的庫檔案,可以透過 [OpenZeppelin GitHub]() 獲取。


此眾籌合約支援以下功能:


1. 設定眾籌目標、截止日期和代幣。

2. 參與者可以透過 `contribute` 函式貢獻代幣。

3. 在達到眾籌目標後,參與者可以透過 `withdraw` 函式提取代幣。

4. 合約擁有者可以透過 `closeCrowdsale` 函式關閉眾籌。


請確保在實際使用前仔細測試和審查合約,以確保其符合專案需求並且安全可靠。



來自 “ ITPUB部落格 ” ,連結:https://blog.itpub.net/70035240/viewspace-3006971/,如需轉載,請註明出處,否則將追究法律責任。

相關文章