contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
finishICO
function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); }
// finish current round
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 7492, 8015 ] }
9,700
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
calcICO
function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } }
// calculate participants in ico round
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 8062, 9555 ] }
9,701
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
valueFromPercent
function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); }
// get value percent
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 9584, 9769 ] }
9,702
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
availableFunds
function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); }
// available funds to withdraw
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 9808, 9941 ] }
9,703
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
participantRoundValue
function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; }
//get ether amount payed by participant in specified round
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 10008, 10273 ] }
9,704
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
participantRoundAmount
function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; }
//get token amount rewarded to participant in specified round
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 10343, 10610 ] }
9,705
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
participantRoundRewarded
function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; }
//is participant rewarded in specified round
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 10663, 10937 ] }
9,706
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
participantRoundCalced
function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; }
//is participant calculated in specified round
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 10992, 11262 ] }
9,707
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
participantRoundChange
function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; }
//get participant's change in specified round
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 11316, 11583 ] }
9,708
ForceSeller
ForceSeller.sol
0x23f9fae90551764955e20c0e9c349a2811a3e0f9
Solidity
ForceSeller
contract ForceSeller is Ownable { using SafeMath for uint; ForceToken public forceToken; uint public currentRound; uint public tokensOnSale;// current tokens amount on sale uint public reservedTokens; uint public reservedFunds; uint public minSalePrice = 1000000000000000; uint public recallPercent = 80; string public information; // info struct Participant { uint index; uint amount; uint value; uint change; bool needReward; bool needCalc; } struct ICO { uint startTime; uint finishTime; uint weiRaised; uint change; uint finalPrice; uint rewardedParticipants; uint calcedParticipants; uint tokensDistributed; uint tokensOnSale; uint reservedTokens; mapping(address => Participant) participants; mapping(uint => address) participantsList; uint totalParticipants; bool active; } mapping(uint => ICO) public ICORounds; // past ICOs event ICOStarted(uint round); event ICOFinished(uint round); event Withdrawal(uint value); event Deposit(address indexed participant, uint value, uint round); event Recall(address indexed participant, uint value, uint round); modifier whenActive(uint _round) { ICO storage ico = ICORounds[_round]; require(ico.active); _; } modifier whenNotActive(uint _round) { ICO storage ico = ICORounds[_round]; require(!ico.active); _; } modifier duringRound(uint _round) { ICO storage ico = ICORounds[_round]; require(now >= ico.startTime && now <= ico.finishTime); _; } function ForceSeller(address _forceTokenAddress) public { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set public information */ function setInformation(string _information) external onlyMasters { information = _information; } /** * @dev set 4TH token address */ function setForceContract(address _forceTokenAddress) external onlyMasters { forceToken = ForceToken(_forceTokenAddress); } /** * @dev set recall percent for participants */ function setRecallPercent(uint _recallPercent) external onlyMasters { recallPercent = _recallPercent; } /** * @dev set minimal token sale price */ function setMinSalePrice(uint _minSalePrice) external onlyMasters { minSalePrice = _minSalePrice; } // start new ico, duration in seconds function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); } function() external payable whenActive(currentRound) duringRound(currentRound) { require(msg.value >= currentPrice()); ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = msg.value; // is it new participant? if (p.index == 0) { p.index = ++ico.totalParticipants; ico.participantsList[ico.totalParticipants] = msg.sender; p.needReward = true; p.needCalc = true; } p.value = p.value.add(value); ico.weiRaised = ico.weiRaised.add(value); reservedFunds = reservedFunds.add(value); emit Deposit(msg.sender, value, currentRound); } // refunds participant if he recall their funds function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); } //get current token price function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; } // allows to participants reward their tokens from the current round function reward() external { rewardRound(currentRound); } // allows to participants reward their tokens from the specified round function rewardRound(uint _round) public whenNotActive(_round) { ICO storage ico = ICORounds[_round]; Participant storage p = ico.participants[msg.sender]; require(p.needReward); p.needReward = false; ico.rewardedParticipants++; if (p.needCalc) { p.needCalc = false; ico.calcedParticipants++; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); } } else { //assuming participant was already calced in calcICO ico.reservedTokens = ico.reservedTokens.sub(p.amount); if (p.change > 0) { reservedFunds = reservedFunds.sub(p.change); } } ico.tokensDistributed = ico.tokensDistributed.add(p.amount); ico.tokensOnSale = ico.tokensOnSale.sub(p.amount); reservedTokens = reservedTokens.sub(p.amount); if (ico.rewardedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } //token transfer require(forceToken.transfer(msg.sender, p.amount)); if (p.change > 0) { //transfer change msg.sender.transfer(p.change); } } // finish current round function finishICO() external whenActive(currentRound) onlyMasters { ICO storage ico = ICORounds[currentRound]; //avoid mistake with date in a far future //require(now > ico.finishTime); ico.finalPrice = currentPrice(); tokensOnSale = 0; ico.active = false; if (ico.totalParticipants == 0) { reservedTokens = reservedTokens.sub(ico.tokensOnSale); ico.tokensOnSale = 0; } emit ICOFinished(currentRound); } // calculate participants in ico round function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; require(ico.totalParticipants > ico.calcedParticipants); require(_toIndex <= ico.totalParticipants); require(_fromIndex > 0 && _fromIndex <= _toIndex); for(uint i = _fromIndex; i <= _toIndex; i++) { address _p = ico.participantsList[i]; Participant storage p = ico.participants[_p]; if (p.needCalc) { p.needCalc = false; p.amount = p.value.div(ico.finalPrice); p.change = p.value % ico.finalPrice; reservedFunds = reservedFunds.sub(p.value); if (p.change > 0) { ico.weiRaised = ico.weiRaised.sub(p.change); ico.change = ico.change.add(p.change); //reserving reservedFunds = reservedFunds.add(p.change); } ico.reservedTokens = ico.reservedTokens.add(p.amount); ico.calcedParticipants++; } } //if last, free all unselled tokens if (ico.calcedParticipants == ico.totalParticipants) { reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens)); ico.tokensOnSale = ico.reservedTokens; } } // get value percent function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(100); return (_amount); } // available funds to withdraw function availableFunds() external view returns (uint amount) { return address(this).balance.sub(reservedFunds); } //get ether amount payed by participant in specified round function participantRoundValue(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.value; } //get token amount rewarded to participant in specified round function participantRoundAmount(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.amount; } //is participant rewarded in specified round function participantRoundRewarded(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needReward; } //is participant calculated in specified round function participantRoundCalced(address _address, uint _round) external view returns (bool) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return !p.needCalc; } //get participant's change in specified round function participantRoundChange(address _address, uint _round) external view returns (uint) { ICO storage ico = ICORounds[_round == 0 ? currentRound : _round]; Participant storage p = ico.participants[_address]; return p.change; } // withdraw available funds from contract function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); } }
withdrawFunds
function withdrawFunds(address _to, uint _value) external onlyMasters { require(address(this).balance.sub(reservedFunds) >= _value); _to.transfer(_value); emit Withdrawal(_value); }
// withdraw available funds from contract
LineComment
v0.4.21+commit.dfe3193c
bzzr://be658cbd39f977f7ee81fcbd380d6ecf5600321c2cc238da44122d1375825b25
{ "func_code_index": [ 11633, 11851 ] }
9,709
SiringClockAuction
SiringClockAuction.sol
0x23bbc7247b4dbdb4487c9b92d998e106883a9efa
Solidity
ERC721
contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); }
totalSupply
function totalSupply() public view returns (uint256 total);
// Required methods
LineComment
v0.4.21+commit.dfe3193c
bzzr://c27a01dea21db6b14606d18a45e0a27f662e6885c07b57ba2974db53595f2c8b
{ "func_code_index": [ 44, 108 ] }
9,710
SiringClockAuction
SiringClockAuction.sol
0x23bbc7247b4dbdb4487c9b92d998e106883a9efa
Solidity
ERC721
contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); }
supportsInterface
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
// Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
LineComment
v0.4.21+commit.dfe3193c
bzzr://c27a01dea21db6b14606d18a45e0a27f662e6885c07b57ba2974db53595f2c8b
{ "func_code_index": [ 1054, 1136 ] }
9,711
SiringClockAuction
SiringClockAuction.sol
0x23bbc7247b4dbdb4487c9b92d998e106883a9efa
Solidity
LogicBase
contract LogicBase is HasNoContracts { /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_NFC = bytes4(0x9f40b779); // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Reference to storage contract StorageBase public storageContract; function LogicBase(address _nftAddress, address _storageAddress) public { // paused by default paused = true; setNFTAddress(_nftAddress); require(_storageAddress != address(0)); storageContract = StorageBase(_storageAddress); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to owner function destroy() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the owner and terminates the contract selfdestruct(owner); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to the new contract function destroyAndSendToStorageOwner() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the new owner of the storage contract and terminates the contract selfdestruct(storageOwner); } // override to make sure everything is initialized before the unpause function unpause() public onlyOwner whenPaused { // can not unpause when the logic contract is not initialzed require(nonFungibleContract != address(0)); require(storageContract != address(0)); // can not unpause when ownership of storage contract is not the current contract require(storageContract.owner() == address(this)); super.unpause(); } function setNFTAddress(address _nftAddress) public onlyOwner { require(_nftAddress != address(0)); ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_NFC)); nonFungibleContract = candidateContract; } // Withdraw balance to the Core Contract function withdrawBalance() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = nftAddress.send(address(this).balance); return res; } function withdrawBalanceFromStorageContract() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = storageContract.withdrawBalance(); return res; } }
destroy
function destroy() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the owner and terminates the contract selfdestruct(owner); }
// Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to owner
LineComment
v0.4.21+commit.dfe3193c
bzzr://c27a01dea21db6b14606d18a45e0a27f662e6885c07b57ba2974db53595f2c8b
{ "func_code_index": [ 970, 1379 ] }
9,712
SiringClockAuction
SiringClockAuction.sol
0x23bbc7247b4dbdb4487c9b92d998e106883a9efa
Solidity
LogicBase
contract LogicBase is HasNoContracts { /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_NFC = bytes4(0x9f40b779); // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Reference to storage contract StorageBase public storageContract; function LogicBase(address _nftAddress, address _storageAddress) public { // paused by default paused = true; setNFTAddress(_nftAddress); require(_storageAddress != address(0)); storageContract = StorageBase(_storageAddress); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to owner function destroy() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the owner and terminates the contract selfdestruct(owner); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to the new contract function destroyAndSendToStorageOwner() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the new owner of the storage contract and terminates the contract selfdestruct(storageOwner); } // override to make sure everything is initialized before the unpause function unpause() public onlyOwner whenPaused { // can not unpause when the logic contract is not initialzed require(nonFungibleContract != address(0)); require(storageContract != address(0)); // can not unpause when ownership of storage contract is not the current contract require(storageContract.owner() == address(this)); super.unpause(); } function setNFTAddress(address _nftAddress) public onlyOwner { require(_nftAddress != address(0)); ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_NFC)); nonFungibleContract = candidateContract; } // Withdraw balance to the Core Contract function withdrawBalance() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = nftAddress.send(address(this).balance); return res; } function withdrawBalanceFromStorageContract() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = storageContract.withdrawBalance(); return res; } }
destroyAndSendToStorageOwner
function destroyAndSendToStorageOwner() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the new owner of the storage contract and terminates the contract selfdestruct(storageOwner); }
// Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to the new contract
LineComment
v0.4.21+commit.dfe3193c
bzzr://c27a01dea21db6b14606d18a45e0a27f662e6885c07b57ba2974db53595f2c8b
{ "func_code_index": [ 1616, 2081 ] }
9,713
SiringClockAuction
SiringClockAuction.sol
0x23bbc7247b4dbdb4487c9b92d998e106883a9efa
Solidity
LogicBase
contract LogicBase is HasNoContracts { /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_NFC = bytes4(0x9f40b779); // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Reference to storage contract StorageBase public storageContract; function LogicBase(address _nftAddress, address _storageAddress) public { // paused by default paused = true; setNFTAddress(_nftAddress); require(_storageAddress != address(0)); storageContract = StorageBase(_storageAddress); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to owner function destroy() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the owner and terminates the contract selfdestruct(owner); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to the new contract function destroyAndSendToStorageOwner() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the new owner of the storage contract and terminates the contract selfdestruct(storageOwner); } // override to make sure everything is initialized before the unpause function unpause() public onlyOwner whenPaused { // can not unpause when the logic contract is not initialzed require(nonFungibleContract != address(0)); require(storageContract != address(0)); // can not unpause when ownership of storage contract is not the current contract require(storageContract.owner() == address(this)); super.unpause(); } function setNFTAddress(address _nftAddress) public onlyOwner { require(_nftAddress != address(0)); ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_NFC)); nonFungibleContract = candidateContract; } // Withdraw balance to the Core Contract function withdrawBalance() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = nftAddress.send(address(this).balance); return res; } function withdrawBalanceFromStorageContract() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = storageContract.withdrawBalance(); return res; } }
unpause
function unpause() public onlyOwner whenPaused { // can not unpause when the logic contract is not initialzed require(nonFungibleContract != address(0)); require(storageContract != address(0)); // can not unpause when ownership of storage contract is not the current contract require(storageContract.owner() == address(this)); super.unpause(); }
// override to make sure everything is initialized before the unpause
LineComment
v0.4.21+commit.dfe3193c
bzzr://c27a01dea21db6b14606d18a45e0a27f662e6885c07b57ba2974db53595f2c8b
{ "func_code_index": [ 2159, 2570 ] }
9,714
SiringClockAuction
SiringClockAuction.sol
0x23bbc7247b4dbdb4487c9b92d998e106883a9efa
Solidity
LogicBase
contract LogicBase is HasNoContracts { /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_NFC = bytes4(0x9f40b779); // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Reference to storage contract StorageBase public storageContract; function LogicBase(address _nftAddress, address _storageAddress) public { // paused by default paused = true; setNFTAddress(_nftAddress); require(_storageAddress != address(0)); storageContract = StorageBase(_storageAddress); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to owner function destroy() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the owner and terminates the contract selfdestruct(owner); } // Very dangerous action, only when new contract has been proved working // Requires storageContract already transferOwnership to the new contract // This method is only used to transfer the balance to the new contract function destroyAndSendToStorageOwner() external onlyOwner whenPaused { address storageOwner = storageContract.owner(); // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible require(storageOwner != address(this)); // Transfers the current balance to the new owner of the storage contract and terminates the contract selfdestruct(storageOwner); } // override to make sure everything is initialized before the unpause function unpause() public onlyOwner whenPaused { // can not unpause when the logic contract is not initialzed require(nonFungibleContract != address(0)); require(storageContract != address(0)); // can not unpause when ownership of storage contract is not the current contract require(storageContract.owner() == address(this)); super.unpause(); } function setNFTAddress(address _nftAddress) public onlyOwner { require(_nftAddress != address(0)); ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_NFC)); nonFungibleContract = candidateContract; } // Withdraw balance to the Core Contract function withdrawBalance() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = nftAddress.send(address(this).balance); return res; } function withdrawBalanceFromStorageContract() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = storageContract.withdrawBalance(); return res; } }
withdrawBalance
function withdrawBalance() external returns (bool) { address nftAddress = address(nonFungibleContract); // either Owner or Core Contract can trigger the withdraw require(msg.sender == owner || msg.sender == nftAddress); // The owner has a method to withdraw balance from multiple contracts together, // use send here to make sure even if one withdrawBalance fails the others will still work bool res = nftAddress.send(address(this).balance); return res; }
// Withdraw balance to the Core Contract
LineComment
v0.4.21+commit.dfe3193c
bzzr://c27a01dea21db6b14606d18a45e0a27f662e6885c07b57ba2974db53595f2c8b
{ "func_code_index": [ 2927, 3455 ] }
9,715
SiringClockAuction
SiringClockAuction.sol
0x23bbc7247b4dbdb4487c9b92d998e106883a9efa
Solidity
ClockAuction
contract ClockAuction is LogicBase { // Reference to contract tracking auction state variables ClockAuctionStorage public clockAuctionStorage; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Minimum cut value on each auction (in WEI) uint256 public minCutValue; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner, address seller, uint256 sellerProceeds); event AuctionCancelled(uint256 tokenId); function ClockAuction(address _nftAddress, address _storageAddress, uint256 _cut, uint256 _minCutValue) LogicBase(_nftAddress, _storageAddress) public { setOwnerCut(_cut); setMinCutValue(_minCutValue); clockAuctionStorage = ClockAuctionStorage(_storageAddress); } function setOwnerCut(uint256 _cut) public onlyOwner { require(_cut <= 10000); ownerCut = _cut; } function setMinCutValue(uint256 _minCutValue) public onlyOwner { minCutValue = _minCutValue; } function getMinPrice() public view returns (uint256) { // return ownerCut > 0 ? (minCutValue / ownerCut * 10000) : 0; // use minCutValue directly, when the price == minCutValue seller will get no profit return minCutValue; } // Only auction from none system user need to verify the price // System auction can set any price function isValidPrice(uint256 _startingPrice, uint256 _endingPrice) public view returns (bool) { return (_startingPrice < _endingPrice ? _startingPrice : _endingPrice) >= getMinPrice(); } function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) public whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); // assigning ownership to this clockAuctionStorage when in auction // it will throw if transfer fails nonFungibleContract.transferFrom(_seller, address(clockAuctionStorage), _tokenId); // Require that all auctions have a duration of at least one minute. require(_duration >= 1 minutes); clockAuctionStorage.addAuction( _tokenId, _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); emit AuctionCreated(_tokenId, _startingPrice, _endingPrice, _duration); } function cancelAuction(uint256 _tokenId) external { require(clockAuctionStorage.isOnAuction(_tokenId)); address seller = clockAuctionStorage.getSeller(_tokenId); require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { require(clockAuctionStorage.isOnAuction(_tokenId)); address seller = clockAuctionStorage.getSeller(_tokenId); _cancelAuction(_tokenId, seller); } function getAuction(uint256 _tokenId) public view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { require(clockAuctionStorage.isOnAuction(_tokenId)); return clockAuctionStorage.getAuction(_tokenId); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { require(clockAuctionStorage.isOnAuction(_tokenId)); return _currentPrice(_tokenId); } function _cancelAuction(uint256 _tokenId, address _seller) internal { clockAuctionStorage.removeAuction(_tokenId); clockAuctionStorage.transfer(nonFungibleContract, _seller, _tokenId); emit AuctionCancelled(_tokenId); } function _bid(uint256 _tokenId, uint256 _bidAmount, address bidder) internal returns (uint256) { require(clockAuctionStorage.isOnAuction(_tokenId)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(_tokenId); require(_bidAmount >= price); address seller = clockAuctionStorage.getSeller(_tokenId); uint256 sellerProceeds = 0; // Remove the auction before sending the fees to the sender so we can't have a reentrancy attack clockAuctionStorage.removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut, so this subtraction can't go negative uint256 auctioneerCut = _computeCut(price); sellerProceeds = price - auctioneerCut; // transfer the sellerProceeds seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid // transfer it back to bidder. // this cannot underflow. uint256 bidExcess = _bidAmount - price; bidder.transfer(bidExcess); emit AuctionSuccessful(_tokenId, price, bidder, seller, sellerProceeds); return price; } function _currentPrice(uint256 _tokenId) internal view returns (uint256) { uint256 secondsPassed = 0; address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; (seller, startingPrice, endingPrice, duration, startedAt) = clockAuctionStorage.getAuction(_tokenId); if (now > startedAt) { secondsPassed = now - startedAt; } return _computeCurrentPrice( startingPrice, endingPrice, duration, secondsPassed ); } function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { if (_secondsPassed >= _duration) { return _endingPrice; } else { // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256) { uint256 cutValue = _price * ownerCut / 10000; if (_price < minCutValue) return cutValue; if (cutValue > minCutValue) return cutValue; return minCutValue; } }
isValidPrice
function isValidPrice(uint256 _startingPrice, uint256 _endingPrice) public view returns (bool) { return (_startingPrice < _endingPrice ? _startingPrice : _endingPrice) >= getMinPrice(); }
// Only auction from none system user need to verify the price // System auction can set any price
LineComment
v0.4.21+commit.dfe3193c
bzzr://c27a01dea21db6b14606d18a45e0a27f662e6885c07b57ba2974db53595f2c8b
{ "func_code_index": [ 1620, 1826 ] }
9,716
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; }
/** * @dev Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 89, 266 ] }
9,717
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 350, 630 ] }
9,718
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
/** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 744, 860 ] }
9,719
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 924, 1054 ] }
9,720
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return totalSupply_; }
/** * @dev total number of tokens in existence */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 199, 287 ] }
9,721
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 445, 777 ] }
9,722
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 983, 1087 ] }
9,723
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 401, 891 ] }
9,724
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 1523, 1718 ] }
9,725
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
allowance
function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 2042, 2207 ] }
9,726
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
increaseApproval
function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 2673, 2980 ] }
9,727
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
decreaseApproval
function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 3451, 3894 ] }
9,728
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 710, 891 ] }
9,729
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); }
/** * @dev Allows the current owner to relinquish control of the contract. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 983, 1100 ] }
9,730
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
MintableToken
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } }
/** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */
NatSpecMultiLine
mint
function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; }
/** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 567, 896 ] }
9,731
FBC
FBC.sol
0xa285b6b0ddc40c20d5441e484403fd41fe46d34e
Solidity
MintableToken
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } }
/** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */
NatSpecMultiLine
finishMinting
function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; }
/** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */
NatSpecMultiLine
v0.4.23+commit.124ca40d
bzzr://4bee1794fec4a5b1d09cf3ed4edd8fc6730cc44d67c749b579f03c59d7c886bf
{ "func_code_index": [ 1013, 1160 ] }
9,732
DexAlpha
DexAlpha.sol
0xf001f36acb8a11158eae0983b6bc24ae0c7239dd
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
Ownable
function Ownable() { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://ce835913c5408a0b6e92cc529b5a1d9c1d1c05eb3d98c64c65045661d92081a2
{ "func_code_index": [ 275, 332 ] }
9,733
DexAlpha
DexAlpha.sol
0xf001f36acb8a11158eae0983b6bc24ae0c7239dd
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://ce835913c5408a0b6e92cc529b5a1d9c1d1c05eb3d98c64c65045661d92081a2
{ "func_code_index": [ 679, 863 ] }
9,734
DexAlpha
DexAlpha.sol
0xf001f36acb8a11158eae0983b6bc24ae0c7239dd
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SaferMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://ce835913c5408a0b6e92cc529b5a1d9c1d1c05eb3d98c64c65045661d92081a2
{ "func_code_index": [ 281, 642 ] }
9,735
DexAlpha
DexAlpha.sol
0xf001f36acb8a11158eae0983b6bc24ae0c7239dd
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SaferMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
balanceOf
function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://ce835913c5408a0b6e92cc529b5a1d9c1d1c05eb3d98c64c65045661d92081a2
{ "func_code_index": [ 862, 982 ] }
9,736
DexAlpha
DexAlpha.sol
0xf001f36acb8a11158eae0983b6bc24ae0c7239dd
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://ce835913c5408a0b6e92cc529b5a1d9c1d1c05eb3d98c64c65045661d92081a2
{ "func_code_index": [ 414, 989 ] }
9,737
DexAlpha
DexAlpha.sol
0xf001f36acb8a11158eae0983b6bc24ae0c7239dd
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
approve
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://ce835913c5408a0b6e92cc529b5a1d9c1d1c05eb3d98c64c65045661d92081a2
{ "func_code_index": [ 1645, 1843 ] }
9,738
DexAlpha
DexAlpha.sol
0xf001f36acb8a11158eae0983b6bc24ae0c7239dd
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
allowance
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://ce835913c5408a0b6e92cc529b5a1d9c1d1c05eb3d98c64c65045661d92081a2
{ "func_code_index": [ 2183, 2332 ] }
9,739
DexAlpha
DexAlpha.sol
0xf001f36acb8a11158eae0983b6bc24ae0c7239dd
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
increaseApproval
function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://ce835913c5408a0b6e92cc529b5a1d9c1d1c05eb3d98c64c65045661d92081a2
{ "func_code_index": [ 2593, 2867 ] }
9,740
DexAlpha
DexAlpha.sol
0xf001f36acb8a11158eae0983b6bc24ae0c7239dd
Solidity
DexAlpha
contract DexAlpha is StandardToken, Ownable { string public constant name = "DexAlpha Tokens"; string public constant symbol = "DXAT"; uint8 public constant decimals = 8; uint256 public constant SUPPLY_CAP = 1000000000 * (10 ** uint256(decimals)); address NULL_ADDRESS = address(0); uint public nonce = 0; event NonceTick(uint nonce); function incNonce() { nonce += 1; if(nonce > 100) { nonce = 0; } NonceTick(nonce); } event PerformingDrop(uint count); function drop(address[] addresses, uint256 amount) public onlyOwner { uint256 amt = amount * 10**8; require(amt > 0); require(amt <= SUPPLY_CAP); PerformingDrop(addresses.length); // Multisend function assert(balances[owner] >= amt * addresses.length); for (uint i = 0; i < addresses.length; i++) { address recipient = addresses[i]; if(recipient != NULL_ADDRESS) { balances[owner] -= amt; balances[recipient] += amt; Transfer(owner, recipient, amt); } } } /** * @dev Constructor that gives msg.sender all of existing tokens.. */ function DexAlpha() { totalSupply = SUPPLY_CAP; balances[msg.sender] = SUPPLY_CAP; } }
DexAlpha
function DexAlpha() { totalSupply = SUPPLY_CAP; balances[msg.sender] = SUPPLY_CAP; }
/** * @dev Constructor that gives msg.sender all of existing tokens.. */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://ce835913c5408a0b6e92cc529b5a1d9c1d1c05eb3d98c64c65045661d92081a2
{ "func_code_index": [ 1254, 1360 ] }
9,741
YFLUSDYFLPool
contracts/IRewardDistributionRecipient.sol
0x5f35334ef7e38ebe1f94d31e6fc3d78b477f4f91
Solidity
YFLUSDYFLPool
contract YFLUSDYFLPool is YFLWrapper, IRewardDistributionRecipient { IERC20 public yflUsd; uint256 public DURATION = 5 days; address public governance; uint256 public starttime; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public deposits; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); constructor( address yflUsd_, address yfl_, uint256 starttime_, address governance_ ) public { yflUsd = IERC20(yflUsd_); yfl = IERC20(yfl_); starttime = starttime_; governance = governance_; } modifier checkStart() { require(block.timestamp >= starttime, 'YFLUSDYFLPool: not start'); _; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier onlyGovernance() { require(msg.sender == governance); _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'YFLUSDYFLPool: Cannot stake 0'); uint256 newDeposit = deposits[msg.sender].add(amount); deposits[msg.sender] = newDeposit; super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'YFLUSDYFLPool: Cannot withdraw 0'); deposits[msg.sender] = deposits[msg.sender].sub(amount); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) checkStart { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; yflUsd.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { /* if (block.timestamp > starttime) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } */ } function notifyRewardAmountByGovernace(uint256 reward) external onlyGovernance updateReward(address(0)) { if (block.timestamp > starttime) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } } function setGovernance(address _governance) external onlyGovernance { governance = _governance; } function setYfl(address _yfl) external onlyGovernance { yfl = IERC20(_yfl); } }
stake
function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'YFLUSDYFLPool: Cannot stake 0'); uint256 newDeposit = deposits[msg.sender].add(amount); deposits[msg.sender] = newDeposit; super.stake(amount); emit Staked(msg.sender, amount); }
// stake visibility is public as overriding LPTokenWrapper's stake() function
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 2436, 2805 ] }
9,742
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
ERC20Interface
contract ERC20Interface { // Get the total token supply function totalSupply() public constant returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
// ---------------------------------------------------------------------------------------------- // Gifto Token by Gifto Limited. // An ERC20 standard // // author: Gifto Team // Contact: [email protected]
LineComment
totalSupply
function totalSupply() public constant returns (uint256 _totalSupply);
// Get the total token supply
LineComment
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 62, 137 ] }
9,743
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
ERC20Interface
contract ERC20Interface { // Get the total token supply function totalSupply() public constant returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
// ---------------------------------------------------------------------------------------------- // Gifto Token by Gifto Limited. // An ERC20 standard // // author: Gifto Team // Contact: [email protected]
LineComment
balanceOf
function balanceOf(address _owner) public constant returns (uint256 balance);
// Get the account balance of another account with address _owner
LineComment
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 212, 294 ] }
9,744
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
ERC20Interface
contract ERC20Interface { // Get the total token supply function totalSupply() public constant returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
// ---------------------------------------------------------------------------------------------- // Gifto Token by Gifto Limited. // An ERC20 standard // // author: Gifto Team // Contact: [email protected]
LineComment
transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// Send _value amount of tokens to address _to
LineComment
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 350, 432 ] }
9,745
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; }
/// @dev Fallback function allows to buy ether.
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 2636, 2995 ] }
9,746
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
Gifto
function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); }
/// @dev Constructor
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 3024, 3186 ] }
9,747
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
totalSupply
function totalSupply() public constant returns (uint256) { return _totalSupply; }
/// @dev Gets totalSupply /// @return Total supply
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 3254, 3383 ] }
9,748
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
setIcoPercent
function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; }
/// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 3477, 3689 ] }
9,749
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
setMinimumBuy
function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; }
/// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 3785, 3941 ] }
9,750
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
setMaximumBuy
function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; }
/// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 4037, 4193 ] }
9,751
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
balanceOf
function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; }
/// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 4312, 4455 ] }
9,752
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
isApprovedInvestor
function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; }
/// @dev check address is approved investor /// @param _addr address
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 4541, 4700 ] }
9,753
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
filterBuyers
function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } }
/// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 4809, 5444 ] }
9,754
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
getInvestorBuyers
function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); }
/// @dev filter buyers are investor in list deposited
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 5510, 5649 ] }
9,755
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
getNormalBuyers
function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); }
/// @dev filter normal Buyers in list buyer deposited
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 5715, 5853 ] }
9,756
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
getDeposit
function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; }
/// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 5976, 6115 ] }
9,757
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
getTotalDeposit
function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } }
/// @dev get total deposit of buyers /// @return amount ETH deposit
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 6200, 6450 ] }
9,758
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
deliveryToken
function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); }
/// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 6629, 7947 ] }
9,759
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
returnETHforNormalBuyers
function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } }
/// @dev return ETH for normal buyers
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 7997, 8540 ] }
9,760
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
transfer
function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } }
/// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 8736, 9356 ] }
9,761
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
turnOnSale
function turnOnSale() onlyOwner public { _selling = true; }
/// @dev Enables sale
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 9387, 9475 ] }
9,762
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
turnOffSale
function turnOffSale() onlyOwner public { _selling = false; }
/// @dev Disables sale
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 9506, 9596 ] }
9,763
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
isSellingNow
function isSellingNow() public constant returns (bool) { return _selling; }
/// @dev Gets selling status
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 9633, 9756 ] }
9,764
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
setBuyPrice
function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; }
/// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit)
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 9856, 9987 ] }
9,765
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
addInvestorList
function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } }
/// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 10146, 10379 ] }
9,766
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
removeInvestorList
function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } }
/// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 10507, 10735 ] }
9,767
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
buy
function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; }
/// @dev Buys Gifto /// @return Amount of requested units
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 10807, 11629 ] }
9,768
Gifto
Gifto.sol
0x5438b0938fb88a979032f45b87d2d1aeffe5cc28
Solidity
Gifto
contract Gifto is ERC20Interface { uint public constant decimals = 5; string public constant symbol = "Gifto"; string public constant name = "Gifto"; bool public _selling = false;//initial not selling uint public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint public _originalBuyPrice = 10 ** 10; // original buy in wei of one unit. Ajustable. // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) balances; // List of approved investors mapping(address => bool) approvedInvestorList; // mapping Deposit mapping(address => uint256) deposit; // buyers buy token deposit address[] buyers; // icoPercent uint _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.1 ETH uint public _minimumBuy = 10 ** 17; // maximum buy 30 ETH uint public _maximumBuy = 30 * 10 ** 18; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier can only be executed by users except owners */ modifier onlyNotOwner() { require(msg.sender != owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling && (_icoSupply > 0) ); _; } /** * Functions with this modifier check the validity of original buy price */ modifier validOriginalBuyPrice() { require(_originalBuyPrice > 0); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // if value < _minimumBuy OR total deposit of msg.sender > maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /// @dev Fallback function allows to buy ether. function() public payable validValue { // check the first buy => push to Array if (deposit[msg.sender] == 0 && msg.value != 0){ // add new buyer to List buyers.push(msg.sender); } // increase amount deposit of buyer deposit[msg.sender] += msg.value; } /// @dev Constructor function Gifto() public { owner = msg.sender; balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner returns (bool){ _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _minimumBuy /// @param newMinimumBuy new value of _minimumBuy function setMinimumBuy(uint256 newMinimumBuy) public onlyOwner returns (bool){ _minimumBuy = newMinimumBuy; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner returns (bool){ _maximumBuy = newMaximumBuy; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev filter buyers in list buyers /// @param isInvestor type buyers, is investor or not function filterBuyers(bool isInvestor) private constant returns(address[] filterList){ address[] memory filterTmp = new address[](buyers.length); uint count = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor){ filterTmp[count] = buyers[i]; count++; } } filterList = new address[](count); for (i = 0; i < count; i++){ if(filterTmp[i] != 0x0){ filterList[i] = filterTmp[i]; } } } /// @dev filter buyers are investor in list deposited function getInvestorBuyers() public constant returns(address[]){ return filterBuyers(true); } /// @dev filter normal Buyers in list buyer deposited function getNormalBuyers() public constant returns(address[]){ return filterBuyers(false); } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev get total deposit of buyers /// @return amount ETH deposit function getTotalDeposit() public constant returns(uint256 totalDeposit){ totalDeposit = 0; for (uint i = 0; i < buyers.length; i++){ totalDeposit += deposit[buyers[i]]; } } /// @dev delivery token for buyer /// @param isInvestor transfer token for investor or not /// true: investors /// false: not investors function deliveryToken(bool isInvestor) public onlyOwner validOriginalBuyPrice { //sumary deposit of investors uint256 sum = 0; for (uint i = 0; i < buyers.length; i++){ if(approvedInvestorList[buyers[i]] == isInvestor) { // compute amount token of each buyer uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice; //check requestedUnits > _icoSupply if(requestedUnits <= _icoSupply && requestedUnits > 0 ){ // prepare transfer data // NOTE: make sure balances owner greater than _icoSupply balances[owner] -= requestedUnits; balances[buyers[i]] += requestedUnits; _icoSupply -= requestedUnits; // submit transfer Transfer(owner, buyers[i], requestedUnits); // reset deposit of buyer sum += deposit[buyers[i]]; deposit[buyers[i]] = 0; } } } //transfer total ETH of investors to owner owner.transfer(sum); } /// @dev return ETH for normal buyers function returnETHforNormalBuyers() public onlyOwner{ for(uint i = 0; i < buyers.length; i++){ // buyer not approve investor if (!approvedInvestorList[buyers[i]]) { // get deposit of buyer uint256 buyerDeposit = deposit[buyers[i]]; // reset deposit of buyer deposit[buyers[i]] = 0; // return deposit amount for buyer buyers[i].transfer(buyerDeposit); } } } /// @dev Transfers the balance from Multisig wallet to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { revert(); } } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } /// @dev Gets selling status function isSellingNow() public constant returns (bool) { return _selling; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint newBuyPrice) onlyOwner public { _originalBuyPrice = newBuyPrice; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Buys Gifto /// @return Amount of requested units function buy() payable onlyNotOwner validOriginalBuyPrice validInvestor onSale public returns (uint256 amount) { // convert buy amount in wei to number of unit want to buy uint requestedUnits = msg.value / _originalBuyPrice ; //check requestedUnits <= _icoSupply require(requestedUnits <= _icoSupply); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // decrease _icoSupply _icoSupply -= requestedUnits; // submit transfer Transfer(owner, msg.sender, requestedUnits); //transfer ETH to owner owner.transfer(msg.value); return requestedUnits; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
withdraw
function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); }
/// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://85b4add34c1c736fc55c8889a7b809f3632522776d785648bf03f8ad284359dd
{ "func_code_index": [ 11729, 11856 ] }
9,769
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
buy
function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); }
// -------------------- user api ----------------//
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 6383, 9544 ] }
9,770
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
calculateBuy
function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); }
// contains some methods for buy or reinvest
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 9597, 12357 ] }
9,771
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
reinvest
function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); }
// contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 12574, 15301 ] }
9,772
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
withdraw
function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); }
// contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 15518, 16786 ] }
9,773
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
supportSubordinateAddress
function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); }
// referral address support subordinate, 10%
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 16839, 18275 ] }
9,774
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
teamReferralReward
function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } }
// -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1];
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 18445, 20695 ] }
9,775
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
calculateProfit
function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; }
// calculate bonus profit
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 22379, 22987 ] }
9,776
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
getPerBonusDivide
function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; }
// get user bonus information for calculate static rewards
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 23054, 23571 ] }
9,777
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
calculateToken
function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); }
// calculate and transfer KOC token
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 23615, 23831 ] }
9,778
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
straightReferralReward
function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } }
// calculate straight reward and record referral address recommendRecord
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 23912, 25130 ] }
9,779
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
straightSortAddress
function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } }
// sort straight address, 10
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 25167, 25846 ] }
9,780
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
quickSort
function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); }
//sort straight address, 10
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 25882, 26754 ] }
9,781
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
settleStraightRewards
function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; }
// settle straight rewards
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 26789, 27815 ] }
9,782
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
ethToBonus
function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; }
// calculate bonus
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 27842, 28529 ] }
9,783
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
sqrt
function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } }
// utils for calculate bonus
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 28566, 28769 ] }
9,784
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
myBonusProfits
function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); }
// get user bonus profits
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 28803, 29024 ] }
9,785
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
setStraightSortRewards
function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; }
// -------------------- set api ---------------- //
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 30142, 30366 ] }
9,786
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
getStraightSortList
function getStraightSortList() public view returns (address[10] memory) { return straightSort; }
// -------------------- get api ---------------- // // get straight sort list, 10 addresses
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 30471, 30606 ] }
9,787
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
getStraightInviteAddress
function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; }
// get effective straight addresses current step
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 30663, 30822 ] }
9,788
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
getcurrentBlockNumber
function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; }
// get currentBlockNumber
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 30856, 30982 ] }
9,789
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
contractStatistics
function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); }
// returns contract statistics
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 34698, 34968 ] }
9,790
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
getCurrentEffectiveUser
function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; }
// return current effective user for initAddressAmount
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 35753, 35886 ] }
9,791
Resonance
Resonance.sol
0xd87c7ef38c3eaa2a196db19a5f1338eec123bec9
Solidity
Resonance
contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } }
getCurrentTerminatorAmountPool
function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); }
//return Current Terminator reward pool amount
LineComment
v0.5.1+commit.c8a2cb62
MIT
bzzr://a1533a2259fca30289db2437294a7f22dad9225667799e7f0acc8ada85f96280
{ "func_code_index": [ 36865, 37067 ] }
9,792
xBRKB
xBRKB.sol
0x8fbedafcc0a4eda503ceed3ff64e668ab27b4d65
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */
NatSpecMultiLine
_add
function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } }
/** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */
NatSpecMultiLine
v0.7.5+commit.eb77ed08
MIT
ipfs://31dd83e84e4a3f9dc5c7bbf56634dd7f042a64777e869deb4e852821435be985
{ "func_code_index": [ 908, 1327 ] }
9,793
xBRKB
xBRKB.sol
0x8fbedafcc0a4eda503ceed3ff64e668ab27b4d65
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */
NatSpecMultiLine
_remove
function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } }
/** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */
NatSpecMultiLine
v0.7.5+commit.eb77ed08
MIT
ipfs://31dd83e84e4a3f9dc5c7bbf56634dd7f042a64777e869deb4e852821435be985
{ "func_code_index": [ 1498, 3047 ] }
9,794
xBRKB
xBRKB.sol
0x8fbedafcc0a4eda503ceed3ff64e668ab27b4d65
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */
NatSpecMultiLine
_contains
function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; }
/** * @dev Returns true if the value is in the set. O(1). */
NatSpecMultiLine
v0.7.5+commit.eb77ed08
MIT
ipfs://31dd83e84e4a3f9dc5c7bbf56634dd7f042a64777e869deb4e852821435be985
{ "func_code_index": [ 3128, 3262 ] }
9,795
xBRKB
xBRKB.sol
0x8fbedafcc0a4eda503ceed3ff64e668ab27b4d65
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */
NatSpecMultiLine
_length
function _length(Set storage set) private view returns (uint256) { return set._values.length; }
/** * @dev Returns the number of values on the set. O(1). */
NatSpecMultiLine
v0.7.5+commit.eb77ed08
MIT
ipfs://31dd83e84e4a3f9dc5c7bbf56634dd7f042a64777e869deb4e852821435be985
{ "func_code_index": [ 3343, 3457 ] }
9,796
xBRKB
xBRKB.sol
0x8fbedafcc0a4eda503ceed3ff64e668ab27b4d65
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */
NatSpecMultiLine
_at
function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; }
/** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */
NatSpecMultiLine
v0.7.5+commit.eb77ed08
MIT
ipfs://31dd83e84e4a3f9dc5c7bbf56634dd7f042a64777e869deb4e852821435be985
{ "func_code_index": [ 3796, 4005 ] }
9,797
xBRKB
xBRKB.sol
0x8fbedafcc0a4eda503ceed3ff64e668ab27b4d65
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */
NatSpecMultiLine
add
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); }
/** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */
NatSpecMultiLine
v0.7.5+commit.eb77ed08
MIT
ipfs://31dd83e84e4a3f9dc5c7bbf56634dd7f042a64777e869deb4e852821435be985
{ "func_code_index": [ 4254, 4384 ] }
9,798
xBRKB
xBRKB.sol
0x8fbedafcc0a4eda503ceed3ff64e668ab27b4d65
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */
NatSpecMultiLine
remove
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); }
/** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */
NatSpecMultiLine
v0.7.5+commit.eb77ed08
MIT
ipfs://31dd83e84e4a3f9dc5c7bbf56634dd7f042a64777e869deb4e852821435be985
{ "func_code_index": [ 4555, 4691 ] }
9,799