Skip to content

Instantly share code, notes, and snippets.

@lyhistory
Created January 30, 2019 06:46
Show Gist options
  • Save lyhistory/b163f41299b87bb363e2cceba6004666 to your computer and use it in GitHub Desktop.
Save lyhistory/b163f41299b87bb363e2cceba6004666 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.5.1+commit.c8a2cb62.js&optimize=false&gist=
pragma solidity >=0.4.11 <0.6.0;
contract CrowFunding {
// Defines a new type with two fields
struct Funder {
address addr;
uint amount;
}
struct Campaign {
address payable beneficiary;
uint fundingGoal;
uint numFunders;
uint amount;
mapping(uint=>Funder) funders;
}
uint numCampaigns;
mapping(uint=>Campaign) campaigns;
function newCampaign(address payable beneficiary, uint goal) public returns(uint campaignID){
campaignID = numCampaigns++; // campaignID is return variable
// Creates new struct in memory and copies it to storage.
// We leave out the mapping type, because it is not valid in memory.
// If structs are copied (even from storage to storage), mapping types
// are always omitted, because they cannot be enumerated.
campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0);
}
function contribute(uint campaignID) public payable{
//Note how in all the functions, a struct type is assigned to a local variable with data location storage. This does not
//copy the struct but only stores a reference so that assignments to members of the local variable actually write to the state
Campaign storage c = campaigns[campaignID];
// Creates a new temporary memory struct, initialised with the given values
// and copies it over to storage.
// Note that you can also use Funder(msg.sender, msg.value) to initialise.
c.funders[c.numFunders++] = Funder({addr:msg.sender, amount:msg.value});
c.amount += msg.value;
}
function checkGoalReached(uint campaignID) public returns(bool reached){
Campaign storage c = campaigns[campaignID];
if(c.amount < c.fundingGoal)
return false;
uint amount = c.amount;
c.amount = 0;
c.beneficiary.transfer(amount);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment