A naive Solidity contract that manages funds for a project
pragma solidity >=0.5.0 <0.6.0; | |
// 10000000000000000000 // 10 Ethers | |
contract Project { | |
// The address who deployed the contract | |
address private owner; | |
// The cap to achieved to fund the project | |
uint public cap; | |
// The total funded. | |
uint private total; | |
// Record of how much each shareholder funded | |
mapping(address => uint) public funds; | |
// List of all the shareholder addresses | |
address payable[] public shareholders; | |
// On deploy, set a cap and the owner of the contract | |
constructor(uint _cap) public { | |
cap = _cap; | |
owner = msg.sender; | |
} | |
/// Add fund to the contract | |
function addFund() public payable { | |
// Cap should not have been reached yet | |
require(total < cap, "Cap already achieved you cannot fund the project anymore"); | |
// Fund should not be 0 | |
require(msg.value != uint(0), "You should provide some funds"); | |
// You should not give more than the cap | |
require(total + msg.value <= cap, "You cannot give more than the cap"); | |
// If shareholder is not yet register, add it to the list | |
if (funds[msg.sender] == uint(0)) { | |
shareholders.push(msg.sender); | |
} | |
// Keep record of the fund given by this shareholder | |
funds[msg.sender] = funds[msg.sender] + msg.value; | |
// Increment the total given | |
total = total + msg.value; | |
} | |
/// Add an income to be shared amongst the shareholders | |
function addIncome() public payable { | |
// Cap should have been reached | |
require(cap == total, "Cannot add income if the project is not funded"); | |
// Income should not be 0 | |
require(msg.value != uint(0), "You should provide some income"); | |
// Iterate over each shareholder | |
for (uint i = 0; i < shareholders.length; i++) { | |
address payable shareholder = shareholders[i]; | |
// IMPORTANT : as there is no double on Ethereum you MUST multiply BEFORE divide | |
// eg: | |
// DO 60 * 120 / 100 = 7200 / 100 = 72 | |
// DON'T 60 / 100 * 120 = 0 * 120 = 120 | |
uint share = msg.value * funds[shareholder] / cap; | |
// Transfer the share on this income to the shareholder | |
shareholder.transfer(share); | |
} | |
} | |
/// Retrieve the total | |
function retrieve() public { | |
// Only the owner can retrieve the total | |
require(msg.sender == owner); | |
// The cap should have been reached | |
require(cap == total, "Cannot retrieve funds if the project is not funded"); | |
// Transfer the funds to the owner | |
msg.sender.transfer(total); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment