Skip to content

Instantly share code, notes, and snippets.

@rohitsethii
Created September 13, 2018 11:11
Show Gist options
  • Save rohitsethii/3072c32118eb9e17d2e8db7217b69eeb to your computer and use it in GitHub Desktop.
Save rohitsethii/3072c32118eb9e17d2e8db7217b69eeb to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.4.24+commit.e67f0147.js&optimize=true&gist=
/*Problem Statement #1
Write a Roulette Contract, which will implement following features:
• At max, 5 players can involve in one game.
• Each player will choose a number in range of 0-4
• One number can be selected by only one player and one player can select only one number.
• While choosing a number, player will put some ETH in it. (MIN: 0.5 ETH, MAX: 5ETH)
• As soon fifth player provides the choice of numbe, roulette will spin to find a random number.
(To find random number, use : previous_block_number % 5 )
• Winner (as per random number calculation) will get all ETH inserted by players
*/
pragma solidity ^0.4.24;
contract Roulette {
// uint guess;
uint numplayers = 0;
uint winningNumber;
bool zero = false;
mapping (uint => address) numXplayer;
mapping (address=>uint) playerXguess;
event NewEntry( uint indexed numplayers,
address indexed playeradd,
uint indexed num
);
modifier Zero{
require(zero == false);
_;
}
function guessNumber(uint _num)
public
payable
{
if(_num == 0){
handleZero();
return;
}
require(_num >=0 && _num <=4,"please enter a valid number");
require(numplayers <= 5,"roulette already full");
require(msg.value >= 0.5 ether && msg.value <= 5 ether, "enter valid amount");
for(uint i = 0; i <= 4;i++){
require(numXplayer[i]!=msg.sender,"user already exist");
require(_num != playerXguess[numXplayer[i]],"number already taken");
}
numXplayer[numplayers] = msg.sender;
playerXguess[msg.sender] = _num;
emit NewEntry(numplayers,msg.sender,_num);
numplayers++;
if(numplayers == 5){
randomnumber();
}
// distribute();
}
function randomnumber() internal returns (uint) {
winningNumber = uint8(block.number%5);
for(uint j=0; j <=4; j++){
if(winningNumber == playerXguess[numXplayer[j]]){
address winner = numXplayer[j];
require(winner.send(address(this).balance));
}
}
}
function handleZero() internal Zero{
numXplayer[numplayers]= msg.sender;
playerXguess[msg.sender]=0;
zero = true;
numplayers++;
if (numplayers == 5)
randomnumber();
return;
}
function bal() view public returns(uint){
uint Bal = address(this).balance;
return Bal;
}
}
pragma solidity ^0.4.4;
contract Marriages {
mapping (address => address) public proposals;
mapping (address => bytes32) public marriageRecords;
mapping (bytes32 => Marriage) public marriages;
struct Marriage {
bool complete;
Person[] people;
uint256 timeStamp;
}
struct Person {
address _address;
bytes32 firstName;
bytes32 middleName;
bytes32 lastName;
bytes32 dateOfBirth;
uint id;
}
function proposalNew(address me, address myPartner) public returns (bool) {
require (!_personIsMarried(me) && !_personIsMarried(myPartner));
proposals[me] = myPartner;
return true;
}
function proposalMatch(address me, address myPartner) public returns (bool) {
return proposals[myPartner] == me ? true : false;
}
function marriageNew(address person1, address person2) public returns (bytes32) {
require (_canMarry(person1, person2));
bytes32 marId = _createMarId(person1, person2);
_newMarriageRecord(person1, marId);
_newMarriageRecord(person2, marId);
return marId;
}
function addPerson(bytes32 marId, address _person, bytes32 firstName, bytes32 middleName, bytes32 lastName, bytes32 dateOfBirth, uint id) public returns (bool) {
marriages[marId].people.push(Person({_address:_person, firstName:firstName, middleName:middleName, lastName:lastName, dateOfBirth:dateOfBirth, id:id}));
_marriageCompleteIfRequired(marId);
return true;
}
function marriageIsComplete(bytes32 marId) public returns (bool) {
return marriages[marId].complete;
}
function marriageGetPersonAddress(bytes32 marId, uint256 index) public returns (address) {
return marriages[marId].people[index]._address;
}
function marriageGetMarIdForPerson(address person) public returns (bytes32) {
return marriageRecords[person];
}
/* Marriage certificate methods */
function marriageGetPersonFirstName(bytes32 marId, uint256 index) public returns (bytes32) {
require (marriageIsComplete(marId));
return marriages[marId].people[index].firstName;
}
function marriageGetPersonMiddleName(bytes32 marId, uint256 index) public returns (bytes32) {
require (marriageIsComplete(marId));
return marriages[marId].people[index].middleName;
}
function marriageGetPersonLastName(bytes32 marId, uint256 index) public returns (bytes32) {
require (marriageIsComplete(marId));
return marriages[marId].people[index].lastName;
}
function marriageGetPersonDateOfBirth(bytes32 marId, uint256 index) public returns (bytes32) {
require (marriageIsComplete(marId));
return marriages[marId].people[index].dateOfBirth;
}
function marriageGetPersonId(bytes32 marId, uint256 index) public returns (uint) {
require (marriageIsComplete(marId));
return marriages[marId].people[index].id;
}
function timeStamp(bytes32 marId) public returns (uint256) {
return marriages[marId].timeStamp;
}
/* Private implementation */
function _newMarriageRecord(address person, bytes32 marId) private returns (bool) {
marriageRecords[person] = marId;
return true;
}
function _canMarry(address person1, address person2) private returns (bool) {
if(_personIsMarried(person1)) { return false; }
if(_personIsMarried(person2)) { return false; }
if(!(proposalMatch(person1, person2) && proposalMatch(person2, person1))) { return false; }
return true;
}
function _createMarId(address person1, address person2) private returns (bytes32) {
if (person1 > person2) {
return keccak256(person1, person2);
} else {
return keccak256(person2, person1);
}
}
function _marriageCompleteIfRequired(bytes32 marId) private returns (bool) {
if (marriages[marId].people.length >= 2) {
marriages[marId].complete = true;
_setTimeStamp(marId);
return true;
} else {
return false;
}
}
function _personIsMarried(address person) private returns(bool) {
return marriageIsComplete(marriageGetMarIdForPerson(person));
}
function _setTimeStamp(bytes32 marId) private returns(uint256) {
uint256 timeNow = now;
marriages[marId].timeStamp = timeNow;
return timeNow;
}
}
pragma solidity ^0.4.0;
contract Ballot {
struct Voter {
uint weight;
bool voted;
uint8 vote;
address delegate;
}
struct Proposal {
uint voteCount;
}
address chairperson;
mapping(address => Voter) voters;
Proposal[] proposals;
/// Create a new ballot with $(_numProposals) different proposals.
function Ballot(uint8 _numProposals) public {
chairperson = msg.sender;
voters[chairperson].weight = 1;
proposals.length = _numProposals;
}
/// Give $(toVoter) the right to vote on this ballot.
/// May only be called by $(chairperson).
function giveRightToVote(address toVoter) public {
if (msg.sender != chairperson || voters[toVoter].voted) return;
voters[toVoter].weight = 1;
}
/// Delegate your vote to the voter $(to).
function delegate(address to) public {
Voter storage sender = voters[msg.sender]; // assigns reference
if (sender.voted) return;
while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender)
to = voters[to].delegate;
if (to == msg.sender) return;
sender.voted = true;
sender.delegate = to;
Voter storage delegateTo = voters[to];
if (delegateTo.voted)
proposals[delegateTo.vote].voteCount += sender.weight;
else
delegateTo.weight += sender.weight;
}
/// Give a single vote to proposal $(toProposal).
function vote(uint8 toProposal) public {
Voter storage sender = voters[msg.sender];
if (sender.voted || toProposal >= proposals.length) return;
sender.voted = true;
sender.vote = toProposal;
proposals[toProposal].voteCount += sender.weight;
}
function winningProposal() public constant returns (uint8 _winningProposal) {
uint256 winningVoteCount = 0;
for (uint8 prop = 0; prop < proposals.length; prop++)
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
_winningProposal = prop;
}
}
}
pragma solidity ^0.4.22;
contract contest{
uint public numtickets;
uint price=1 ether;
address owner;
bool open;
bytes32 Hash;
address[] public allbuyers;
mapping(address => uint)public buyers;
event bought(address,uint);
constructor (uint t) public {
require(t>0,"invalid entry");
owner=msg.sender;
numtickets = t;
}
modifier notowner(){
require(msg.sender != owner,
"Only buyer can call this."
);
_;
}
modifier onlyowner(){
require(msg.sender == owner,
"Only owner can call this."
);
_;
}
/*
modifier onlyonetime(){
for(uint i=0)
require(msg.sender!= buyers[i], "already bought");
_;
}
*/
/*function () public payable{
buytickets(1);
}
*/
function allowPurchase() onlyowner {
open = true;
}
function lockPurchase() onlyowner {
open = false;
}
modifier Open(){
require(open,"closed! try after sometime");
_;
}
function buytickets(uint n) public notowner Open payable returns(bytes32) {
if(msg.value == n * price || numtickets > n){
allbuyers.push(msg.sender);
buyers[msg.sender] += n;
numtickets -= n;
emit bought(msg.sender,n);
Hash = key(msg.sender,n);
return Hash;
}
if(numtickets==0){
selfdestruct(owner);
}
}
function getalltickets() returns(uint x){
for(uint i=0;i<allbuyers.length;i++){
return x=totaltickets(i);
}//return x;
}
function totaltickets(uint i) returns(uint) {
return buyers[allbuyers[i]];
}
function yourtickets(address your) public returns (uint){
return buyers[your];
}
function key(address buyer,uint _n) private returns (bytes32){
//return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
//bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount,nonce, this)));
return keccak256(abi.encodePacked(buyer,_n));
}
function getBalance() constant returns (uint) {
return this.balance;
}
}
pragma solidity ^0.4.17;
library Dictionary {
uint constant private NULL = 0;
struct Node {
uint prev;
uint next;
bytes data;
bool initialized;
}
struct Data {
mapping(uint => Node) list;
uint firstNodeId;
uint lastNodeId;
uint len;
}
function insertAfter(Data storage self, uint afterId, uint id, bytes data) internal {
if (self.list[id].initialized) {
self.list[id].data = data;
return;
}
self.list[id].prev = afterId;
if (self.list[afterId].next == NULL) {
self.list[id].next = NULL;
self.lastNodeId = id;
} else {
self.list[id].next = self.list[afterId].next;
self.list[self.list[afterId].next].prev = id;
}
self.list[id].data = data;
self.list[id].initialized = true;
self.list[afterId].next = id;
self.len++;
}
function insertBefore(Data storage self, uint beforeId, uint id, bytes data) internal {
if (self.list[id].initialized) {
self.list[id].data = data;
return;
}
self.list[id].next = beforeId;
if (self.list[beforeId].prev == NULL) {
self.list[id].prev = NULL;
self.firstNodeId = id;
} else {
self.list[id].prev = self.list[beforeId].prev;
self.list[self.list[beforeId].prev].next = id;
}
self.list[id].data = data;
self.list[id].initialized = true;
self.list[beforeId].prev = id;
self.len++;
}
function insertBeginning(Data storage self, uint id, bytes data) internal {
if (self.list[id].initialized) {
self.list[id].data = data;
return;
}
if (self.firstNodeId == NULL) {
self.firstNodeId = id;
self.lastNodeId = id;
self.list[id] = Node({ prev: 0, next: 0, data: data, initialized: true });
self.len++;
} else
insertBefore(self, self.firstNodeId, id, data);
}
function insertEnd(Data storage self, uint id, bytes data) internal {
if (self.lastNodeId == NULL) insertBeginning(self, id, data);
else
insertAfter(self, self.lastNodeId, id, data);
}
function set(Data storage self, uint id, bytes data) internal {
insertEnd(self, id, data);
}
function get(Data storage self, uint id) internal view returns (bytes) {
return self.list[id].data;
}
function remove(Data storage self, uint id) internal returns (bool) {
uint nextId = self.list[id].next;
uint prevId = self.list[id].prev;
if (prevId == NULL) self.firstNodeId = nextId; //first node
else self.list[prevId].next = nextId;
if (nextId == NULL) self.lastNodeId = prevId; //last node
else self.list[nextId].prev = prevId;
delete self.list[id];
self.len--;
return true;
}
function getSize(Data storage self) internal view returns (uint) {
return self.len;
}
function next(Data storage self, uint id) internal view returns (uint) {
return self.list[id].next;
}
function prev(Data storage self, uint id) internal view returns (uint) {
return self.list[id].prev;
}
function keys(Data storage self) internal constant returns (uint[]) {
uint[] memory arr = new uint[](self.len);
uint node = self.firstNodeId;
for (uint i=0; i < self.len; i++) {
arr[i] = node;
node = next(self, node);
}
return arr;
}
}
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
// to add a check for total number of participants and
//owner cannot draw a winner while participant has made a guess and tx is pending
contract Rlottery
{
address addr;
TokenERC20 tokenn = TokenERC20(addr);
address owner;
address[] public allholders;
address[] public winners;
uint price=1000000 wei;
uint[] public allguess;
uint count=0;
uint public LuckyNumber;
uint public Total;
uint public playerID = 0;
bool public winnerDrawn = false;
bool public active = true;
//-----------------------------------------Mappings----------------------------------------
mapping (uint => address) public holders; // PlayerID => participant_address
mapping (address => uint) public Guesses; //participant_address => guess
//-----------------------------------------Events----------------------------------------
event Guess(
address indexed from,
uint indexed PlayerID,
uint indexed _guess,
uint value
);
//-----------------------------------------Modifiers------------------------------------
modifier onlyowner(){
require(msg.sender==owner);
_;
}
modifier notowner(){
require(msg.sender!=owner);
_;
}
modifier alreadyDrawn(){
require(!winnerDrawn);
_;
}
modifier LotteryActive{
require(active==true);
_;
}
//------------------------------------constructor----------------------------------------------------
constructor() public{
owner=msg.sender;
//bytes32 winninghash= keccak256(abi.encode(winninghash));
}
//------------------------------------Public Functions----------------------------------------------------
function receiveApproval(address _sender,
uint256 _value,
TokenERC20 _tokenContract,
bytes guess) {
require(_tokenContract == tokenn);
require(tokenn.transferFrom(_sender, address(this), 10));
}
function() payable{
require(msg.value==price,"insufficient amount of wei");
address add = msg.sender;
tokenn.transfer(add,10);
}
function gettoken()
payable
public
returns(bool){
require(msg.value==price,"insufficient amount of wei");
address add = msg.sender;
tokenn.transfer(add,10);
return true;
}
function makeGuess(uint guess)
notowner
LotteryActive
public
//payable
returns(bool){
require(guess != 0x20);
require(guess<=20);
// require(msg.value == price);
allholders.push(msg.sender);
holders[playerID]= msg.sender;
emit Guess(msg.sender,playerID,guess,msg.value);
playerID++;
allguess.push(guess);
Guesses[msg.sender]= guess;
Total=Total + msg.value;
return true;
}
function drawwinner()
public
onlyowner
alreadyDrawn
returns(address[]) {
LuckyNumber=uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%21);
for(uint i=0;i<allholders.length;i++){
if( LuckyNumber==allguess[i] ){
winners.push(allholders[i]);
count++;
}
}
winnerDrawn=true;
return winners;
}
function distributeReward()
onlyowner
LotteryActive
internal
{
if(count == 0){
//selfdestruct(owner);
owner.transfer(address(this).balance);
DeleteAll();
return;
}
uint winnerreward= (address(this).balance/2)/count;
for(uint j=0;j<winners.length;j++){
winners[j].transfer(winnerreward);
}
owner.transfer(address(this).balance);
DeleteAll();
return;
}
//-----------------------------------------Delete all variables to play next round-----------------------------
function DeleteAll()
onlyowner
internal
{
winnerDrawn = false;
active = true;
delete LuckyNumber;
delete Total;
delete allholders;
delete count;
delete winners;
delete allguess;
delete Total;
delete playerID;
}
}
pragma solidity ^0.4.22;
interface InfoFeed {
function info() public returns (uint ret);}
contract A is InfoFeed{
function info() returns (uint){
return 42;
}
}
contract Call{
A i=new A();
function call() returns(uint){
uint x= i.info();
return x;
}
}
contract Consumer {
InfoFeed feed;
function setFeed(address addr) public { feed = InfoFeed(addr); }
function callFeed() public returns (uint){
address z=new A();
A c = A(z);
uint x=c.info();
return x;
}
}
contract Sharer {
uint public x=1 ;
int8 public y = -3;
//uint public x = uint(y);
uint public balanceBeforeTransfer;
function sendHalf(address addr) public payable returns (uint balance) {
require(msg.value % 2 == 0, "Even value required.");
balanceBeforeTransfer = address(this).balance;
addr.transfer(msg.value / 2);
// Since transfer throws an exception on failure and
// cannot call back here, there should be no way for us to
// still have half of the money.
assert(address(this).balance == balanceBeforeTransfer - msg.value / 2);
return address(this).balance;
}
function a() returns (uint[]){
delete x;
}
}
pragma solidity ^0.4.22;
contract Lottery{
address owner;
address winner;
address[] public allholders;
address[] public winners;
uint price=1000000 wei;
uint[] public allguess;
uint count=0;
uint public w;
uint public Total;
uint playerID = 0;
//uint round = 3 minutes;
//uint startround = now + round;
bool winnerDrawn = false;
bool active = true;
//-----------------------------------------Mappings----------------------------------------
mapping (uint => address) public holders; // PlayerID => participant_address
mapping (address => uint) public Guesses; //participant_address => guess
//-----------------------------------------Events----------------------------------------
event Guess(
address indexed from,
uint indexed PlayerID,
uint indexed _guess,
uint value
);
//-----------------------------------------Modifiers------------------------------------
modifier onlyowner(){
require(msg.sender==owner);
_;
}
modifier notowner(){
require(msg.sender!=owner);
_;
}
modifier alreadyDrawn(){
require(!winnerDrawn);
_;
}
modifier LotteryActive{
require(active==true);
_;
}
//------------------------------------constructor----------------------------------------------------
constructor() public{
owner=msg.sender;
//bytes32 winninghash= keccak256(abi.encode(winninghash));
}
function makeGuess(uint guess)
notowner
LotteryActive
public
payable
returns(bool){
require(guess != 0x20);
require(guess<=20);
require(msg.value == price);
allholders.push(msg.sender);
holders[playerID]= msg.sender;
emit Guess(msg.sender,playerID,guess,msg.value);
playerID++;
allguess.push(guess);
Guesses[msg.sender]= guess;
Total=Total + msg.value;
return true;
}
//------------------------------------Public Functions----------------------------------------------------
function drawwinner()
public
onlyowner
alreadyDrawn
returns(address[]) {
w=uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%21);
for(uint i=0;i<allholders.length;i++){
if( w==allguess[i] ){
winners.push(allholders[i]);
count++;
}
}
winnerDrawn=true;
return winners;
}
function distributeReward()
public
onlyowner
LotteryActive
{
if(count == 0){
selfdestruct(owner);
}
uint winnerreward= (address(this).balance/2)/count;
for(uint j=0;j<winners.length;j++){
winners[j].transfer(winnerreward);
}
selfdestruct(owner);
// owner.transfer(address(this).balance);
// if (address(this).balance == 0){
// winnerDrawn = false;
// active = true;
// delete w;
// delete Total;
// delete allholders;
// }
}
}
pragma solidity ^0.4.24;
/**
* @title -FoMo-3D v0.7.1
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ .--,-``-.
*========,---,.======================____==========================/ / '.=======,---,====*
* ,' .' | ,' , `. / ../ ; .' .' `\
* ,---.' | ,---. ,-+-,.' _ | ,---. \ ``\ .`- ' ,---.' \
* | | .' ' ,'\ ,-+-. ; , || ' ,'\ ,---,. \___\/ \ : | | .`\ |
* : : : / / | ,--.'|' | || / / | ,' .' | \ : | : : | ' |
* : | |-, . ; ,. : | | ,', | |, . ; ,. : ,---.' | / / / | ' ' ; :
* | : ;/| ' | |: : | | / | |--' ' | |: : | | .' \ \ \ ' | ; . |
* | | .' ' | .; : | : | | , ' | .; : : |.' ___ / : | | | : | '
* ' : ' | : | | : | |/ | : | `---' / /\ / : ' : | / ;
* | | | \ \ / | | |`-' \ \ / / ,,/ ',- . | | '` ,/
* | : \ `----' | ;/ `----' \ ''\ ; ; : .'
*====| | ,'=============='---'==========(soon edition)===========\ \ .'===| ,.'======*
* `----' `--`-,,-' '---'
* ╔═╗┌─┐┌─┐┬┌─┐┬┌─┐┬ ┌─────────────────────────┐ ╦ ╦┌─┐┌┐ ╔═╗┬┌┬┐┌─┐
* ║ ║├┤ ├┤ ││ │├─┤│ │ https://exitscam.me │ ║║║├┤ ├┴┐╚═╗│ │ ├┤
* ╚═╝└ └ ┴└─┘┴┴ ┴┴─┘ └─┬─────────────────────┬─┘ ╚╩╝└─┘└─┘╚═╝┴ ┴ └─┘
* ┌────────────────────────────────┘ └──────────────────────────────┐
* │╔═╗┌─┐┬ ┬┌┬┐┬┌┬┐┬ ┬ ╔╦╗┌─┐┌─┐┬┌─┐┌┐┌ ╦┌┐┌┌┬┐┌─┐┬─┐┌─┐┌─┐┌─┐┌─┐ ╔═╗┌┬┐┌─┐┌─┐┬┌─│
* │╚═╗│ ││ │ │││ │ └┬┘ ═ ║║├┤ └─┐││ ┬│││ ═ ║│││ │ ├┤ ├┬┘├┤ ├─┤│ ├┤ ═ ╚═╗ │ ├─┤│ ├┴┐│
* │╚═╝└─┘┴─┘┴─┴┘┴ ┴ ┴ ═╩╝└─┘└─┘┴└─┘┘└┘ ╩┘└┘ ┴ └─┘┴└─└ ┴ ┴└─┘└─┘ ╚═╝ ┴ ┴ ┴└─┘┴ ┴│
* │ ┌──────────┐ ┌───────┐ ┌─────────┐ ┌────────┐ │
* └────┤ Inventor ├───────────┤ Justo ├────────────┤ Sumpunk ├──────────────┤ Mantso ├──┘
* └──────────┘ └───────┘ └─────────┘ └────────┘
* ┌─────────────────────────────────────────────────────────┐ ╔╦╗┬ ┬┌─┐┌┐┌┬┌─┌─┐ ╔╦╗┌─┐
* │ Ambius, Aritz Cracker, Cryptoknight, Crypto McPump, │ ║ ├─┤├─┤│││├┴┐└─┐ ║ │ │
* │ Capex, JogFera, The Shocker, Daok, Randazzz, PumpRabbi, │ ╩ ┴ ┴┴ ┴┘└┘┴ ┴└─┘ ╩ └─┘
* │ Kadaz, Incognito Jo, Lil Stronghands, Maojk, Psaints, └───────────────────────────┐
* │ P3DHeem, 3DCrypto, FaFiam, Crypto Yardi, Ninja Turtle, Psaints, Satoshi, Vitalik, │
* │ Justin Sun, Nano 2nd, Bogdanoffs Isaac Newton, Nikola Tesla, │
* │ Le Comte De Saint Germain, Albert Einstein, Socrates, & all the volunteer moderator │
* │ & support staff, content, creators, autonomous agents, and indie devs for P3D. │
* │ Without your help, we wouldn't have the time to code this. │
* └─────────────────────────────────────────────────────────────────────────────────────┘
*
* This product is protected under license. Any unauthorized copy, modification, or use without
* express written consent from the creators is prohibited.
*
* WARNING: THIS PRODUCT IS HIGHLY ADDICTIVE. IF YOU HAVE AN ADDICTIVE NATURE. DO NOT PLAY.
*/
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
contract F3Devents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract FoMo3DSoon is F3Devents{
using SafeMath for uint256;
using NameFilter for string;
using F3DKeysCalcFast for uint256;
DiviesInterface constant private Divies = DiviesInterface(0xC0c001140319C5f114F8467295b1F22F86929Ad0);
JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0xdd4950F977EE28D2C132f1353D1595035Db444EE);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xD60d353610D9a5Ca478769D371b53CEfAA7B6E4c);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "FoMo3D Soon(tm) Edition";
string constant public symbol = "F3D";
uint256 private rndGap_ = 60 seconds; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 5 minutes; // round timer starts at this
uint256 constant private rndInc_ = 5 minutes; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 5 minutes; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
require (_addr == tx.origin);
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no"); /** NOTE THIS NEEDS TO BE CHECKED **/
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// set up our tx event data
F3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit F3Devents.onNewName(_pID, _addr, _name, isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* - during live round. this is accurate. (well... unless someone buys before
* you do and ups the price! you better HURRY!)
* - during ICO phase. this is the max you would get based on current eth
* invested during ICO phase. if others invest after you, you will receive
* less. (so distract them with meme vids till ICO is over)
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// is ICO phase over?? & theres eth in the round?
if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)
return ( ((round_[_rID].ico.keys()).add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 100000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in ICO phase?
if (_now <= round_[_rID].strt + rndGap_)
return( ((round_[_rID].end).sub(rndInit_)).sub(_now) );
else
if (_now < round_[_rID].end)
return( (round_[_rID].end).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false)
{
uint256 _roundMask;
uint256 _roundEth;
uint256 _roundKeys;
uint256 _roundPot;
if (round_[_rID].eth == 0 && round_[_rID].ico > 0)
{
// create a temp round eth based on eth sent in during ICO phase
_roundEth = round_[_rID].ico;
// create a temp round keys based on keys bought during ICO phase
_roundKeys = (round_[_rID].ico).keys();
// create a temp round mask based on eth and keys from ICO phase
_roundMask = ((round_[_rID].icoGen).mul(1000000000000000000)) / _roundKeys;
// create a temp rount pot based on pot, and dust from mask
_roundPot = (round_[_rID].pot).add((round_[_rID].icoGen).sub((_roundMask.mul(_roundKeys)) / (1000000000000000000)));
} else {
_roundEth = round_[_rID].eth;
_roundKeys = round_[_rID].keys;
_roundMask = round_[_rID].mask;
_roundPot = round_[_rID].pot;
}
uint256 _playerKeys;
if (plyrRnds_[_pID][plyr_[_pID].lrnd].ico == 0)
_playerKeys = plyrRnds_[_pID][plyr_[_pID].lrnd].keys;
else
_playerKeys = calcPlayerICOPhaseKeys(_pID, _rID);
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( (_roundPot.mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _roundMask, _roundPot, _roundKeys, _playerKeys) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _roundMask, _roundPot, _roundKeys, _playerKeys) ),
plyr_[_pID].aff
);
}
// if round is still going on, we are in ico phase, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _roundMask, uint256 _roundPot, uint256 _roundKeys, uint256 _playerKeys)
private
view
returns(uint256)
{
return( (((_roundMask.add((((_roundPot.mul(potSplit_[round_[rID_].team].gen)) / 100).mul(1000000000000000000)) / _roundKeys)).mul(_playerKeys)) / 1000000000000000000).sub(plyrRnds_[_pID][rID_].mask) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (round_[_rID].eth != 0)
{
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
} else {
return
(
round_[_rID].ico, //0
_rID, //1
(round_[_rID].ico).keys(), //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player ico eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
if (plyrRnds_[_pID][_rID].ico == 0)
{
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
0 //6
);
} else {
return
(
_pID, //0
plyr_[_pID].name, //1
calcPlayerICOPhaseKeys(_pID, _rID), //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].ico //6
);
}
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in ICO phase or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// check to see if round has ended. and if player is new to round
_eventData_ = manageRoundAndPlayer(_pID, _eventData_);
// are we in ICO phase?
if (now <= round_[rID_].strt + rndGap_)
{
// let event data know this is a ICO phase buy order
_eventData_.compressedData = _eventData_.compressedData + 2000000000000000000000000000000;
// ICO phase core
icoPhaseCore(_pID, msg.value, _team, _affID, _eventData_);
// round is live
} else {
// let event data know this is a buy order
_eventData_.compressedData = _eventData_.compressedData + 1000000000000000000000000000000;
// call core
core(_pID, msg.value, _affID, _team, _eventData_);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in ICO phase or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
// check to see if round has ended. and if player is new to round
_eventData_ = manageRoundAndPlayer(_pID, _eventData_);
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// are we in ICO phase?
if (now <= round_[rID_].strt + rndGap_)
{
// let event data know this is an ICO phase reload
_eventData_.compressedData = _eventData_.compressedData + 3000000000000000000000000000000;
// ICO phase core
icoPhaseCore(_pID, _eth, _team, _affID, _eventData_);
// round is live
} else {
// call core
core(_pID, _eth, _affID, _team, _eventData_);
}
}
/**
* @dev during ICO phase all eth sent in by each player. will be added to an
* "investment pool". upon end of ICO phase, all eth will be used to buy keys.
* each player receives an amount based on how much they put in, and the
* the average price attained.
*/
function icoPhaseCore(uint256 _pID, uint256 _eth, uint256 _team, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// if they bought at least 1 whole key (at time of purchase)
if ((round_[_rID].ico).keysRec(_eth) >= 1000000000000000000 || round_[_rID].plyr == 0)
{
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// add eth to our players & rounds ICO phase investment. this will be used
// to determine total keys and each players share
plyrRnds_[_pID][_rID].ico = _eth.add(plyrRnds_[_pID][_rID].ico);
round_[_rID].ico = _eth.add(round_[_rID].ico);
// add eth in to team eth tracker
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// send eth share to com, p3d, affiliate, and fomo3d long
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// add gen share to rounds ICO phase gen tracker (will be distributed
// when round starts)
round_[_rID].icoGen = _gen.add(round_[_rID].icoGen);
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// calculate pot share pot (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) - gen
uint256 _pot = (_eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100))).sub(_gen);
// add eth to pot
round_[_rID].pot = _pot.add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
// fire event
endTx(_rID, _pID, _team, _eth, 0, _eventData_);
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// check to see if its a new round (past ICO phase) && keys were bought in ICO phase
if (round_[_rID].eth == 0 && round_[_rID].ico > 0)
roundClaimICOKeys(_rID);
// if player is new to round and is owed keys from ICO phase
if (plyrRnds_[_pID][_rID].keys == 0 && plyrRnds_[_pID][_rID].ico > 0)
{
// assign player their keys from ICO phase
plyrRnds_[_pID][_rID].keys = calcPlayerICOPhaseKeys(_pID, _rID);
// zero out ICO phase investment
plyrRnds_[_pID][_rID].ico = 0;
}
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 1 prize was won
_eventData_.compressedData += 100000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_rID, _pID, _team, _eth, _keys, _eventData_);
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
// if player does not have unclaimed keys bought in ICO phase
// return their earnings based on keys held only.
if (plyrRnds_[_pID][_rIDlast].ico == 0)
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
else
if (now > round_[_rIDlast].strt + rndGap_ && round_[_rIDlast].eth == 0)
return( (((((round_[_rIDlast].icoGen).mul(1000000000000000000)) / (round_[_rIDlast].ico).keys()).mul(calcPlayerICOPhaseKeys(_pID, _rIDlast))) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
else
return( (((round_[_rIDlast].mask).mul(calcPlayerICOPhaseKeys(_pID, _rIDlast))) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
// otherwise return earnings based on keys owed from ICO phase
// (this would be a scenario where they only buy during ICO phase, and never
// buy/reload during round)
}
/**
* @dev average ico phase key price is total eth put in, during ICO phase,
* divided by the number of keys that were bought with that eth.
* -functionhash- 0xdcb6af48
* @return average key price
*/
function calcAverageICOPhaseKeyPrice(uint256 _rID)
public
view
returns(uint256)
{
return( (round_[_rID].ico).mul(1000000000000000000) / (round_[_rID].ico).keys() );
}
/**
* @dev at end of ICO phase, each player is entitled to X keys based on final
* average ICO phase key price, and the amount of eth they put in during ICO.
* if a player participates in the round post ICO, these will be "claimed" and
* added to their rounds total keys. if not, this will be used to calculate
* their gen earnings throughout round and on round end.
* -functionhash- 0x75661f4c
* @return players keys bought during ICO phase
*/
function calcPlayerICOPhaseKeys(uint256 _pID, uint256 _rID)
public
view
returns(uint256)
{
if (round_[_rID].icoAvg != 0 || round_[_rID].ico == 0 )
return( ((plyrRnds_[_pID][_rID].ico).mul(1000000000000000000)) / round_[_rID].icoAvg );
else
return( ((plyrRnds_[_pID][_rID].ico).mul(1000000000000000000)) / calcAverageICOPhaseKeyPrice(_rID) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* - during live round. this is accurate. (well... unless someone buys before
* you do and ups the price! you better HURRY!)
* - during ICO phase. this is the max you would get based on current eth
* invested during ICO phase. if others invest after you, you will receive
* less. (so distract them with meme vids till ICO is over)
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// is ICO phase over?? & theres eth in the round?
if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)
return ( (round_[_rID].eth).keysRec(_eth) );
else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)
return ( (round_[_rID].ico).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* - during live round. this is accurate. (well... unless someone buys before
* you do and ups the price! you better HURRY!)
* - during ICO phase. this is the max you would get based on current eth
* invested during ICO phase. if others invest after you, you will receive
* less. (so distract them with meme vids till ICO is over)
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// is ICO phase over?? & theres eth in the round?
if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)
return ( (((round_[_rID].ico).keys()).add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function manageRoundAndPlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// check to see if round has ended. we use > instead of >= so that LAST
// second snipe tx can extend the round.
if (_now > round_[_rID].end)
{
// check to see if round end has been run yet. (distributes pot)
if (round_[_rID].ended == false)
{
_eventData_ = endRound(_eventData_);
round_[_rID].ended = true;
}
// start next round in ICO phase
rID_++;
_rID++;
round_[_rID].strt = _now;
round_[_rID].end = _now.add(rndInit_).add(rndGap_);
}
// is player new to round?
if (plyr_[_pID].lrnd != _rID)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = _rID;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
}
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// check to round ended with ONLY ico phase transactions
if (round_[_rID].eth == 0 && round_[_rID].ico > 0)
roundClaimICOKeys(_rID);
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _p3d.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// send share for p3d to divies
if (_p3d > 0)
Divies.deposit.value(_p3d)();
// fill next round pot with its share
round_[_rID + 1].pot += _res;
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
return(_eventData_);
}
/**
* @dev takes keys bought during ICO phase, and adds them to round. pays
* out gen rewards that accumulated during ICO phase
*/
function roundClaimICOKeys(uint256 _rID)
private
{
// update round eth to account for ICO phase eth investment
round_[_rID].eth = round_[_rID].ico;
// add keys to round that were bought during ICO phase
round_[_rID].keys = (round_[_rID].ico).keys();
// store average ICO key price
round_[_rID].icoAvg = calcAverageICOPhaseKeyPrice(_rID);
// set round mask from ICO phase
uint256 _ppt = ((round_[_rID].icoGen).mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = (round_[_rID].icoGen).sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000));
if (_dust > 0)
round_[_rID].pot = (_dust).add(round_[_rID].pot); // <<< your adding to pot and havent updated event data
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// calculate time based on number of keys bought
uint256 _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// grab time
uint256 _now = now;
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _com;
_com = 0;
}
// pay 1% out to FoMo3D long
uint256 _long = _eth / 100;
round_[_rID + 1].pot += _long;
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to divies contract
Divies.deposit.value(_p3d)();
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _rID, uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (_rID * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C ||
msg.sender == 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D ||
msg.sender == 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53 ||
msg.sender == 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C ||
msg.sender == 0xF39e044e1AB204460e06E87c6dca2c6319fC69E3,
"only team just can activate"
);
// can only be ran once
require(activated_ == false, "fomo3d already activated");
// activate the contract
activated_ = true;
// lets start first round in ICO phase
rID_ = 1;
round_[1].strt = now;
round_[1].end = now + rndInit_ + rndGap_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library F3Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library F3DKeysCalcFast {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(200000000000000000000000000000000)).add(2500000000000000000000000000000000000000000000000000000000000000)).sqrt()).sub(50000000000000000000000000000000)) / (100000000000000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((50000000000000).mul(_keys.sq()).add(((100000000000000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface DiviesInterface {
function deposit() external payable;
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
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;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @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)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
pragma solidity ^0.4.16;
contract A{
function b(uint) internal returns (bool) {
return true;
}
}
contract B is A{
function c(uint a) returns (bool){
return b(a);
}
}
contract A {
function foo() {
}
}
contract B {
function createFoo (address _contractAddress){
A a = A(_contractAddress);
a.foo();
}
function callFoo (address _contractAddress) {
address newAddress = _contractAddress;
newAddress.call(bytes4(sha3("foo()")));
}
}
pragma solidity ^0.4.22;
//pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if(address(OAR)==0) oraclize_setNetwork(networkID_auto);
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed);
return true;
}
if (getCodeSize(0xc03a2615d5efaf5f49f60b7bb6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03a2615d5efaf5f49f60b7bb6583eaec212fdf1);
return true;
}
if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf);
return true;
}
if (getCodeSize(0x93bbbe5ce77034e3095f0479919962a903f898ad)>0){ //norsborg testnet
OAR = OraclizeAddrResolverI(0x93bbbe5ce77034e3095f0479919962a903f898ad);
return true;
}
if (getCodeSize(0x51efaf4c8b3c9afbd5ab9f4bbc82784ab6ef8faa)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaf4c8b3c9afbd5ab9f4bbc82784ab6ef8faa);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int)
{
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
// </ORACLIZE_API>
contract Lottery{
uint tickets;
uint price=1 ether;
address owner;
address winner;
address[] public allholders;
uint[] public allguess;
//uint public winningNumber;
uint public count=0;
address[] public winners;
uint public w;
//bytes random= keccak256(abi.encode("0x12133"));
mapping (uint => address) public holders;
modifier onlyowner(){
require(msg.sender==owner);
_;
}
modifier notowner(){
require(msg.sender!=owner);
_;
}
constructor() public{
owner=msg.sender;
//w= winningNumber;
//bytes32 winninghash= keccak256(abi.encode(winninghash));
}
function makeGuess(uint guess) notowner public payable returns(bytes32){
require(msg.value == price);
require(guess<=250);
allholders.push(msg.sender);
holders[guess]= msg.sender;
allguess.push(guess);
bytes32 guesshash= keccak256(abi.encode(guess));
return guesshash;
}
function drawwinner() public onlyowner returns(address[]) {
w=uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
for(uint i=0;i<allholders.length;i++){
if(w==allguess[i] ){
winners.push(allholders[i]);
count++;
}
}
return winners;
}
function distributeReward() onlyowner {
if(count==0){
selfdestruct(owner);
}
uint winnerreward= this.balance/count;
for(uint j=0;j<winners.length;j++){
winners[j].transfer(winnerreward);
}
selfdestruct(owner);
}
/*
function random() private view returns (uint8) {
return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
}*/
}
contract randomNumber is usingOraclize {
uint public result;
bytes32 public oraclizeID;
function flipCoin() payable {
oraclizeID = oraclize_query("WolframAlpha", "random number between 0 and 250");
}
function __callback(bytes32 _oraclizeID, uint _result) {
if(msg.sender != oraclize_cbAddress()) throw;
result = _result;
}
}
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
// to add a check for total number of participants and
//owner cannot draw a winner while participant has made a guess and tx is pending
contract Lottery{
address token_addr = 0x5e72914535f202659083db3a02c984188fa26e9f;
TokenERC20 tokenn = TokenERC20(token_addr);
address owner;
// address public winner;
address[] public allholders;
address[] public winners;
uint price=1000000 wei;
uint[] public allguess;
uint count=0;
uint public LuckyNumber;
uint public Total;
uint public playerID = 0;
//uint round = 3 minutes;
//uint startround = now + round;
bool public winnerDrawn = false;
bool public active = true;
//-----------------------------------------Mappings----------------------------------------
mapping (uint => address) public holders; // PlayerID => participant_address
mapping (address => uint) public guesses; //participant_address => guess
//-----------------------------------------Events----------------------------------------
event guess(
address indexed from,
uint indexed PlayerID,
uint indexed _guess,
uint value
);
//-----------------------------------------Modifiers------------------------------------
modifier onlyowner(){
require(msg.sender==owner);
_;
}
modifier notowner(){
require(msg.sender!=owner);
_;
}
modifier alreadyDrawn(){
require(!winnerDrawn);
_;
}
modifier LotteryActive{
require(active==true);
_;
}
//------------------------------------constructor----------------------------------------------------
constructor() public{
owner=msg.sender;
//bytes32 winninghash= keccak256(abi.encode(winninghash));
}
//------------------------------------Public Functions----------------------------------------------------
//function receiveApproval(address msg.sender, uint256 20, address _token, bytes guess) {
function receiveApproval(address _sender,
uint256 _value,
TokenERC20 _tokenContract,
bytes guess) {
require(_tokenContract == tokenn);
require(tokenn.transferFrom(_sender, address(this), 10));
//
}
function() payable{
require(msg.value==price,"insufficient amount of wei");
address add = msg.sender;
tokenn.transfer(add,10);
}
function gettoken()
payable
public
returns(bool){
require(msg.value==price,"insufficient amount of wei");
address add = msg.sender;
tokenn.transfer(add,10);
return true;
}
function makeguess(uint guess)
notowner
LotteryActive
public
// payable
returns(bool){
require(guess != 0x20);
require(guess<=20);
require(msg.value == price);
allholders.push(msg.sender);
holders[playerID]= msg.sender;
emit guess(msg.sender,playerID,guess,msg.value);
playerID++;
allguess.push(guess);
guesses[msg.sender]= guess;
Total=Total + msg.value;
return true;
}
function drawwinner()
public
onlyowner
alreadyDrawn
returns(address[]) {
LuckyNumber=uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%21);
for(uint i=0;i<allholders.length;i++){
if( LuckyNumber==allguess[i] ){
winners.push(allholders[i]);
count++;
}
}
winnerDrawn=true;
return winners;
}
function distributeReward()
onlyowner
LotteryActive
internal
{
if(count == 0){
//selfdestruct(owner);
owner.transfer(address(this).balance);
DeleteAll();
return;
}
uint winnerreward= (address(this).balance/2)/count;
for(uint j=0;j<winners.length;j++){
winners[j].transfer(winnerreward);
}
owner.transfer(address(this).balance);
DeleteAll();
return;
}
function getbal() returns (uint){
uint bal;
bal = address(this).balance;
return bal;
}
//-----------------------------------------Delete all variables to play next round-----------------------------
function DeleteAll()
onlyowner
internal
{
winnerDrawn = false;
active = true;
delete LuckyNumber;
delete Total;
delete allholders;
delete count;
delete winners;
delete allguess;
delete Total;
delete playerID;
}
}
// pragma solidity ^0.4.18;
interface token {
function transfer(address receiver, uint amount) external;
}
contract Crowdsale {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint public deadline;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constructor function
*
* Setup the owner
*/
function Crowdsale(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
uint etherCostOfEachToken,
address addressOfTokenUsedAsReward
) public {
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
price = etherCostOfEachToken * 1 ether;
tokenReward = token(addressOfTokenUsedAsReward);
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function () payable public {
require(!crowdsaleClosed);
uint amount = msg.value;
balanceOf[msg.sender] += amount;
amountRaised += amount;
tokenReward.transfer(msg.sender, amount / price);
emit FundTransfer(msg.sender, amount, true);
}
modifier afterDeadline() { if (now >= deadline) _; }
/**
* Check if goal was reached
*
* Checks if the goal or time limit has been reached and ends the campaign
*/
function checkGoalReached() public afterDeadline {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
emit GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
/**
* Withdraw the funds
*
* Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached,
* sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw
* the amount they contributed.
*/
function safeWithdrawal() public afterDeadline {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
emit FundTransfer(msg.sender, amount, false);
} else {
balanceOf[msg.sender] = amount;
}
}
}
if (fundingGoalReached && beneficiary == msg.sender) {
if (beneficiary.send(amountRaised)) {
emit FundTransfer(beneficiary, amountRaised, false);
} else {
//If we fail to send the funds to beneficiary, unlock funders balance
fundingGoalReached = false;
}
}
}
}
contract test{
function send() payable{
address addr= 0xcbbe6ec46746218a5bed5b336ab86a0a22804d39;
addr.send(msg.value);
}
}
/*Write a Marriage Contract in which there will be three entities: Groom, Bride & Lawyer. Contract should
facilitate following interactions :
• Registration: At very initial level, before performing any activity, all entities need to register with
the contract putting all required information.
• Marriage: Two person can marry with each other in the presence of lawyer. Groom or Bride can
approach the lawyer with required information of couple and paying the fee to lawyer ( fee = 2
ETH). Only registered unmarried or divorced male and female marriage is possible.
• Divorce: Two person can go for the divorce with each other in the presence of lawyer. Groom or
Bride can approach the lawyer with required information of couple and paying the fee to lawyer (
fee = 4 ETH). Only registered people married with each other can go for the divorce
• Marriage lawyer should not be same as divorce lawyer.
• Each entity will be identified by its Ethereum address
• Sending of any accidental Ether should be prevented.
• Details of any entity can be seen at any time by anyone by passing the Ethereum address and
without paying any gas fee.
*/
pragma solidity ^0.4.24;
contract Marriage {
uint RegID;
bytes32 marid;
enum Status {
Married,
Single
}
enum Type {
Bride,
Groom,
Lawyer
}
struct Data {
uint Id;
string name;
bool registered;
Status status;
Type types;
}
mapping (address => Data) public data;
mapping (address => address) public femaleXmale;
mapping (address => address) public maleXfemae;
mapping (bytes32 => address ) marriageidXlawyer;
event marriage( bytes32 indexed mid,
address indexed mpartner1,
address indexed mpartner2,
address mlawyer
);
event Divorce( bytes32 indexed did,
address indexed dpartner1,
address indexed dpartner2,
address dlawyer
);
event Register( uint RegID,
address user,
string name,
string types
);
modifier NotRegistered() {
require(!data[msg.sender].registered,"Already registered");
_;
}
modifier Allregistered(address _groom,address _bride,address _lawyer) {
require(data[_groom].registered && data[_bride].registered && data[_lawyer].registered,"User is Not Registered");
require(msg.sender == _groom || msg.sender == _bride,"Only bride or groom can call");
_;
}
modifier BothSingle(address _groom,address _bride) {
require(data[_groom].status == Status.Single && data[_bride].status == Status.Single,"Already Married");
_;
}
modifier BothMarried(address _groom,address _bride) {
require(data[_groom].status == Status.Married && data[_bride].status == Status.Married,"Both are Not Married");
_;
}
function register(string _name,string _type)
public
NotRegistered
returns (bool) {
bytes32 _Type = keccak256(abi.encodePacked(_type));
bytes32 bride = keccak256(abi.encodePacked("Bride"));
bytes32 groom = keccak256(abi.encodePacked("Groom"));
bytes32 lawyer = keccak256(abi.encodePacked("Lawyer"));
require(_Type == bride || _Type == groom || _Type == lawyer,"Enter Groom,Bride or Lawyer ");
Type t;
if (_Type == bride){
t = Type.Bride;
}
else if(_Type == keccak256("Groom")){
t = Type.Groom;
}
else{
t = Type.Lawyer;
}
data[msg.sender] = Data(RegID,_name,true,Status.Single,t);
emit Register(RegID,msg.sender,_name,_type);
RegID++;
return true;
}
function marry(address _groom,address _bride,address _lawyer)
public
Allregistered(_groom,_bride ,_lawyer)
BothSingle(_groom,_bride)
payable
returns(bytes32) {
require(msg.value == 2 ether,"Invalid amount of ether");
require(data[_groom].types == Type.Groom && data[_bride].types == Type.Bride,"male and female only");
require(data[_lawyer].types == Type.Lawyer);
marid = keccak256(abi.encodePacked(_groom,_bride));
marriageidXlawyer[marid] = _lawyer;
data[_groom].status = Status.Married;
data[_bride].status = Status.Married;
femaleXmale[_bride] = _groom;
maleXfemae[_groom] = _bride;
emit marriage(marid,_groom,_bride,_lawyer);
require(_lawyer.send(2 ether));
return marid;
}
//"0xf815944e284c41b4b2a15760806a6e3ca7d72fa8215800559e6c6946210fa3e8","0xca35b7d915458ef540ade6068dfe2f44e8fa733c","0x14723a09acff6d2a60dcdf7aa4aff308fddc160c","0xdd870fa1b7c4700f2bd7f44238821c26f7392148"
function divorce(bytes32 _marid,address _groom,address _bride,address _lawyer)
public
Allregistered(_groom,_bride ,_lawyer)
BothMarried(_groom,_bride)
payable
returns(bool) {
require(msg.value == 4 ether,"Invalid amount of ether");
require(marriageidXlawyer[_marid] != _lawyer,"Marriage Lawyer cannot involve in Divorce");
require(_marid == keccak256(abi.encodePacked(_groom,_bride)),"Both are not Married to each other");
data[_groom].status = Status.Single;
data[_bride].status = Status.Single;
delete femaleXmale[_bride];
delete maleXfemae[_groom];
emit Divorce(_marid,_groom,_bride,_lawyer);
require(_lawyer.send(4 ether));
return true;
}
function getBal() view public returns (uint){
return address(this).balance;
}
function getDetails() view public returns (uint Id,string name,bool registered,Status status,Type types){
return (data[msg.sender].Id,data[msg.sender].name,data[msg.sender].registered,data[msg.sender].status,data[msg.sender].types);
}
function getType() view public returns (Type){
return data[msg.sender].types;
}
}
pragma solidity ^0.4.4;
contract A{
bool public a;
uint sum = 0;
function p3 ( uint x ) returns(uint){
uint temp = 0;
for ( uint i = 0 ; i < x ; i++)
temp += i;
sum += temp;
return sum;
}
}
// pragma solidity ^0.4.18;
contract C {
uint[20] public x;
function f() public {
h(x);
g(x);
}
function g(uint[20] storage y) internal {
y[2] = 3;
}
function h(uint[20] memory y) internal {
y[2] = 4;
}
}
pragma solidity ^0.4.22;
//pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if(address(OAR)==0) oraclize_setNetwork(networkID_auto);
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed);
return true;
}
if (getCodeSize(0xc03a2615d5efaf5f49f60b7bb6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03a2615d5efaf5f49f60b7bb6583eaec212fdf1);
return true;
}
if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf);
return true;
}
if (getCodeSize(0x93bbbe5ce77034e3095f0479919962a903f898ad)>0){ //norsborg testnet
OAR = OraclizeAddrResolverI(0x93bbbe5ce77034e3095f0479919962a903f898ad);
return true;
}
if (getCodeSize(0x51efaf4c8b3c9afbd5ab9f4bbc82784ab6ef8faa)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaf4c8b3c9afbd5ab9f4bbc82784ab6ef8faa);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int)
{
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
// </ORACLIZE_API>
contract Lottery{
uint tickets;
uint price=1 ether;
address owner;
address winner;
address[] public allholders;
uint[] public allguess;
//uint public winningNumber;
uint public count=0;
address[] public winners;
uint public w;
//bytes random= keccak256(abi.encode("0x12133"));
mapping (uint => address) public holders;
modifier onlyowner(){
require(msg.sender==owner);
_;
}
modifier notowner(){
require(msg.sender!=owner);
_;
}
constructor() public{
owner=msg.sender;
//w= winningNumber;
//bytes32 winninghash= keccak256(abi.encode(winninghash));
}
function makeGuess(uint guess) notowner public payable returns(bytes32){
require(msg.value == price);
require(guess<=250);
allholders.push(msg.sender);
holders[guess]= msg.sender;
allguess.push(guess);
bytes32 guesshash= keccak256(abi.encode(guess));
return guesshash;
}
function drawwinner() public onlyowner returns(address[]) {
w=uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
for(uint i=0;i<allholders.length;i++){
if(w==allguess[i] ){
winners.push(allholders[i]);
count++;
}
}
return winners;
}
function distributeReward() onlyowner {
if(count==0){
selfdestruct(owner);
}
uint winnerreward= this.balance/count;
for(uint j=0;j<winners.length;j++){
winners[j].transfer(winnerreward);
}
selfdestruct(owner);
}
/*
function random() private view returns (uint8) {
return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
}*/
}
contract randomNumber is usingOraclize {
uint public result;
bytes32 public oraclizeID;
function flipCoin() payable {
oraclizeID = oraclize_query("WolframAlpha", "flip a coin");
}
function __callback(bytes32 _oraclizeID, uint _result) {
// if(msg.sender != oraclize_cbAddress()) throw;
result = _result;
}
}
pragma solidity ^0.4.11;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
contract RandomExample is usingOraclize {
event newRandomNumber_bytes(bytes);
event newRandomNumber_uint(uint);
function constructor() {
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof in the constructor
update(); // let's ask for N random bytes immediately when the contract is created!
}
// the callback function is called by Oraclize when the result is ready
// the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code:
// the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof)
{
if (msg.sender != oraclize_cbAddress()) throw;
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
// the proof verification has failed, do we need to take any action here? (depends on the use case)
} else {
// the proof verification has passed
// now that we know that the random number was safely generated, let's use it..
newRandomNumber_bytes(bytes(_result)); // this is the resulting random number (bytes)
// for simplicity of use, let's also convert the random bytes to uint if we need
uint maxRange = 2**(8* 7); // this is the highest uint we want to get. It should never be greater than 2^(8*N), where N is the number of random bytes we had asked the datasource to return
uint randomNumber = uint(sha3(_result)) % maxRange; // this is an efficient way to get the uint out in the [0, maxRange] range
newRandomNumber_uint(randomNumber); // this is the resulting random number (uint)
}
}
function update() payable {
uint N = 7; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
uint callbackGas = 200000; // amount of gas we want Oraclize to set for the callback function
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, callbackGas); // this function internally generates the correct oraclize_query and returns its queryId
}
}
pragma solidity ^0.4.24;
contract SimplePaymentChannel {
address public sender; // The account sending payments.
address public recipient; // The account receiving the payments.
uint256 public expiration; // Timeout in case the recipient never closes.
constructor (address _recipient, uint256 duration)
public
payable
{
sender = msg.sender;
recipient = _recipient;
expiration = now + duration;
}
function isValidSignature(uint256 amount, bytes signature)
public
view
returns (bytes32)
{
bytes32 message = prefixed(keccak256(abi.encodePacked(this, amount)));
// check that the signature is from the payment sender
return message;
//return recoverSigner(message, signature) == sender;
}
/// the recipient can close the channel at any time by presenting a
/// signed amount from the sender. the recipient will be sent that amount,
/// and the remainder will go back to the sender
function close(uint256 amount, bytes signature) public {
require(msg.sender == recipient);
//require(isValidSignature(amount, signature));
recipient.transfer(amount);
selfdestruct(sender);
}
/// the sender can extend the expiration at any time
function extend(uint256 newExpiration) public {
require(msg.sender == sender);
require(newExpiration > expiration);
expiration = newExpiration;
}
/// if the timeout is reached without the recipient closing the channel,
/// then the Ether is released back to the sender.
function claimTimeout() public {
require(now >= expiration);
selfdestruct(sender);
}
/// All functions below this are just taken from the chapter
/// 'creating and verifying signatures' chapter.
function splitSignature(bytes sig)
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(sig.length == 65);
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function recoverSigner(bytes32 message, bytes sig)
internal
pure
returns (address)
{
(uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
/// builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
/*Problem Statement #1
Write a Roulette Contract, which will implement following features:
• At max, 5 players can involve in one game.
• Each player will choose a number in range of 0-4
• One number can be selected by only one player and one player can select only one number.
• While choosing a number, player will put some ETH in it. (MIN: 0.5 ETH, MAX: 5ETH)
• As soon fifth player provides the choice of numbe, roulette will spin to find a random number.
(To find random number, use : previous_block_number % 5 )
• Winner (as per random number calculation) will get all ETH inserted by players
*/
pragma solidity ^0.4.24;
contract Roulette {
uint public numplayers;
uint public winningNumber;
mapping (uint => address) guessXplayer;
mapping (address=>uint) playerXguess;
event NewEntry( uint indexed numplayers,
address indexed playeradd,
uint indexed num
);
function guessNumber(uint _num)
public
payable
{
if(_num == 0){
_num = 5;
}
require(_num >=0 && _num <=5,"please enter a valid number");
require(numplayers <= 5,"roulette already full");
require(msg.value >= 0.5 ether && msg.value <= 5 ether, "enter valid amount");
require(playerXguess[msg.sender]==0,"user already exist");
require(guessXplayer[_num] == 0x0000000000000000000000000000000000000000,"number already taken");
guessXplayer[_num] = msg.sender;
playerXguess[msg.sender] = _num;
emit NewEntry(numplayers,msg.sender,_num);
numplayers++;
if(numplayers == 5){
randomnumber();
}
}
function randomnumber()
internal {
winningNumber = (block.number-1)%5;
if (winningNumber == 0 ) {
winningNumber = 5;
}
address winner = guessXplayer[winningNumber];
require(winner.send(address(this).balance));
}
}
contract test {
enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
ActionChoices choice;
ActionChoices constant defaultChoice = ActionChoices.GoStraight;
function setGoStraight() public {
choice = ActionChoices.GoRight;
}
// Since enum types are not part of the ABI, the signature of "getChoice"
// will automatically be changed to "getChoice() returns (uint8)"
// for all matters external to Solidity. The integer type used is just
// large enough to hold all enum values, i.e. if you have more than 256 values,
// `uint16` will be used and so on.
function getChoice() public view returns (ActionChoices) {
return choice;
}
function getDefaultChoice() public pure returns (uint) {
return uint(defaultChoice);
}
}
contract Lottery{
uint tickets;
uint price=1000 wei;
address owner;
address winner;
address[] public allholders;
uint[] public allguess;
//uint public winningNumber;
uint public count=0;
address[] public winners;
uint public w;
//bytes random= keccak256(abi.encode("0x12133"));
uint public Total = this.balance;
mapping (uint => address) public holders;
modifier onlyowner(){
require(msg.sender==owner);
_;
}
modifier notowner(){
require(msg.sender!=owner);
_;
}
constructor() public{
owner=msg.sender;
//w= winningNumber;
//bytes32 winninghash= keccak256(abi.encode(winninghash));
}
function makeGuess(uint guess) notowner public payable returns(string){
require(msg.value == price);
require(guess<=250);
allholders.push(msg.sender);
holders[guess]= msg.sender;
allguess.push(guess);
Total=Total + msg.value;
return "congrats";
}
function drawwinner() public onlyowner returns(address[]) {
w=uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
for(uint i=0;i<allholders.length;i++){
if(w==allguess[i] ){
winners.push(allholders[i]);
count++;
}
}
return winners;
}
function distributeReward() onlyowner {
if(count == 0){
selfdestruct(owner);
}
uint winnerreward= this.balance/count;
for(uint j=0;j<winners.length;j++){
winners[j].transfer(winnerreward);
}
selfdestruct(owner);
}
/*
function random() private view returns (uint8) {
return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
}*/
}
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/math/Math.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/ISecurityToken.sol";
import "../interfaces/IModule.sol";
import "../interfaces/IModuleFactory.sol";
import "../interfaces/IModuleRegistry.sol";
import "../interfaces/IST20.sol";
import "../modules/TransferManager/ITransferManager.sol";
import "../modules/PermissionManager/IPermissionManager.sol";
import "../interfaces/ITokenBurner.sol";
import "../RegistryUpdater.sol";
import "openzeppelin-solidity/contracts/ReentrancyGuard.sol";
/**
* @title Security Token contract
* @notice SecurityToken is an ERC20 token with added capabilities:
* @notice - Implements the ST-20 Interface
* @notice - Transfers are restricted
* @notice - Modules can be attached to it to control its behaviour
* @notice - ST should not be deployed directly, but rather the SecurityTokenRegistry should be used
*/
contract SecurityToken is ISecurityToken, ReentrancyGuard, RegistryUpdater {
using SafeMath for uint256;
bytes32 public constant securityTokenVersion = "0.0.1";
// Reference to token burner contract
ITokenBurner public tokenBurner;
// Use to halt all the transactions
bool public freeze = false;
struct ModuleData {
bytes32 name;
address moduleAddress;
}
// Structures to maintain checkpoints of balances for governance / dividends
struct Checkpoint {
uint256 checkpointId;
uint256 value;
}
mapping (address => Checkpoint[]) public checkpointBalances;
Checkpoint[] public checkpointTotalSupply;
bool public finishedIssuerMinting = false;
bool public finishedSTOMinting = false;
mapping (bytes4 => bool) transferFunctions;
// Module list should be order agnostic!
mapping (uint8 => ModuleData[]) public modules;
uint8 public constant MAX_MODULES = 20;
mapping (address => bool) public investorListed;
// Emit at the time when module get added
event LogModuleAdded(
uint8 indexed _type,
bytes32 _name,
address _moduleFactory,
address _module,
uint256 _moduleCost,
uint256 _budget,
uint256 _timestamp
);
// Emit when the token details get updated
event LogUpdateTokenDetails(string _oldDetails, string _newDetails);
// Emit when the granularity get changed
event LogGranularityChanged(uint256 _oldGranularity, uint256 _newGranularity);
// Emit when Module get removed from the securityToken
event LogModuleRemoved(uint8 indexed _type, address _module, uint256 _timestamp);
// Emit when the budget allocated to a module is changed
event LogModuleBudgetChanged(uint8 indexed _moduleType, address _module, uint256 _budget);
// Emit when all the transfers get freeze
event LogFreezeTransfers(bool _freeze, uint256 _timestamp);
// Emit when new checkpoint created
event LogCheckpointCreated(uint256 indexed _checkpointId, uint256 _timestamp);
// Emit when the minting get finished for the Issuer
event LogFinishMintingIssuer(uint256 _timestamp);
// Emit when the minting get finished for the STOs
event LogFinishMintingSTO(uint256 _timestamp);
// Change the STR address in the event of a upgrade
event LogChangeSTRAddress(address indexed _oldAddress, address indexed _newAddress);
// If _fallback is true, then for STO module type we only allow the module if it is set, if it is not set we only allow the owner
// for other _moduleType we allow both issuer and module.
modifier onlyModule(uint8 _moduleType, bool _fallback) {
//Loop over all modules of type _moduleType
bool isModuleType = false;
for (uint8 i = 0; i < modules[_moduleType].length; i++) {
isModuleType = isModuleType || (modules[_moduleType][i].moduleAddress == msg.sender);
}
if (_fallback && !isModuleType) {
if (_moduleType == STO_KEY)
require(modules[_moduleType].length == 0 && msg.sender == owner, "Sender is not owner or STO module is attached");
else
require(msg.sender == owner, "Sender is not owner");
} else {
require(isModuleType, "Sender is not correct module type");
}
_;
}
modifier checkGranularity(uint256 _amount) {
require(_amount % granularity == 0, "Unable to modify token balances at this granularity");
_;
}
// Checks whether the minting is allowed or not, check for the owner if owner is no the msg.sender then check
// for the finishedSTOMinting flag because only STOs and owner are allowed for minting
modifier isMintingAllowed() {
if (msg.sender == owner) {
require(!finishedIssuerMinting, "Minting is finished for Issuer");
} else {
require(!finishedSTOMinting, "Minting is finished for STOs");
}
_;
}
/**
* @notice Constructor
* @param _name Name of the SecurityToken
* @param _symbol Symbol of the Token
* @param _decimals Decimals for the securityToken
* @param _granularity granular level of the token
* @param _tokenDetails Details of the token that are stored off-chain (IPFS hash)
* @param _polymathRegistry Contract address of the polymath registry
*/
constructor (
string _name,
string _symbol,
uint8 _decimals,
uint256 _granularity,
string _tokenDetails,
address _polymathRegistry
)
public
DetailedERC20(_name, _symbol, _decimals)
RegistryUpdater(_polymathRegistry)
{
//When it is created, the owner is the STR
updateFromRegistry();
tokenDetails = _tokenDetails;
granularity = _granularity;
transferFunctions[bytes4(keccak256("transfer(address,uint256)"))] = true;
transferFunctions[bytes4(keccak256("transferFrom(address,address,uint256)"))] = true;
transferFunctions[bytes4(keccak256("mint(address,uint256)"))] = true;
transferFunctions[bytes4(keccak256("burn(uint256)"))] = true;
}
/**
* @notice Function used to attach the module in security token
* @param _moduleFactory Contract address of the module factory that needs to be attached
* @param _data Data used for the intialization of the module factory variables
* @param _maxCost Maximum cost of the Module factory
* @param _budget Budget of the Module factory
*/
function addModule(
address _moduleFactory,
bytes _data,
uint256 _maxCost,
uint256 _budget
) external onlyOwner nonReentrant {
_addModule(_moduleFactory, _data, _maxCost, _budget);
}
/**
* @notice _addModule handles the attachment (or replacement) of modules for the ST
* @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it
* @dev to control restrictions on transfers.
* @dev You are allowed to add a new moduleType if:
* @dev - there is no existing module of that type yet added
* @dev - the last member of the module list is replacable
* @param _moduleFactory is the address of the module factory to be added
* @param _data is data packed into bytes used to further configure the module (See STO usage)
* @param _maxCost max amount of POLY willing to pay to module. (WIP)
*/
function _addModule(address _moduleFactory, bytes _data, uint256 _maxCost, uint256 _budget) internal {
//Check that module exists in registry - will throw otherwise
IModuleRegistry(moduleRegistry).useModule(_moduleFactory);
IModuleFactory moduleFactory = IModuleFactory(_moduleFactory);
uint8 moduleType = moduleFactory.getType();
require(modules[moduleType].length < MAX_MODULES, "Limit of MAX MODULES is reached");
uint256 moduleCost = moduleFactory.setupCost();
require(moduleCost <= _maxCost, "Max Cost is always be greater than module cost");
//Approve fee for module
require(ERC20(polyToken).approve(_moduleFactory, moduleCost), "Not able to approve the module cost");
//Creates instance of module from factory
address module = moduleFactory.deploy(_data);
//Approve ongoing budget
require(ERC20(polyToken).approve(module, _budget), "Not able to approve the budget");
//Add to SecurityToken module map
bytes32 moduleName = moduleFactory.getName();
modules[moduleType].push(ModuleData(moduleName, module));
//Emit log event
emit LogModuleAdded(moduleType, moduleName, _moduleFactory, module, moduleCost, _budget, now);
}
/**
* @notice Removes a module attached to the SecurityToken
* @param _moduleType is which type of module we are trying to remove
* @param _moduleIndex is the index of the module within the chosen type
*/
function removeModule(uint8 _moduleType, uint8 _moduleIndex) external onlyOwner {
require(_moduleIndex < modules[_moduleType].length,
"Module index doesn't exist as per the choosen module type");
require(modules[_moduleType][_moduleIndex].moduleAddress != address(0),
"Module contract address should not be 0x");
//Take the last member of the list, and replace _moduleIndex with this, then shorten the list by one
emit LogModuleRemoved(_moduleType, modules[_moduleType][_moduleIndex].moduleAddress, now);
modules[_moduleType][_moduleIndex] = modules[_moduleType][modules[_moduleType].length - 1];
modules[_moduleType].length = modules[_moduleType].length - 1;
}
/**
* @notice Returns module list for a module type
* @param _moduleType is which type of module we are trying to get
* @param _moduleIndex is the index of the module within the chosen type
* @return bytes32
* @return address
*/
function getModule(uint8 _moduleType, uint _moduleIndex) public view returns (bytes32, address) {
if (modules[_moduleType].length > 0) {
return (
modules[_moduleType][_moduleIndex].name,
modules[_moduleType][_moduleIndex].moduleAddress
);
} else {
return ("", address(0));
}
}
/**
* @notice returns module list for a module name - will return first match
* @param _moduleType is which type of module we are trying to get
* @param _name is the name of the module within the chosen type
* @return bytes32
* @return address
*/
function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address) {
if (modules[_moduleType].length > 0) {
for (uint256 i = 0; i < modules[_moduleType].length; i++) {
if (modules[_moduleType][i].name == _name) {
return (
modules[_moduleType][i].name,
modules[_moduleType][i].moduleAddress
);
}
}
return ("", address(0));
} else {
return ("", address(0));
}
}
/**
* @notice allows the owner to withdraw unspent POLY stored by them on the ST.
* @dev Owner can transfer POLY to the ST which will be used to pay for modules that require a POLY fee.
* @param _amount amount of POLY to withdraw
*/
function withdrawPoly(uint256 _amount) public onlyOwner {
require(ERC20(polyToken).transfer(owner, _amount), "In-sufficient balance");
}
/**
* @notice allows owner to approve more POLY to one of the modules
* @param _moduleType module type
* @param _moduleIndex module index
* @param _budget new budget
*/
function changeModuleBudget(uint8 _moduleType, uint8 _moduleIndex, uint256 _budget) public onlyOwner {
require(_moduleType != 0, "Module type cannot be zero");
require(_moduleIndex < modules[_moduleType].length, "Incorrrect module index");
uint256 _currentAllowance = IERC20(polyToken).allowance(address(this), modules[_moduleType][_moduleIndex].moduleAddress);
if (_budget < _currentAllowance) {
require(IERC20(polyToken).decreaseApproval(modules[_moduleType][_moduleIndex].moduleAddress, _currentAllowance.sub(_budget)), "Insufficient balance to decreaseApproval");
} else {
require(IERC20(polyToken).increaseApproval(modules[_moduleType][_moduleIndex].moduleAddress, _budget.sub(_currentAllowance)), "Insufficient balance to increaseApproval");
}
emit LogModuleBudgetChanged(_moduleType, modules[_moduleType][_moduleIndex].moduleAddress, _budget);
}
/**
* @notice change the tokenDetails
* @param _newTokenDetails New token details
*/
function updateTokenDetails(string _newTokenDetails) public onlyOwner {
emit LogUpdateTokenDetails(tokenDetails, _newTokenDetails);
tokenDetails = _newTokenDetails;
}
/**
* @notice allows owner to change token granularity
* @param _granularity granularity level of the token
*/
function changeGranularity(uint256 _granularity) public onlyOwner {
require(_granularity != 0, "Granularity can not be 0");
emit LogGranularityChanged(granularity, _granularity);
granularity = _granularity;
}
/**
* @notice keeps track of the number of non-zero token holders
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
*/
function adjustInvestorCount(address _from, address _to, uint256 _value) internal {
if ((_value == 0) || (_from == _to)) {
return;
}
// Check whether receiver is a new token holder
if ((balanceOf(_to) == 0) && (_to != address(0))) {
investorCount = investorCount.add(1);
}
// Check whether sender is moving all of their tokens
if (_value == balanceOf(_from)) {
investorCount = investorCount.sub(1);
}
//Also adjust investor list
if (!investorListed[_to] && (_to != address(0))) {
investors.push(_to);
investorListed[_to] = true;
}
}
/**
* @notice removes addresses with zero balances from the investors list
* @param _start Index in investor list at which to start removing zero balances
* @param _iters Max number of iterations of the for loop
* NB - pruning this list will mean you may not be able to iterate over investors on-chain as of a historical checkpoint
*/
function pruneInvestors(uint256 _start, uint256 _iters) public onlyOwner {
for (uint256 i = _start; i < Math.min256(_start.add(_iters), investors.length); i++) {
if ((i < investors.length) && (balanceOf(investors[i]) == 0)) {
investorListed[investors[i]] = false;
investors[i] = investors[investors.length - 1];
investors.length--;
}
}
}
/**
* @notice gets length of investors array
* NB - this length may differ from investorCount if list has not been pruned of zero balance investors
* @return length
*/
function getInvestorsLength() public view returns(uint256) {
return investors.length;
}
/**
* @notice freeze all the transfers
*/
function freezeTransfers() public onlyOwner {
require(!freeze);
freeze = true;
emit LogFreezeTransfers(freeze, now);
}
/**
* @notice un-freeze all the transfers
*/
function unfreezeTransfers() public onlyOwner {
require(freeze);
freeze = false;
emit LogFreezeTransfers(freeze, now);
}
/**
* @notice adjust totalsupply at checkpoint after minting or burning tokens
*/
function adjustTotalSupplyCheckpoints() internal {
adjustCheckpoints(checkpointTotalSupply, totalSupply());
}
/**
* @notice adjust token holder balance at checkpoint after a token transfer
* @param _investor address of the token holder affected
*/
function adjustBalanceCheckpoints(address _investor) internal {
adjustCheckpoints(checkpointBalances[_investor], balanceOf(_investor));
}
/**
* @notice store the changes to the checkpoint objects
* @param _checkpoints the affected checkpoint object array
* @param _newValue the new value that needs to be stored
*/
function adjustCheckpoints(Checkpoint[] storage _checkpoints, uint256 _newValue) internal {
//No checkpoints set yet
if (currentCheckpointId == 0) {
return;
}
//No previous checkpoint data - add current balance against checkpoint
if (_checkpoints.length == 0) {
_checkpoints.push(
Checkpoint({
checkpointId: currentCheckpointId,
value: _newValue
})
);
return;
}
//No new checkpoints since last update
if (_checkpoints[_checkpoints.length - 1].checkpointId == currentCheckpointId) {
return;
}
//New checkpoint, so record balance
_checkpoints.push(
Checkpoint({
checkpointId: currentCheckpointId,
value: _newValue
})
);
}
/**
* @notice Overloaded version of the transfer function
* @param _to receiver of transfer
* @param _value value of transfer
* @return bool success
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
adjustInvestorCount(msg.sender, _to, _value);
require(verifyTransfer(msg.sender, _to, _value), "Transfer is not valid");
adjustBalanceCheckpoints(msg.sender);
adjustBalanceCheckpoints(_to);
require(super.transfer(_to, _value));
return true;
}
/**
* @notice Overloaded version of the transferFrom function
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
* @return bool success
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
adjustInvestorCount(_from, _to, _value);
require(verifyTransfer(_from, _to, _value), "Transfer is not valid");
adjustBalanceCheckpoints(_from);
adjustBalanceCheckpoints(_to);
require(super.transferFrom(_from, _to, _value));
return true;
}
/**
* @notice validate transfer with TransferManager module if it exists
* @dev TransferManager module has a key of 2
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _amount value of transfer
* @return bool
*/
function verifyTransfer(address _from, address _to, uint256 _amount) public checkGranularity(_amount) returns (bool) {
if (!freeze) {
bool isTransfer = false;
if (transferFunctions[getSig(msg.data)]) {
isTransfer = true;
}
if (modules[TRANSFERMANAGER_KEY].length == 0) {
return true;
}
bool isInvalid = false;
bool isValid = false;
bool isForceValid = false;
for (uint8 i = 0; i < modules[TRANSFERMANAGER_KEY].length; i++) {
ITransferManager.Result valid = ITransferManager(modules[TRANSFERMANAGER_KEY][i].moduleAddress).verifyTransfer(_from, _to, _amount, isTransfer);
if (valid == ITransferManager.Result.INVALID) {
isInvalid = true;
}
if (valid == ITransferManager.Result.VALID) {
isValid = true;
}
if (valid == ITransferManager.Result.FORCE_VALID) {
isForceValid = true;
}
}
return isForceValid ? true : (isInvalid ? false : isValid);
}
return false;
}
/**
* @notice End token minting period permanently for Issuer
*/
function finishMintingIssuer() public onlyOwner {
finishedIssuerMinting = true;
emit LogFinishMintingIssuer(now);
}
/**
* @notice End token minting period permanently for STOs
*/
function finishMintingSTO() public onlyOwner {
finishedSTOMinting = true;
emit LogFinishMintingSTO(now);
}
/**
* @notice mints new tokens and assigns them to the target _investor.
* @dev Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet)
* @param _investor Address to whom the minted tokens will be dilivered
* @param _amount Number of tokens get minted
* @return success
*/
function mint(address _investor, uint256 _amount) public onlyModule(STO_KEY, true) checkGranularity(_amount) isMintingAllowed() returns (bool success) {
require(_investor != address(0), "Investor address should not be 0x");
adjustInvestorCount(address(0), _investor, _amount);
require(verifyTransfer(address(0), _investor, _amount), "Transfer is not valid");
adjustBalanceCheckpoints(_investor);
adjustTotalSupplyCheckpoints();
totalSupply_ = totalSupply_.add(_amount);
balances[_investor] = balances[_investor].add(_amount);
emit Minted(_investor, _amount);
emit Transfer(address(0), _investor, _amount);
return true;
}
/**
* @notice mints new tokens and assigns them to the target _investor.
* Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet)
* @param _investors A list of addresses to whom the minted tokens will be dilivered
* @param _amounts A list of number of tokens get minted and transfer to corresponding address of the investor from _investor[] list
* @return success
*/
function mintMulti(address[] _investors, uint256[] _amounts) public onlyModule(STO_KEY, true) returns (bool success) {
require(_investors.length == _amounts.length, "Mis-match in the length of the arrays");
for (uint256 i = 0; i < _investors.length; i++) {
mint(_investors[i], _amounts[i]);
}
return true;
}
/**
* @notice Validate permissions with PermissionManager if it exists, If no Permission return false
* @dev Note that IModule withPerm will allow ST owner all permissions anyway
* @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
* @param _delegate address of delegate
* @param _module address of PermissionManager module
* @param _perm the permissions
* @return success
*/
function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) {
if (modules[PERMISSIONMANAGER_KEY].length == 0) {
return false;
}
for (uint8 i = 0; i < modules[PERMISSIONMANAGER_KEY].length; i++) {
if (IPermissionManager(modules[PERMISSIONMANAGER_KEY][i].moduleAddress).checkPermission(_delegate, _module, _perm)) {
return true;
}
}
}
/**
* @notice used to set the token Burner address. It only be called by the owner
* @param _tokenBurner Address of the token burner contract
*/
function setTokenBurner(address _tokenBurner) public onlyOwner {
tokenBurner = ITokenBurner(_tokenBurner);
}
/**
* @notice Burn function used to burn the securityToken
* @param _value No. of token that get burned
*/
function burn(uint256 _value) checkGranularity(_value) public {
adjustInvestorCount(msg.sender, address(0), _value);
require(tokenBurner != address(0), "Token Burner contract address is not set yet");
require(verifyTransfer(msg.sender, address(0), _value), "Transfer is not valid");
require(_value <= balances[msg.sender], "Value should no be greater than the balance of msg.sender");
adjustBalanceCheckpoints(msg.sender);
adjustTotalSupplyCheckpoints();
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[msg.sender] = balances[msg.sender].sub(_value);
require(tokenBurner.burn(msg.sender, _value), "Token burner process is not validated");
totalSupply_ = totalSupply_.sub(_value);
emit Burnt(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
/**
* @notice Get function signature from _data
* @param _data passed data
* @return bytes4 sig
*/
function getSig(bytes _data) internal pure returns (bytes4 sig) {
uint len = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < len; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i))));
}
}
/**
* @notice Creates a checkpoint that can be used to query historical balances / totalSuppy
* @return uint256
*/
function createCheckpoint() public onlyModule(CHECKPOINT_KEY, true) returns(uint256) {
require(currentCheckpointId < 2**256 - 1);
currentCheckpointId = currentCheckpointId + 1;
emit LogCheckpointCreated(currentCheckpointId, now);
return currentCheckpointId;
}
/**
* @notice Queries totalSupply as of a defined checkpoint
* @param _checkpointId Checkpoint ID to query
* @return uint256
*/
function totalSupplyAt(uint256 _checkpointId) public view returns(uint256) {
return getValueAt(checkpointTotalSupply, _checkpointId, totalSupply());
}
/**
* @notice Queries value at a defined checkpoint
* @param checkpoints is array of Checkpoint objects
* @param _checkpointId Checkpoint ID to query
* @param _currentValue Current value of checkpoint
* @return uint256
*/
function getValueAt(Checkpoint[] storage checkpoints, uint256 _checkpointId, uint256 _currentValue) internal view returns(uint256) {
require(_checkpointId <= currentCheckpointId);
//Checkpoint id 0 is when the token is first created - everyone has a zero balance
if (_checkpointId == 0) {
return 0;
}
if (checkpoints.length == 0) {
return _currentValue;
}
if (checkpoints[0].checkpointId >= _checkpointId) {
return checkpoints[0].value;
}
if (checkpoints[checkpoints.length - 1].checkpointId < _checkpointId) {
return _currentValue;
}
if (checkpoints[checkpoints.length - 1].checkpointId == _checkpointId) {
return checkpoints[checkpoints.length - 1].value;
}
uint256 min = 0;
uint256 max = checkpoints.length - 1;
while (max > min) {
uint256 mid = (max + min) / 2;
if (checkpoints[mid].checkpointId == _checkpointId) {
max = mid;
break;
}
if (checkpoints[mid].checkpointId < _checkpointId) {
min = mid + 1;
} else {
max = mid;
}
}
return checkpoints[max].value;
}
/**
* @notice Queries balances as of a defined checkpoint
* @param _investor Investor to query balance for
* @param _checkpointId Checkpoint ID to query as of
*/
function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256) {
return getValueAt(checkpointBalances[_investor], _checkpointId, balanceOf(_investor));
}
}
pragma solidity ^0.4.22;
//import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
contract MyToken {
address owner;
string public standard = 'Token 0.1';
string public name="Rose";
string public symbol="ROS";
uint8 public decimals=18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
constructor(
//uint256 initialSupply,
//string tokenName,
//uint8 decimalUnits,
//string tokenSymbol
) public{
owner=msg.sender;
uint256 initialSupply=250;
//string tokenName;
// uint8 decimalUnits;
// string tokenSymbol;
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
// name = tokenName; // Set the name for display purposes
//symbol = tokenSymbol; // Set the symbol for display purposes
//decimals = decimalUnits; // Amount of decimals for display purposes
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
}
contract Lottery is MyToken{
uint tickets;
uint price=1 ether;
address winner;
address[] allholders;
uint[] allguess;
//uint public winningNumber;
uint count=0;
address[] public winners;
uint w;
//bytes random= keccak256(abi.encode("0x12133"));
mapping (uint => address) public holders;
modifier onlyowner(){
require(msg.sender==owner);
_;
}
modifier notowner(){
require(msg.sender!=owner);
_;
}
constructor() public{
owner=msg.sender;
//w= winningNumber;
//bytes32 winninghash= keccak256(abi.encode(winninghash));
}
function gettoken(uint token) public payable{
if(msg.value == token * price){
transfer(msg.sender,token);
//approve(msg.sender,token);
}
}
function makeGuess(uint guess) notowner public returns(bytes32){
transfer(owner,1);
require(guess<=250);
allholders.push(msg.sender);
holders[guess]= msg.sender;
allguess.push(guess);
bytes32 guesshash= keccak256(abi.encode(guess));
return guesshash;
}
function drawwinner() public onlyowner returns(address[]) {
w=uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
for(uint i=0;i<allholders.length;i++){
if(w==allguess[i] ){
winners.push(allholders[i]);
count++;
}
}
return winners;
}
function distributeReward() onlyowner {
if(count==0){
selfdestruct(owner);
}
uint winnerreward= this.balance/count;
for(uint j=0;j<winners.length;j++){
winners[j].transfer(winnerreward);
}
selfdestruct(owner);
}
/*
function random() private view returns (uint8) {
return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
}*/
}
/*
contract randomNumber is usingOraclize {
uint public result;
bytes32 public oraclizeID;
function flipCoin() payable {
oraclizeID = oraclize_query("WolframAlpha", "flip a coin");
}
function __callback(bytes32 _oraclizeID, uint _result) {
if(msg.sender != oraclize_cbAddress()) throw;
result = _result;
}
}*/
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 4;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
// to add a check for total number of participants and
//owner cannot draw a winner while participant has made a guess and tx is pending
contract Lottery is TokenERC20{
address owner;
// address public winner;
address[] public allholders;
address[] public winners;
uint price=1000000 wei;
uint[] public allguess;
uint count=0;
uint public LuckyNumber;
uint public Total;
uint public playerID = 0;
//uint round = 3 minutes;
//uint startround = now + round;
bool public winnerDrawn = false;
bool public active = true;
//-----------------------------------------Mappings----------------------------------------
mapping (uint => address) public holders; // PlayerID => participant_address
mapping (address => uint) public Guesses; //participant_address => guess
mapping (address => uint) public TokenHolders;
//-----------------------------------------Events----------------------------------------
event Guess(
address indexed from,
uint indexed PlayerID,
uint indexed _guess,
uint value
);
event TokenBought(
address seller,
address buyer,
uint _amount
);
//-----------------------------------------Modifiers------------------------------------
modifier onlyowner(){
require(msg.sender==owner);
_;
}
modifier notowner(){
require(msg.sender!=owner);
_;
}
modifier alreadyDrawn(){
require(!winnerDrawn);
_;
}
modifier LotteryActive{
require(active==true);
_;
}
//------------------------------------constructor----------------------------------------------------
//
//------------------------------------Public Functions----------------------------------------------------
function getToken( uint amount)
notowner
public
payable{
require(msg.value == price);
require(amount == 1);
_transfer(owner,msg.sender,amount);
TokenHolders[msg.sender] += amount;
emit TokenBought(owner,msg.sender,amount);
}
function PayToken()
public
returns (bool)
{
require(TokenHolders[msg.sender] >= 1 );
_transfer(msg.sender,this,1);
TokenHolders[msg.sender] -= 1;
return true;
}
function makeGuess(uint guess)
notowner
LotteryActive
public
payable
returns(bool){
require(guess != 0x20);
require(guess<=20);
require(msg.value == price);
allholders.push(msg.sender);
holders[playerID]= msg.sender;
emit Guess(msg.sender,playerID,guess,msg.value);
playerID++;
allguess.push(guess);
Guesses[msg.sender]= guess;
Total=Total + msg.value;
return true;
}
function drawwinner()
public
onlyowner
alreadyDrawn
returns(address[]) {
LuckyNumber=uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%21);
for(uint i=0;i<allholders.length;i++){
if( LuckyNumber==allguess[i] ){
winners.push(allholders[i]);
count++;
}
}
winnerDrawn=true;
return winners;
}
function distributeReward()
onlyowner
LotteryActive
internal
{
if(count == 0){
//selfdestruct(owner);
owner.transfer(address(this).balance);
DeleteAll();
return;
}
uint winnerreward= (address(this).balance/2)/count;
for(uint j=0;j<winners.length;j++){
winners[j].transfer(winnerreward);
}
owner.transfer(address(this).balance);
DeleteAll();
return;
}
//-----------------------------------------Delete all variables to play next round-----------------------------
function DeleteAll()
onlyowner
internal
{
winnerDrawn = false;
active = true;
delete LuckyNumber;
delete Total;
delete allholders;
delete count;
delete winners;
delete allguess;
delete Total;
delete playerID;
}
}
pragma solidity ^0.4.22;
//import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
contract MyToken {
string public standard = 'Token 0.1';
string public name="Rose";
string public symbol="ROS";
uint8 public decimals=18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
constructor(
//uint256 initialSupply,
//string tokenName,
//uint8 decimalUnits,
//string tokenSymbol
)
public
{
uint256 initialSupply=250;
//string tokenName;
// uint8 decimalUnits;
// string tokenSymbol;
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
// name = tokenName; // Set the name for display purposes
//symbol = tokenSymbol; // Set the symbol for display purposes
//decimals = decimalUnits; // Amount of decimals for display purposes
}
/* Send coins */
function transfer(address _to, uint256 _value) public {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
}
contract Lottery is MyToken{
uint tickets;
uint price=1 ether;
address owner;
address winner;
address[] allholders;
uint[] allguess;
//uint public winningNumber;
uint count=0;
address[] public winners;
uint w;
//bytes random= keccak256(abi.encode("0x12133"));
mapping (uint => address) public holders;
modifier onlyowner(){
require(msg.sender==owner);
_;
}
modifier notowner(){
require(msg.sender!=owner);
_;
}
constructor() public{
owner=msg.sender;
//w= winningNumber;
//bytes32 winninghash= keccak256(abi.encode(winninghash));
}
function makeGuess(uint guess) notowner public payable returns(bytes32){
require(msg.value == price);
require(guess<=250);
allholders.push(msg.sender);
holders[guess]= msg.sender;
allguess.push(guess);
bytes32 guesshash= keccak256(abi.encode(guess));
return guesshash;
}
function drawwinner() public onlyowner returns(address[]) {
w=uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
for(uint i=0;i<allholders.length;i++){
if(w==allguess[i] ){
winners.push(allholders[i]);
count++;
}
}
return winners;
}
function distributeReward() onlyowner {
if(count==0){
selfdestruct(owner);
}
uint winnerreward= this.balance/count;
for(uint j=0;j<winners.length;j++){
winners[j].transfer(winnerreward);
}
selfdestruct(owner);
}
/*
function random() private view returns (uint8) {
return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%251);
}*/
}
/*
contract randomNumber is usingOraclize {
uint public result;
bytes32 public oraclizeID;
function flipCoin() payable {
oraclizeID = oraclize_query("WolframAlpha", "flip a coin");
}
function __callback(bytes32 _oraclizeID, uint _result) {
if(msg.sender != oraclize_cbAddress()) throw;
result = _result;
}
}*/
pragma solidity ^0.4.8;
contract MyToken {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name="Rose";
string public symbol="ROS";
uint8 public decimals=18;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MyToken(
/*uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
*/) {
uint256 initialSupply=10000000 * 1 wei;
//string tokenName;
// uint8 decimalUnits;
// string tokenSymbol;
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
// name = tokenName; // Set the name for display purposes
//symbol = tokenSymbol; // Set the symbol for display purposes
//decimals = decimalUnits; // Amount of decimals for display purposes
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
}
pragma solidity ^0.4.22;
contract Purchase {
uint public value;
address public seller;
address public buyer;
enum State { Created, Locked, Inactive }
State public state;
// Ensure that `msg.value` is an even number.
// Division will truncate if it is an odd number.
// Check via multiplication that it wasn't an odd number.
constructor() public payable {
seller = msg.sender;
value = msg.value / 2;
require((2 * value) == msg.value, "Value has to be even.");
}
modifier condition(bool _condition) {
require(_condition);
_;
}
modifier onlyBuyer() {
require(
msg.sender == buyer,
"Only buyer can call this."
);
_;
}
modifier onlySeller() {
require(
msg.sender == seller,
"Only seller can call this."
);
_;
}
modifier inState(State _state) {
require(
state == _state,
"Invalid state."
);
_;
}
event Aborted();
event PurchaseConfirmed();
event ItemReceived();
/// Abort the purchase and reclaim the ether.
/// Can only be called by the seller before
/// the contract is locked.
function abort()
public
onlySeller
inState(State.Created)
{
emit Aborted();
state = State.Inactive;
seller.transfer(address(this).balance);
}
/// Confirm the purchase as buyer.
/// Transaction has to include `2 * value` ether.
/// The ether will be locked until confirmReceived
/// is called.
function confirmPurchase()
public
inState(State.Created)
condition(msg.value == (2 * value))
payable
{
emit PurchaseConfirmed();
buyer = msg.sender;
state = State.Locked;
}
/// Confirm that you (the buyer) received the item.
/// This will release the locked ether.
function confirmReceived()
public
onlyBuyer
inState(State.Locked)
{
emit ItemReceived();
// It is important to change the state first because
// otherwise, the contracts called using `send` below
// can call in again here.
state = State.Inactive;
// NOTE: This actually allows both the buyer and the seller to
// block the refund - the withdraw pattern should be used.
buyer.transfer(value);
seller.transfer(address(this).balance);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment