Last active
October 27, 2021 09:17
-
-
Save DubovinaDj/643819cbf66f8b346dd607d26b771cfd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.4; | |
import "@openzeppelin/contracts/access/Ownable.sol"; | |
contract Donation is Ownable { | |
address public immutable ADMIN; | |
struct Campaign { // grouped attributes | |
string name; | |
string description; | |
uint duration; | |
uint goal; | |
uint raised; | |
bool completed; | |
} | |
mapping(uint => Campaign) public campaigns; //mapping from uint to Campaign attributes (id to Campaign) | |
uint256 campaignIndex = 0; | |
constructor() { | |
ADMIN = payable(msg.sender); | |
} | |
modifier onlyAdmin { | |
require(msg.sender == ADMIN, "Only admin can call this function"); | |
_; | |
} | |
// Create campaign (only Admin can create campaigns) | |
function createCampaign( | |
string memory _name, string memory _description, | |
uint _duration, uint _goal | |
) public onlyAdmin { | |
bool completed = false; | |
uint raised = 0; | |
campaignIndex += 1; //index start from 1 | |
campaigns[campaignIndex] = Campaign(_name, _description, _duration + block.timestamp, _goal, raised, completed); | |
} | |
//Function for donation | |
function donate(uint _index) public payable { | |
require (block.timestamp < campaigns[_index].duration, "Campaign Failed!"); | |
require(campaigns[_index].raised < campaigns[_index].goal,"Goal achieved"); | |
campaigns[_index].raised += msg.value; | |
if (campaigns[_index].raised + msg.value > campaigns[_index].goal) { | |
uint _amount = campaigns[_index].raised - campaigns[_index].goal; | |
campaigns[_index].raised -= _amount; | |
campaigns[_index].completed = true; | |
payable(msg.sender).call{value: _amount}; | |
} else if (campaigns[_index].raised == campaigns[_index].goal) campaigns[_index].completed = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment