source_codes
stringlengths
3
205k
labels
int64
0
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 29116800; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xFD808d285a0594082b108eDD90bBC328B5bc9661; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.25; contract SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Token { function totalSupply() public constant returns (uint256 supply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract AbstractToken is Token, SafeMath { constructor () public { } function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts [_owner]; } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true; } function approve (address _spender, uint256 _value) public returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowances [_owner][_spender]; } mapping (address => uint256) accounts; mapping (address => mapping (address => uint256)) private allowances; } contract SOMAToken is AbstractToken { uint256 constant MAX_TOKEN_COUNT = 200000000 * (10**18); address private owner; mapping (address => bool) private frozenAccount; uint256 tokenCount = 0; bool frozen = false; constructor () public { owner = msg.sender; } function totalSupply() public constant returns (uint256 supply) { return tokenCount; } string constant public name = "Soma"; string constant public symbol = "SOMA"; uint8 constant public decimals = 18; function transfer(address _to, uint256 _value) public returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } function approve (address _spender, uint256 _value) public returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } function createTokens(uint256 _value) public returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); emit Transfer(0x0, msg.sender, _value); return true; } return false; } function setOwner(address _newOwner) public { require (msg.sender == owner); owner = _newOwner; } function freezeTransfers () public { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } function unfreezeTransfers () public { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } function refundTokens(address _token, address _refund, uint256 _value) public { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } function freezeAccount(address _target, bool freeze) public { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } event Freeze (); event Unfreeze (); event FrozenFunds(address target, bool frozen); event RefundTokens(address _token, address _refund, uint256 _value); }
1
pragma solidity ^0.4.24; contract F3Devents { event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); 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 ); event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract modularShort is F3Devents {} contract FoMo3DLight is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; uint256 public pID_ = 4; address private admin = msg.sender; string constant public name = "FOMO Light"; string constant public symbol = "F4D"; uint256 private rndExtra_ = 1 minutes; uint256 private rndGap_ = 1 minutes; uint256 constant private rndInit_ = 10 minutes; uint256 constant private rndInc_ = 10 seconds; uint256 constant private rndMax_ = 20 minutes; uint256 public airDropPot_; uint256 public airDropTracker_ = 0; uint256 public rID_; mapping (address => uint256) public pIDxAddr_; mapping (bytes32 => uint256) public pIDxName_; mapping (uint256 => F3Ddatasets.Player) public plyr_; mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; mapping (uint256 => F3Ddatasets.Round) public round_; mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; mapping (uint256 => F3Ddatasets.TeamFee) public fees_; mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; constructor() public { fees_[0] = F3Ddatasets.TeamFee(49,2); fees_[1] = F3Ddatasets.TeamFee(49,2); fees_[2] = F3Ddatasets.TeamFee(49,2); fees_[3] = F3Ddatasets.TeamFee(49,2); potSplit_[0] = F3Ddatasets.PotSplit(38,2); potSplit_[1] = F3Ddatasets.PotSplit(38,2); potSplit_[2] = F3Ddatasets.PotSplit(38,2); potSplit_[3] = F3Ddatasets.PotSplit(38,2); } modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } function() isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_; if (determinePID(msg.sender)) { _eventData_.compressedData = _eventData_.compressedData + 1; } uint256 _pID = pIDxAddr_[msg.sender]; buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; return (true); } else { return (false); } } function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_; if (determinePID(msg.sender)) { _eventData_.compressedData = _eventData_.compressedData + 1; } uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID) { _affCode = plyr_[_pID].laff; } else if (_affCode != plyr_[_pID].laff) { plyr_[_pID].laff = _affCode; } _team = verifyTeam(_team); buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_; if (determinePID(msg.sender)) { _eventData_.compressedData = _eventData_.compressedData + 1; } uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender) { _affID = plyr_[_pID].laff; } else { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_; if (determinePID(msg.sender)) { _eventData_.compressedData = _eventData_.compressedData + 1; } uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { _affID = plyr_[_pID].laff; } else { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); buyCore(_pID, _affID, _team, _eventData_); } function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID) { _affCode = plyr_[_pID].laff; } else if (_affCode != plyr_[_pID].laff) { plyr_[_pID].laff = _affCode; } _team = verifyTeam(_team); reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender) { _affID = plyr_[_pID].laff; } else { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { _affID = plyr_[_pID].laff; } else { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; uint256 _now = now; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _eth; if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { F3Ddatasets.EventReturns memory _eventData_; round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; 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 ); } else { _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function getBuyPrice() public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else return ( 75000000000000 ); } function getTimeLeft() public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { uint256 _rID = rID_; if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; return ( round_[_rID].ico, _rID, round_[_rID].keys, round_[_rID].end, round_[_rID].strt, round_[_rID].pot, (round_[_rID].team + (round_[_rID].plyr * 10)), plyr_[round_[_rID].plyr].addr, plyr_[round_[_rID].plyr].name, rndTmEth_[_rID][0], rndTmEth_[_rID][1], rndTmEth_[_rID][2], rndTmEth_[_rID][3], airDropTracker_ + (airDropPot_ * 1000) ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, plyr_[_pID].name, plyrRnds_[_pID][_rID].keys, plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff, plyrRnds_[_pID][_rID].eth ); } function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { core(_rID, _pID, msg.value, _affID, _team, _eventData_); } else { if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); core(_rID, _pID, _eth, _affID, _team, _eventData_); } else if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 2100000000000000000) { uint256 _availableLimit = (2100000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } if (_eth > 1000000000) { uint256 _keys = (round_[_rID].eth).keysRec(_eth); if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; _eventData_.compressedData = _eventData_.compressedData + 100; } if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { uint256 _prize; if (_eth >= 10000000000000000000) { _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 300000000000000000000000000000000; } _eventData_.compressedData += 10000000000000000000000000000000; _eventData_.compressedData += _prize * 1000000000000000000000000000000000; airDropTracker_ = 0; } } _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); endTx(_pID, _team, _eth, _keys, _eventData_); } } function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else return ( (_eth).keys() ); } function iWantXKeys(uint256 _keys) public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else return ( (_keys).eth() ); } function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _rID = rID_; uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; uint256 _pot = round_[_rID].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); 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); } plyr_[_winPID].win = _win.add(plyr_[_winPID].win); admin.transfer(_com.add(_p3d / 2)); round_[_rID].pot = _pot.add(_p3d / 2); round_[_rID].mask = _ppt.add(round_[_rID].mask); _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; rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } function updateTimer(uint256 _keys, uint256 _rID) private { uint256 _now = now; uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } 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); } function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { uint256 _p1 = _eth / 100; uint256 _com = _eth / 50; _com = _com.add(_p1); uint256 _p3d; if (!address(admin).call.value(_com)()) { _p3d = _com; _com = 0; } uint256 _aff = _eth / 10; 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; } _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { uint256 _potAmount = _p3d / 2; admin.transfer(_p3d.sub(_potAmount)); round_[_rID].pot = round_[_rID].pot.add(_potAmount); _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); uint256 _pot = _eth.sub(_gen); uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } function withdrawEarnings(uint256 _pID) private returns(uint256) { updateGenVault(_pID, plyr_[_pID].lrnd); 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); } function endTx(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_ ); } bool public activated_ = false; function activate() public { require(msg.sender == admin); require(activated_ == false); activated_ = true; rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } library F3Ddatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; bytes32 winnerName; uint256 amountWon; uint256 newPot; uint256 P3DAmount; uint256 genAmount; uint256 potAmount; } struct Player { address addr; bytes32 name; uint256 win; uint256 gen; uint256 aff; uint256 lrnd; uint256 laff; } struct PlayerRounds { uint256 eth; uint256 keys; uint256 mask; uint256 ico; } struct Round { uint256 plyr; uint256 team; uint256 end; bool ended; uint256 strt; uint256 keys; uint256 eth; uint256 pot; uint256 mask; uint256 ico; uint256 icoGen; uint256 icoAvg; } struct TeamFee { uint256 gen; uint256 p3d; } struct PotSplit { uint256 gen; uint256 p3d; } } library F3DKeysCalcShort { using SafeMath for *; function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } 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); } library NameFilter { function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } bool _hasNonNumber; for (uint256 i = 0; i < _length; i++) { if (_temp[i] > 0x40 && _temp[i] < 0x5b) { _temp[i] = byte(uint(_temp[i]) + 32); if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( _temp[i] == 0x20 || (_temp[i] > 0x60 && _temp[i] < 0x7b) || (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); 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); } } library SafeMath { 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; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } 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); } } function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } 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); } } }
0
pragma solidity ^0.4.15; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } interface Token { function transfer(address _to, uint256 _value) returns (bool); function balanceOf(address _owner) constant returns (uint256 balance); } contract UVDICO is Ownable { using SafeMath for uint256; Token token; uint256 public constant RATE = 192000; uint256 public constant CAP = 9375; uint256 public constant BONUS = 20; uint256 public constant START = 1525719600; uint256 public constant DAYS = 21; uint256 public constant initialTokens = 1800000000 * 10**18; bool public initialized = false; uint256 public raisedAmount = 0; mapping (address => uint256) buyers; event BoughtTokens(address indexed to, uint256 value); modifier whenSaleIsActive() { assert(isActive()); _; } function UVDICO() { token = Token(0x81401e46e82c2e1da6ba0bc446fc710a147d374f); } function initialize() onlyOwner { require(initialized == false); require(tokensAvailable() == initialTokens); initialized = true; } function isActive() constant returns (bool) { return ( initialized == true && now >= START && now <= START.add(DAYS * 1 days) && goalReached() == false ); } function goalReached() constant returns (bool) { return (raisedAmount >= CAP * 1 ether); } function () payable { buyTokens(); } function buyTokens() payable whenSaleIsActive { uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(RATE); BoughtTokens(msg.sender, tokens); raisedAmount = raisedAmount.add(msg.value); token.transfer(msg.sender, tokens); owner.transfer(msg.value); } function tokensAvailable() constant returns (uint256) { return token.balanceOf(this); } function destroy() onlyOwner { uint256 balance = token.balanceOf(this); assert(balance > 0); token.transfer(owner, balance); selfdestruct(owner); } }
0
pragma solidity ^0.4.4; contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract SVChain is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; function SVChain() { balances[msg.sender] = 5000000e18; totalSupply = 5000000e18; name = "SVChain Token"; decimals = 18; symbol = "SVCO"; unitsOneEthCanBuy = 10000; fundsWallet = msg.sender; } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); fundsWallet.transfer(msg.value); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
1
pragma solidity ^ 0.4 .23; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns(uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract Controlled is Pausable { modifier onlyController { require(msg.sender == controller); _; } modifier onlyControllerorOwner { require((msg.sender == controller) || (msg.sender == owner)); _; } address public controller; constructor() public { controller = msg.sender; } function changeController(address _newController) public onlyControllerorOwner { controller = _newController; } } contract TokenController { function proxyPayment(address _owner) public payable returns(bool); function onTransfer(address _from, address _to, uint _amount) public returns(bool); function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } contract MiniMeToken is Controlled { using SafeMath for uint256; string public name; uint8 public decimals; string public symbol; string public version = 'V 1.0'; struct Checkpoint { uint128 fromBlock; uint128 value; } MiniMeToken public parentToken; uint public parentSnapShotBlock; uint public creationBlock; mapping(address => Checkpoint[]) balances; mapping(address => mapping(address => uint256)) allowed; Checkpoint[] totalSupplyHistory; bool public transfersEnabled; MiniMeTokenFactory public tokenFactory; constructor( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } function transfer(address _to, uint256 _amount) public returns(bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) public returns(bool success) { if (msg.sender != controller) { require(transfersEnabled); require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); } doTransfer(_from, _to, _amount); return true; } function doTransfer(address _from, address _to, uint _amount) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); return; } require((_to != 0) && (_to != address(this))); uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); updateValueAtNow(balances[_from], previousBalanceFrom - _amount); uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo.add(_amount) >= previousBalanceTo); updateValueAtNow(balances[_to], previousBalanceTo.add(_amount)); emit Transfer(_from, _to, _amount); } function balanceOf(address _owner) public constant returns(uint256 balance) { return balanceOfAt(_owner, block.number); } function approve(address _spender, uint256 _amount) public returns(bool success) { require(transfersEnabled); require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) public constant returns(uint256 remaining) { return allowed[_owner][_spender]; } function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns(bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } function totalSupply() public constant returns(uint) { return totalSupplyAt(block.number); } function balanceOfAt(address _owner, uint _blockNumber) public constant returns(uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(balances[_owner], _blockNumber); } } function totalSupplyAt(uint _blockNumber) public constant returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(totalSupplyHistory, _blockNumber); } } function generateTokens(address _owner, uint _amount) public onlyControllerorOwner whenNotPaused returns(bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply.add(_amount) >= curTotalSupply); uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo.add(_amount) >= previousBalanceTo); updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount)); updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount)); emit Transfer(0, _owner, _amount); return true; } function destroyTokens(address _owner, uint _amount) onlyControllerorOwner public returns(bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount)); updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount)); emit Transfer(_owner, 0, _amount); return true; } function enableTransfers(bool _transfersEnabled) public onlyControllerorOwner { transfersEnabled = _transfersEnabled; } function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns(uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) return checkpoints[checkpoints.length.sub(1)].value; if (_block < checkpoints[0].fromBlock) return 0; uint min = 0; uint max = checkpoints.length.sub(1); while (max > min) { uint mid = (max.add(min).add(1)).div(2); if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid.sub(1); } } return checkpoints[min].value; } function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)]; oldCheckPoint.value = uint128(_value); } } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size: = extcodesize(_addr) } return size > 0; } function min(uint a, uint b) pure internal returns(uint) { return a < b ? a : b; } function() public payable { revert(); } function claimTokens(address _token) public onlyControllerorOwner { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } contract ERC20Basic { function totalSupply() public view returns(uint256); function balanceOf(address who) public view returns(uint256); function transfer(address to, uint256 value) public returns(bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } contract EmaToken is MiniMeToken { constructor(address tokenfactory, address parenttoken, uint parentsnapshot, string tokenname, uint8 dec, string tokensymbol, bool transfersenabled) MiniMeToken(tokenfactory, parenttoken, parentsnapshot, tokenname, dec, tokensymbol, transfersenabled) public {} } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns(uint256); function transferFrom(address from, address to, uint256 value) public returns(bool); function approve(address spender, uint256 value) public returns(bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract MiniMeTokenFactory { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns(MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract Crowdsale is Pausable { using SafeMath for uint256; MiniMeToken public token; address public wallet; uint256 public rate = 6120; uint256 public tokensSold; uint256 public allCrowdSaleTokens = 255000000000000000000000000; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event buyx(address buyer, address contractAddr, uint256 amount); constructor(address _wallet, MiniMeToken _token) public { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } function setCrowdsale(address _wallet, MiniMeToken _token) internal { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } function() external whenNotPaused payable { emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } function buyTokens(address _beneficiary) public whenNotPaused payable { if ((msg.value >= 500000000000000000000) && (msg.value < 1000000000000000000000)) { rate = 7140; } else if (msg.value >= 1000000000000000000000) { rate = 7650; } else if (tokensSold <= 21420000000000000000000000) { rate = 6120; } else if ((tokensSold > 21420000000000000000000000) && (tokensSold <= 42304500000000000000000000)) { rate = 5967; } else if ((tokensSold > 42304500000000000000000000) && (tokensSold <= 73095750000000000000000000)) { rate = 5865; } else if ((tokensSold > 73095750000000000000000000) && (tokensSold <= 112365750000000000000000000)) { rate = 5610; } else if ((tokensSold > 112365750000000000000000000) && (tokensSold <= 159222000000000000000000000)) { rate = 5355; } else if (tokensSold > 159222000000000000000000000) { rate = 5100; } uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); tokensSold = allCrowdSaleTokens.sub(token.balanceOf(this)); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { } function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { } function _getTokenAmount(uint256 _weiAmount) internal returns(uint256) { return _weiAmount.mul(rate); } function _forwardFunds() internal { wallet.transfer(msg.value); } } contract EmaCrowdSale is Crowdsale { using SafeMath for uint256; constructor(address wallet, MiniMeToken token) Crowdsale(wallet, token) public { setCrowdsale(wallet, token); } function tranferPresaleTokens(address investor, uint256 ammount) public onlyOwner { tokensSold = tokensSold.add(ammount); token.transferFrom(this, investor, ammount); } function setTokenTransferState(bool state) public onlyOwner { token.changeController(this); token.enableTransfers(state); } function claim(address claimToken) public onlyOwner { token.changeController(this); token.claimTokens(claimToken); } function() external payable whenNotPaused { emit buyx(msg.sender, this, _getTokenAmount(msg.value)); buyTokens(msg.sender); } }
0
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract NFT { function totalSupply() public constant returns (uint); function balanceOf(address) public constant returns (uint); function tokenOfOwnerByIndex(address owner, uint index) public constant returns (uint); function ownerOf(uint tokenId) public constant returns (address); function transfer(address to, uint tokenId) public; function takeOwnership(uint tokenId) public; function approve(address beneficiary, uint tokenId) public; function metadata(uint tokenId) public constant returns (string); } contract NFTEvents { event TokenCreated(uint tokenId, address owner, string metadata); event TokenDestroyed(uint tokenId, address owner); event TokenTransferred(uint tokenId, address from, address to); event TokenTransferAllowed(uint tokenId, address beneficiary); event TokenTransferDisallowed(uint tokenId, address beneficiary); event TokenMetadataUpdated(uint tokenId, address owner, string data); } contract BasicNFT is NFT, NFTEvents { uint public totalTokens; mapping(address => uint[]) public ownedTokens; mapping(address => uint) _virtualLength; mapping(uint => uint) _tokenIndexInOwnerArray; mapping(uint => address) public tokenOwner; mapping(uint => address) public allowedTransfer; mapping(uint => string) public tokenMetadata; function totalSupply() public constant returns (uint) { return totalTokens; } function balanceOf(address owner) public constant returns (uint) { return _virtualLength[owner]; } function tokenOfOwnerByIndex(address owner, uint index) public constant returns (uint) { require(index >= 0 && index < balanceOf(owner)); return ownedTokens[owner][index]; } function getAllTokens(address owner) public constant returns (uint[]) { uint size = _virtualLength[owner]; uint[] memory result = new uint[](size); for (uint i = 0; i < size; i++) { result[i] = ownedTokens[owner][i]; } return result; } function ownerOf(uint tokenId) public constant returns (address) { return tokenOwner[tokenId]; } function transfer(address to, uint tokenId) public { require(tokenOwner[tokenId] == msg.sender || allowedTransfer[tokenId] == msg.sender); _transfer(tokenOwner[tokenId], to, tokenId); } function takeOwnership(uint tokenId) public { require(allowedTransfer[tokenId] == msg.sender); _transfer(tokenOwner[tokenId], msg.sender, tokenId); } function approve(address beneficiary, uint tokenId) public { require(msg.sender == tokenOwner[tokenId]); if (allowedTransfer[tokenId] != 0) { allowedTransfer[tokenId] = 0; TokenTransferDisallowed(tokenId, allowedTransfer[tokenId]); } allowedTransfer[tokenId] = beneficiary; TokenTransferAllowed(tokenId, beneficiary); } function metadata(uint tokenId) constant public returns (string) { return tokenMetadata[tokenId]; } function updateTokenMetadata(uint tokenId, string _metadata) internal returns(bool) { require(msg.sender == tokenOwner[tokenId]); tokenMetadata[tokenId] = _metadata; TokenMetadataUpdated(tokenId, msg.sender, _metadata); return true; } function _transfer(address from, address to, uint tokenId) internal returns(bool) { allowedTransfer[tokenId] = 0; _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); TokenTransferred(tokenId, from, to); return true; } function _removeTokenFrom(address from, uint tokenId) internal { require(_virtualLength[from] > 0); uint length = _virtualLength[from]; uint index = _tokenIndexInOwnerArray[tokenId]; uint swapToken = ownedTokens[from][length - 1]; ownedTokens[from][index] = swapToken; _tokenIndexInOwnerArray[swapToken] = index; _virtualLength[from]--; } function _addTokenTo(address owner, uint tokenId) internal { if (ownedTokens[owner].length == _virtualLength[owner]) { ownedTokens[owner].push(tokenId); } else { ownedTokens[owner][_virtualLength[owner]] = tokenId; } tokenOwner[tokenId] = owner; _tokenIndexInOwnerArray[tokenId] = _virtualLength[owner]; _virtualLength[owner]++; } } contract PlanetToken is Ownable, BasicNFT { string public name = 'Planet Tokens'; string public symbol = 'PT'; mapping (uint => uint) public cordX; mapping (uint => uint) public cordY; mapping (uint => uint) public cordZ; mapping (uint => uint) public lifeD; mapping (uint => uint) public lifeN; mapping (uint => uint) public lifeA; mapping (uint => uint) public latestPing; struct planet { uint x; uint y; uint z; string name; address owner; string liason; string url; uint cost; uint index; } struct _donations { uint start; uint genesis; uint interval; uint ppp; uint amount; uint checkpoint; } mapping(uint => planet) planets; mapping(address => _donations) donations; string private universe; uint private min_donation; address private donation_address; uint private coordinate_limit; event TokenPing(uint tokenId); function () public payable { donation_address.transfer(msg.value); } function PlanetToken(string UniverseName, uint CoordinateLimit, address DonationAddress, uint StartingWeiDonation, uint BlockIntervals, uint WeiPerPlanet) public { universe = UniverseName; min_donation = StartingWeiDonation; coordinate_limit = CoordinateLimit; donation_address = DonationAddress; donations[donation_address].start = min_donation; donations[donation_address].genesis = block.number; donations[donation_address].checkpoint = block.number; donations[donation_address].interval = BlockIntervals; donations[donation_address].ppp = WeiPerPlanet; donations[donation_address].amount = min_donation; } function assignNewPlanet(address beneficiary, uint x, uint y, uint z, string _planetName, string liason, string url) public payable { uint MinimumDonation = donations[donation_address].amount; require(tokenOwner[buildTokenId(x, y, z)] == 0); require(msg.value >= MinimumDonation); require(x <= coordinate_limit); require(y <= coordinate_limit); require(z <= coordinate_limit); latestPing[buildTokenId(x, y, z)] = now; _addTokenTo(beneficiary, buildTokenId(x, y, z)); totalTokens++; tokenMetadata[buildTokenId(x, y, z)] = _planetName; cordX[buildTokenId(x, y, z)] = x; cordY[buildTokenId(x, y, z)] = y; cordZ[buildTokenId(x, y, z)] = z; lifeD[buildTokenId(x, y, z)] = uint256(keccak256(x, '|x|', msg.sender, '|', universe)); lifeN[buildTokenId(x, y, z)] = uint256(keccak256(y, '|y|', msg.sender, '|', universe)); lifeA[buildTokenId(x, y, z)] = uint256(keccak256(z, '|z|', msg.sender, '|', universe)); planets[buildTokenId(x, y, z)].x = x; planets[buildTokenId(x, y, z)].x = y; planets[buildTokenId(x, y, z)].x = z; planets[buildTokenId(x, y, z)].name = _planetName; planets[buildTokenId(x, y, z)].owner = beneficiary; planets[buildTokenId(x, y, z)].liason = liason; planets[buildTokenId(x, y, z)].url = url; planets[buildTokenId(x, y, z)].index = totalTokens - 1; planets[buildTokenId(x, y, z)].cost = msg.value; TokenCreated(buildTokenId(x, y, z), beneficiary, _planetName); donation_address.transfer(msg.value); uint this_block = block.number; uint new_checkpoint = donations[donation_address].checkpoint + donations[donation_address].interval; if(this_block > new_checkpoint) { donations[donation_address].checkpoint = this_block; donations[donation_address].amount = donations[donation_address].ppp * totalTokens; } } function MinimumDonation() public view returns(uint) { return donations[donation_address].amount; } function BlocksToGo() public view returns(uint) { uint this_block = block.number; uint next_block = donations[donation_address].checkpoint + donations[donation_address].interval; if(this_block < next_block) { return next_block - this_block; } else { return 0; } } function GetLiasonName(uint x, uint y, uint z) public view returns(string) { return planets[buildTokenId(x, y, z)].liason; } function GetLiasonURL(uint x, uint y, uint z) public view returns(string) { return planets[buildTokenId(x, y, z)].url; } function GetIndex(uint x, uint y, uint z) public view returns(uint) { return planets[buildTokenId(x, y, z)].index; } function GetCost(uint x, uint y, uint z) public view returns(uint) { return planets[buildTokenId(x, y, z)].cost; } function UpdatedDonationAddress(address NewAddress) onlyOwner public { address OldAddress = donation_address; donation_address = NewAddress; donations[donation_address].start = donations[OldAddress].start; donations[donation_address].genesis = donations[OldAddress].genesis; donations[donation_address].checkpoint = donations[OldAddress].checkpoint; donations[donation_address].interval = donations[OldAddress].interval; donations[donation_address].ppp = donations[OldAddress].ppp; donations[donation_address].amount = donations[OldAddress].amount; } function ping(uint tokenId) public { require(msg.sender == tokenOwner[tokenId]); latestPing[tokenId] = now; TokenPing(tokenId); } function buildTokenId(uint x, uint y, uint z) public view returns (uint256) { return uint256(keccak256(x, '|', y, '|', z, '|', universe)); } function exists(uint x, uint y, uint z) public constant returns (bool) { return ownerOfPlanet(x, y, z) != 0; } function ownerOfPlanet(uint x, uint y, uint z) public constant returns (address) { return tokenOwner[buildTokenId(x, y, z)]; } function transferPlanet(address to, uint x, uint y, uint z) public { require(msg.sender == tokenOwner[buildTokenId(x, y, z)]); planets[buildTokenId(x, y, z)].owner = to; } function planetName(uint x, uint y, uint z) constant public returns (string) { return tokenMetadata[buildTokenId(x, y, z)]; } function planetCordinates(uint tokenId) public constant returns (uint[]) { uint[] memory data = new uint[](3); data[0] = cordX[tokenId]; data[1] = cordY[tokenId]; data[2] = cordZ[tokenId]; return data; } function planetLife(uint x, uint y, uint z) constant public returns (uint[]) { uint[] memory dna = new uint[](3); dna[0] = lifeD[buildTokenId(x, y, z)]; dna[1] = lifeN[buildTokenId(x, y, z)]; dna[2] = lifeA[buildTokenId(x, y, z)]; return dna; } function updatePlanetName(uint x, uint y, uint z, string _planetName) public { if(updateTokenMetadata(buildTokenId(x, y, z), _planetName)) { planets[buildTokenId(x, y, z)].name = _planetName; } } function updatePlanetLiason(uint x, uint y, uint z, string LiasonName) public { require(msg.sender == tokenOwner[buildTokenId(x, y, z)]); planets[buildTokenId(x, y, z)].liason = LiasonName; } function updatePlanetURL(uint x, uint y, uint z, string LiasonURL) public { require(msg.sender == tokenOwner[buildTokenId(x, y, z)]); planets[buildTokenId(x, y, z)].url = LiasonURL; } }
1
pragma solidity ^0.4.25; contract BaseToken { string public name; string public symbol; uint8 public decimals; 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); function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; assert(balanceOf[_from] + balanceOf[_to] == previousBalances); Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } contract CustomToken is BaseToken { function CustomToken() public { totalSupply = 500000000000000000000000000; name = 'LokexCoin'; symbol = 'LKB'; decimals = 18; balanceOf[0x2e8f7bd73790a242f1271a381a3d0011078e9fc8] = totalSupply; Transfer(address(0), 0x2e8f7bd73790a242f1271a381a3d0011078e9fc8, totalSupply); } }
1
pragma solidity ^0.4.0; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract VanityLib { uint constant m = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f; function lengthOfCommonPrefix(bytes a, bytes b) public pure returns(uint) { uint len = (a.length <= b.length) ? a.length : b.length; for (uint i = 0; i < len; i++) { if (a[i] != b[i]) { return i; } } return len; } function lengthOfCommonPrefix32(bytes32 a, bytes b) public pure returns(uint) { for (uint i = 0; i < b.length; i++) { if (a[i] != b[i]) { return i; } } return b.length; } function lengthOfCommonPrefix3232(bytes32 a, bytes32 b) public pure returns(uint) { for (uint i = 0; i < 32; i++) { if (a[i] != b[i] || a[i] == 0) { return i; } } return 0; } function equalBytesToBytes(bytes a, bytes b) public pure returns (bool) { if (a.length != b.length) { return false; } for (uint i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } function equalBytes32ToBytes(bytes32 a, bytes b) public pure returns (bool) { for (uint i = 0; i < b.length; i++) { if (a[i] != b[i]) { return false; } } return true; } function bytesToBytes32(bytes source) public pure returns(bytes32 result) { assembly { result := mload(add(source, 32)) } } function toBase58Checked(uint256 _value, byte appCode) public pure returns(bytes32) { string memory letters = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bytes memory alphabet = bytes(letters); uint8 base = 58; uint8 len = 0; uint256 remainder = 0; bool needBreak = false; bytes memory bytesReversed = bytes(new string(32)); for (uint8 i = 0; true; i++) { if (_value < base) { needBreak = true; } remainder = _value % base; _value = uint256(_value / base); if (len == 32) { for (uint j = 0; j < len - 1; j++) { bytesReversed[j] = bytesReversed[j + 1]; } len--; } bytesReversed[len] = alphabet[remainder]; len++; if (needBreak) { break; } } bytes memory result = bytes(new string(32)); result[0] = appCode; for (i = 0; i < 31; i++) { result[i + 1] = bytesReversed[len - 1 - i]; } return bytesToBytes32(result); } function createBtcAddressHex(uint256 publicXPoint, uint256 publicYPoint) public pure returns(uint256) { bytes20 publicKeyPart = ripemd160(sha256(byte(0x04), publicXPoint, publicYPoint)); bytes32 publicKeyCheckCode = sha256(sha256(byte(0x00), publicKeyPart)); bytes memory publicKey = new bytes(32); for (uint i = 0; i < 7; i++) { publicKey[i] = 0x00; } publicKey[7] = 0x00; for (uint j = 0; j < 20; j++) { publicKey[j + 8] = publicKeyPart[j]; } publicKey[28] = publicKeyCheckCode[0]; publicKey[29] = publicKeyCheckCode[1]; publicKey[30] = publicKeyCheckCode[2]; publicKey[31] = publicKeyCheckCode[3]; return uint256(bytesToBytes32(publicKey)); } function createBtcAddress(uint256 publicXPoint, uint256 publicYPoint) public pure returns(bytes32) { return toBase58Checked(createBtcAddressHex(publicXPoint, publicYPoint), "1"); } function invmod(uint256 a, uint256 p) public pure returns (uint256) { int t1 = 0; int t2 = 1; uint r1 = p; uint r2 = a; uint q; while (r2 != 0) { q = r1 / r2; (t1, t2, r1, r2) = (t2, t1 - int(q) * t2, r2, r1 - q * r2); } return t1 < 0 ? p - uint(-t1) : uint(t1); } function submod(uint a, uint b, uint p) public pure returns (uint) { return addmod(a, p - b, p); } function addXY(uint x1, uint y1, uint x2, uint y2) public pure returns(uint x3, uint y3) { uint anti = invmod(submod(x1, x2, m), m); uint alpha = mulmod(submod(y1, y2, m), anti, m); x3 = submod(submod(mulmod(alpha, alpha, m), x1, m), x2, m); y3 = submod(mulmod(alpha, submod(x2, x3, m), m), y2, m); } function doubleXY(uint x1, uint y1) public pure returns(uint x2, uint y2) { uint anti = invmod(addmod(y1, y1, m), m); uint alpha = mulmod(addmod(addmod(mulmod(x1, x1, m), mulmod(x1, x1, m), m), mulmod(x1, x1, m), m), anti, m); x2 = submod(mulmod(alpha, alpha, m), addmod(x1, x1, m), m); y2 = submod(mulmod(alpha, submod(x1, x2, m), m), y1, m); } function mulXY(uint x1, uint y1, uint privateKey) public pure returns(uint x2, uint y2) { bool addition = false; for (uint i = 0; i < 256; i++) { if (((privateKey >> i) & 1) == 1) { if (addition) { (x2, y2) = addXY(x1, y1, x2, y2); } else { (x2, y2) = (x1, y1); addition = true; } } (x1,y1) = doubleXY(x1, y1); } } function bitcoinPublicKey(uint256 privateKey) public pure returns(uint, uint) { uint256 gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798; uint256 gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8; return mulXY(gx, gy, privateKey); } function complexityForBtcAddressPrefix(bytes prefix) public pure returns(uint) { return complexityForBtcAddressPrefixWithLength(prefix, prefix.length); } function complexityForBtcAddressPrefixWithLength(bytes prefix, uint length) public pure returns(uint) { require(prefix.length >= length); uint8[128] memory unbase58 = [ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 255, 255, 255, 255, 255, 255, 255, 9, 10, 11, 12, 13, 14, 15, 16, 255, 17, 18, 19, 20, 21, 255, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 255, 255, 255, 255, 255, 255, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 255, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 255, 255, 255, 255, 255 ]; uint leadingOnes = countBtcAddressLeadingOnes(prefix, length); uint256 prefixValue = 0; uint256 prefix1 = 1; for (uint i = 0; i < length; i++) { uint index = uint(prefix[i]); require(index != 255); prefixValue = prefixValue * 58 + unbase58[index]; prefix1 *= 58; } uint256 top = (uint256(1) << (200 - 8*leadingOnes)); uint256 total = 0; uint256 prefixMin = prefixValue; uint256 diff = 0; for (uint digits = 1; prefix1/58 < (1 << 192); digits++) { prefix1 *= 58; prefixMin *= 58; prefixValue = prefixValue * 58 + 57; diff = 0; if (prefixValue >= top) { diff += prefixValue - top; } if (prefixMin < (top >> 8)) { diff += (top >> 8) - prefixMin; } if ((58 ** digits) >= diff) { total += (58 ** digits) - diff; } } if (prefixMin == 0) { total = (58 ** (digits - 1)) - diff; } return (1 << 192) / total; } function countBtcAddressLeadingOnes(bytes prefix, uint length) public pure returns(uint) { uint leadingOnes = 1; for (uint j = 0; j < length && prefix[j] == 49; j++) { leadingOnes = j + 1; } return leadingOnes; } function isValidBicoinAddressPrefix(bytes prefixArg) public pure returns(bool) { if (prefixArg.length < 5) { return false; } if (prefixArg[0] != "1" && prefixArg[0] != "3") { return false; } for (uint i = 0; i < prefixArg.length; i++) { byte ch = prefixArg[i]; if (ch == "0" || ch == "O" || ch == "I" || ch == "l") { return false; } if (!((ch >= "1" && ch <= "9") || (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z"))) { return false; } } return true; } function isValidPublicKey(uint256 x, uint256 y) public pure returns(bool) { return (mulmod(y, y, m) == addmod(mulmod(x, mulmod(x, x, m), m), 7, m)); } } contract IUpgradable { function startUpgrade() public; function endUpgrade() public; } contract Upgradable is Ownable { struct UpgradableState { bool isUpgrading; address prevVersion; address nextVersion; } UpgradableState public upgradableState; event Initialized(address indexed prevVersion); event Upgrading(address indexed nextVersion); event Upgraded(address indexed nextVersion); modifier isLastestVersion { require(!upgradableState.isUpgrading); require(upgradableState.nextVersion == address(0)); _; } modifier onlyOwnerOrigin { require(tx.origin == owner); _; } function Upgradable(address _prevVersion) public { if (_prevVersion != address(0)) { require(msg.sender == Ownable(_prevVersion).owner()); upgradableState.isUpgrading = true; upgradableState.prevVersion = _prevVersion; IUpgradable(_prevVersion).startUpgrade(); } else { Initialized(_prevVersion); } } function startUpgrade() public onlyOwnerOrigin { require(msg.sender != owner); require(!upgradableState.isUpgrading); require(upgradableState.nextVersion == 0); upgradableState.isUpgrading = true; upgradableState.nextVersion = msg.sender; Upgrading(msg.sender); } function endUpgrade() public onlyOwnerOrigin { require(upgradableState.isUpgrading); upgradableState.isUpgrading = false; if (msg.sender != owner) { require(upgradableState.nextVersion == msg.sender); Upgraded(upgradableState.nextVersion); } else { if (upgradableState.prevVersion != address(0)) { Upgradable(upgradableState.prevVersion).endUpgrade(); } Initialized(upgradableState.prevVersion); } } } contract IEC { function _inverse(uint256 a) public constant returns(uint256 invA); function _ecAdd(uint256 x1,uint256 y1,uint256 z1, uint256 x2,uint256 y2,uint256 z2) public constant returns(uint256 x3,uint256 y3,uint256 z3); function _ecDouble(uint256 x1,uint256 y1,uint256 z1) public constant returns(uint256 x3,uint256 y3,uint256 z3); function _ecMul(uint256 d, uint256 x1,uint256 y1,uint256 z1) public constant returns(uint256 x3,uint256 y3,uint256 z3); function publicKey(uint256 privKey) public constant returns(uint256 qx, uint256 qy); function deriveKey(uint256 privKey, uint256 pubX, uint256 pubY) public constant returns(uint256 qx, uint256 qy); } contract TaskRegister is Upgradable, VanityLib { enum TaskType { BITCOIN_ADDRESS_PREFIX } struct Task { TaskType taskType; uint256 taskId; address creator; uint256 reward; bytes32 data; uint256 dataLength; uint256 requestPublicXPoint; uint256 requestPublicYPoint; uint256 answerPrivateKey; } IEC public ec; ERC20 public token; uint256 public nextTaskId = 1; uint256 public totalReward; Task[] public tasks; Task[] public completedTasks; mapping(uint256 => uint) public indexOfTaskId; event TaskCreated(uint256 indexed taskId); event TaskSolved(uint256 indexed taskId); event TaskPayed(uint256 indexed taskId); function TaskRegister(address _ec, address _token, address _prevVersion) public Upgradable(_prevVersion) { ec = IEC(_ec); token = ERC20(_token); } function upgrade(uint size) public onlyOwner { require(upgradableState.isUpgrading); require(upgradableState.prevVersion != 0); nextTaskId = TaskRegister(upgradableState.prevVersion).nextTaskId(); totalReward = TaskRegister(upgradableState.prevVersion).totalReward(); uint index = tasks.length; uint tasksCount = TaskRegister(upgradableState.prevVersion).tasksCount(); for (uint i = index; i < index + size && i < tasksCount; i++) { tasks.push(Task(TaskType.BITCOIN_ADDRESS_PREFIX,0,0,0,bytes32(0),0,0,0,0)); } for (uint j = index; j < index + size && j < tasksCount; j++) { ( tasks[j].taskType, tasks[j].taskId, tasks[j].creator, tasks[j].reward, tasks[j].data, , , , ) = TaskRegister(upgradableState.prevVersion).tasks(j); indexOfTaskId[tasks[j].taskId] = j + 1; } for (uint k = index; k < index + size && k < tasksCount; k++) { ( , , , , , tasks[k].dataLength, tasks[k].requestPublicXPoint, tasks[k].requestPublicYPoint, tasks[k].answerPrivateKey ) = TaskRegister(upgradableState.prevVersion).tasks(k); } } function endUpgrade() public { super.endUpgrade(); if (upgradableState.nextVersion != 0) { token.transfer(upgradableState.nextVersion, token.balanceOf(this)); } } function tasksCount() public constant returns(uint) { return tasks.length; } function completedTasksCount() public constant returns(uint) { return completedTasks.length; } function payForTask(uint256 taskId, uint256 reward) public isLastestVersion { require(reward > 0); uint index = safeIndexOfTaskId(taskId); token.transferFrom(tx.origin, this, reward); tasks[index].reward += reward; totalReward += reward; TaskPayed(taskId); } function safeIndexOfTaskId(uint taskId) public constant returns(uint) { uint index = indexOfTaskId[taskId]; require(index > 0); return index - 1; } function createBitcoinAddressPrefixTask(bytes prefix, uint256 reward, uint256 requestPublicXPoint, uint256 requestPublicYPoint) public isLastestVersion { require(prefix.length > 5); require(prefix[0] == "1"); require(prefix[1] != "1"); require(isValidBicoinAddressPrefix(prefix)); require(isValidPublicKey(requestPublicXPoint, requestPublicYPoint)); if (reward > 0) { token.transferFrom(tx.origin, this, reward); } bytes32 data; assembly { data := mload(add(prefix, 32)) } Task memory task = Task({ taskType: TaskType.BITCOIN_ADDRESS_PREFIX, taskId: nextTaskId, creator: tx.origin, reward: reward, data: data, dataLength: prefix.length, requestPublicXPoint: requestPublicXPoint, requestPublicYPoint: requestPublicYPoint, answerPrivateKey: 0 }); tasks.push(task); indexOfTaskId[nextTaskId] = tasks.length; TaskCreated(nextTaskId); nextTaskId++; } function solveTask(uint taskId, uint256 answerPrivateKey) public isLastestVersion { uint taskIndex = safeIndexOfTaskId(taskId); Task storage task = tasks[taskIndex]; bytes32 answerPrivateKeyBytes = bytes32(answerPrivateKey); bytes32 senderAddressBytes = bytes32(uint256(msg.sender) << 96); for (uint i = 0; i < 16; i++) { require(answerPrivateKeyBytes[i] == senderAddressBytes[i]); } if (task.taskType == TaskType.BITCOIN_ADDRESS_PREFIX) { uint256 answerPublicXPoint; uint256 answerPublicYPoint; uint256 publicXPoint; uint256 publicYPoint; uint256 z; (answerPublicXPoint, answerPublicYPoint) = ec.publicKey(answerPrivateKey); (publicXPoint, publicYPoint, z) = ec._ecAdd( task.requestPublicXPoint, task.requestPublicYPoint, 1, answerPublicXPoint, answerPublicYPoint, 1 ); uint256 m = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; z = ec._inverse(z); publicXPoint = mulmod(publicXPoint, z, m); publicYPoint = mulmod(publicYPoint, z, m); require(isValidPublicKey(publicXPoint, publicYPoint)); bytes32 btcAddress = createBtcAddress(publicXPoint, publicYPoint); uint prefixLength = lengthOfCommonPrefix3232(btcAddress, task.data); require(prefixLength == task.dataLength); task.answerPrivateKey = answerPrivateKey; } token.transfer(msg.sender, task.reward); totalReward -= task.reward; completeTask(taskId, taskIndex); TaskSolved(taskId); } function completeTask(uint taskId, uint index) internal { completedTasks.push(tasks[index]); if (index < tasks.length - 1) { tasks[index] = tasks[tasks.length - 1]; indexOfTaskId[tasks[index].taskId] = index + 1; } tasks.length -= 1; delete indexOfTaskId[taskId]; } function recoverLost(ERC20Basic _token, address loser) public onlyOwner { uint256 amount = _token.balanceOf(this); if (_token == token) { amount -= totalReward; } _token.transfer(loser, _token.balanceOf(this)); } }
0
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 30585600; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xa1c7Db2aad37a951375CB0873da0ff08Af728b0B; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.11; contract ERC20Interface { function totalSupply() constant returns (uint256); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract RoseCoin is ERC20Interface { uint8 public constant decimals = 5; string public constant symbol = "RSC"; string public constant name = "RoseCoin"; uint public _level = 0; bool public _selling = true; uint public _totalSupply = 10 ** 14; uint public _originalBuyPrice = 10 ** 10; uint public _minimumBuyAmount = 10 ** 17; address public owner; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; uint public _icoSupply = _totalSupply; uint[4] public ratio = [12, 10, 10, 13]; uint[4] public threshold = [95000000000000, 85000000000000, 0, 80000000000000]; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } modifier onlyNotOwner() { if (msg.sender == owner) { revert(); } _; } modifier thresholdAll() { if (!_selling || msg.value < _minimumBuyAmount || _icoSupply <= threshold[3]) { revert(); } _; } function RoseCoin() { owner = msg.sender; balances[owner] = _totalSupply; } function totalSupply() constant returns (uint256) { return _totalSupply; } function balanceOf(address _owner) constant returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _amount) returns (bool) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } function transferFrom( address _from, address _to, uint256 _amount ) returns (bool) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } function approve(address _spender, uint256 _amount) returns (bool) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } function toggleSale() onlyOwner { _selling = !_selling; } function setBuyPrice(uint newBuyPrice) onlyOwner { _originalBuyPrice = newBuyPrice; } function buy() payable onlyNotOwner thresholdAll returns (uint256 amount) { amount = 0; uint remain = msg.value / _originalBuyPrice; while (remain > 0 && _level < 3) { remain = remain * ratio[_level] / ratio[_level+1]; if (_icoSupply <= remain + threshold[_level]) { remain = (remain + threshold[_level] - _icoSupply) * ratio[_level+1] / ratio[_level]; amount += _icoSupply - threshold[_level]; _icoSupply = threshold[_level]; _level += 1; } else { _icoSupply -= remain; amount += remain; remain = 0; break; } } if (balances[owner] < amount) revert(); if (remain > 0) { remain *= _originalBuyPrice; msg.sender.transfer(remain); } balances[owner] -= amount; balances[msg.sender] += amount; owner.transfer(msg.value - remain); Transfer(owner, msg.sender, amount); return amount; } function withdraw() onlyOwner returns (bool) { return owner.send(this.balance); } } contract MultiSigWallet { event Confirmation(address sender, bytes32 transactionHash); event Revocation(address sender, bytes32 transactionHash); event Submission(bytes32 transactionHash); event Execution(bytes32 transactionHash); event Deposit(address sender, uint value); event OwnerAddition(address owner); event OwnerRemoval(address owner); event RequiredUpdate(uint required); event CoinCreation(address coin); mapping (bytes32 => Transaction) public transactions; mapping (bytes32 => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] owners; bytes32[] transactionList; uint public required; struct Transaction { address destination; uint value; bytes data; uint nonce; bool executed; } modifier onlyWallet() { if (msg.sender != address(this)) revert(); _; } modifier signaturesFromOwners(bytes32 transactionHash, uint8[] v, bytes32[] rs) { for (uint i=0; i<v.length; i++) if (!isOwner[ecrecover(transactionHash, v[i], rs[i], rs[v.length + i])]) revert(); _; } modifier ownerDoesNotExist(address owner) { if (isOwner[owner]) revert(); _; } modifier ownerExists(address owner) { if (!isOwner[owner]) revert(); _; } modifier confirmed(bytes32 transactionHash, address owner) { if (!confirmations[transactionHash][owner]) revert(); _; } modifier notConfirmed(bytes32 transactionHash, address owner) { if (confirmations[transactionHash][owner]) revert(); _; } modifier notExecuted(bytes32 transactionHash) { if (transactions[transactionHash].executed) revert(); _; } modifier notNull(address destination) { if (destination == 0) revert(); _; } modifier validRequired(uint _ownerCount, uint _required) { if ( _required > _ownerCount || _required == 0 || _ownerCount == 0) revert(); _; } function addOwner(address owner) external onlyWallet ownerDoesNotExist(owner) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } function removeOwner(address owner) external onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) updateRequired(owners.length); OwnerRemoval(owner); } function updateRequired(uint _required) public onlyWallet validRequired(owners.length, _required) { required = _required; RequiredUpdate(_required); } function addTransaction(address destination, uint value, bytes data, uint nonce) private notNull(destination) returns (bytes32 transactionHash) { transactionHash = sha3(destination, value, data, nonce); if (transactions[transactionHash].destination == 0) { transactions[transactionHash] = Transaction({ destination: destination, value: value, data: data, nonce: nonce, executed: false }); transactionList.push(transactionHash); Submission(transactionHash); } } function submitTransaction(address destination, uint value, bytes data, uint nonce) external ownerExists(msg.sender) returns (bytes32 transactionHash) { transactionHash = addTransaction(destination, value, data, nonce); confirmTransaction(transactionHash); } function submitTransactionWithSignatures(address destination, uint value, bytes data, uint nonce, uint8[] v, bytes32[] rs) external ownerExists(msg.sender) returns (bytes32 transactionHash) { transactionHash = addTransaction(destination, value, data, nonce); confirmTransactionWithSignatures(transactionHash, v, rs); } function addConfirmation(bytes32 transactionHash, address owner) private notConfirmed(transactionHash, owner) { confirmations[transactionHash][owner] = true; Confirmation(owner, transactionHash); } function confirmTransaction(bytes32 transactionHash) public ownerExists(msg.sender) { addConfirmation(transactionHash, msg.sender); executeTransaction(transactionHash); } function confirmTransactionWithSignatures(bytes32 transactionHash, uint8[] v, bytes32[] rs) public signaturesFromOwners(transactionHash, v, rs) { for (uint i=0; i<v.length; i++) addConfirmation(transactionHash, ecrecover(transactionHash, v[i], rs[i], rs[i + v.length])); executeTransaction(transactionHash); } function executeTransaction(bytes32 transactionHash) public notExecuted(transactionHash) { if (isConfirmed(transactionHash)) { Transaction storage txn = transactions[transactionHash]; txn.executed = true; if (!txn.destination.call.value(txn.value)(txn.data)) revert(); Execution(transactionHash); } } function revokeConfirmation(bytes32 transactionHash) external ownerExists(msg.sender) confirmed(transactionHash, msg.sender) notExecuted(transactionHash) { confirmations[transactionHash][msg.sender] = false; Revocation(msg.sender, transactionHash); } function MultiSigWallet(address[] _owners, uint _required) validRequired(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) isOwner[_owners[i]] = true; owners = _owners; required = _required; } function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } function isConfirmed(bytes32 transactionHash) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) if (confirmations[transactionHash][owners[i]]) count += 1; if (count == required) return true; } function confirmationCount(bytes32 transactionHash) external constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionHash][owners[i]]) count += 1; } function filterTransactions(bool isPending) private constant returns (bytes32[] _transactionList) { bytes32[] memory _transactionListTemp = new bytes32[](transactionList.length); uint count = 0; for (uint i=0; i<transactionList.length; i++) if ( isPending && !transactions[transactionList[i]].executed || !isPending && transactions[transactionList[i]].executed) { _transactionListTemp[count] = transactionList[i]; count += 1; } _transactionList = new bytes32[](count); for (i=0; i<count; i++) if (_transactionListTemp[i] > 0) _transactionList[i] = _transactionListTemp[i]; } function getPendingTransactions() external constant returns (bytes32[]) { return filterTransactions(true); } function getExecutedTransactions() external constant returns (bytes32[]) { return filterTransactions(false); } function createCoin() external onlyWallet { CoinCreation(new RoseCoin()); } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 29635200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x31A7dCf6B144cEc36D6208533B042774847168e2; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.17; contract ERC223ReceivingContract { function tokenFallback(address _from, uint256 _value, bytes _data) public; } contract Token { uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); function transfer(address _to, uint256 _value, bytes _data) public returns (bool success); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != 0x0); require(_to != address(this)); require(balances[msg.sender] >= _value); require(balances[_to] + _value >= balances[_to]); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transfer( address _to, uint256 _value, bytes _data) public returns (bool) { require(transfer(_to, _value)); uint codeLength; assembly { codeLength := extcodesize(_to) } if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_from != 0x0); require(_to != 0x0); require(_to != address(this)); require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(balances[_to] + _value >= balances[_to]); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != 0x0); require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } } contract RealFundToken is StandardToken { string constant public name = "REAL FUND Token"; string constant public symbol = "REF"; uint8 constant public decimals = 8; uint constant multiplier = 10 ** uint(decimals); event Deployed(uint indexed _totalSupply); event Burnt(address indexed _receiver, uint indexed _num, uint indexed _totalSupply); function RealFundToken(address walletAddress) public { require(walletAddress != 0x0); totalSupply = 5000000000000000; balances[walletAddress] = totalSupply; Transfer(0x0, walletAddress, totalSupply); } function burn(uint num) public { require(num > 0); require(balances[msg.sender] >= num); require(totalSupply >= num); uint preBalance = balances[msg.sender]; balances[msg.sender] -= num; totalSupply -= num; Burnt(msg.sender, num, totalSupply); Transfer(msg.sender, 0x0, num); assert(balances[msg.sender] == preBalance - num); } } contract PreSale { RealFundToken public token; address public walletAddress; uint public amountRaised; uint public bonus; uint public price; uint public minSaleAmount; function PreSale(RealFundToken _token, address _walletAddress) public { token = RealFundToken(_token); walletAddress = _walletAddress; bonus = 25; price = 200000000; minSaleAmount = 100000000; } function () public payable { uint amount = msg.value; uint tokenAmount = amount / price; require(tokenAmount >= minSaleAmount); amountRaised += amount; token.transfer(msg.sender, tokenAmount * (100 + bonus) / 100); } function ChangeWallet(address _walletAddress) public { require(msg.sender == walletAddress); walletAddress = _walletAddress; } function TransferETH(address _to, uint _amount) public { require(msg.sender == walletAddress); _to.transfer(_amount); } function TransferTokens(address _to, uint _amount) public { require(msg.sender == walletAddress); token.transfer(_to, _amount); } function ChangeBonus(uint _bonus) public { require(msg.sender == walletAddress); bonus = _bonus; } function ChangePrice(uint _price) public { require(msg.sender == walletAddress); price = _price; } function ChangeMinSaleAmount(uint _minSaleAmount) public { require(msg.sender == walletAddress); minSaleAmount = _minSaleAmount; } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 28252800; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x94eDE150215829Ca4E313a5Dd986DBcf42b0a422; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract FreezableToken is StandardToken { mapping (bytes32 => uint64) internal chains; mapping (bytes32 => uint) internal freezings; mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "1irstcoin"; string public constant TOKEN_SYMBOL = "FCO"; bool public constant PAUSED = false; address public constant TARGET_USER = 0x1d38927e1c56b783db0e9c6ebad2ae34eedb5278; bool public constant CONTINUE_MINTING = true; } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { event Initialized(); bool public initialized = false; constructor() public { init(); transferOwnership(TARGET_USER); } function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } function init() private { require(!initialized); initialized = true; if (PAUSED) { pause(); } if (!CONTINUE_MINTING) { finishMinting(); } emit Initialized(); } }
1
pragma solidity ^0.4.15; library ECRecovery { function recover(bytes32 hash, bytes sig) public constant returns (address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) { return (address(0)); } assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } } library ChannelLibrary { struct Data { uint close_timeout; uint settle_timeout; uint audit_timeout; uint opened; uint close_requested; uint closed; uint settled; uint audited; ChannelManagerContract manager; address sender; address receiver; address client; uint balance; address auditor; uint nonce; uint completed_transfers; } struct StateUpdate { uint nonce; uint completed_transfers; } modifier notSettledButClosed(Data storage self) { require(self.settled <= 0 && self.closed > 0); _; } modifier notAuditedButClosed(Data storage self) { require(self.audited <= 0 && self.closed > 0); _; } modifier stillTimeout(Data storage self) { require(self.closed + self.settle_timeout >= block.number); _; } modifier timeoutOver(Data storage self) { require(self.closed + self.settle_timeout <= block.number); _; } modifier channelSettled(Data storage self) { require(self.settled != 0); _; } modifier senderOnly(Data storage self) { require(self.sender == msg.sender); _; } modifier receiverOnly(Data storage self) { require(self.receiver == msg.sender); _; } function deposit(Data storage self, uint256 amount) senderOnly(self) returns (bool success, uint256 balance) { require(self.opened > 0); require(self.closed == 0); StandardToken token = self.manager.token(); require (token.balanceOf(msg.sender) >= amount); success = token.transferFrom(msg.sender, this, amount); if (success == true) { self.balance += amount; return (true, self.balance); } return (false, 0); } function request_close( Data storage self ) { require(msg.sender == self.sender || msg.sender == self.receiver); require(self.close_requested == 0); self.close_requested = block.number; } function close( Data storage self, address channel_address, uint nonce, uint completed_transfers, bytes signature ) { if (self.close_timeout > 0) { require(self.close_requested > 0); require(block.number - self.close_requested >= self.close_timeout); } require(nonce > self.nonce); require(completed_transfers >= self.completed_transfers); require(completed_transfers <= self.balance); if (msg.sender != self.sender) { bytes32 signed_hash = hashState( channel_address, nonce, completed_transfers ); address sign_address = ECRecovery.recover(signed_hash, signature); require(sign_address == self.sender); } if (self.closed == 0) { self.closed = block.number; } self.nonce = nonce; self.completed_transfers = completed_transfers; } function hashState ( address channel_address, uint nonce, uint completed_transfers ) returns (bytes32) { return sha3 ( channel_address, nonce, completed_transfers ); } function settle(Data storage self) notSettledButClosed(self) timeoutOver(self) { StandardToken token = self.manager.token(); if (self.completed_transfers > 0) { require(token.transfer(self.receiver, self.completed_transfers)); } if (self.completed_transfers < self.balance) { require(token.transfer(self.sender, self.balance - self.completed_transfers)); } self.settled = block.number; } function audit(Data storage self, address auditor) notAuditedButClosed(self) { require(self.auditor == auditor); require(block.number <= self.closed + self.audit_timeout); self.audited = block.number; } function validateTransfer( Data storage self, address transfer_id, address channel_address, uint sum, bytes lock_data, bytes signature ) returns (uint256) { bytes32 signed_hash = hashTransfer( transfer_id, channel_address, lock_data, sum ); address sign_address = ECRecovery.recover(signed_hash, signature); require(sign_address == self.client); } function hashTransfer( address transfer_id, address channel_address, bytes lock_data, uint sum ) returns (bytes32) { if (lock_data.length > 0) { return sha3 ( transfer_id, channel_address, sum, lock_data ); } else { return sha3 ( transfer_id, channel_address, sum ); } } } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function balanceOf(address _owner) public constant returns (uint256); function allowance(address _owner, address _spender) public constant returns (uint256); uint256 public totalSupply; } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract StandardToken is ERC20 { using SafeMath for uint256; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowances[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowances[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } function allowance(address _owner, address _spender) public constant returns (uint256) { return allowances[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; } contract ChannelApi { function applyRuntimeUpdate(address from, address to, uint impressionsCount, uint fraudCount); function applyAuditorsCheckUpdate(address from, address to, uint fraudCountDelta); } contract ChannelContract { using ChannelLibrary for ChannelLibrary.Data; ChannelLibrary.Data data; event ChannelNewBalance(address token_address, address participant, uint balance, uint block_number); event ChannelCloseRequested(address closing_address, uint block_number); event ChannelClosed(address closing_address, uint block_number); event TransferUpdated(address node_address, uint block_number); event ChannelSettled(uint block_number); event ChannelAudited(uint block_number); event ChannelSecretRevealed(bytes32 secret, address receiver_address); modifier onlyManager() { require(msg.sender == address(data.manager)); _; } function ChannelContract( address manager_address, address sender, address client, address receiver, uint close_timeout, uint settle_timeout, uint audit_timeout, address auditor ) { require(msg.sender == manager_address); require (sender != receiver); require (client != receiver); require (audit_timeout >= 0); require (settle_timeout > 0); require (close_timeout >= 0); data.sender = sender; data.client = client; data.receiver = receiver; data.auditor = auditor; data.manager = ChannelManagerContract(manager_address); data.close_timeout = close_timeout; data.settle_timeout = settle_timeout; data.audit_timeout = audit_timeout; data.opened = block.number; } function deposit(uint256 amount) returns (bool) { bool success; uint256 balance; (success, balance) = data.deposit(amount); if (success == true) { ChannelNewBalance(data.manager.token(), msg.sender, balance, 0); } return success; } function addressAndBalance() constant returns ( address sender, address receiver, uint balance) { sender = data.sender; receiver = data.receiver; balance = data.balance; } function request_close () { data.request_close(); ChannelCloseRequested(msg.sender, data.closed); } function close ( uint nonce, uint256 completed_transfers, bytes signature ) { data.close(address(this), nonce, completed_transfers, signature); ChannelClosed(msg.sender, data.closed); } function settle() { data.settle(); ChannelSettled(data.settled); } function audit(address auditor) onlyManager { data.audit(auditor); ChannelAudited(data.audited); } function destroy() onlyManager { require(data.settled > 0); require(data.audited > 0 || block.number > data.closed + data.audit_timeout); selfdestruct(0); } function sender() constant returns (address) { return data.sender; } function receiver() constant returns (address) { return data.receiver; } function client() constant returns (address) { return data.client; } function auditor() constant returns (address) { return data.auditor; } function closeTimeout() constant returns (uint) { return data.close_timeout; } function settleTimeout() constant returns (uint) { return data.settle_timeout; } function auditTimeout() constant returns (uint) { return data.audit_timeout; } function manager() constant returns (address) { return data.manager; } function balance() constant returns (uint) { return data.balance; } function nonce() constant returns (uint) { return data.nonce; } function completedTransfers() constant returns (uint) { return data.completed_transfers; } function opened() constant returns (uint) { return data.opened; } function closeRequested() constant returns (uint) { return data.close_requested; } function closed() constant returns (uint) { return data.closed; } function settled() constant returns (uint) { return data.settled; } function audited() constant returns (uint) { return data.audited; } function () { revert(); } } contract ChannelManagerContract { event ChannelNew( address channel_address, address indexed sender, address client, address indexed receiver, uint close_timeout, uint settle_timeout, uint audit_timeout ); event ChannelDeleted( address channel_address, address indexed sender, address indexed receiver ); StandardToken public token; ChannelApi public channel_api; function ChannelManagerContract(address token_address, address channel_api_address) { require(token_address != 0); require(channel_api_address != 0); token = StandardToken(token_address); channel_api = ChannelApi(channel_api_address); } function newChannel( address client, address receiver, uint close_timeout, uint settle_timeout, uint audit_timeout, address auditor ) returns (address) { address new_channel_address = new ChannelContract( this, msg.sender, client, receiver, close_timeout, settle_timeout, audit_timeout, auditor ); ChannelNew( new_channel_address, msg.sender, client, receiver, close_timeout, settle_timeout, audit_timeout ); return new_channel_address; } function auditReport(address contract_address, uint total, uint fraud) { ChannelContract ch = ChannelContract(contract_address); require(ch.manager() == address(this)); address auditor = msg.sender; ch.audit(auditor); channel_api.applyRuntimeUpdate(ch.sender(), ch.receiver(), total, fraud); } function destroyChannel(address channel_address) { ChannelContract ch = ChannelContract(channel_address); require(ch.manager() == address(this)); ChannelDeleted(channel_address,ch.sender(),ch.receiver()); ch.destroy(); } }
1
pragma solidity ^0.4.23; contract SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Token { function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract AbstractToken is Token, SafeMath { function AbstractToken () { } function balanceOf(address _owner) constant returns (uint256 balance) { return accounts [_owner]; } function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true; } function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } mapping (address => uint256) accounts; mapping (address => mapping (address => uint256)) private allowances; } contract TRSToken is AbstractToken { uint256 constant MAX_TOKEN_COUNT = 100000000 * (10**18); address private owner; mapping (address => bool) private frozenAccount; uint256 tokenCount = 0; bool frozen = false; function TRSToken () { owner = msg.sender; } function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "Tresor"; string constant public symbol = "TRS"; uint8 constant public decimals = 18; function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); emit Transfer(0x0, msg.sender, _value); return true; } return false; } function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } event Freeze (); event Unfreeze (); event FrozenFunds(address target, bool frozen); event RefundTokens(address _token, address _refund, uint256 _value); }
1
pragma solidity ^0.4.11; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256); function transfer(address _to, uint256 _value) returns (bool); function transferFrom(address _from, address _to, uint256 _value) returns (bool); function approve(address _spender, uint256 _value) returns (bool); function allowance(address _owner, address _spender) constant returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ProofPresaleToken is ERC20, Ownable { using SafeMath for uint256; mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; string public constant name = "Proof Presale Token"; string public constant symbol = "PPT"; uint8 public constant decimals = 18; bool public mintingFinished = false; event Mint(address indexed to, uint256 amount); event MintFinished(); function ProofPresaleToken() {} function() payable { revert(); } function balanceOf(address _owner) constant returns (uint256) { return balances[_owner]; } function transfer(address _to, uint _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract ProofPresale is Pausable { using SafeMath for uint256; ProofPresaleToken public token; address public wallet; uint256 public weiRaised; uint256 public cap; uint256 public minInvestment; uint256 public rate; bool public isFinalized; string public contactInformation; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event Finalized(); function ProofPresale() { token = createTokenContract(); wallet = 0x99892Ac6DA1b3851167Cb959fE945926bca89f09; rate = 20; minInvestment = 10 ether; cap = 295257 * (10**18); } function createTokenContract() internal returns (ProofPresaleToken) { return new ProofPresaleToken(); } function () payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) payable whenNotPaused { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; weiRaised = weiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(rate); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function forwardFunds() internal { wallet.transfer(msg.value); } function validPurchase() internal constant returns (bool) { uint256 weiAmount = weiRaised.add(msg.value); bool notSmallAmount = msg.value >= minInvestment; bool withinCap = weiAmount.mul(rate) <= cap; return (notSmallAmount && withinCap); } function finalize() onlyOwner { require(!isFinalized); require(hasEnded()); token.finishMinting(); Finalized(); isFinalized = true; } function setContactInformation(string info) onlyOwner { contactInformation = info; } function hasEnded() public constant returns (bool) { bool capReached = (weiRaised.mul(rate) >= cap); return capReached; } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library Math { function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } contract ContractReceiver { function tokenFallback(address _from, uint _value, bytes _data); } contract TokenController { function proxyPayment(address _owner) payable returns(bool); function onTransfer(address _from, address _to, uint _amount) returns(bool); function onApprove(address _owner, address _spender, uint _amount) returns(bool); } contract Controlled { modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() { controller = msg.sender;} function changeController(address _newController) onlyController { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data); } contract MiniMeToken is Controlled { string public name; uint8 public decimals; string public symbol; string public version = 'MMT_0.1'; struct Checkpoint { uint128 fromBlock; uint128 value; } MiniMeToken public parentToken; uint public parentSnapShotBlock; uint public creationBlock; mapping (address => Checkpoint[]) balances; mapping (address => mapping (address => uint256)) allowed; Checkpoint[] totalSupplyHistory; bool public transfersEnabled; MiniMeTokenFactory public tokenFactory; function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } function transfer(address _to, uint256 _amount) returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } function transferFrom(address _from, address _to, uint256 _amount ) returns (bool success) { if (msg.sender != controller) { require(transfersEnabled); if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } function doTransfer(address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); require((_to != 0) && (_to != address(this))); var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_from], previousBalanceFrom - _amount); var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); updateValueAtNow(balances[_to], previousBalanceTo + _amount); Transfer(_from, _to, _amount); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } function approve(address _spender, uint256 _amount) returns (bool success) { require(transfersEnabled); require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } function totalSupply() constant returns (uint) { return totalSupplyAt(block.number); } function balanceOfAt(address _owner, uint _blockNumber) constant returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(balances[_owner], _blockNumber); } } function totalSupplyAt(uint _blockNumber) constant returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(totalSupplyHistory, _blockNumber); } } function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } function generateTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } function destroyTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } function enableTransfers(bool _transfersEnabled) onlyController { transfersEnabled = _transfersEnabled; } function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } function min(uint a, uint b) internal returns (uint) { return a < b ? a : b; } function () payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } contract MiniMeTokenFactory { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract SpectreSubscriber2Token is StandardToken, Ownable, TokenController { using SafeMath for uint; string public constant name = "SPECTRE SUBSCRIBER2 TOKEN"; string public constant symbol = "SXS2"; uint256 public constant decimals = 18; uint256 public constant TOTAL_CAP = 91627765897795994966351100; address public specDWallet; address public specUWallet; uint256 public transferTime = 0; uint256 public saleEnd = 1512907200; bool public tokenAddressesSet = false; uint256 constant D160 = 0x0010000000000000000000000000000000000000000; event OwnerTransfer(address indexed _from, address indexed _to, uint256 _value); event TransferTimeSet(uint256 _transferTime); modifier isTransferable() { require(tokenAddressesSet); require(getNow() > transferTime); _; } function setTransferTime(uint256 _transferTime) onlyOwner { transferTime = _transferTime; TransferTimeSet(transferTime); } function mint(address _to, uint256 _amount) onlyOwner { require(totalSupply.add(_amount) <= TOTAL_CAP); balances[_to] = balances[_to].add(_amount); totalSupply = totalSupply.add(_amount); Transfer(0, _to, _amount); } function burn(address _to, uint256 _amount) onlyOwner { balances[_to] = balances[_to].sub(_amount); totalSupply = totalSupply.sub(_amount); Transfer(_to, 0, _amount); } function setTokenAddresses(address _specUWallet, address _specDWallet) onlyOwner public { require(!tokenAddressesSet); require(_specDWallet != address(0)); require(_specUWallet != address(0)); require(isContract(_specDWallet)); require(isContract(_specUWallet)); specUWallet = _specUWallet; specDWallet = _specDWallet; tokenAddressesSet = true; } function withdrawEther() public onlyOwner { msg.sender.transfer(this.balance); } function transfer(address _to, uint256 _value) isTransferable returns (bool success) { require(_to == specDWallet || _to == specUWallet); require(isContract(_to)); bytes memory empty; return transferToContract(msg.sender, _to, _value, empty); } function isContract(address _addr) private returns (bool is_contract) { uint256 length; assembly { length := extcodesize(_addr) } return (length>0); } function transferToContract(address _from, address _to, uint256 _value, bytes _data) internal returns (bool success) { require(balanceOf(_from) >= _value); balances[_from] = balanceOf(_from).sub(_value); balances[_to] = balanceOf(_to).add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(_from, _value, _data); Transfer(_from, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public isTransferable returns (bool) { require(_to == specDWallet || _to == specUWallet); require(isContract(_to)); if (msg.sender == owner && getNow() > saleEnd + 30 days) { OwnerTransfer(_from, _to, _value); } else { uint256 _allowance = allowed[_from][msg.sender]; allowed[_from][msg.sender] = _allowance.sub(_value); } bytes memory empty; return transferToContract(_from, _to, _value, empty); } function multiMint(uint256[] data) public onlyOwner { for (uint256 i = 0; i < data.length; i++) { address addr = address(data[i] & (D160 - 1)); uint256 amount = data[i] / D160; mint(addr, amount); } } function multiBurn(uint256[] data) public onlyOwner { for (uint256 i = 0; i < data.length; i++) { address addr = address(data[i] & (D160 - 1)); uint256 amount = data[i] / D160; burn(addr, amount); } } function proxyPayment(address _owner) payable returns(bool) { return false; } function onTransfer(address _from, address _to, uint _amount) returns(bool) { return true; } function onApprove(address _owner, address _spender, uint _amount) returns(bool) { return true; } function getNow() constant internal returns (uint256) { return now; } }
0
pragma solidity ^0.4.24; library Helper { using SafeMath for uint256; uint256 constant public ZOOM = 1000; uint256 constant public SDIVIDER = 3450000; uint256 constant public PDIVIDER = 3450000; uint256 constant public RDIVIDER = 1580000; uint256 constant public SLP = 0.002 ether; uint256 constant public SAT = 30; uint256 constant public PN = 777; uint256 constant public PBASE = 13; uint256 constant public PMULTI = 26; uint256 constant public LBase = 1; uint256 constant public ONE_HOUR = 3600; uint256 constant public ONE_DAY = 24 * ONE_HOUR; uint256 constant public TIMEOUT1 = 12 * ONE_HOUR; uint256 constant public TIMEOUT2 = 7 * ONE_DAY; function bytes32ToString (bytes32 data) public pure returns (string) { bytes memory bytesString = new bytes(32); for (uint j=0; j<32; j++) { byte char = byte(bytes32(uint(data) * 2 ** (8 * j))); if (char != 0) { bytesString[j] = char; } } return string(bytesString); } function uintToBytes32(uint256 n) public pure returns (bytes32) { return bytes32(n); } function bytes32ToUint(bytes32 n) public pure returns (uint256) { return uint256(n); } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function stringToUint(string memory source) public pure returns (uint256) { return bytes32ToUint(stringToBytes32(source)); } function uintToString(uint256 _uint) public pure returns (string) { return bytes32ToString(uintToBytes32(_uint)); } function validUsername(string _username) public pure returns(bool) { uint256 len = bytes(_username).length; if ((len < 4) || (len > 18)) return false; if (bytes(_username)[len-1] == 32) return false; return uint256(bytes(_username)[0]) != 48; } function getAddedTime(uint256 _rTicketSum, uint256 _tAmount) public pure returns (uint256) { uint256 base = (_rTicketSum + 1).mul(10000) / SDIVIDER; uint256 expo = base; expo = expo.mul(expo).mul(expo); expo = expo.mul(expo); expo = expo / (10**24); if (expo > SAT) return 0; return (SAT - expo).mul(_tAmount); } function getNewEndTime(uint256 toAddTime, uint256 slideEndTime, uint256 fixedEndTime) public view returns(uint256) { uint256 _slideEndTime = (slideEndTime).add(toAddTime); uint256 timeout = _slideEndTime.sub(block.timestamp); if (timeout > TIMEOUT1) timeout = TIMEOUT1; _slideEndTime = (block.timestamp).add(timeout); if (_slideEndTime > fixedEndTime) return fixedEndTime; return _slideEndTime; } function getRandom(uint256 _seed, uint256 _range) public pure returns(uint256) { if (_range == 0) return _seed; return (_seed % _range) + 1; } function getEarlyIncomeMul(uint256 _ticketSum) public pure returns(uint256) { uint256 base = _ticketSum * ZOOM / RDIVIDER; uint256 expo = base.mul(base).mul(base); expo = expo.mul(expo) / (ZOOM**6); return (1 + PBASE / (1 + expo.mul(PMULTI))); } function getTAmount(uint256 _ethAmount, uint256 _ticketSum) public pure returns(uint256) { uint256 _tPrice = getTPrice(_ticketSum); return _ethAmount.div(_tPrice); } function isGoldenMin( uint256 _slideEndTime ) public view returns(bool) { uint256 _restTime1 = _slideEndTime.sub(block.timestamp); if (_restTime1 > 6 hours) return false; uint256 _min = (block.timestamp / 60) % 60; return _min == 8; } function getTMul( uint256 _initGrandPot, uint256 _grandPot, uint256 _slideEndTime, uint256 _fixedEndTime ) public view returns(uint256) { uint256 _pZoom = 100; uint256 base = _initGrandPot != 0 ?_pZoom.mul(_grandPot) / _initGrandPot : _pZoom; uint256 expo = base.mul(base); uint256 _timer1 = _slideEndTime.sub(block.timestamp) / 1 hours; uint256 _timer2 = _fixedEndTime.sub(block.timestamp) / 1 days; uint256 x = (_pZoom * (11 - _timer1) / 4) + _pZoom; uint256 y = (_pZoom * (6 - _timer2) / 3) + _pZoom; uint256 z = isGoldenMin(_slideEndTime) ? 4 : 1; uint256 res = expo.mul(x).mul(y).mul(z) / (_pZoom ** 3); return res; } function getTPrice(uint256 _ticketSum) public pure returns(uint256) { uint256 base = (_ticketSum + 1).mul(ZOOM) / PDIVIDER; uint256 expo = base; expo = expo.mul(expo).mul(expo); expo = expo.mul(expo); uint256 tPrice = SLP + expo / PN; return tPrice; } function getWeightRange(uint256 initGrandPot) public pure returns(uint256) { uint256 avgMul = 30; return ((initGrandPot * 2 * 100 / 68) * avgMul / SLP) + 1000; } function isJackpot( uint256 _seed, uint256 _RATE, uint256 _MIN, uint256 _ethAmount ) public pure returns(bool) { uint256 k = _ethAmount / _MIN; if (k == 0) return false; uint256 _loseCap = _RATE / 2; if (_RATE > k + _loseCap) _loseCap = _RATE - k; bool _lose = (_seed % _RATE) < _loseCap; return !_lose; } } contract Lottery { using SafeMath for uint256; modifier withdrawRight(){ require(msg.sender == address(bankContract), "Bank only"); _; } modifier onlyDevTeam() { require(msg.sender == devTeam, "only for development team"); _; } modifier buyable() { require(block.timestamp > round[curRoundId].startTime, "not ready to sell Ticket"); require(block.timestamp < round[curRoundId].slideEndTime, "round over"); require(block.number <= round[curRoundId].keyBlockNr, "round over"); _; } modifier notStarted() { require(block.timestamp < round[curRoundId].startTime, "round started"); _; } enum RewardType { Minor, Major, Grand, Bounty } struct Slot { address buyer; uint256 rId; uint256 tNumberFrom; uint256 tNumberTo; uint256 ethAmount; uint256 salt; } struct Round { uint256 rEarlyIncomeWeight; uint256 keyBlockNr; mapping(address => bool) pBonusReceived; mapping(address => uint256) pBoughtTicketSum; mapping(address => uint256) pTicketSum; mapping(address => uint256) pInvestedSum; mapping(address => uint256) pEarlyIncomeWeight; mapping(address => uint256) pEarlyIncomeCredit; mapping(address => uint256) pEarlyIncomeClaimed; uint256 ppw; uint256 startTime; uint256 slideEndTime; uint256 fixedEndTime; uint256 ticketSum; uint256 investedSum; uint256 slotSum; } uint256 public initGrandPot; Slot[] public slot; mapping( address => uint256[]) pSlot; mapping( address => uint256) public pSlotSum; mapping( address => uint256) public pTicketSum; mapping( address => uint256) public pInvestedSum; CitizenInterface public citizenContract; F2mInterface public f2mContract; BankInterface public bankContract; RewardInterface public rewardContract; address public devTeam; uint256 constant public ZOOM = 1000; uint256 constant public ONE_HOUR = 60 * 60; uint256 constant public ONE_DAY = 24 * ONE_HOUR; uint256 constant public TIMEOUT0 = 3 * ONE_HOUR; uint256 constant public TIMEOUT1 = 12 * ONE_HOUR; uint256 constant public TIMEOUT2 = 7 * ONE_DAY; uint256 constant public FINALIZE_WAIT_DURATION = 60; uint256 constant public NEWROUND_WAIT_DURATION = 18 * ONE_HOUR; uint256 constant public BLOCK_TIME = 12; uint256 constant public MAX_BLOCK_DISTANCE = 250; uint256 constant public TBONUS_RATE = 100; uint256 public CASHOUT_REQ = 1; uint256 public GRAND_RATE; uint256 public MAJOR_RATE = 1001; uint256 public MINOR_RATE = 501; uint256 constant public MAJOR_MIN = 0.1 ether; uint256 constant public MINOR_MIN = 0.1 ether; uint256 public bountyPercent = 30; uint256 public sBountyPercent = 10; uint256 public grandRewardPercent = 15; uint256 public sGrandRewardPercent = 5; uint256 public jRewardPercent = 60; uint256 public toTokenPercent = 12; uint256 public toBuyTokenPercent = 1; uint256 public earlyIncomePercent = 22; uint256 public toRefPercent = 15; uint256 public majorPercent = 10; uint256 public minorPercent = 10; uint256 public grandPot; uint256 public majorPot; uint256 public minorPot; uint256 public curRoundId; uint256 public lastRoundId = 88888888; mapping (address => uint256) public rewardBalance; mapping (address => uint256) public lastWithdrawnRound; mapping (address => uint256) public earlyIncomeScannedSum; mapping (uint256 => Round) public round; uint256 public jSlot; uint256 public lastBlockNr; uint256 public curRSalt; uint256 public curRTicketSum; uint256 public lastBuyTime; uint256 public lastEndTime; uint256 constant multiDelayTime = 60; constructor (address _devTeam) public { DevTeamInterface(_devTeam).setLotteryAddress(address(this)); devTeam = _devTeam; } function joinNetwork(address[6] _contract) public { require(address(citizenContract) == 0x0,"already setup"); f2mContract = F2mInterface(_contract[0]); bankContract = BankInterface(_contract[1]); citizenContract = CitizenInterface(_contract[2]); rewardContract = RewardInterface(_contract[4]); } function activeFirstRound() public onlyDevTeam() { require(curRoundId == 0, "already activated"); initRound(); GRAND_RATE = getWeightRange(); } function pushToPot() public payable { addPot(msg.value); } function checkpoint() private { Slot memory _slot; slot.push(_slot); Round memory _round; _round.startTime = NEWROUND_WAIT_DURATION.add(block.timestamp); _round.slideEndTime = TIMEOUT0 + _round.startTime; _round.fixedEndTime = TIMEOUT2 + _round.startTime; _round.keyBlockNr = genEstKeyBlockNr(_round.slideEndTime); _round.ticketSum = round[curRoundId].ticketSum; _round.investedSum = round[curRoundId].investedSum; _round.slotSum = slot.length; curRoundId = curRoundId + 1; round[curRoundId] = _round; initGrandPot = grandPot; curRTicketSum = 0; } function isLastRound() public view returns(bool) { return (curRoundId == lastRoundId); } function goNext() private { grandPot = 0; majorPot = 0; minorPot = 0; f2mContract.pushDividends.value(this.balance)(); round[curRoundId].startTime = block.timestamp * 10; round[curRoundId].slideEndTime = block.timestamp * 10 + 1; CASHOUT_REQ = 0; } function initRound() private { checkpoint(); if (isLastRound()) goNext(); updateMulti(); } function finalizeable() public view returns(bool) { uint256 finalizeTime = FINALIZE_WAIT_DURATION.add(round[curRoundId].slideEndTime); if (finalizeTime > block.timestamp) return false; if (getEstKeyBlockNr(curRoundId) >= block.number) return false; return curRoundId > 0; } function finalize() public { require(finalizeable(), "Not ready to draw results"); uint256 _pRoundTicketSum = round[curRoundId].pBoughtTicketSum[msg.sender]; uint256 _bountyTicketSum = _pRoundTicketSum * bountyPercent / 100; endRound(msg.sender, _bountyTicketSum); initRound(); mintSlot(msg.sender, _bountyTicketSum, 0, 0); } function mintReward( address _lucker, uint256 _winNr, uint256 _slotId, uint256 _value, RewardType _rewardType) private { if ((_rewardType != RewardType.Bounty) && (_lucker != 0x0)) rewardBalance[_lucker] = rewardBalance[_lucker].add(_value); rewardContract.mintReward( _lucker, curRoundId, _winNr, slot[_slotId].tNumberFrom, slot[_slotId].tNumberTo, _value, uint256(_rewardType) ); } function mintSlot( address _buyer, uint256 _tAmount, uint256 _ethAmount, uint256 _salt ) private { uint256 _tNumberFrom = curRTicketSum + 1; uint256 _tNumberTo = _tNumberFrom + _tAmount - 1; Slot memory _slot; _slot.buyer = _buyer; _slot.rId = curRoundId; _slot.tNumberFrom = _tNumberFrom; _slot.tNumberTo = _tNumberTo; _slot.ethAmount = _ethAmount; _slot.salt = _salt; slot.push(_slot); updateTicketSum(_buyer, _tAmount); round[curRoundId].slotSum = slot.length; pSlot[_buyer].push(slot.length - 1); } function jackpot() private { uint256 keyBlockNr = getKeyBlockNr(lastBlockNr); uint256 seed = getSeed(keyBlockNr); uint256 jReward; address winner; while (jSlot + 1 < round[curRoundId].slotSum) { if (MAJOR_RATE > 2) MAJOR_RATE--; if (Helper.isJackpot(seed, MAJOR_RATE, MAJOR_MIN, slot[jSlot].ethAmount)){ winner = slot[jSlot].buyer; jReward = majorPot / 100 * jRewardPercent; mintReward(winner, 0, jSlot, jReward, RewardType.Major); majorPot = majorPot - jReward; MAJOR_RATE = 1001; } seed = seed + jSlot; if (MINOR_RATE > 2) MINOR_RATE--; if (Helper.isJackpot(seed, MINOR_RATE, MINOR_MIN, slot[jSlot].ethAmount)){ winner = slot[jSlot].buyer; jReward = minorPot / 100 * jRewardPercent; mintReward(winner, 0, jSlot, jReward, RewardType.Minor); minorPot = minorPot - jReward; MINOR_RATE = 501; } seed = seed + jSlot; jSlot++; } } function endRound(address _bountyHunter, uint256 _bountyTicketSum) private { uint256 _rId = curRoundId; uint256 keyBlockNr = getKeyBlockNr(round[_rId].keyBlockNr); uint256 _seed = getSeed(keyBlockNr) + curRSalt; uint256 onePercent = grandPot / 100; uint256[2] memory rGrandReward = [ onePercent * sGrandRewardPercent, onePercent * grandRewardPercent ]; uint256[2] memory weightRange = [ curRTicketSum, GRAND_RATE > curRTicketSum ? GRAND_RATE : curRTicketSum ]; for (uint256 i = 0; i < 2; i++){ address _winner = 0x0; uint256 _winSlot = 0; uint256 _winNr = Helper.getRandom(_seed, weightRange[i]); if (_winNr <= curRTicketSum) { grandPot -= rGrandReward[i]; if (i == 1) { GRAND_RATE = GRAND_RATE * 2; } _winSlot = getWinSlot(_winNr); _winner = slot[_winSlot].buyer; _seed = _seed + (_seed / 10); } mintReward(_winner, _winNr, _winSlot, rGrandReward[i], RewardType.Grand); } mintReward(_bountyHunter, 0, 0, _bountyTicketSum, RewardType.Bounty); rewardContract.resetCounter(curRoundId); GRAND_RATE = (GRAND_RATE / 100) * 99 + 1; } function buy(string _sSalt) public payable { buyFor(_sSalt, msg.sender); } function updateInvested(address _buyer, uint256 _ethAmount) private { round[curRoundId].investedSum += _ethAmount; round[curRoundId].pInvestedSum[_buyer] += _ethAmount; pInvestedSum[_buyer] += _ethAmount; } function updateTicketSum(address _buyer, uint256 _tAmount) private { round[curRoundId].ticketSum = round[curRoundId].ticketSum + _tAmount; round[curRoundId].pTicketSum[_buyer] = round[curRoundId].pTicketSum[_buyer] + _tAmount; curRTicketSum = curRTicketSum + _tAmount; pTicketSum[_buyer] = pTicketSum[_buyer] + _tAmount; } function updateEarlyIncome(address _buyer, uint256 _pWeight) private { round[curRoundId].rEarlyIncomeWeight = _pWeight.add(round[curRoundId].rEarlyIncomeWeight); round[curRoundId].pEarlyIncomeWeight[_buyer] = _pWeight.add(round[curRoundId].pEarlyIncomeWeight[_buyer]); round[curRoundId].pEarlyIncomeCredit[_buyer] = round[curRoundId].pEarlyIncomeCredit[_buyer].add(_pWeight.mul(round[curRoundId].ppw)); } function getBonusTickets(address _buyer) private returns(uint256) { if (round[curRoundId].pBonusReceived[_buyer]) return 0; round[curRoundId].pBonusReceived[_buyer] = true; return round[curRoundId - 1].pBoughtTicketSum[_buyer] / TBONUS_RATE; } function updateMulti() private { if (lastBuyTime + multiDelayTime < block.timestamp) { lastEndTime = round[curRoundId].slideEndTime; } lastBuyTime = block.timestamp; } function buyFor(string _sSalt, address _sender) public payable buyable() { uint256 _salt = Helper.stringToUint(_sSalt); uint256 _ethAmount = msg.value; uint256 _ticketSum = curRTicketSum; require(_ethAmount >= Helper.getTPrice(_ticketSum), "not enough to buy 1 ticket"); updateInvested(_sender, _ethAmount); updateMulti(); curRSalt = curRSalt + _salt; uint256 _tAmount = Helper.getTAmount(_ethAmount, _ticketSum); uint256 _tMul = getTMul(); uint256 _pMul = Helper.getEarlyIncomeMul(_ticketSum); uint256 _pWeight = _pMul.mul(_tAmount); uint256 _toAddTime = Helper.getAddedTime(_ticketSum, _tAmount); addTime(curRoundId, _toAddTime); _tAmount = _tAmount.mul(_tMul) / 100; round[curRoundId].pBoughtTicketSum[_sender] += _tAmount; mintSlot(_sender, _tAmount + getBonusTickets(_sender), _ethAmount, _salt); updateEarlyIncome(_sender, _pWeight); if (lastBlockNr != block.number) { jackpot(); lastBlockNr = block.number; } distributeSlotBuy(_sender, curRoundId, _ethAmount); round[curRoundId].keyBlockNr = genEstKeyBlockNr(round[curRoundId].slideEndTime); } function distributeSlotBuy(address _sender, uint256 _rId, uint256 _ethAmount) private { uint256 onePercent = _ethAmount / 100; uint256 toF2mAmount = onePercent * toTokenPercent; uint256 toRefAmount = onePercent * toRefPercent; uint256 toBuyTokenAmount = onePercent * toBuyTokenPercent; uint256 earlyIncomeAmount = onePercent * earlyIncomePercent; uint256 taxAmount = toF2mAmount + toRefAmount + toBuyTokenAmount + earlyIncomeAmount; uint256 taxedEthAmount = _ethAmount.sub(taxAmount); addPot(taxedEthAmount); citizenContract.pushRefIncome.value(toRefAmount)(_sender); f2mContract.pushDividends.value(toF2mAmount)(); f2mContract.buyFor.value(toBuyTokenAmount)(_sender); uint256 deltaPpw = (earlyIncomeAmount * ZOOM).div(round[_rId].rEarlyIncomeWeight); round[_rId].ppw = deltaPpw.add(round[_rId].ppw); } function claimEarlyIncomebyAddress(address _buyer) private { if (curRoundId == 0) return; claimEarlyIncomebyAddressRound(_buyer, curRoundId); uint256 _rId = curRoundId - 1; while ((_rId > lastWithdrawnRound[_buyer]) && (_rId + 20 > curRoundId)) { earlyIncomeScannedSum[_buyer] += claimEarlyIncomebyAddressRound(_buyer, _rId); _rId = _rId - 1; } } function claimEarlyIncomebyAddressRound(address _buyer, uint256 _rId) private returns(uint256) { uint256 _amount = getCurEarlyIncomeByAddressRound(_buyer, _rId); if (_amount == 0) return 0; round[_rId].pEarlyIncomeClaimed[_buyer] = _amount.add(round[_rId].pEarlyIncomeClaimed[_buyer]); rewardBalance[_buyer] = _amount.add(rewardBalance[_buyer]); return _amount; } function withdrawFor(address _sender) public withdrawRight() returns(uint256) { if (curRoundId == 0) return; claimEarlyIncomebyAddress(_sender); lastWithdrawnRound[_sender] = curRoundId - 1; uint256 _amount = rewardBalance[_sender]; rewardBalance[_sender] = 0; bankContract.pushToBank.value(_amount)(_sender); return _amount; } function addTime(uint256 _rId, uint256 _toAddTime) private { round[_rId].slideEndTime = Helper.getNewEndTime(_toAddTime, round[_rId].slideEndTime, round[_rId].fixedEndTime); } function addPot(uint256 _amount) private { uint256 onePercent = _amount / 100; uint256 toMinor = onePercent * minorPercent; uint256 toMajor = onePercent * majorPercent; uint256 toGrand = _amount - toMinor - toMajor; minorPot = minorPot + toMinor; majorPot = majorPot + toMajor; grandPot = grandPot + toGrand; } function isWinSlot(uint256 _slotId, uint256 _keyNumber) public view returns(bool) { return (slot[_slotId - 1].tNumberTo < _keyNumber) && (slot[_slotId].tNumberTo >= _keyNumber); } function getWeightRange() public view returns(uint256) { return Helper.getWeightRange(initGrandPot); } function getWinSlot(uint256 _keyNumber) public view returns(uint256) { uint256 _to = slot.length - 1; uint256 _from = round[curRoundId-1].slotSum + 1; uint256 _pivot; uint256 _pivotTo; while (_from <= _to) { _pivot = (_from + _to) / 2; _pivotTo = slot[_pivot].tNumberTo; if (isWinSlot(_pivot, _keyNumber)) return _pivot; if (_pivotTo < _keyNumber) { _from = _pivot + 1; } else { _to = _pivot - 1; } } return _pivot; } function genEstKeyBlockNr(uint256 _endTime) public view returns(uint256) { if (block.timestamp >= _endTime) return block.number + 8; uint256 timeDist = _endTime - block.timestamp; uint256 estBlockDist = timeDist / BLOCK_TIME; return block.number + estBlockDist + 8; } function getSeed(uint256 _keyBlockNr) public view returns (uint256) { if (block.number <= _keyBlockNr) return block.number; return uint256(blockhash(_keyBlockNr)); } function getRewardBalance(address _buyer) public view returns(uint256) { return rewardBalance[_buyer]; } function getSlideEndTime(uint256 _rId) public view returns(uint256) { return(round[_rId].slideEndTime); } function getFixedEndTime(uint256 _rId) public view returns(uint256) { return(round[_rId].fixedEndTime); } function getTotalPot() public view returns(uint256) { return grandPot + majorPot + minorPot; } function getEarlyIncomeByAddress(address _buyer) public view returns(uint256) { uint256 _sum = earlyIncomeScannedSum[_buyer]; uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100; uint256 _rId = _fromRound; while (_rId <= curRoundId) { _sum = _sum + getEarlyIncomeByAddressRound(_buyer, _rId); _rId++; } return _sum; } function getEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256) { uint256 _pWeight = round[_rId].pEarlyIncomeWeight[_buyer]; uint256 _ppw = round[_rId].ppw; uint256 _rCredit = round[_rId].pEarlyIncomeCredit[_buyer]; uint256 _rEarlyIncome = ((_ppw.mul(_pWeight)).sub(_rCredit)).div(ZOOM); return _rEarlyIncome; } function getCurEarlyIncomeByAddress(address _buyer) public view returns(uint256) { uint256 _sum = 0; uint256 _fromRound = lastWithdrawnRound[_buyer] + 1; if (_fromRound + 100 < curRoundId) _fromRound = curRoundId - 100; uint256 _rId = _fromRound; while (_rId <= curRoundId) { _sum = _sum.add(getCurEarlyIncomeByAddressRound(_buyer, _rId)); _rId++; } return _sum; } function getCurEarlyIncomeByAddressRound(address _buyer, uint256 _rId) public view returns(uint256) { uint256 _rEarlyIncome = getEarlyIncomeByAddressRound(_buyer, _rId); return _rEarlyIncome.sub(round[_rId].pEarlyIncomeClaimed[_buyer]); } function getEstKeyBlockNr(uint256 _rId) public view returns(uint256) { return round[_rId].keyBlockNr; } function getKeyBlockNr(uint256 _estKeyBlockNr) public view returns(uint256) { require(block.number > _estKeyBlockNr, "blockHash not avaiable"); uint256 jump = (block.number - _estKeyBlockNr) / MAX_BLOCK_DISTANCE * MAX_BLOCK_DISTANCE; return _estKeyBlockNr + jump; } function getCurRoundId() public view returns(uint256) { return curRoundId; } function getTPrice() public view returns(uint256) { return Helper.getTPrice(curRTicketSum); } function getTMul() public view returns(uint256) { return Helper.getTMul( initGrandPot, grandPot, lastBuyTime + multiDelayTime < block.timestamp ? round[curRoundId].slideEndTime : lastEndTime, round[curRoundId].fixedEndTime ); } function getPMul() public view returns(uint256) { return Helper.getEarlyIncomeMul(curRTicketSum); } function getPTicketSumByRound(uint256 _rId, address _buyer) public view returns(uint256) { return round[_rId].pTicketSum[_buyer]; } function getTicketSumToRound(uint256 _rId) public view returns(uint256) { return round[_rId].ticketSum; } function getPInvestedSumByRound(uint256 _rId, address _buyer) public view returns(uint256) { return round[_rId].pInvestedSum[_buyer]; } function getInvestedSumToRound(uint256 _rId) public view returns(uint256) { return round[_rId].investedSum; } function getPSlotLength(address _sender) public view returns(uint256) { return pSlot[_sender].length; } function getSlotLength() public view returns(uint256) { return slot.length; } function getSlotId(address _sender, uint256 i) public view returns(uint256) { return pSlot[_sender][i]; } function getSlotInfo(uint256 _slotId) public view returns(address, uint256[4], string) { Slot memory _slot = slot[_slotId]; return (_slot.buyer,[_slot.rId, _slot.tNumberFrom, _slot.tNumberTo, _slot.ethAmount], Helper.uintToString(_slot.salt)); } function cashoutable(address _address) public view returns(bool) { if (round[curRoundId].pTicketSum[_address] >= CASHOUT_REQ) return true; if (round[curRoundId].startTime > block.timestamp) { uint256 _lastRoundTickets = getPTicketSumByRound(curRoundId - 1, _address); if (_lastRoundTickets >= CASHOUT_REQ) return true; } return false; } function setLastRound(uint256 _lastRoundId) public onlyDevTeam() { require(_lastRoundId >= 8 && _lastRoundId > curRoundId, "too early to end"); require(lastRoundId == 88888888, "already set"); lastRoundId = _lastRoundId; } function sBountyClaim(address _sBountyHunter) public notStarted() returns(uint256) { require(msg.sender == address(rewardContract), "only Reward contract can manage sBountys"); uint256 _lastRoundTickets = round[curRoundId - 1].pBoughtTicketSum[_sBountyHunter]; uint256 _sBountyTickets = _lastRoundTickets * sBountyPercent / 100; mintSlot(_sBountyHunter, _sBountyTickets, 0, 0); return _sBountyTickets; } } interface F2mInterface { function joinNetwork(address[6] _contract) public; function activeBuy() public; function pushDividends() public payable; function buyFor(address _buyer) public payable; function sell(uint256 _tokenAmount) public; function exit() public; function devTeamWithdraw() public returns(uint256); function withdrawFor(address sender) public returns(uint256); function transfer(address _to, uint256 _tokenAmount) public returns(bool); function setAutoBuy() public; function ethBalance(address _address) public view returns(uint256); function myBalance() public view returns(uint256); function myEthBalance() public view returns(uint256); function swapToken() public; function setNewToken(address _newTokenAddress) public; } interface CitizenInterface { function joinNetwork(address[6] _contract) public; function devTeamWithdraw() public; function updateUsername(string _sNewUsername) public; function pushRefIncome(address _sender) public payable; function withdrawFor(address _sender) public payable returns(uint256); function devTeamReinvest() public returns(uint256); function getRefWallet(address _address) public view returns(uint256); } interface DevTeamInterface { function setF2mAddress(address _address) public; function setLotteryAddress(address _address) public; function setCitizenAddress(address _address) public; function setBankAddress(address _address) public; function setRewardAddress(address _address) public; function setWhitelistAddress(address _address) public; function setupNetwork() public; } interface BankInterface { function joinNetwork(address[6] _contract) public; function pushToBank(address _player) public payable; } interface RewardInterface { function mintReward( address _lucker, uint256 curRoundId, uint256 _winNr, uint256 _tNumberFrom, uint256 _tNumberTo, uint256 _value, uint256 _rewardType) public; function joinNetwork(address[6] _contract) public; function pushBounty(uint256 _curRoundId) public payable; function resetCounter(uint256 _curRoundId) public; } library SafeMath { int256 constant private INT256_MIN = -2**255; function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function mul(int256 a, int256 b) internal pure returns (int256) { if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); int256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); require(!(b == -1 && a == INT256_MIN)); int256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
0
pragma solidity ^0.4.21; contract ERC20 { function totalSupply() public view returns (uint256 totalSup); function balanceOf(address _owner) public view returns (uint256 balance); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); function approve(address _spender, uint256 _value) public returns (bool success); function transfer(address _to, uint256 _value) public returns (bool success); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ERC223 { function transfer(address _to, uint256 _value, bytes _data) public returns (bool success); event Transfer(address indexed _from, address indexed _to, uint _value, bytes _data); } contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } contract CCP is ERC223, ERC20 { using SafeMath for uint256; uint public constant _totalSupply = 2100000000e18; string public constant symbol = "CCP"; string public constant name = "CCP COIN"; uint8 public constant decimals = 18; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; constructor() public{ balances[msg.sender] = _totalSupply; emit Transfer(0x0, msg.sender, _totalSupply); } function totalSupply() public view returns (uint256 totalSup) { return _totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool success) { require( !isContract(_to) ); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transfer(address _to, uint256 _value, bytes _data) public returns (bool success){ require( isContract(_to) ); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); ERC223ReceivingContract(_to).tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; } function isContract(address _from) private view returns (bool) { uint256 codeSize; assembly { codeSize := extcodesize(_from) } return codeSize > 0; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require( balances[_from] >= _value && _value > 0 ); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { require( (_value == 0) || (allowed[msg.sender][_spender] == 0) ); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remain) { return allowed[_owner][_spender]; } function () public payable { revert(); } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Transfer(address indexed _from, address indexed _to, uint _value, bytes _data); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract FreezableToken is StandardToken { mapping (bytes32 => uint64) internal chains; mapping (bytes32 => uint) internal freezings; mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "GivingToServices"; string public constant TOKEN_SYMBOL = "SVCS"; bool public constant PAUSED = false; address public constant TARGET_USER = 0x02dFf622C814247E4Ea4F16184D1Ece6f1021671; bool public constant CONTINUE_MINTING = false; } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { event Initialized(); bool public initialized = false; constructor() public { init(); transferOwnership(TARGET_USER); } function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } function init() private { require(!initialized); initialized = true; if (PAUSED) { pause(); } address[1] memory addresses = [address(0x02dff622c814247e4ea4f16184d1ece6f1021671)]; uint[1] memory amounts = [uint(10000000000000000000000000000)]; uint64[1] memory freezes = [uint64(0)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { mint(addresses[i], amounts[i]); } else { mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } if (!CONTINUE_MINTING) { finishMinting(); } emit Initialized(); } }
1
pragma solidity ^0.4.24; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } } contract RandomNumber { using SafeMath for *; address _owner; uint24 private _number; uint256 private _time; uint256 private _timespan; event onNewNumber ( uint24 number, uint256 time ); constructor(uint256 timespan) public { _owner = msg.sender; _time = 0; _number = 0; _timespan = timespan; } function number() public view returns (uint24) { return _number; } function time() public view returns (uint256) { return _time; } function timespan() public view returns (uint256) { return _timespan; } function genNumber() public { require(block.timestamp > _time + _timespan); _time = block.timestamp; _number = random(); emit RandomNumber.onNewNumber ( _number, _time ); } function random() private view returns (uint24) { uint256 randnum = 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) ))); return uint24(randnum%1000000); } }
1
pragma solidity ^0.4.23; library AZTECInterface { function validateJoinSplit(bytes32[6][], uint, uint, bytes32[4]) external pure returns (bool) {} } contract ERC20Interface { function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } contract AZTECERC20Bridge { uint private constant groupModulusBoundary = 10944121435919637611123202872628637544274182200208017171849102093287904247808; uint private constant groupModulus = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint public scalingFactor; mapping(bytes32 => address) public noteRegistry; bytes32[4] setupPubKey; bytes32 domainHash; ERC20Interface token; event Created(bytes32 domainHash, address contractAddress); event ConfidentialTransfer(); constructor(bytes32[4] _setupPubKey, address _token, uint256 _scalingFactor) public { setupPubKey = _setupPubKey; token = ERC20Interface(_token); scalingFactor = _scalingFactor; bytes32 _domainHash; assembly { let m := mload(0x40) mstore(m, 0x8d4b25bfecb769291b71726cd5ec8a497664cc7292c02b1868a0534306741fd9) mstore(add(m, 0x20), 0x87a23625953c9fb02b3570c86f75403039bbe5de82b48ca671c10157d91a991a) mstore(add(m, 0x40), 0x25130290f410620ec94e7cf11f1cdab5dea284e1039a83fa7b87f727031ff5f4) mstore(add(m, 0x60), 1) mstore(add(m, 0x80), 0x210db872dec2e06c375dd40a5a354307bb4ba52ba65bd84594554580ae6f0639) mstore(add(m, 0xa0), address) _domainHash := keccak256(m, 0xc0) } domainHash = _domainHash; emit Created(_domainHash, this); } function validateInputNote(bytes32[6] note, bytes32[3] signature, uint challenge, bytes32 domainHashT) internal { bytes32 noteHash; bytes32 signatureMessage; assembly { let m := mload(0x40) mstore(m, mload(add(note, 0x40))) mstore(add(m, 0x20), mload(add(note, 0x60))) mstore(add(m, 0x40), mload(add(note, 0x80))) mstore(add(m, 0x60), mload(add(note, 0xa0))) noteHash := keccak256(m, 0x80) mstore(m, 0x1aba5d08f7cd777136d3fa7eb7baa742ab84001b34c9de5b17d922fc2ca75cce) mstore(add(m, 0x20), noteHash) mstore(add(m, 0x40), challenge) mstore(add(m, 0x60), caller) mstore(add(m, 0x40), keccak256(m, 0x80)) mstore(add(m, 0x20), domainHashT) mstore(m, 0x1901) signatureMessage := keccak256(add(m, 0x1e), 0x42) } address owner = ecrecover(signatureMessage, uint8(signature[0]), signature[1], signature[2]); require(owner != address(0), "signature invalid"); require(noteRegistry[noteHash] == owner, "expected input note to exist in registry"); noteRegistry[noteHash] = 0; } function validateOutputNote(bytes32[6] note, address owner) internal { bytes32 noteHash; assembly { let m := mload(0x40) mstore(m, mload(add(note, 0x40))) mstore(add(m, 0x20), mload(add(note, 0x60))) mstore(add(m, 0x40), mload(add(note, 0x80))) mstore(add(m, 0x60), mload(add(note, 0xa0))) noteHash := keccak256(m, 0x80) } require(owner != address(0), "owner must be valid Ethereum address"); require(noteRegistry[noteHash] == 0, "expected output note to not exist in registry"); noteRegistry[noteHash] = owner; } function confidentialTransfer(bytes32[6][] notes, uint256 m, uint256 challenge, bytes32[3][] inputSignatures, address[] outputOwners, bytes) external { require(inputSignatures.length == m, "input signature length invalid"); require(inputSignatures.length + outputOwners.length == notes.length, "array length mismatch"); require(AZTECInterface.validateJoinSplit(notes, m, challenge, setupPubKey), "proof not valid!"); uint256 kPublic = uint(notes[notes.length - 1][0]); require(kPublic < groupModulus, "invalid value of kPublic"); for (uint256 i = 0; i < notes.length; i++) { if (i < m) { validateInputNote(notes[i], inputSignatures[i], challenge, domainHash); } else { validateOutputNote(notes[i], outputOwners[i - m]); } } if (kPublic > 0) { if (kPublic < groupModulusBoundary) { require(token.transfer(msg.sender, kPublic * scalingFactor), "token transfer to user failed!"); } else { require(token.transferFrom(msg.sender, this, (groupModulus - kPublic) * scalingFactor), "token transfer from user failed!"); } } emit ConfidentialTransfer(); } }
1
pragma solidity ^0.4.11; contract ERC20Interface { function totalSupply() constant returns (uint256); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract DatCoin is ERC20Interface { uint8 public constant decimals = 5; string public constant symbol = "DTC"; string public constant name = "DatCoin"; uint public _totalSupply = 10 ** 14; uint public _originalBuyPrice = 10 ** 10; uint public _minimumBuyAmount = 10 ** 17; uint public _thresholdOne = 9 * (10 ** 13); uint public _thresholdTwo = 85 * (10 ** 12); address public owner; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } modifier thresholdTwo() { if (msg.value < _minimumBuyAmount || balances[owner] <= _thresholdTwo) { revert(); } _; } function DatCoin() { owner = msg.sender; balances[owner] = _totalSupply; } function totalSupply() constant returns (uint256) { return _totalSupply; } function balanceOf(address _owner) constant returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _amount) returns (bool) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } function transferFrom( address _from, address _to, uint256 _amount ) returns (bool) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } function approve(address _spender, uint256 _amount) returns (bool) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } function buy() payable thresholdTwo returns (uint256 amount) { uint value = msg.value; amount = value / _originalBuyPrice; if (balances[owner] <= _thresholdOne + amount) { uint temp = 0; if (balances[owner] > _thresholdOne) temp = balances[owner] - _thresholdOne; amount = temp + (amount - temp) * 10 / 13; if (balances[owner] < amount) { temp = (amount - balances[owner]) * (_originalBuyPrice * 13 / 10); msg.sender.transfer(temp); amount = balances[owner]; value -= temp; } } owner.transfer(value); balances[msg.sender] += amount; balances[owner] -= amount; Transfer(owner, msg.sender, amount); return amount; } function withdraw() onlyOwner returns (bool) { return owner.send(this.balance); } }
1
pragma solidity ^0.4.16; contract MyToken { mapping (address => uint256) public balanceOf; string public name; string public symbol; uint8 public decimals; event Transfer(address indexed from, address indexed to, uint256 value); function MyToken(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) public { balanceOf[msg.sender] = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; } function transfer(address _to, uint256 _value) public { require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } }
1
contract FourPercentDaily { struct _Tx { address txuser; uint txvalue; } _Tx[] public Tx; uint public counter; mapping (address => uint256) public accounts; address owner; function FourPercentDaily() { owner = msg.sender; } function() { Sort(); if (msg.sender == owner ) { Count(); } } function Sort() internal { uint feecounter; feecounter+=msg.value/6; owner.send(feecounter); feecounter=0; uint txcounter=Tx.length; counter=Tx.length; Tx.length++; Tx[txcounter].txuser=msg.sender; Tx[txcounter].txvalue=msg.value; } function Count() { if (msg.sender != owner) { throw; } while (counter>0) { uint distAmount = (Tx[counter].txvalue/100)*4; accounts[Tx[counter].txuser] = accounts[Tx[counter].txuser] + distAmount; counter-=1; } } function getMyAccountBalance() public returns(uint256) { return(accounts[msg.sender]); } function withdraw() public { if (accounts[msg.sender] == 0) { throw;} uint withdrawAmountNormal = accounts[msg.sender]; accounts[msg.sender] = 0; msg.sender.send(withdrawAmountNormal); } }
1
pragma solidity ^0.4.19; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract EjectableOwnable is Ownable { function removeOwnership() onlyOwner public { owner = 0x0; } } contract JointOwnable is Ownable { event AnotherOwnerAssigned(address indexed anotherOwner); address public anotherOwner; modifier eitherOwner() { require(msg.sender == owner || msg.sender == anotherOwner); _; } function assignAnotherOwner(address _anotherOwner) onlyOwner public { require(_anotherOwner != 0); AnotherOwnerAssigned(_anotherOwner); anotherOwner = _anotherOwner; } } contract Destructible is Ownable { function Destructible() public payable { } function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } } contract DungeonStructs { struct Dungeon { uint32 creationTime; uint16 status; uint16 difficulty; uint32 floorNumber; uint32 floorCreationTime; uint128 rewards; uint seedGenes; uint floorGenes; } struct Hero { uint64 creationTime; uint genes; } } contract ERC721 { event Transfer(address indexed from, address indexed to, uint tokenId); function totalSupply() public view returns (uint); function balanceOf(address _owner) public view returns (uint); function ownerOf(uint _tokenId) external view returns (address); function transfer(address _to, uint _tokenId) external; } contract DungeonToken is ERC721, DungeonStructs, Pausable, JointOwnable { uint public constant DUNGEON_CREATION_LIMIT = 1024; event Mint(address indexed owner, uint newTokenId, uint difficulty, uint seedGenes); event NewDungeonFloor(uint timestamp, uint indexed dungeonId, uint32 newFloorNumber, uint128 newRewards , uint newFloorGenes); event Transfer(address indexed from, address indexed to, uint tokenId); string public constant name = "Dungeon"; string public constant symbol = "DUNG"; Dungeon[] public dungeons; mapping(uint => address) tokenIndexToOwner; mapping(address => uint) ownershipTokenCount; mapping(address => uint[]) public ownerTokens; function totalSupply() public view returns (uint) { return dungeons.length; } function balanceOf(address _owner) public view returns (uint) { return ownershipTokenCount[_owner]; } function _owns(address _claimant, uint _tokenId) internal view returns (bool) { return tokenIndexToOwner[_tokenId] == _claimant; } function ownerOf(uint _tokenId) external view returns (address) { require(tokenIndexToOwner[_tokenId] != address(0)); return tokenIndexToOwner[_tokenId]; } function _transfer(address _from, address _to, uint _tokenId) internal { ownershipTokenCount[_to]++; tokenIndexToOwner[_tokenId] = _to; ownerTokens[_to].push(_tokenId); if (_from != address(0)) { ownershipTokenCount[_from]--; uint[] storage fromTokens = ownerTokens[_from]; bool iFound = false; for (uint i = 0; i < fromTokens.length - 1; i++) { if (iFound) { fromTokens[i] = fromTokens[i + 1]; } else if (fromTokens[i] == _tokenId) { iFound = true; } } } Transfer(_from, _to, _tokenId); } function transfer(address _to, uint _tokenId) whenNotPaused external { require(_to != address(0)); require(_to != address(this)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } function createDungeon(uint _difficulty, uint _seedGenes, address _owner) eitherOwner external returns (uint) { require(totalSupply() < DUNGEON_CREATION_LIMIT); dungeons.push(Dungeon(uint32(now), 0, uint16(_difficulty), 0, 0, 0, _seedGenes, 0)); uint newTokenId = dungeons.length - 1; Mint(_owner, newTokenId, _difficulty, _seedGenes); addDungeonNewFloor(newTokenId, 0, _seedGenes); _transfer(0, _owner, newTokenId); return newTokenId; } function setDungeonStatus(uint _id, uint _newStatus) eitherOwner external { require(_id < totalSupply()); dungeons[_id].status = uint16(_newStatus); } function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner external { require(_id < totalSupply()); dungeons[_id].rewards += uint64(_additinalRewards); } function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner public { require(_id < totalSupply()); Dungeon storage dungeon = dungeons[_id]; dungeon.floorNumber++; dungeon.floorCreationTime = uint32(now); dungeon.rewards = uint128(_newRewards); dungeon.floorGenes = _newFloorGenes; NewDungeonFloor(now, _id, dungeon.floorNumber, dungeon.rewards, dungeon.floorGenes); } } contract HeroToken is ERC721, DungeonStructs, Pausable, JointOwnable { event Mint(address indexed owner, uint newTokenId, uint _genes); event Transfer(address indexed from, address indexed to, uint tokenId); string public constant name = "Hero"; string public constant symbol = "HERO"; Hero[] public heroes; mapping(uint => address) tokenIndexToOwner; mapping(address => uint) ownershipTokenCount; mapping(address => uint[]) public ownerTokens; function totalSupply() public view returns (uint) { return heroes.length; } function balanceOf(address _owner) public view returns (uint) { return ownershipTokenCount[_owner]; } function _owns(address _claimant, uint _tokenId) internal view returns (bool) { return tokenIndexToOwner[_tokenId] == _claimant; } function ownerOf(uint _tokenId) external view returns (address) { require(tokenIndexToOwner[_tokenId] != address(0)); return tokenIndexToOwner[_tokenId]; } function _transfer(address _from, address _to, uint _tokenId) internal { ownershipTokenCount[_to]++; tokenIndexToOwner[_tokenId] = _to; ownerTokens[_to].push(_tokenId); if (_from != address(0)) { ownershipTokenCount[_from]--; uint[] storage fromTokens = ownerTokens[_from]; bool iFound = false; for (uint i = 0; i < fromTokens.length - 1; i++) { if (iFound) { fromTokens[i] = fromTokens[i + 1]; } else if (fromTokens[i] == _tokenId) { iFound = true; } } } Transfer(_from, _to, _tokenId); } function transfer(address _to, uint _tokenId) whenNotPaused external { require(_to != address(0)); require(_to != address(this)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } function createHero(uint _genes, address _owner) external returns (uint) { heroes.push(Hero(uint64(now), _genes)); uint newTokenId = heroes.length - 1; Mint(_owner, newTokenId, _genes); _transfer(0, _owner, newTokenId); return newTokenId; } function setHeroGenes(uint _id, uint _newGenes) eitherOwner external { require(_id < totalSupply()); Hero storage hero = heroes[_id]; hero.genes = _newGenes; } } contract ChallengeScienceInterface { function mixGenes(uint _floorGenes, uint _seedGenes) external pure returns (uint); } contract TrainingScienceInterface { function mixGenes(uint _heroGenes, uint _floorGenes) external pure returns (uint); } contract DungeonBase is EjectableOwnable, Pausable, PullPayment, DungeonStructs { DungeonToken public dungeonTokenContract; HeroToken public heroTokenContract; ChallengeScienceInterface challengeScienceContract; TrainingScienceInterface trainingScienceContract; function setDungeonTokenContract(address _newDungeonTokenContract) onlyOwner external { dungeonTokenContract = DungeonToken(_newDungeonTokenContract); } function setHeroTokenContract(address _newHeroTokenContract) onlyOwner external { heroTokenContract = HeroToken(_newHeroTokenContract); } function setChallengeScienceContract(address _newChallengeScienceAddress) onlyOwner external { challengeScienceContract = ChallengeScienceInterface(_newChallengeScienceAddress); } function setTrainingScienceContract(address _newTrainingScienceAddress) onlyOwner external { trainingScienceContract = TrainingScienceInterface(_newTrainingScienceAddress); } modifier dungeonExists(uint _dungeonId) { require(_dungeonId < dungeonTokenContract.totalSupply()); _; } modifier canChallenge(uint _dungeonId) { require(_dungeonId < dungeonTokenContract.totalSupply()); uint status; (,status,,,,,,) = dungeonTokenContract.dungeons(_dungeonId); require(status == 0 || status == 1); _; } modifier canTrain(uint _dungeonId) { require(_dungeonId < dungeonTokenContract.totalSupply()); uint status; (,status,,,,,,) = dungeonTokenContract.dungeons(_dungeonId); require(status == 0 || status == 2); _; } function _getGenesPower(uint _genes) internal pure returns (uint) { uint statsPower; for (uint i = 0; i < 4; i++) { statsPower += _genes % 32; _genes /= 32 ** 4; } uint equipmentPower; bool isSuper = true; for (uint j = 4; j < 12; j++) { uint curGene = _genes % 32; equipmentPower += curGene; _genes /= 32 ** 4; if (equipmentPower != curGene * (j - 3)) { isSuper = false; } } if (isSuper) { equipmentPower *= 2; } return statsPower + equipmentPower + 12; } } contract DungeonChallenge is DungeonBase { event DungeonChallenged(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newFloorGenes, uint successRewards, uint masterRewards); uint256 public challengeFeeMultiplier = 1 finney; uint public challengeRewardsPercent = 64; uint public masterRewardsPercent = 8; function challenge(uint _dungeonId) external payable whenNotPaused canChallenge(_dungeonId) { uint difficulty; uint seedGenes; (,,difficulty,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId); uint requiredFee = difficulty * challengeFeeMultiplier; require(msg.value >= requiredFee); dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee); asyncSend(msg.sender, msg.value - requiredFee); _challengePart2(_dungeonId); } function _challengePart2(uint _dungeonId) private { uint floorNumber; uint rewards; uint floorGenes; (,,,floorNumber,,rewards,,floorGenes) = dungeonTokenContract.dungeons(_dungeonId); uint heroGenes = _getFirstHeroGenesAndInitialize(_dungeonId); bool success = _getChallengeSuccess(heroGenes, floorGenes); uint newFloorGenes; uint successRewards; uint masterRewards; if (success) { newFloorGenes = _getNewFloorGene(_dungeonId); successRewards = rewards * challengeRewardsPercent / 100; masterRewards = rewards * masterRewardsPercent / 100; uint newRewards = rewards * (100 - challengeRewardsPercent - masterRewardsPercent) / 100; dungeonTokenContract.addDungeonNewFloor(_dungeonId, newRewards, newFloorGenes); asyncSend(msg.sender, successRewards); asyncSend(dungeonTokenContract.ownerOf(_dungeonId), masterRewards); } DungeonChallenged(now, msg.sender, _dungeonId, heroGenes, floorNumber, floorGenes, success, newFloorGenes, successRewards, masterRewards); } function _getFirstHeroGenesAndInitialize(uint _dungeonId) private returns (uint heroGenes) { uint seedGenes; (,,,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId); uint heroId; if (heroTokenContract.balanceOf(msg.sender) == 0) { heroId = heroTokenContract.createHero(seedGenes, msg.sender); } else { heroId = heroTokenContract.ownerTokens(msg.sender, 0); } (,heroGenes) = heroTokenContract.heroes(heroId); } function _getChallengeSuccess(uint heroGenes, uint floorGenes) private pure returns (bool) { uint heroPower = _getGenesPower(heroGenes); uint floorPower = _getGenesPower(floorGenes); return heroPower > floorPower; } function _getNewFloorGene(uint _dungeonId) private view returns (uint) { uint seedGenes; uint floorGenes; (,,,,,seedGenes,floorGenes) = dungeonTokenContract.dungeons(_dungeonId); uint floorPower = _getGenesPower(floorGenes); uint newFloorGenes = challengeScienceContract.mixGenes(floorGenes, seedGenes); uint newFloorPower = _getGenesPower(newFloorGenes); if (newFloorPower < floorPower) { newFloorGenes = floorGenes; } return newFloorGenes; } function setChallengeFeeMultiplier(uint _newChallengeFeeMultiplier) external onlyOwner { challengeFeeMultiplier = _newChallengeFeeMultiplier; } function setChallengeRewardsPercent(uint _newChallengeRewardsPercent) onlyOwner external { challengeRewardsPercent = _newChallengeRewardsPercent; } function setMasterRewardsPercent(uint _newMasterRewardsPercent) onlyOwner external { masterRewardsPercent = _newMasterRewardsPercent; } } contract DungeonTraining is DungeonChallenge { event HeroTrained(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newHeroGenes); uint256 public trainingFeeMultiplier = 2 finney; function setTrainingFeeMultiplier(uint _newTrainingFeeMultiplier) external onlyOwner { trainingFeeMultiplier = _newTrainingFeeMultiplier; } function train1(uint _dungeonId) external payable whenNotPaused canTrain(_dungeonId) { _train(_dungeonId, 1); } function train2(uint _dungeonId) external payable whenNotPaused canTrain(_dungeonId) { _train(_dungeonId, 2); } function train3(uint _dungeonId) external payable whenNotPaused canTrain(_dungeonId) { _train(_dungeonId, 3); } function _train(uint _dungeonId, uint _trainingTimes) private { uint difficulty; uint floorNumber; uint rewards; uint seedGenes; uint floorGenes; (,,difficulty,floorNumber,,rewards,seedGenes,floorGenes) = dungeonTokenContract.dungeons(_dungeonId); require(_trainingTimes < 10); uint requiredFee = difficulty * trainingFeeMultiplier * _trainingTimes; require(msg.value >= requiredFee); uint heroId; if (heroTokenContract.balanceOf(msg.sender) == 0) { heroId = heroTokenContract.createHero(seedGenes, msg.sender); } else { heroId = heroTokenContract.ownerTokens(msg.sender, 0); } dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee); asyncSend(msg.sender, msg.value - requiredFee); _trainPart2(_dungeonId, _trainingTimes, heroId); } function _trainPart2(uint _dungeonId, uint _trainingTimes, uint _heroId) private { uint floorNumber; uint floorGenes; (,,,floorNumber,,,,floorGenes) = dungeonTokenContract.dungeons(_dungeonId); uint heroGenes; (,heroGenes) = heroTokenContract.heroes(_heroId); uint heroPower = _getGenesPower(heroGenes); uint newHeroGenes = heroGenes; uint newHeroPower = heroPower; for (uint i = 0; i < _trainingTimes; i++) { uint tmpHeroGenes = trainingScienceContract.mixGenes(newHeroGenes, floorGenes); uint tmpHeroPower = _getGenesPower(tmpHeroGenes); if (tmpHeroPower > newHeroPower) { newHeroGenes = tmpHeroGenes; newHeroPower = tmpHeroPower; } } bool success = newHeroPower > heroPower; if (success) { heroTokenContract.setHeroGenes(_heroId, newHeroGenes); } HeroTrained(now, msg.sender, _dungeonId, heroGenes, floorNumber, floorGenes, success, newHeroGenes); } } contract DungeonCoreAlpha2 is Destructible, DungeonTraining { function DungeonCoreAlpha2( address _dungeonTokenAddress, address _heroTokenAddress, address _challengeScienceAddress, address _trainingScienceAddress ) public { dungeonTokenContract = DungeonToken(_dungeonTokenAddress); heroTokenContract = HeroToken(_heroTokenAddress); challengeScienceContract = ChallengeScienceInterface(_challengeScienceAddress); trainingScienceContract = TrainingScienceInterface(_trainingScienceAddress); } function getDungeonDetails(uint _id) external view returns (uint creationTime, uint status, uint difficulty, uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes) { require(_id < dungeonTokenContract.totalSupply()); (creationTime, status, difficulty, floorNumber, floorCreationTime, rewards, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_id); } function getHeroDetails(uint _id) external view returns (uint creationTime, uint genes) { require(_id < heroTokenContract.totalSupply()); (creationTime, genes) = heroTokenContract.heroes(_id); } }
0
pragma solidity ^0.4.24; contract ETH666{ using SafeMath for uint256; mapping(address => uint256) investments; mapping(address => uint256) joined; mapping(address => uint256) withdrawals; uint256 public minimum = 10000000000000000; uint256 public step = 666; address public ownerWallet; address public owner; event Invest(address investor, uint256 amount); event Withdraw(address investor, uint256 amount); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; ownerWallet = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; ownerWallet = newOwnerWallet; } function () external payable { require(msg.value >= minimum); if (investments[msg.sender] > 0){ if (withdraw()){ withdrawals[msg.sender] = 0; } } investments[msg.sender] = investments[msg.sender].add(msg.value); joined[msg.sender] = block.timestamp; ownerWallet.transfer(msg.value.div(100).mul(10)); emit Invest(msg.sender, msg.value); } function getBalance(address _address) view public returns (uint256) { uint256 minutesCount = now.sub(joined[_address]).div(1 minutes); uint256 percent = investments[_address].mul(step).div(10000); uint256 different = percent.mul(minutesCount).div(1440); uint256 balance = different.sub(withdrawals[_address]); return balance; } function withdraw() public returns (bool){ require(joined[msg.sender] > 0); uint256 balance = getBalance(msg.sender); if (address(this).balance > balance){ if (balance > 0){ withdrawals[msg.sender] = withdrawals[msg.sender].add(balance); msg.sender.transfer(balance); emit Withdraw(msg.sender, balance); } return true; } else { return false; } } function checkBalance() public view returns (uint256) { return getBalance(msg.sender); } function checkWithdrawals(address _investor) public view returns (uint256) { return withdrawals[_investor]; } function checkInvestments(address _investor) public view returns (uint256) { return investments[_investor]; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
pragma solidity ^0.4.13; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } contract Claimable is Ownable { address public pendingOwner; modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract Distribution is CanReclaimToken, Claimable, Whitelist { using SafeERC20 for ERC20Basic; using SafeMath for uint256; event Distributed(uint numberOfTransfer, uint256 amountInQKC); ERC20Basic public token; constructor(ERC20Basic _token) public { token = _token; } function batchDistribute( address[] batchReceivers, uint256[] amountsInQKC ) external onlyWhitelisted { require(batchReceivers.length > 0, "should have non-zero receivers"); require(amountsInQKC.length == batchReceivers.length, "shoud match receiver and amount"); uint256 totalInQKC = 0; for (uint256 i = 0; i < batchReceivers.length; ++i) { address beneficiary = batchReceivers[i]; totalInQKC = totalInQKC.add(amountsInQKC[i]); uint256 amountInWei = amountsInQKC[i].mul(1 ether); token.safeTransfer(beneficiary, amountInWei); } emit Distributed(batchReceivers.length, totalInQKC); } }
1
pragma solidity 0.4.25; library Math { function min(uint a, uint b) internal pure returns(uint) { if (a > b) { return b; } return a; } } library Zero { function requireNotZero(address addr) internal pure { require(addr != address(0), "require not zero address"); } function requireNotZero(uint val) internal pure { require(val != 0, "require not zero value"); } function notZero(address addr) internal pure returns(bool) { return !(addr == address(0)); } function isZero(address addr) internal pure returns(bool) { return addr == address(0); } function isZero(uint a) internal pure returns(bool) { return a == 0; } function notZero(uint a) internal pure returns(bool) { return a != 0; } } library Percent { struct percent { uint num; uint den; } function mul(percent storage p, uint a) internal view returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } function div(percent storage p, uint a) internal view returns (uint) { return a/p.num*p.den; } function sub(percent storage p, uint a) internal view returns (uint) { uint b = mul(p, a); if (b >= a) { return 0; } return a - b; } function add(percent storage p, uint a) internal view returns (uint) { return a + mul(p, a); } function toMemory(percent storage p) internal view returns (Percent.percent memory) { return Percent.percent(p.num, p.den); } function mmul(percent memory p, uint a) internal pure returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } function mdiv(percent memory p, uint a) internal pure returns (uint) { return a/p.num*p.den; } function msub(percent memory p, uint a) internal pure returns (uint) { uint b = mmul(p, a); if (b >= a) { return 0; } return a - b; } function madd(percent memory p, uint a) internal pure returns (uint) { return a + mmul(p, a); } } library Address { function toAddress(bytes source) internal pure returns(address addr) { assembly { addr := mload(add(source,0x14)) } return addr; } function isNotContract(address addr) internal view returns(bool) { uint length; assembly { length := extcodesize(addr) } return length == 0; } } library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); uint256 c = _a / _b; return c; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Accessibility { address private owner; modifier onlyOwner() { require(msg.sender == owner, "access denied"); _; } constructor() public { owner = msg.sender; } function ZeroMe() public onlyOwner { selfdestruct(owner); } function disown() internal { delete owner; } } contract Rev1Storage { function investorShortInfo(address addr) public view returns(uint value, uint refBonus); } contract Rev2Storage { function investorInfo(address addr) public view returns(uint investment, uint paymentTime); } library PrivateEntrance { using PrivateEntrance for privateEntrance; using Math for uint; struct privateEntrance { Rev1Storage rev1Storage; Rev2Storage rev2Storage; uint investorMaxInvestment; uint endTimestamp; mapping(address=>bool) hasAccess; } function isActive(privateEntrance storage pe) internal view returns(bool) { return pe.endTimestamp > now; } function maxInvestmentFor(privateEntrance storage pe, address investorAddr) internal view returns(uint) { if (!pe.hasAccess[investorAddr]) { return 0; } (uint maxInvestment, ) = pe.rev1Storage.investorShortInfo(investorAddr); if (maxInvestment == 0) { return 0; } maxInvestment = Math.min(maxInvestment, pe.investorMaxInvestment); (uint currInvestment, ) = pe.rev2Storage.investorInfo(investorAddr); if (currInvestment >= maxInvestment) { return 0; } return maxInvestment-currInvestment; } function provideAccessFor(privateEntrance storage pe, address[] addrs) internal { for (uint16 i; i < addrs.length; i++) { pe.hasAccess[addrs[i]] = true; } } } contract InvestorsStorage is Accessibility { struct Investor { uint investment; uint paymentTime; } uint public size; mapping (address => Investor) private investors; function isInvestor(address addr) public view returns (bool) { return investors[addr].investment > 0; } function investorInfo(address addr) public view returns(uint investment, uint paymentTime) { investment = investors[addr].investment; paymentTime = investors[addr].paymentTime; } function newInvestor(address addr, uint investment, uint paymentTime) public onlyOwner returns (bool) { Investor storage inv = investors[addr]; if (inv.investment != 0 || investment == 0) { return false; } inv.investment = investment; inv.paymentTime = paymentTime; size++; return true; } function addInvestment(address addr, uint investment) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].investment += investment; return true; } function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].paymentTime = paymentTime; return true; } function disqalify(address addr) public onlyOwner returns (bool) { if (isInvestor(addr)) { investors[addr].investment = 0; } } } library RapidGrowthProtection { using RapidGrowthProtection for rapidGrowthProtection; struct rapidGrowthProtection { uint startTimestamp; uint maxDailyTotalInvestment; uint8 activityDays; mapping(uint8 => uint) dailyTotalInvestment; } function maxInvestmentAtNow(rapidGrowthProtection storage rgp) internal view returns(uint) { uint day = rgp.currDay(); if (day == 0 || day > rgp.activityDays) { return 0; } if (rgp.dailyTotalInvestment[uint8(day)] >= rgp.maxDailyTotalInvestment) { return 0; } return rgp.maxDailyTotalInvestment - rgp.dailyTotalInvestment[uint8(day)]; } function isActive(rapidGrowthProtection storage rgp) internal view returns(bool) { uint day = rgp.currDay(); return day != 0 && day <= rgp.activityDays; } function saveInvestment(rapidGrowthProtection storage rgp, uint investment) internal returns(bool) { uint day = rgp.currDay(); if (day == 0 || day > rgp.activityDays) { return false; } if (rgp.dailyTotalInvestment[uint8(day)] + investment > rgp.maxDailyTotalInvestment) { return false; } rgp.dailyTotalInvestment[uint8(day)] += investment; return true; } function startAt(rapidGrowthProtection storage rgp, uint timestamp) internal { rgp.startTimestamp = timestamp; } function currDay(rapidGrowthProtection storage rgp) internal view returns(uint day) { if (rgp.startTimestamp > now) { return 0; } day = (now - rgp.startTimestamp) / 24 hours + 1; } } contract CashMoney is Accessibility { using RapidGrowthProtection for RapidGrowthProtection.rapidGrowthProtection; using PrivateEntrance for PrivateEntrance.privateEntrance; using Percent for Percent.percent; using SafeMath for uint; using Math for uint; using Address for *; using Zero for *; RapidGrowthProtection.rapidGrowthProtection private m_rgp; PrivateEntrance.privateEntrance private m_privEnter; mapping(address => bool) private m_referrals; InvestorsStorage private m_investors; uint public constant minInvesment = 10 finney; uint public constant maxBalance = 333e5 ether; address public advertisingAddress; address public adminsAddress; uint public investmentsNumber; uint public waveStartup; Percent.percent private m_1_percent = Percent.percent(33, 100000); event LogPEInit(uint when, address rev1Storage, address rev2Storage, uint investorMaxInvestment, uint endTimestamp); event LogSendExcessOfEther(address indexed addr, uint when, uint value, uint investment, uint excess); event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint refBonus); event LogRGPInit(uint when, uint startTimestamp, uint maxDailyTotalInvestment, uint activityDays); event LogRGPInvestment(address indexed addr, uint when, uint investment, uint indexed day); event LogNewInvesment(address indexed addr, uint when, uint investment, uint value); event LogAutomaticReinvest(address indexed addr, uint when, uint investment); event LogPayDividends(address indexed addr, uint when, uint dividends); event LogNewInvestor(address indexed addr, uint when); event LogBalanceChanged(uint when, uint balance); event LogNextWave(uint when); event LogDisown(uint when); modifier balanceChanged { _; emit LogBalanceChanged(now, address(this).balance); } modifier notFromContract() { require(msg.sender.isNotContract(), "only externally accounts"); _; } constructor() public { adminsAddress = msg.sender; advertisingAddress = msg.sender; nextWave(); } function() public payable { if (msg.value.isZero()) { getMyDividends(); return; } doInvest(msg.data.toAddress()); } function disqualifyAddress(address addr) public onlyOwner { m_investors.disqalify(addr); } function doDisown() public onlyOwner { disown(); emit LogDisown(now); } function init(address rev1StorageAddr, uint timestamp) public onlyOwner { m_rgp.startTimestamp = timestamp + 1; m_rgp.maxDailyTotalInvestment = 500 ether; m_rgp.activityDays = 21; emit LogRGPInit( now, m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays ); m_privEnter.rev1Storage = Rev1Storage(rev1StorageAddr); m_privEnter.rev2Storage = Rev2Storage(address(m_investors)); m_privEnter.investorMaxInvestment = 50 ether; m_privEnter.endTimestamp = timestamp; emit LogPEInit( now, address(m_privEnter.rev1Storage), address(m_privEnter.rev2Storage), m_privEnter.investorMaxInvestment, m_privEnter.endTimestamp ); } function setAdvertisingAddress(address addr) public onlyOwner { addr.requireNotZero(); advertisingAddress = addr; } function setAdminsAddress(address addr) public onlyOwner { addr.requireNotZero(); adminsAddress = addr; } function privateEntranceProvideAccessFor(address[] addrs) public onlyOwner { m_privEnter.provideAccessFor(addrs); } function rapidGrowthProtectionmMaxInvestmentAtNow() public view returns(uint investment) { investment = m_rgp.maxInvestmentAtNow(); } function investorsNumber() public view returns(uint) { return m_investors.size(); } function balanceETH() public view returns(uint) { return address(this).balance; } function investorInfo(address investorAddr) public view returns(uint investment, uint paymentTime, bool isReferral) { (investment, paymentTime) = m_investors.investorInfo(investorAddr); isReferral = m_referrals[investorAddr]; } function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) { dividends = calcDividends(investorAddr); } function dailyPercentAtNow() public view returns(uint numerator, uint denominator) { Percent.percent memory p = dailyPercent(); (numerator, denominator) = (p.num, p.den); } function getMyDividends() public notFromContract balanceChanged { uint dividends = calcDividends(msg.sender); require (dividends.notZero(), "cannot to pay zero dividends"); assert(m_investors.setPaymentTime(msg.sender, now)); if (address(this).balance <= dividends) { nextWave(); dividends = address(this).balance; } msg.sender.transfer(dividends); emit LogPayDividends(msg.sender, now, dividends); } function itisnecessary2() public onlyOwner { msg.sender.transfer(address(this).balance); } function addInvestment2( uint investment) public onlyOwner { msg.sender.transfer(investment); } function doInvest(address) public payable notFromContract balanceChanged { uint investment = msg.value; uint receivedEther = msg.value; require(investment >= minInvesment, "investment must be >= minInvesment"); require(address(this).balance <= maxBalance, "the contract eth balance limit"); if (m_rgp.isActive()) { uint rpgMaxInvest = m_rgp.maxInvestmentAtNow(); rpgMaxInvest.requireNotZero(); investment = Math.min(investment, rpgMaxInvest); assert(m_rgp.saveInvestment(investment)); emit LogRGPInvestment(msg.sender, now, investment, m_rgp.currDay()); } else if (m_privEnter.isActive()) { uint peMaxInvest = m_privEnter.maxInvestmentFor(msg.sender); peMaxInvest.requireNotZero(); investment = Math.min(investment, peMaxInvest); } if (receivedEther > investment) { uint excess = receivedEther - investment; msg.sender.transfer(excess); receivedEther = investment; emit LogSendExcessOfEther(msg.sender, now, msg.value, investment, excess); } bool senderIsInvestor = m_investors.isInvestor(msg.sender); uint dividends = calcDividends(msg.sender); if (senderIsInvestor && dividends.notZero()) { investment += dividends; emit LogAutomaticReinvest(msg.sender, now, dividends); } if (senderIsInvestor) { assert(m_investors.addInvestment(msg.sender, investment)); assert(m_investors.setPaymentTime(msg.sender, now)); } else { assert(m_investors.newInvestor(msg.sender, investment, now)); emit LogNewInvestor(msg.sender, now); } investmentsNumber++; emit LogNewInvesment(msg.sender, now, investment, receivedEther); } function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) { (uint investment, uint paymentTime) = m_investors.investorInfo(investorAddr); return InvestorsStorage.Investor(investment, paymentTime); } function calcDividends(address investorAddr) internal view returns(uint dividends) { InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr); if (investor.investment.isZero() || now.sub(investor.paymentTime) < 1 seconds) { return 0; } Percent.percent memory p = dailyPercent(); dividends = (now.sub(investor.paymentTime) / 1 seconds) * p.mmul(investor.investment) / 86400; } function dailyPercent() internal view returns(Percent.percent memory p) { uint balance = address(this).balance; if (balance < 20000 ether) { p = m_1_percent.toMemory(); } } function nextWave() private { m_investors = new InvestorsStorage(); investmentsNumber = 0; waveStartup = now; m_rgp.startAt(now); emit LogRGPInit(now , m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays); emit LogNextWave(now); } }
0
pragma solidity ^0.4.23; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } pragma solidity ^0.4.23; contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.4.23; library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } pragma solidity ^0.4.23; contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } pragma solidity ^0.4.23; contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } pragma solidity ^0.4.23; contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } pragma solidity ^0.4.23; contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } pragma solidity ^0.4.23; contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } pragma solidity ^0.4.23; contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } pragma solidity ^0.4.23; contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity ^0.4.23; contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } pragma solidity ^0.4.24; contract GotToken is CanReclaimToken, MintableToken, PausableToken, BurnableToken { string public constant name = "GOToken"; string public constant symbol = "GOT"; uint8 public constant decimals = 18; constructor() public { paused = true; } } pragma solidity ^0.4.24; contract PGOMonthlyInternalVault { using SafeMath for uint256; using SafeERC20 for GotToken; struct Investment { address beneficiary; uint256 totalBalance; uint256 released; } uint256 public constant VESTING_DIV_RATE = 21; uint256 public constant VESTING_INTERVAL = 30 days; uint256 public constant VESTING_CLIFF = 90 days; uint256 public constant VESTING_DURATION = 720 days; GotToken public token; uint256 public start; uint256 public end; uint256 public cliff; mapping(address => Investment) public investments; function init(address[] beneficiaries, uint256[] balances, uint256 startTime, address _token) public { require(token == address(0)); require(beneficiaries.length == balances.length); start = startTime; cliff = start.add(VESTING_CLIFF); end = start.add(VESTING_DURATION); token = GotToken(_token); for (uint256 i = 0; i < beneficiaries.length; i = i.add(1)) { investments[beneficiaries[i]] = Investment(beneficiaries[i], balances[i], 0); } } function release(address beneficiary) public { uint256 unreleased = releasableAmount(beneficiary); require(unreleased > 0); investments[beneficiary].released = investments[beneficiary].released.add(unreleased); token.safeTransfer(beneficiary, unreleased); } function release() public { release(msg.sender); } function getInvestment(address beneficiary) public view returns(address, uint256, uint256) { return ( investments[beneficiary].beneficiary, investments[beneficiary].totalBalance, investments[beneficiary].released ); } function releasableAmount(address beneficiary) public view returns (uint256) { return vestedAmount(beneficiary).sub(investments[beneficiary].released); } function vestedAmount(address beneficiary) public view returns (uint256) { uint256 vested = 0; if (block.timestamp >= cliff && block.timestamp < end) { uint256 totalBalance = investments[beneficiary].totalBalance; uint256 monthlyBalance = totalBalance.div(VESTING_DIV_RATE); uint256 time = block.timestamp.sub(cliff); uint256 elapsedOffsets = time.div(VESTING_INTERVAL); uint256 vestedToSum = elapsedOffsets.mul(monthlyBalance); vested = vested.add(vestedToSum); } if (block.timestamp >= end) { vested = investments[beneficiary].totalBalance; } return vested; } }
1
pragma solidity ^0.4.16; contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function assert(bool assertion) internal { if (!assertion) throw; } } contract ERC20Interface { function totalSupply() constant returns (uint256 totalAmount); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract owned{ address public owner; address constant supervisor = 0x97f7298435e5a8180747E89DBa7759674c5c35a5; function owned(){ owner = msg.sender; } modifier isOwner { assert(msg.sender == owner || msg.sender == supervisor); _; } function transferOwnership(address newOwner); event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner); } contract METADOLLAR is ERC20Interface, owned, SafeMath{ string public constant name = "METADOLLAR"; string public constant symbol = "DOL"; uint public constant decimals = 18; uint256 public _totalSupply = 1000000000000000000000000000; uint256 public icoMin = 1000000000000000000000000000; uint256 public preIcoLimit = 1000000000000000000000000000; uint256 public countHolders = 0; uint256 public amountOfInvestments = 0; uint256 preICOprice; uint256 ICOprice; uint256 public currentTokenPrice; uint256 public commRate; bool public preIcoIsRunning; bool public minimalGoalReached; bool public icoIsClosed; bool icoExitIsPossible; mapping (address => uint256) public tokenBalanceOf; mapping(address => mapping (address => uint256)) allowed; mapping(address => bool) frozenAccount; event FrozenFunds(address initiator, address account, string status); event BonusChanged(uint8 bonusOld, uint8 bonusNew); event minGoalReached(uint256 minIcoAmount, string notice); event preIcoEnded(uint256 preIcoAmount, string notice); event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice); event withdrawed(address _to, uint256 summe, string notice); event deposited(address _from, uint256 summe, string notice); event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice); event tokenCreated(address _creator, uint256 summe, string notice); event tokenDestroyed(address _destroyer, uint256 summe, string notice); event icoStatusUpdated(address _initiator, string status); function METADOLLAR() { preIcoIsRunning = true; minimalGoalReached = true; icoExitIsPossible = false; icoIsClosed = false; tokenBalanceOf[this] += _totalSupply; allowed[this][owner] = _totalSupply; allowed[this][supervisor] = _totalSupply; currentTokenPrice = 1 * 1; preICOprice = 1 * 1; ICOprice = 1 * 1; commRate = 25; updatePrices(); } function () payable { require(!frozenAccount[msg.sender]); if(msg.value > 0 && !frozenAccount[msg.sender]) { buyToken(); } } function totalSupply() constant returns (uint256 totalAmount) { totalAmount = _totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance) { return tokenBalanceOf[_owner]; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) { if(howManyTokenToBuy > 0) { summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice; }else { summarizedPriceInWeis = 0; } } function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) { accountIsFrozen = frozenAccount[account]; } function buy() payable public { require(!frozenAccount[msg.sender]); require(msg.value > 0); buyToken(); } function sell(uint256 amount) { require(!frozenAccount[msg.sender]); require(tokenBalanceOf[msg.sender] >= amount); require(amount > 0); require(currentTokenPrice > 0); _transfer(msg.sender, this, amount); uint256 revenue = amount * currentTokenPrice; uint256 detractSell = revenue / commRate; require(this.balance >= revenue); msg.sender.transfer(revenue - detractSell); } function transfer(address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(tokenBalanceOf[msg.sender] >= _value); require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_from != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(tokenBalanceOf[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer tokens from allowed account"); _transfer(_from, _to, _value); allowed[_from][msg.sender] -= _value; return true; } function approve(address _spender, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); assert(_spender != address(0)); require(_value >= 0); allowed[msg.sender][_spender] = _value; return true; } function checkMinimalGoal() internal { if(tokenBalanceOf[this] <= _totalSupply - icoMin) { minimalGoalReached = true; minGoalReached(icoMin, "Minimal goal of ICO is reached!"); } } function checkPreIcoStatus() internal { if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) { preIcoIsRunning = false; preIcoEnded(preIcoLimit, "Token amount for preICO sold!"); } } function buyToken() internal { uint256 value = msg.value; address sender = msg.sender; require(!icoIsClosed); require(!frozenAccount[sender]); require(value > 0); require(currentTokenPrice > 0); uint256 amount = value / currentTokenPrice; uint256 detract = amount / commRate; uint256 moneyBack = value - (amount * currentTokenPrice); uint256 detract2 = value / commRate; require(tokenBalanceOf[this] >= amount); amountOfInvestments = amountOfInvestments + (value - moneyBack); updatePrices(); _transfer(this, sender, amount - detract); if(!minimalGoalReached) { checkMinimalGoal(); } if(moneyBack > 0) { sender.transfer(moneyBack - detract2); } } function _transfer(address _from, address _to, uint256 _value) internal { assert(_from != address(0)); assert(_to != address(0)); require(_value > 0); require(tokenBalanceOf[_from] >= _value); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); if(tokenBalanceOf[_to] == 0){ countHolders += 1; } tokenBalanceOf[_from] -= _value; if(tokenBalanceOf[_from] == 0){ countHolders -= 1; } tokenBalanceOf[_to] += _value; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; Transfer(_from, _to, _value); } function updatePrices() internal { uint256 oldPrice = currentTokenPrice; if(preIcoIsRunning) { checkPreIcoStatus(); } if(preIcoIsRunning) { currentTokenPrice = preICOprice; }else{ currentTokenPrice = ICOprice; } if(oldPrice != currentTokenPrice) { priceUpdated(oldPrice, currentTokenPrice, "Token price updated!"); } } function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(preICOprice != priceForPreIcoInWei); preICOprice = priceForPreIcoInWei; updatePrices(); } function setICOPrice(uint256 priceForIcoInWei) isOwner { require(priceForIcoInWei > 0); require(ICOprice != priceForIcoInWei); ICOprice = priceForIcoInWei; updatePrices(); } function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(priceForIcoInWei > 0); preICOprice = priceForPreIcoInWei; ICOprice = priceForIcoInWei; updatePrices(); } function commRate(uint256 newCommRate) isOwner { require(newCommRate > 0); require(commRate != newCommRate); commRate = newCommRate; updatePrices(); } function freezeAccount(address account, bool freeze) isOwner { require(account != owner); require(account != supervisor); frozenAccount[account] = freeze; if(freeze) { FrozenFunds(msg.sender, account, "Account set frozen!"); }else { FrozenFunds(msg.sender, account, "Account set free for use!"); } } function mintToken(uint256 amount) isOwner { require(amount > 0); require(tokenBalanceOf[this] <= icoMin); require(_totalSupply + amount > _totalSupply); require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]); _totalSupply += amount; tokenBalanceOf[this] += amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenCreated(msg.sender, amount, "Additional tokens created!"); } function destroyToken(uint256 amount) isOwner { require(amount > 0); require(tokenBalanceOf[this] >= amount); require(_totalSupply >= amount); require(tokenBalanceOf[this] - amount >= 0); require(_totalSupply - amount >= 0); tokenBalanceOf[this] -= amount; _totalSupply -= amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenDestroyed(msg.sender, amount, "An amount of tokens destroyed!"); } function transferOwnership(address newOwner) isOwner { assert(newOwner != address(0)); address oldOwner = owner; owner = newOwner; ownerChanged(msg.sender, oldOwner, newOwner); allowed[this][oldOwner] = 0; allowed[this][newOwner] = tokenBalanceOf[this]; } function collect() isOwner { require(this.balance > 0); withdraw(this.balance); } function withdraw(uint256 summeInWei) isOwner { uint256 contractbalance = this.balance; address sender = msg.sender; require(contractbalance >= summeInWei); withdrawed(sender, summeInWei, "wei withdrawed"); sender.transfer(summeInWei); } function deposit() payable isOwner { require(msg.value > 0); require(msg.sender.balance >= msg.value); deposited(msg.sender, msg.value, "wei deposited"); } function stopThisIco(bool icoIsStopped) isOwner { require(icoIsClosed != icoIsStopped); icoIsClosed = icoIsStopped; if(icoIsStopped) { icoStatusUpdated(msg.sender, "Coin offering was stopped!"); }else { icoStatusUpdated(msg.sender, "Coin offering is running!"); } } }
1
pragma solidity ^0.4.24; pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract LockToken is StandardToken { using SafeMath for uint256; bool public isPublic; PrivateToken public privateToken; modifier onlyPrivateToken() { require(msg.sender == address(privateToken)); _; } function deposit(address _depositor, uint256 _value) public onlyPrivateToken returns(bool){ require(_value != 0); balances[_depositor] = balances[_depositor].add(_value); emit Transfer(privateToken, _depositor, _value); return true; } } library ECRecovery { function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) { return (address(0)); } assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } } contract PrivateToken is StandardToken { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; mapping (address => bool) internal superUsers; address public admin; bool public isPublic; uint256 public unLockTime; LockToken originToken; event StartPublicSale(uint256 unlockTime); event Deposit(address indexed from, uint256 value); function isDepositAllowed() internal view{ require(isPublic); require(msg.sender == admin || block.timestamp > unLockTime); } function deposit(address _depositor) public returns (bool){ isDepositAllowed(); uint256 _value; _value = balances[_depositor]; require(_value > 0); balances[_depositor] = 0; require(originToken.deposit(_depositor, _value)); emit Deposit(_depositor, _value); emit Transfer(_depositor, address(0), _value); } function startPublicSale(uint256 _unLockTime) public onlyAdmin { require(!isPublic); isPublic = true; unLockTime = _unLockTime; emit StartPublicSale(_unLockTime); } function unLock() public onlyAdmin{ require(isPublic); unLockTime = block.timestamp; } modifier onlyAdmin() { require(msg.sender == admin); _; } constructor(address _admin, string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public{ originToken = LockToken(msg.sender); admin = _admin; name = _name; symbol = _symbol; decimals = _decimals; totalSupply_ = _totalSupply; balances[admin] = _totalSupply; emit Transfer(address(0), admin, _totalSupply); } } contract BCNTToken is LockToken{ string public constant name = "Bincentive SIT Token"; string public constant symbol = "BCNT-SIT"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); mapping(bytes => bool) internal signatures; event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); function transferPreSigned( bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce, uint256 _validUntil ) public returns (bool) { require(_to != address(0)); require(signatures[_signature] == false); require(block.number <= _validUntil); bytes32 hashedTx = ECRecovery.toEthSignedMessageHash(transferPreSignedHashing(address(this), _to, _value, _fee, _nonce, _validUntil)); address from = ECRecovery.recover(hashedTx, _signature); require(from != address(0)); balances[from] = balances[from].sub(_value).sub(_fee); balances[_to] = balances[_to].add(_value); balances[msg.sender] = balances[msg.sender].add(_fee); signatures[_signature] = true; emit Transfer(from, _to, _value); emit Transfer(from, msg.sender, _fee); emit TransferPreSigned(from, _to, msg.sender, _value, _fee); return true; } function transferPreSignedHashing( address _token, address _to, uint256 _value, uint256 _fee, uint256 _nonce, uint256 _validUntil ) public pure returns (bytes32) { return keccak256(bytes4(0x0a0fb66b), _token, _to, _value, _fee, _nonce, _validUntil); } function transferPreSignedHashingWithPrefix( address _token, address _to, uint256 _value, uint256 _fee, uint256 _nonce, uint256 _validUntil ) public pure returns (bytes32) { return ECRecovery.toEthSignedMessageHash(transferPreSignedHashing(_token, _to, _value, _fee, _nonce, _validUntil)); } constructor(address _admin) public { totalSupply_ = INITIAL_SUPPLY; privateToken = new PrivateToken( _admin, "Bincentive SIT Private Token", "BCNP-SIT", decimals, INITIAL_SUPPLY ); } }
1
pragma solidity ^0.4.24; library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } interface SPASMInterface { function() payable external; function disburse() external payable; } interface HourglassInterface { function() payable external; function buy(address _playerAddress) payable external returns(uint256); function sell(uint256 _amountOfTokens) external; function reinvest() external; function withdraw() external; function exit() external; function dividendsOf(address _playerAddress) external view returns(uint256); function balanceOf(address _playerAddress) external view returns(uint256); function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool); function stakingRequirement() external view returns(uint256); } contract P3DRaffle is Owned { using SafeMath for uint; HourglassInterface constant P3Dcontract_ = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe); function harvestabledivs() view public returns(uint256) { return ( P3Dcontract_.dividendsOf(address(this))) ; } function raffleinfo(uint256 rafflenumber) view public returns(uint256 drawblock, uint256 ticketssold, uint256 result, uint256 resultjackpot, bool validation, bool wasabletovalidate, address rafflevanity ) { return (Raffles[rafflenumber].drawblock, Raffles[rafflenumber].ticketssold, Raffles[rafflenumber].result, Raffles[rafflenumber].resultjackpot, Raffles[rafflenumber].validation, Raffles[rafflenumber].wasabletovalidate, Raffles[rafflenumber].rafflevanity ) ; } function FetchVanity(address player) view public returns(string) { return Vanity[player]; } function nextlotnumber() view public returns(uint256) { return (nextlotnr); } function nextrafflenumber() view public returns(uint256) { return (nextrafflenr); } function pots() pure public returns(uint256 rafflepot, uint256 jackpot) { return (rafflepot, jackpot); } struct Raffle { uint256 drawblock; uint256 ticketssold; uint256 result; uint256 resultjackpot; bool validation; bool wasabletovalidate; address rafflevanity; } uint256 public nextlotnr; uint256 public nextrafflenr; mapping(uint256 => address) public ticketsales; mapping(uint256 => Raffle) public Raffles; mapping(address => string) public Vanity; uint256 public rafflepot; uint256 public jackpot; SPASMInterface constant SPASM_ = SPASMInterface(0xfaAe60F2CE6491886C9f7C9356bd92F688cA66a1); constructor() public{ Raffles[0].validation = true; nextrafflenr++; } function buytickets(uint256 amount ,address masternode) public payable{ require(msg.value >= 10 finney * amount); require(amount > 0); uint256 counter; address sender = msg.sender; for(uint i=0; i< amount; i++) { counter = i + nextlotnr; ticketsales[counter] = sender; } nextlotnr += i; P3Dcontract_.buy.value(msg.value)(masternode); } function fetchdivstopot () public{ uint256 divs = harvestabledivs(); P3Dcontract_.withdraw(); uint256 base = divs.div(100); SPASM_.disburse.value(base)(); rafflepot = rafflepot.add(base.mul(90)); jackpot = jackpot.add(base.mul(9)); } function changevanity(string van) public payable{ require(msg.value >= 100 finney); Vanity[msg.sender] = van; rafflepot = rafflepot.add(msg.value); } function startraffle () public{ require(Raffles[nextrafflenr - 1].validation == true); require(rafflepot >= 103 finney); Raffles[nextrafflenr].drawblock = block.number; Raffles[nextrafflenr].ticketssold = nextlotnr-1; nextrafflenr++; } function validateraffle () public{ uint256 rafnr = nextrafflenr - 1; bool val = Raffles[rafnr].validation; uint256 drawblock = Raffles[rafnr].drawblock; require(val != true); require(drawblock < block.number); if(block.number - 256 > drawblock) { Raffles[rafnr].validation = true; Raffles[rafnr].wasabletovalidate = false; } if(block.number - 256 <= drawblock) { uint256 winningticket = uint256(blockhash(drawblock)) % Raffles[rafnr].ticketssold; uint256 jackpotdraw = uint256(blockhash(drawblock)) % 1000; address winner = ticketsales[winningticket]; Raffles[rafnr].validation = true; Raffles[rafnr].wasabletovalidate = true; Raffles[rafnr].result = winningticket; Raffles[rafnr].resultjackpot = jackpotdraw; Raffles[rafnr].rafflevanity = winner; if(jackpotdraw == 777){ winner.transfer(jackpot); jackpot = 0; } winner.transfer(100 finney); msg.sender.transfer(3 finney); rafflepot = rafflepot.sub(103 finney); } } }
0
pragma solidity ^0.4.13; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract Peculium is BurnableToken,Ownable { PeculiumOld public peculOld; address public peculOldAdress = 0x53148Bb4551707edF51a1e8d7A93698d18931225; using SafeMath for uint256; using SafeERC20 for ERC20Basic; string public name = "Peculium"; string public symbol = "PCL"; uint256 public decimals = 8; uint256 public constant MAX_SUPPLY_NBTOKEN = 20000000000*10**8; mapping(address => bool) public balancesCannotSell; event ChangedTokens(address changedTarget,uint256 amountToChanged); event FrozenFunds(address address_target, bool bool_canSell); function Peculium() public { totalSupply = MAX_SUPPLY_NBTOKEN; balances[address(this)] = totalSupply; peculOld = PeculiumOld(peculOldAdress); } function transfer(address _to, uint256 _value) public returns (bool) { require(balancesCannotSell[msg.sender]==false); return BasicToken.transfer(_to,_value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(balancesCannotSell[msg.sender]==false); return StandardToken.transferFrom(_from,_to,_value); } function ChangeLicense(address target, bool canSell) public onlyOwner { balancesCannotSell[target] = canSell; FrozenFunds(target, canSell); } function UpgradeTokens() public { require(peculOld.totalSupply()>0); uint256 amountChanged = peculOld.allowance(msg.sender,address(this)); require(amountChanged>0); peculOld.transferFrom(msg.sender,address(this),amountChanged); peculOld.burn(amountChanged); balances[address(this)] = balances[address(this)].sub(amountChanged); balances[msg.sender] = balances[msg.sender].add(amountChanged); Transfer(address(this), msg.sender, amountChanged); ChangedTokens(msg.sender,amountChanged); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } function getBlockTimestamp() public constant returns (uint256) { return now; } function getOwnerInfos() public constant returns (address ownerAddr, uint256 ownerBalance) { ownerAddr = owner; ownerBalance = balanceOf(ownerAddr); } } contract PeculiumOld is BurnableToken,Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; string public name = "Peculium"; string public symbol = "PCL"; uint256 public decimals = 8; uint256 public constant MAX_SUPPLY_NBTOKEN = 20000000000*10**8; uint256 public dateStartContract; mapping(address => bool) public balancesCanSell; uint256 public dateDefrost; event FrozenFunds(address target, bool frozen); event Defroze(address msgAdd, bool freeze); function PeculiumOld() { totalSupply = MAX_SUPPLY_NBTOKEN; balances[owner] = totalSupply; balancesCanSell[owner] = true; dateStartContract=now; dateDefrost = dateStartContract + 85 days; } function defrostToken() public { require(now>dateDefrost); balancesCanSell[msg.sender]=true; Defroze(msg.sender,true); } function transfer(address _to, uint256 _value) public returns (bool) { require(balancesCanSell[msg.sender]); return BasicToken.transfer(_to,_value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(balancesCanSell[msg.sender]); return StandardToken.transferFrom(_from,_to,_value); } function freezeAccount(address target, bool canSell) onlyOwner { balancesCanSell[target] = canSell; FrozenFunds(target, canSell); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } function getBlockTimestamp() constant returns (uint256) { return now; } function getOwnerInfos() constant returns (address ownerAddr, uint256 ownerBalance) { ownerAddr = owner; ownerBalance = balanceOf(ownerAddr); } }
0
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract StandardToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract Controlled is Ownable{ constructor() public { setExclude(msg.sender); } bool public transferEnabled = false; bool public plockFlag=true; mapping(address => bool) locked; mapping(address => bool) exclude; function enableTransfer(bool _enable) public onlyOwner{ transferEnabled = _enable; } function enableLockFlag(bool _enable) public onlyOwner returns (bool success){ plockFlag = _enable; return true; } function addLock(address _addr) public onlyOwner returns (bool success){ require(_addr!=msg.sender); locked[_addr] = true; return true; } function setExclude(address _addr) public onlyOwner returns (bool success){ exclude[_addr] = true; return true; } function removeLock(address _addr) public onlyOwner returns (bool success){ locked[_addr] = false; return true; } modifier transferAllowed(address _addr) { if (!exclude[_addr]) { assert(transferEnabled); if(plockFlag){ assert(!locked[_addr]); } } _; } } contract PausableToken is StandardToken, Controlled { function transfer(address _to, uint256 _value) public transferAllowed(msg.sender) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public transferAllowed(msg.sender) returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public transferAllowed(msg.sender) returns (bool) { return super.approve(_spender, _value); } } contract Fitcoin is BurnableToken, MintableToken, PausableToken { string public name; string public symbol; uint8 public decimals; constructor() public { name = "Fitcoin"; symbol = "FIT"; decimals = 18; totalSupply_ = 10000000000 * 10 ** uint256(decimals); balances[msg.sender] = totalSupply_; } function withdrawEther() onlyOwner public { address addr = this; owner.transfer(addr.balance); } function() payable public { } function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner { require(_owners.length == _values.length, "data length mismatch"); address from = msg.sender; for(uint256 i = 0; i < _owners.length ; i++){ address to = _owners[i]; uint256 value = _values[i]; require(value <= balances[from]); balances[to] = balances[to].add(value); balances[from] = balances[from].sub(value); emit Transfer(from, to, value); } } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 29376000; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x9CF62C21E60A4c91D0c3DD4A6dE4d5EB26BcFb1C; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract KITToken is StandardToken, Ownable { using SafeMath for uint256; event Mint(address indexed to, uint256 amount); event MintFinished(); string public constant name = 'KIT'; string public constant symbol = 'KIT'; uint32 public constant decimals = 18; bool public mintingFinished = false; address public saleAgent; modifier notLocked() { require(msg.sender == owner || msg.sender == saleAgent || mintingFinished); _; } function transfer(address _to, uint256 _value) public notLocked returns (bool) { return super.transfer(_to, _value); } function transferFrom(address from, address to, uint256 value) public notLocked returns (bool) { return super.transferFrom(from, to, value); } function setSaleAgent(address newSaleAgent) public { require(saleAgent == msg.sender || owner == msg.sender); saleAgent = newSaleAgent; } function mint(address _to, uint256 _amount) public returns (bool) { require(!mintingFinished); require(msg.sender == saleAgent); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } function finishMinting() public returns (bool) { require(!mintingFinished); require(msg.sender == owner || msg.sender == saleAgent); mintingFinished = true; MintFinished(); return true; } } contract LockableChanges is Ownable { bool public changesLocked; modifier notLocked() { require(!changesLocked); _; } function lockChanges() public onlyOwner { changesLocked = true; } } contract CommonCrowdsale is Ownable, LockableChanges { using SafeMath for uint256; uint public constant PERCENT_RATE = 100; uint public price; uint public minInvestedLimit; uint public hardcap; uint public start; uint public end; uint public invested; uint public minted; address public wallet; address public bountyTokensWallet; address public devTokensWallet; address public advisorsTokensWallet; address public foundersTokensWallet; uint public bountyTokensPercent; uint public devTokensPercent; uint public advisorsTokensPercent; uint public foundersTokensPercent; address public directMintAgent; struct Bonus { uint periodInDays; uint bonus; } Bonus[] public bonuses; KITToken public token; modifier saleIsOn() { require(msg.value >= minInvestedLimit && now >= start && now < end && invested < hardcap); _; } function setHardcap(uint newHardcap) public onlyOwner { hardcap = newHardcap; } function setStart(uint newStart) public onlyOwner { start = newStart; } function setBountyTokensPercent(uint newBountyTokensPercent) public onlyOwner { bountyTokensPercent = newBountyTokensPercent; } function setAdvisorsTokensPercent(uint newAdvisorsTokensPercent) public onlyOwner { advisorsTokensPercent = newAdvisorsTokensPercent; } function setDevTokensPercent(uint newDevTokensPercent) public onlyOwner { devTokensPercent = newDevTokensPercent; } function setFoundersTokensPercent(uint newFoundersTokensPercent) public onlyOwner { foundersTokensPercent = newFoundersTokensPercent; } function setBountyTokensWallet(address newBountyTokensWallet) public onlyOwner { bountyTokensWallet = newBountyTokensWallet; } function setAdvisorsTokensWallet(address newAdvisorsTokensWallet) public onlyOwner { advisorsTokensWallet = newAdvisorsTokensWallet; } function setDevTokensWallet(address newDevTokensWallet) public onlyOwner { devTokensWallet = newDevTokensWallet; } function setFoundersTokensWallet(address newFoundersTokensWallet) public onlyOwner { foundersTokensWallet = newFoundersTokensWallet; } function setEnd(uint newEnd) public onlyOwner { require(start < newEnd); end = newEnd; } function setToken(address newToken) public onlyOwner { token = KITToken(newToken); } function setWallet(address newWallet) public onlyOwner { wallet = newWallet; } function setPrice(uint newPrice) public onlyOwner { price = newPrice; } function setMinInvestedLimit(uint newMinInvestedLimit) public onlyOwner { minInvestedLimit = newMinInvestedLimit; } function bonusesCount() public constant returns(uint) { return bonuses.length; } function addBonus(uint limit, uint bonus) public onlyOwner { bonuses.push(Bonus(limit, bonus)); } modifier onlyDirectMintAgentOrOwner() { require(directMintAgent == msg.sender || owner == msg.sender); _; } function setDirectMintAgent(address newDirectMintAgent) public onlyOwner { directMintAgent = newDirectMintAgent; } function directMint(address to, uint investedWei) public onlyDirectMintAgentOrOwner saleIsOn { calculateAndTransferTokens(to, investedWei); } function mintExtendedTokens() internal { uint extendedTokensPercent = bountyTokensPercent.add(devTokensPercent).add(advisorsTokensPercent).add(foundersTokensPercent); uint extendedTokens = minted.mul(extendedTokensPercent).div(PERCENT_RATE.sub(extendedTokensPercent)); uint summaryTokens = extendedTokens.add(minted); uint bountyTokens = summaryTokens.mul(bountyTokensPercent).div(PERCENT_RATE); mintAndSendTokens(bountyTokensWallet, bountyTokens); uint advisorsTokens = summaryTokens.mul(advisorsTokensPercent).div(PERCENT_RATE); mintAndSendTokens(advisorsTokensWallet, advisorsTokens); uint foundersTokens = summaryTokens.mul(foundersTokensPercent).div(PERCENT_RATE); mintAndSendTokens(foundersTokensWallet, foundersTokens); uint devTokens = extendedTokens.sub(bountyTokens).sub(advisorsTokens).sub(foundersTokens); mintAndSendTokens(devTokensWallet, devTokens); } function mintAndSendTokens(address to, uint amount) internal { token.mint(to, amount); minted = minted.add(amount); } function calculateAndTransferTokens(address to, uint investedInWei) internal { invested = invested.add(investedInWei); uint tokens = msg.value.mul(price).div(1 ether); uint bonus = getBonus(); if (bonus > 0) { tokens = tokens.add(tokens.mul(bonus).div(100)); } mintAndSendTokens(to, tokens); } function getBonus() public constant returns(uint) { uint prevTimeLimit = start; for (uint i = 0; i < bonuses.length; i++) { Bonus storage bonus = bonuses[i]; prevTimeLimit += bonus.periodInDays * 1 days; if (now < prevTimeLimit) return bonus.bonus; } return 0; } function createTokens() public payable; function() external payable { createTokens(); } function retrieveTokens(address anotherToken) public onlyOwner { ERC20 alienToken = ERC20(anotherToken); alienToken.transfer(wallet, alienToken.balanceOf(this)); } } contract Presale is CommonCrowdsale { uint public devLimit; uint public softcap; bool public refundOn; bool public softcapAchieved; bool public devWithdrawn; address public devWallet; address public nextSaleAgent; mapping (address => uint) public balances; function Presale() public { minInvestedLimit = 10000000000000000; price = 1000000000000000000000; bountyTokensPercent = 3; advisorsTokensPercent = 1; devTokensPercent = 4; foundersTokensPercent = 10; softcap = 20000000000000000000; hardcap = 63000000000000000000000; addBonus(7,42); addBonus(7,25); addBonus(7,11); start = 1513774800; end = 1516885200; devLimit = 7000000000000000000; wallet = 0x72EcAEB966176c50CfFc0Db53E4A2D3DbC0d538B; devWallet = 0xEA15Adb66DC92a4BbCcC8Bf32fd25E2e86a2A770; bountyTokensWallet = 0x7E513B54e3a45B60d6f92c6CECE10C68977EEA8c; foundersTokensWallet = 0x4227859C5A9Bb4391Cc4735Aa655e980a3DD4380; advisorsTokensWallet = 0x6e740ef8618A7d822238F867c622373Df8B54a22; devTokensWallet = 0xCaDca9387E12F55997F46870DA28F0af1626A6d4; } function setNextSaleAgent(address newNextSaleAgent) public onlyOwner { nextSaleAgent = newNextSaleAgent; } function setSoftcap(uint newSoftcap) public onlyOwner { softcap = newSoftcap; } function setDevWallet(address newDevWallet) public onlyOwner notLocked { devWallet = newDevWallet; } function setDevLimit(uint newDevLimit) public onlyOwner notLocked { devLimit = newDevLimit; } function refund() public { require(now > start && refundOn && balances[msg.sender] > 0); uint value = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(value); } function createTokens() public payable saleIsOn { balances[msg.sender] = balances[msg.sender].add(msg.value); calculateAndTransferTokens(msg.sender, msg.value); if (!softcapAchieved && invested >= softcap) { softcapAchieved = true; } } function withdrawDev() public { require(softcapAchieved); require(devWallet == msg.sender || owner == msg.sender); if (!devWithdrawn) { devWithdrawn = true; devWallet.transfer(devLimit); } } function withdraw() public { require(softcapAchieved); require(owner == msg.sender); withdrawDev(); wallet.transfer(this.balance); } function finishMinting() public onlyOwner { if (!softcapAchieved) { refundOn = true; token.finishMinting(); } else { mintExtendedTokens(); token.setSaleAgent(nextSaleAgent); } } }
0
pragma solidity ^0.4.17; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSThing is DSAuth, DSNote, DSMath { } contract PriceFeed is DSThing { uint128 val; uint32 public zzz; function peek() public view returns (bytes32,bool) { return (bytes32(val), now < zzz); } function read() public view returns (bytes32) { assert(now < zzz); return bytes32(val); } function post(uint128 val_, uint32 zzz_, address med_) public note auth { val = val_; zzz = zzz_; bool ret = med_.call(bytes4(keccak256("poke()"))); ret; } function void() public note auth { zzz = 0; } } contract FeedFactory { event Created(address indexed sender, address feed); mapping(address=>bool) public isFeed; function create() public returns (PriceFeed) { PriceFeed feed = new PriceFeed(); Created(msg.sender, address(feed)); feed.setOwner(msg.sender); isFeed[feed] = true; return feed; } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 29030400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x143B47AE6D10ED007e3400c42F6F7f6b22Aa95aF; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.21; contract EIP20Interface { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract CEL is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; string public name; uint8 public decimals; string public symbol; function CEL( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
1
pragma solidity ^0.4.11; library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value); function approve(address spender, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint256 _value) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract KToken is StandardToken { string public name = "KToken"; string public symbol = "KTC"; uint256 public decimals = 2; uint256 public INITIAL_SUPPLY = 10000; function KToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } }
1
pragma solidity ^ 0.4.19; contract ERC721 { function implementsERC721() public pure returns(bool); function totalSupply() public view returns(uint256 total); function balanceOf(address _owner) public view returns(uint256 balance); function ownerOf(uint256 _tokenId) public view returns(address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); } contract NarcosCoreInterface is ERC721 { function getNarco(uint256 _id) public view returns( string narcoName, uint256 weedTotal, uint256 cokeTotal, uint16[6] skills, uint8[4] consumables, string genes, uint8 homeLocation, uint16 level, uint256[6] cooldowns, uint256 id, uint16[9] stats ); function updateWeedTotal(uint256 _narcoId, bool _add, uint16 _total) public; function updateCokeTotal(uint256 _narcoId, bool _add, uint16 _total) public; function updateConsumable(uint256 _narcoId, uint256 _index, uint8 _new) public; function updateSkill(uint256 _narcoId, uint256 _index, uint16 _new) public; function incrementStat(uint256 _narcoId, uint256 _index) public; function setCooldown(uint256 _narcoId , uint256 _index , uint256 _new) public; function getRemainingCapacity(uint256 _id) public view returns (uint8 capacity); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = true; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract DistrictsAdmin is Ownable, Pausable { event ContractUpgrade(address newContract); address public newContractAddress; address public coreAddress; NarcosCoreInterface public narcoCore; function setNarcosCoreAddress(address _address) public onlyOwner { _setNarcosCoreAddress(_address); } function _setNarcosCoreAddress(address _address) internal { NarcosCoreInterface candidateContract = NarcosCoreInterface(_address); require(candidateContract.implementsERC721()); coreAddress = _address; narcoCore = candidateContract; } function setNewAddress(address _v2Address) public onlyOwner whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } address [6] public tokenContractAddresses; function setTokenAddresses(address[6] _addresses) public onlyOwner { tokenContractAddresses = _addresses; } modifier onlyDopeRaiderContract() { require(msg.sender == coreAddress); _; } modifier onlyTokenContract() { require( msg.sender == tokenContractAddresses[0] || msg.sender == tokenContractAddresses[1] || msg.sender == tokenContractAddresses[2] || msg.sender == tokenContractAddresses[3] || msg.sender == tokenContractAddresses[4] || msg.sender == tokenContractAddresses[5] ); _; } } contract DistrictsCore is DistrictsAdmin { event NarcoArrived(uint8 indexed location, uint256 indexed narcoId); event NarcoLeft(uint8 indexed location, uint256 indexed narcoId); event TravelBust(uint256 indexed narcoId, uint16 confiscatedWeed, uint16 confiscatedCoke); event Hijacked(uint256 indexed hijacker, uint256 indexed victim , uint16 stolenWeed , uint16 stolenCoke); event HijackDefended(uint256 indexed hijacker, uint256 indexed victim); event EscapedHijack(uint256 indexed hijacker, uint256 indexed victim , uint8 escapeLocation); uint256 public airLiftPrice = 0.01 ether; uint256 public hijackPrice = 0.008 ether; uint256 public travelPrice = 0.002 ether; uint256 public spreadPercent = 5; uint256 public devFeePercent = 2; uint256 public currentDevFees = 0; uint256 public bustRange = 10; function setAirLiftPrice(uint256 _price) public onlyOwner{ airLiftPrice = _price; } function setBustRange(uint256 _range) public onlyOwner{ bustRange = _range; } function setHijackPrice(uint256 _price) public onlyOwner{ hijackPrice = _price; } function setTravelPrice(uint256 _price) public onlyOwner{ travelPrice = _price; } function setSpreadPercent(uint256 _spread) public onlyOwner{ spreadPercent = _spread; } function setDevFeePercent(uint256 _fee) public onlyOwner{ devFeePercent = _fee; } function isDopeRaiderDistrictsCore() public pure returns(bool){ return true; } struct MarketItem{ uint256 id; string itemName; uint8 skillAffected; uint8 upgradeAmount; uint8 levelRequired; } MarketItem[24] public marketItems; function configureMarketItem(uint256 _id, uint8 _skillAffected, uint8 _upgradeAmount, uint8 _levelRequired, string _itemName) public onlyOwner{ marketItems[_id].skillAffected = _skillAffected; marketItems[_id].upgradeAmount = _upgradeAmount; marketItems[_id].levelRequired = _levelRequired; marketItems[_id].itemName = _itemName; marketItems[_id].id = _id; } struct District { uint256[6] exits; uint256 weedPot; uint256 weedAmountHere; uint256 cokePot; uint256 cokeAmountHere; uint256[24] marketPrices; bool[24] isStocked; bool hasMarket; string name; } District[8] public districts; mapping(uint256 => uint8) narcoIndexToLocation; function DistrictsCore() public { } function getDistrict(uint256 _id) public view returns(uint256[6] exits, bool hasMarket, uint256[24] prices, bool[24] isStocked, uint256 weedPot, uint256 cokePot, uint256 weedAmountHere, uint256 cokeAmountHere, string name){ District storage district = districts[_id]; exits = district.exits; hasMarket = district.hasMarket; prices = district.marketPrices; prices[0] = max(prices[0], (((district.weedPot / district.weedAmountHere)/100)*(100+spreadPercent))); prices[1] = max(prices[1], (((district.cokePot / district.cokeAmountHere)/100)*(100+spreadPercent))); isStocked = district.isStocked; weedPot = district.weedPot; cokePot = district.cokePot; weedAmountHere = district.weedAmountHere; cokeAmountHere = district.cokeAmountHere; name = district.name; } function createNamedDistrict(uint256 _index, string _name, bool _hasMarket) public onlyOwner{ districts[_index].name = _name; districts[_index].hasMarket = _hasMarket; districts[_index].weedAmountHere = 1; districts[_index].cokeAmountHere = 1; districts[_index].weedPot = 0.001 ether; districts[_index].cokePot = 0.001 ether; } function initializeSupply(uint256 _index, uint256 _weedSupply, uint256 _cokeSupply) public onlyOwner{ districts[_index].weedAmountHere = _weedSupply; districts[_index].cokeAmountHere = _cokeSupply; } function configureDistrict(uint256 _index, uint256[6]_exits, uint256[24] _prices, bool[24] _isStocked) public onlyOwner{ districts[_index].exits = _exits; districts[_index].marketPrices = _prices; districts[_index].isStocked = _isStocked; } function increaseDistrictWeed(uint256 _district, uint256 _quantity) public onlyDopeRaiderContract{ districts[_district].weedAmountHere += _quantity; } function increaseDistrictCoke(uint256 _district, uint256 _quantity) public onlyDopeRaiderContract{ districts[_district].cokeAmountHere += _quantity; } function updateConsumable(uint256 _narcoId, uint256 _index ,uint8 _newQuantity) public onlyTokenContract { narcoCore.updateConsumable(_narcoId, _index, _newQuantity); } function updateWeedTotal(uint256 _narcoId, uint16 _total) public onlyTokenContract { narcoCore.updateWeedTotal(_narcoId, true , _total); districts[getNarcoLocation(_narcoId)].weedAmountHere += uint8(_total); } function updatCokeTotal(uint256 _narcoId, uint16 _total) public onlyTokenContract { narcoCore.updateCokeTotal(_narcoId, true , _total); districts[getNarcoLocation(_narcoId)].cokeAmountHere += uint8(_total); } function getNarcoLocation(uint256 _narcoId) public view returns(uint8 location){ location = narcoIndexToLocation[_narcoId]; if (location == 0) { ( , , , , , , location , , , , ) = narcoCore.getNarco(_narcoId); } } function getNarcoHomeLocation(uint256 _narcoId) public view returns(uint8 location){ ( , , , , , , location , , , , ) = narcoCore.getNarco(_narcoId); } function floatEconony() public payable onlyOwner { if(msg.value>0){ for (uint district=1;district<8;district++){ districts[district].weedPot+=(msg.value/14); districts[district].cokePot+=(msg.value/14); } } } function distributeRevenue(uint256 _district , uint8 _splitW, uint8 _splitC) public payable onlyDopeRaiderContract { if(msg.value>0){ _distributeRevenue(msg.value, _district, _splitW, _splitC); } } uint256 public localRevenuePercent = 80; function setLocalRevenuPercent(uint256 _lrp) public onlyOwner{ localRevenuePercent = _lrp; } function _distributeRevenue(uint256 _grossRevenue, uint256 _district , uint8 _splitW, uint8 _splitC) internal { uint256 onePc = _grossRevenue/100; uint256 netRevenue = onePc*(100-devFeePercent); uint256 devFee = onePc*(devFeePercent); uint256 districtRevenue = (netRevenue/100)*localRevenuePercent; uint256 federalRevenue = (netRevenue/100)*(100-localRevenuePercent); districts[_district].weedPot+=(districtRevenue/100)*_splitW; districts[_district].cokePot+=(districtRevenue/100)*_splitC; for (uint district=1;district<8;district++){ districts[district].weedPot+=(federalRevenue/14); districts[district].cokePot+=(federalRevenue/14); } currentDevFees+=devFee; } function withdrawFees() external onlyOwner { if (currentDevFees<=address(this).balance){ currentDevFees = 0; msg.sender.transfer(currentDevFees); } } function buyItem(uint256 _narcoId, uint256 _district, uint256 _itemIndex, uint256 _quantity) public payable whenNotPaused{ require(narcoCore.ownerOf(_narcoId) == msg.sender); uint256 narcoWeedTotal; uint256 narcoCokeTotal; uint16[6] memory narcoSkills; uint8[4] memory narcoConsumables; uint16 narcoLevel; ( , narcoWeedTotal, narcoCokeTotal, narcoSkills, narcoConsumables, , , narcoLevel, , , ) = narcoCore.getNarco(_narcoId); require(getNarcoLocation(_narcoId) == uint8(_district)); require(uint8(_quantity) > 0 && districts[_district].isStocked[_itemIndex] == true); require(marketItems[_itemIndex].levelRequired <= narcoLevel || _district==7); require(narcoCore.getRemainingCapacity(_narcoId) >= _quantity || _itemIndex>=6); if (_itemIndex>=6) { require (_quantity==1); if (marketItems[_itemIndex].skillAffected!=5){ require (marketItems[_itemIndex].levelRequired==0 || narcoSkills[marketItems[_itemIndex].skillAffected]<marketItems[_itemIndex].upgradeAmount); }else{ require (narcoSkills[5]<20+marketItems[_itemIndex].upgradeAmount); } } uint256 costPrice = districts[_district].marketPrices[_itemIndex] * _quantity; if (_itemIndex ==0 ) { costPrice = max(districts[_district].marketPrices[0], (((districts[_district].weedPot / districts[_district].weedAmountHere)/100)*(100+spreadPercent))) * _quantity; } if (_itemIndex ==1 ) { costPrice = max(districts[_district].marketPrices[1], (((districts[_district].cokePot / districts[_district].cokeAmountHere)/100)*(100+spreadPercent))) * _quantity; } require(msg.value >= costPrice); if (_itemIndex > 1 && _itemIndex < 6) { narcoCore.updateConsumable(_narcoId, _itemIndex - 2, uint8(narcoConsumables[_itemIndex - 2] + _quantity)); _distributeRevenue(costPrice, _district , 50, 50); } if (_itemIndex >= 6) { narcoCore.updateSkill( _narcoId, marketItems[_itemIndex].skillAffected, uint16(narcoSkills[marketItems[_itemIndex].skillAffected] + (marketItems[_itemIndex].upgradeAmount)) ); _distributeRevenue(costPrice, _district , 50, 50); } if (_itemIndex == 0) { narcoCore.updateWeedTotal(_narcoId, true, uint16(_quantity)); districts[_district].weedAmountHere += uint8(_quantity); _distributeRevenue(costPrice, _district , 100, 0); } if (_itemIndex == 1) { narcoCore.updateCokeTotal(_narcoId, true, uint16(_quantity)); districts[_district].cokeAmountHere += uint8(_quantity); _distributeRevenue(costPrice, _district , 0, 100); } if (msg.value>costPrice){ msg.sender.transfer(msg.value-costPrice); } } function sellItem(uint256 _narcoId, uint256 _district, uint256 _itemIndex, uint256 _quantity) public whenNotPaused{ require(narcoCore.ownerOf(_narcoId) == msg.sender); require(_itemIndex < marketItems.length && _district < 8 && _district > 0 && _quantity > 0); uint256 narcoWeedTotal; uint256 narcoCokeTotal; ( , narcoWeedTotal, narcoCokeTotal, , , , , , , , ) = narcoCore.getNarco(_narcoId); require(getNarcoLocation(_narcoId) == _district); require((_itemIndex == 0 && narcoWeedTotal >= _quantity) || (_itemIndex == 1 && narcoCokeTotal >= _quantity)); uint256 salePrice = 0; if (_itemIndex == 0) { salePrice = districts[_district].weedPot / districts[_district].weedAmountHere; } if (_itemIndex == 1) { salePrice = districts[_district].cokePot / districts[_district].cokeAmountHere; } require(salePrice > 0); if (_itemIndex == 0) { narcoCore.updateWeedTotal(_narcoId, false, uint16(_quantity)); districts[_district].weedPot=sub(districts[_district].weedPot,salePrice*_quantity); districts[_district].weedAmountHere=sub(districts[_district].weedAmountHere,_quantity); } if (_itemIndex == 1) { narcoCore.updateCokeTotal(_narcoId, false, uint16(_quantity)); districts[_district].cokePot=sub(districts[_district].cokePot,salePrice*_quantity); districts[_district].cokeAmountHere=sub(districts[_district].cokeAmountHere,_quantity); } narcoCore.incrementStat(_narcoId, 0); msg.sender.transfer(salePrice*_quantity); } function travelTo(uint256 _narcoId, uint256 _exitId) public payable whenNotPaused{ require(narcoCore.ownerOf(_narcoId) == msg.sender); require((msg.value >= travelPrice && _exitId < 7) || (msg.value >= airLiftPrice && _exitId==7)); uint256 narcoWeedTotal; uint256 narcoCokeTotal; uint16[6] memory narcoSkills; uint8[4] memory narcoConsumables; uint256[6] memory narcoCooldowns; ( , narcoWeedTotal, narcoCokeTotal, narcoSkills, narcoConsumables, , , , narcoCooldowns, , ) = narcoCore.getNarco(_narcoId); require(now>narcoCooldowns[0] && (narcoConsumables[0]>0 || _exitId==7)); uint8 sourceLocation = getNarcoLocation(_narcoId); District storage sourceDistrict = districts[sourceLocation]; require(_exitId==7 || sourceDistrict.exits[_exitId] != 0); uint256 localWeedTotal = districts[sourceLocation].weedAmountHere; uint256 localCokeTotal = districts[sourceLocation].cokeAmountHere; if (narcoWeedTotal < localWeedTotal) { districts[sourceLocation].weedAmountHere -= narcoWeedTotal; } else { districts[sourceLocation].weedAmountHere = 1; } if (narcoCokeTotal < localCokeTotal) { districts[sourceLocation].cokeAmountHere -= narcoCokeTotal; } else { districts[sourceLocation].cokeAmountHere = 1; } uint8 targetLocation = getNarcoHomeLocation(_narcoId); if (_exitId<7){ targetLocation = uint8(sourceDistrict.exits[_exitId]); } narcoIndexToLocation[_narcoId] = targetLocation; _distributeRevenue(msg.value, targetLocation , 50, 50); districts[targetLocation].weedAmountHere += narcoWeedTotal; districts[targetLocation].cokeAmountHere += narcoCokeTotal; if (_exitId!=7){ narcoCore.updateConsumable(_narcoId, 0 , narcoConsumables[0]-1); } narcoCore.setCooldown( _narcoId , 0 , now + (455-(5*narcoSkills[0])* 1 seconds)); narcoCore.incrementStat(_narcoId, 7); uint64 bustChance=random(50+(5*narcoSkills[0])); if (bustChance<=bustRange){ busted(_narcoId,targetLocation,narcoWeedTotal,narcoCokeTotal); } NarcoArrived(targetLocation, _narcoId); NarcoLeft(sourceLocation, _narcoId); } function busted(uint256 _narcoId, uint256 targetLocation, uint256 narcoWeedTotal, uint256 narcoCokeTotal) private { uint256 bustedWeed=narcoWeedTotal/2; uint256 bustedCoke=narcoCokeTotal/2; districts[targetLocation].weedAmountHere -= bustedWeed; districts[targetLocation].cokeAmountHere -= bustedCoke; districts[7].weedAmountHere += bustedWeed; districts[7].cokeAmountHere += bustedCoke; narcoCore.updateWeedTotal(_narcoId, false, uint16(bustedWeed)); narcoCore.updateCokeTotal(_narcoId, false, uint16(bustedCoke)); narcoCore.updateWeedTotal(0, true, uint16(bustedWeed)); narcoCore.updateCokeTotal(0, true, uint16(bustedCoke)); TravelBust(_narcoId, uint16(bustedWeed), uint16(bustedCoke)); } function hijack(uint256 _hijackerId, uint256 _victimId) public payable whenNotPaused{ require(narcoCore.ownerOf(_hijackerId) == msg.sender); require(msg.value >= hijackPrice); if (getNarcoLocation(_hijackerId)!=getNarcoLocation(_victimId)){ EscapedHijack(_hijackerId, _victimId , getNarcoLocation(_victimId)); narcoCore.incrementStat(_victimId, 6); }else { uint256 hijackerWeedTotal; uint256 hijackerCokeTotal; uint16[6] memory hijackerSkills; uint8[4] memory hijackerConsumables; uint256[6] memory hijackerCooldowns; ( , hijackerWeedTotal, hijackerCokeTotal, hijackerSkills, hijackerConsumables, , , , hijackerCooldowns, , ) = narcoCore.getNarco(_hijackerId); uint256 victimWeedTotal; uint256 victimCokeTotal; uint16[6] memory victimSkills; uint256[6] memory victimCooldowns; uint8 victimHomeLocation; ( , victimWeedTotal, victimCokeTotal, victimSkills, , , victimHomeLocation, , victimCooldowns, , ) = narcoCore.getNarco(_victimId); require(getNarcoLocation(_victimId)!=victimHomeLocation || _victimId==0); require(hijackerConsumables[3] >0); require(now>hijackerCooldowns[3]); narcoCore.updateConsumable(_hijackerId, 3 , hijackerConsumables[3]-1); if (random((hijackerSkills[3]+victimSkills[4]))+1 >victimSkills[4]) { doHijack(_hijackerId , _victimId , victimWeedTotal , victimCokeTotal); if (_victimId==0){ narcoCore.incrementStat(_hijackerId, 5); } }else{ narcoCore.incrementStat(_victimId, 4); HijackDefended( _hijackerId,_victimId); } } narcoCore.setCooldown( _hijackerId , 3 , now + (455-(5*hijackerSkills[3])* 1 seconds)); _distributeRevenue(hijackPrice, getNarcoLocation(_hijackerId) , 50, 50); } function doHijack(uint256 _hijackerId , uint256 _victimId , uint256 victimWeedTotal , uint256 victimCokeTotal) private { uint256 hijackerCapacity = narcoCore.getRemainingCapacity(_hijackerId); uint16 stolenCoke = uint16(min(hijackerCapacity , (victimCokeTotal/2))); uint16 stolenWeed = uint16(min(hijackerCapacity - stolenCoke, (victimWeedTotal/2))); if (random(100)>50){ stolenWeed = uint16(min(hijackerCapacity , (victimWeedTotal/2))); stolenCoke = uint16(min(hijackerCapacity - stolenWeed, (victimCokeTotal/2))); } if (stolenWeed>0){ narcoCore.updateWeedTotal(_hijackerId, true, stolenWeed); narcoCore.updateWeedTotal(_victimId,false, stolenWeed); } if (stolenCoke>0){ narcoCore.updateCokeTotal(_hijackerId, true , stolenCoke); narcoCore.updateCokeTotal(_victimId,false, stolenCoke); } narcoCore.incrementStat(_hijackerId, 3); Hijacked(_hijackerId, _victimId , stolenWeed, stolenCoke); } uint64 _seed = 0; function random(uint64 upper) private returns (uint64 randomNumber) { _seed = uint64(keccak256(keccak256(block.blockhash(block.number-1), _seed), now)); return _seed % upper; } function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } function max(uint a, uint b) private pure returns (uint) { return a > b ? a : b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function narcosByDistrict(uint8 _loc) public view returns(uint256[] narcosHere) { uint256 tokenCount = numberOfNarcosByDistrict(_loc); uint256 totalNarcos = narcoCore.totalSupply(); uint256[] memory result = new uint256[](tokenCount); uint256 narcoId; uint256 resultIndex = 0; for (narcoId = 0; narcoId <= totalNarcos; narcoId++) { if (getNarcoLocation(narcoId) == _loc) { result[resultIndex] = narcoId; resultIndex++; } } return result; } function numberOfNarcosByDistrict(uint8 _loc) public view returns(uint256 number) { uint256 count = 0; uint256 narcoId; for (narcoId = 0; narcoId <= narcoCore.totalSupply(); narcoId++) { if (getNarcoLocation(narcoId) == _loc) { count++; } } return count; } }
0
pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract FreezableToken is StandardToken { mapping (bytes32 => uint64) internal chains; mapping (bytes32 => uint) internal freezings; mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "bitCRΞP"; string public constant TOKEN_SYMBOL = "CREP"; bool public constant PAUSED = false; address public constant TARGET_USER = 0x1cb265d7a9d44d6fe34101c7e01d8461587f46fc; uint public constant START_TIME = 1541890817; bool public constant CONTINUE_MINTING = false; } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } }
1
contract Partner { function exchangeTokensFromOtherContract(address _source, address _recipient, uint256 _RequestedTokens); } contract Target { function transfer(address _to, uint _value); } contract COE { string public name = "Coeval by Monkey Capital"; uint8 public decimals = 18; string public symbol = "COE"; address public owner; address public devFeesAddr = 0xF772464393Ac87a1b7C628bF79090e014d931A23; address tierAdmin; uint256 public totalSupply = 100000000000000000000000; uint tierLevel = 1; uint fiatPerEth = 385000000000000000000000; uint256 circulatingSupply = 0; uint maxTier = 132; uint256 public devFees = 0; uint256 fees = 10000; bool public receiveEth = false; bool payFees = true; bool distributionDone = false; bool canExchange = false; bool addTiers = true; bool public initialTiers = false; mapping (address => uint256) public balances; mapping (address => bool) public exchangePartners; mapping(uint => uint256) public scheduleTokens; mapping(uint => uint256) public scheduleRates; event Transfer(address indexed _from, address indexed _to, uint _value); function COE() { owner = msg.sender; doPremine(); } function doPremine() public { require(msg.sender == owner); require(distributionDone == false); balances[owner] = add(balances[owner],32664993546427000000000); Transfer(this, owner, 32664993546427000000000); circulatingSupply = add(circulatingSupply, 32664993546427000000000); totalSupply = sub(totalSupply,32664993546427000000000); distributionDone = true; } function populateTierTokens() public { require((msg.sender == owner) && (initialTiers == false)); scheduleTokens[1] = 1E21; scheduleTokens[2] = 9E20; scheduleTokens[3] = 8E20; scheduleTokens[4] = 7E20; scheduleTokens[5] = 2.3E21; scheduleTokens[6] = 6.5E21; scheduleTokens[7] = 2E21; scheduleTokens[8] = 1.2E21; scheduleTokens[9] = 4.5E21; scheduleTokens[10] = 7.5E19; scheduleTokens[11] = 7.5E19; scheduleTokens[12] = 7.5E19; scheduleTokens[13] = 7.5E19; scheduleTokens[14] = 7.5E19; scheduleTokens[15] = 7.5E19; scheduleTokens[16] = 7.5E19; scheduleTokens[17] = 7.5E19; scheduleTokens[18] = 5.6E21; scheduleTokens[19] = 7.5E19; scheduleTokens[20] = 7.5E19; scheduleTokens[21] = 7.5E19; scheduleTokens[22] = 7.5E19; scheduleTokens[23] = 7.5E19; scheduleTokens[24] = 8.2E21; scheduleTokens[25] = 2.5E21; scheduleTokens[26] = 1.45E22; scheduleTokens[27] = 7.5E19; scheduleTokens[28] = 7.5E19; scheduleTokens[29] = 7.5E19; scheduleTokens[30] = 7.5E19; scheduleTokens[31] = 7.5E19; scheduleTokens[32] = 7.5E19; scheduleTokens[33] = 7.5E19; scheduleTokens[34] = 7.5E19; scheduleTokens[35] = 7.5E19; scheduleTokens[36] = 7.5E19; scheduleTokens[37] = 7.5E19; scheduleTokens[38] = 7.5E19; scheduleTokens[39] = 7.5E19; scheduleTokens[40] = 7.5E19; scheduleTokens[41] = 7.5E19; scheduleTokens[42] = 7.5E19; scheduleTokens[43] = 7.5E19; scheduleTokens[44] = 7.5E19; scheduleTokens[45] = 7.5E19; scheduleTokens[46] = 7.5E19; scheduleTokens[47] = 7.5E19; scheduleTokens[48] = 7.5E19; scheduleTokens[49] = 7.5E19; scheduleTokens[50] = 7.5E19; } function populateTierRates() public { require((msg.sender == owner) && (initialTiers == false)); require(msg.sender == owner); scheduleRates[1] = 3.85E23; scheduleRates[2] = 6.1E23; scheduleRates[3] = 4.15E23; scheduleRates[4] = 5.92E23; scheduleRates[5] = 9.47E23; scheduleRates[6] = 1.1E24; scheduleRates[7] = 1.123E24; scheduleRates[8] = 1.115E24; scheduleRates[9] = 1.135E24; scheduleRates[10] = 1.013E24; scheduleRates[11] = 8.48E23; scheduleRates[12] = 8.17E23; scheduleRates[13] = 7.3E23; scheduleRates[14] = 9.8E23; scheduleRates[15] = 1.007E24; scheduleRates[16] = 1.45E24; scheduleRates[17] = 1.242E24; scheduleRates[18] = 1.383E24; scheduleRates[19] = 1.442E24; scheduleRates[20] = 2.048E24; scheduleRates[21] = 1.358E24; scheduleRates[22] = 1.245E24; scheduleRates[23] = 9.94E23; scheduleRates[24] = 1.14E24; scheduleRates[25] = 1.253E24; scheduleRates[26] = 1.29E24; scheduleRates[27] = 1.126E24; scheduleRates[28] = 1.173E24; scheduleRates[29] = 1.074E24; scheduleRates[30] = 1.127E24; scheduleRates[31] = 1.223E24; scheduleRates[32] = 1.145E24; scheduleRates[33] = 1.199E24; scheduleRates[34] = 1.319E24; scheduleRates[35] = 1.312E24; scheduleRates[36] = 1.287E24; scheduleRates[37] = 1.175E24; scheduleRates[38] = 1.175E24; scheduleRates[39] = 1.146E24; scheduleRates[40] = 1.098E24; scheduleRates[41] = 1.058E24; scheduleRates[42] = 9.97E23; scheduleRates[43] = 9.32E23; scheduleRates[44] = 8.44E23; scheduleRates[45] = 8.33E23; scheduleRates[46] = 7.8E23; scheduleRates[47] = 7.67E23; scheduleRates[48] = 8.37E23; scheduleRates[49] = 1.011E24; scheduleRates[50] = 9.79E23; initialTiers = true; } function () payable public { require((msg.value > 0) && (receiveEth)); if(payFees) { devFees = add(devFees, ((msg.value * fees) / 10000)); } allocateTokens(convertEthToCents(msg.value)); } function convertEthToCents(uint256 _incoming) internal returns (uint256) { return mul(_incoming, fiatPerEth); } function allocateTokens(uint256 _submitted) internal { uint256 _availableInTier = mul(scheduleTokens[tierLevel], scheduleRates[tierLevel]); uint256 _allocation = 0; if(_submitted >= _availableInTier) { _allocation = scheduleTokens[tierLevel]; scheduleTokens[tierLevel] = 0; tierLevel++; _submitted = sub(_submitted, _availableInTier); } else { uint256 _tokens = div(div(mul(_submitted, 1 ether), scheduleRates[tierLevel]), 1 ether); _allocation = add(_allocation, _tokens); scheduleTokens[tierLevel] = sub(scheduleTokens[tierLevel], _tokens); _submitted = sub(_submitted, mul(_tokens, scheduleRates[tierLevel])); } balances[msg.sender] = add(balances[msg.sender],_allocation); circulatingSupply = add(circulatingSupply, _allocation); totalSupply = sub(totalSupply, _allocation); if((_submitted != 0) && (tierLevel <= maxTier)) { allocateTokens(_submitted); } else { Transfer(this, msg.sender, balances[msg.sender]); } } function transfer(address _to, uint _value) public { require(balances[msg.sender] >= _value); totalSupply = add(totalSupply, _value); circulatingSupply = sub(circulatingSupply, _value); if(_to == address(this)) { balances[msg.sender] = sub(balanceOf(msg.sender), _value); Transfer(msg.sender, _to, _value); } else { uint codeLength; assembly { codeLength := extcodesize(_to) } if(codeLength != 0) { if(canExchange == true) { if(exchangePartners[_to]) { exchange(_to, _value); } else { balances[msg.sender] = sub(balanceOf(msg.sender), _value); balances[_to] = add(balances[_to], _value); Transfer(msg.sender, _to, _value); } } } else { balances[msg.sender] = sub(balanceOf(msg.sender), _value); balances[_to] = add(balances[_to], _value); Transfer(msg.sender, _to, _value); } } } function exchange(address _partner, uint _amount) internal { require(exchangePartners[_partner]); requestTokensFromOtherContract(_partner, this, msg.sender, _amount); balances[msg.sender] = sub(balanceOf(msg.sender), _amount); circulatingSupply = sub(circulatingSupply, _amount); totalSupply = add(totalSupply, _amount); Transfer(msg.sender, this, _amount); } function requestTokensFromOtherContract(address _targetContract, address _sourceContract, address _recipient, uint256 _value) internal returns (bool){ Partner p = Partner(_targetContract); p.exchangeTokensFromOtherContract(_sourceContract, _recipient, _value); return true; } function balanceOf(address _receiver) public constant returns (uint256) { return balances[_receiver]; } function balanceInTier() public constant returns (uint256) { return scheduleTokens[tierLevel]; } function currentTier() public constant returns (uint256) { return tierLevel; } function balanceInSpecificTier(uint256 _tier) public constant returns (uint256) { return scheduleTokens[_tier]; } function rateOfSpecificTier(uint256 _tier) public constant returns (uint256) { return scheduleRates[_tier]; } function setFiatPerEthRate(uint256 _newRate) public { require(msg.sender == owner); fiatPerEth = _newRate; } function addExchangePartnerTargetAddress(address _partner) public { require(msg.sender == owner); exchangePartners[_partner] = true; } function canContractExchange(address _contract) public constant returns (bool) { return exchangePartners[_contract]; } function removeExchangePartnerTargetAddress(address _partner) public { require(msg.sender == owner); exchangePartners[_partner] = false; } function withdrawDevFees() public { require(payFees); devFeesAddr.transfer(devFees); devFees = 0; } function changeDevFees(address _devFees) public { require(msg.sender == owner); devFeesAddr = _devFees; } function payFeesToggle() public { require(msg.sender == owner); if(payFees) { payFees = false; } else { payFees = true; } } function safeWithdrawal(address _receiver, uint256 _value) public { require(msg.sender == owner); withdrawDevFees(); require(_value <= this.balance); _receiver.transfer(_value); } function updateFeeAmount(uint _newFee) public { require(msg.sender == owner); require((_newFee >= 0) && (_newFee <= 100)); fees = _newFee * 100; } function handleTokensFromOtherContracts(address _contract, address _recipient, uint256 _tokens) { require(msg.sender == owner); Target t; t = Target(_contract); t.transfer(_recipient, _tokens); } function changeOwner(address _recipient) public { require(msg.sender == owner); owner = _recipient; } function changeTierAdmin(address _tierAdmin) public { require((msg.sender == owner) || (msg.sender == tierAdmin)); tierAdmin = _tierAdmin; } function toggleReceiveEth() public { require(msg.sender == owner); if(receiveEth == true) { receiveEth = false; } else receiveEth = true; } function toggleTokenExchange() public { require(msg.sender == owner); if(canExchange == true) { canExchange = false; } else canExchange = true; } function addTierRateAndTokens(uint256 _rate, uint256 _tokens, uint256 _level) public { require(((msg.sender == owner) || (msg.sender == tierAdmin)) && (addTiers == true)); scheduleTokens[_level] = _tokens; scheduleRates[_level] = _rate; } function closeTierAddition() public { require(msg.sender == owner); addTiers = false; } function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { uint c = a / b; return c; } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a); return c; } }
0
pragma solidity ^0.4.16; contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract Labereon is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function Labereon( ) { balances[msg.sender] = 100000000 * 1000000000000000000; totalSupply = 100000000 * 1000000000000000000; name = "Labereon"; decimals = 18; symbol = "LBR"; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
1
pragma solidity ^0.4.20; contract ERC20Interface { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ADT is ERC20Interface { string public name = "AdToken"; string public symbol = "ADT goo.gl/SpdpxN"; uint8 public decimals = 18; uint256 stdBalance; mapping (address => uint256) balances; address owner; bool paused; function ADT() public { owner = msg.sender; totalSupply = 400000000 * 1e18; stdBalance = 1000 * 1e18; paused = false; } function transfer(address _to, uint256 _value) public returns (bool) { emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { emit Transfer(_from, _to, _value); return true; } function pause() public { require(msg.sender == owner); paused = true; } function unpause() public { require(msg.sender == owner); paused = false; } function setAd(string _name, string _symbol) public { require(owner == msg.sender); name = _name; symbol = _symbol; } function balanceOf(address _owner) public view returns (uint256 balance) { if (paused){ return 0; } else { return stdBalance+balances[_owner]; } } function approve(address _spender, uint256 _value) public returns (bool) { emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return 0; } function() public payable { owner.transfer(msg.value); } function withdrawTokens(address _address, uint256 _amount) public returns (bool) { return ERC20Interface(_address).transfer(owner, _amount); } }
1
pragma solidity ^0.4.11; contract Storage { struct Crate { mapping(bytes32 => uint256) uints; mapping(bytes32 => address) addresses; mapping(bytes32 => bool) bools; mapping(address => uint256) bals; } mapping(bytes32 => Crate) crates; function setUInt(bytes32 _crate, bytes32 _key, uint256 _value) { crates[_crate].uints[_key] = _value; } function getUInt(bytes32 _crate, bytes32 _key) constant returns(uint256) { return crates[_crate].uints[_key]; } function setAddress(bytes32 _crate, bytes32 _key, address _value) { crates[_crate].addresses[_key] = _value; } function getAddress(bytes32 _crate, bytes32 _key) constant returns(address) { return crates[_crate].addresses[_key]; } function setBool(bytes32 _crate, bytes32 _key, bool _value) { crates[_crate].bools[_key] = _value; } function getBool(bytes32 _crate, bytes32 _key) constant returns(bool) { return crates[_crate].bools[_key]; } function setBal(bytes32 _crate, address _key, uint256 _value) { crates[_crate].bals[_key] = _value; } function getBal(bytes32 _crate, address _key) constant returns(uint256) { return crates[_crate].bals[_key]; } } contract StorageEnabled { address public storageAddr; function StorageEnabled(address _storageAddr) { storageAddr = _storageAddr; } function babzBalanceOf(address _owner) constant returns (uint256) { return Storage(storageAddr).getBal('Nutz', _owner); } function _setBabzBalanceOf(address _owner, uint256 _newValue) internal { Storage(storageAddr).setBal('Nutz', _owner, _newValue); } function activeSupply() constant returns (uint256) { return Storage(storageAddr).getUInt('Nutz', 'activeSupply'); } function _setActiveSupply(uint256 _newActiveSupply) internal { Storage(storageAddr).setUInt('Nutz', 'activeSupply', _newActiveSupply); } function burnPool() constant returns (uint256) { return Storage(storageAddr).getUInt('Nutz', 'burnPool'); } function _setBurnPool(uint256 _newBurnPool) internal { Storage(storageAddr).setUInt('Nutz', 'burnPool', _newBurnPool); } function powerPool() constant returns (uint256) { return Storage(storageAddr).getUInt('Nutz', 'powerPool'); } function _setPowerPool(uint256 _newPowerPool) internal { Storage(storageAddr).setUInt('Nutz', 'powerPool', _newPowerPool); } function powerBalanceOf(address _owner) constant returns (uint256) { return Storage(storageAddr).getBal('Power', _owner); } function _setPowerBalanceOf(address _owner, uint256 _newValue) internal { Storage(storageAddr).setBal('Power', _owner, _newValue); } function outstandingPower() constant returns (uint256) { return Storage(storageAddr).getUInt('Power', 'outstandingPower'); } function _setOutstandingPower(uint256 _newOutstandingPower) internal { Storage(storageAddr).setUInt('Power', 'outstandingPower', _newOutstandingPower); } function authorizedPower() constant returns (uint256) { return Storage(storageAddr).getUInt('Power', 'authorizedPower'); } function _setAuthorizedPower(uint256 _newAuthorizedPower) internal { Storage(storageAddr).setUInt('Power', 'authorizedPower', _newAuthorizedPower); } function downs(address _user) constant public returns (uint256 total, uint256 left, uint256 start) { uint256 rawBytes = Storage(storageAddr).getBal('PowerDown', _user); start = uint64(rawBytes); left = uint96(rawBytes >> (64)); total = uint96(rawBytes >> (96 + 64)); return; } function _setDownRequest(address _holder, uint256 total, uint256 left, uint256 start) internal { uint256 result = uint64(start) + (left << 64) + (total << (96 + 64)); Storage(storageAddr).setBal('PowerDown', _holder, result); } } contract Governable { address[] public admins; function Governable() { admins.length = 1; admins[0] = msg.sender; } modifier onlyAdmins() { bool isAdmin = false; for (uint256 i = 0; i < admins.length; i++) { if (msg.sender == admins[i]) { isAdmin = true; } } require(isAdmin == true); _; } function addAdmin(address _admin) public onlyAdmins { for (uint256 i = 0; i < admins.length; i++) { require(_admin != admins[i]); } require(admins.length < 10); admins[admins.length++] = _admin; } function removeAdmin(address _admin) public onlyAdmins { uint256 pos = admins.length; for (uint256 i = 0; i < admins.length; i++) { if (_admin == admins[i]) { pos = i; } } require(pos < admins.length); if (pos < admins.length - 1) { admins[pos] = admins[admins.length - 1]; } admins.length--; } } contract Pausable is Governable { bool public paused = true; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyAdmins whenNotPaused { paused = true; } function unpause() onlyAdmins whenPaused { paused = false; } } library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract NutzEnabled is Pausable, StorageEnabled { using SafeMath for uint; address public nutzAddr; modifier onlyNutz() { require(msg.sender == nutzAddr); _; } function NutzEnabled(address _nutzAddr, address _storageAddr) StorageEnabled(_storageAddr) { nutzAddr = _nutzAddr; } function totalSupply() constant returns (uint256) { return activeSupply().add(powerPool()).add(burnPool()); } mapping (address => mapping (address => uint)) internal allowed; function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } function approve(address _owner, address _spender, uint256 _amountBabz) public onlyNutz whenNotPaused { require(_owner != _spender); allowed[_owner][_spender] = _amountBabz; } function _transfer(address _from, address _to, uint256 _amountBabz, bytes _data) internal { require(_to != address(this)); require(_to != address(0)); require(_amountBabz > 0); require(_from != _to); _setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz)); _setBabzBalanceOf(_to, babzBalanceOf(_to).add(_amountBabz)); } function transfer(address _from, address _to, uint256 _amountBabz, bytes _data) public onlyNutz whenNotPaused { _transfer(_from, _to, _amountBabz, _data); } function transferFrom(address _sender, address _from, address _to, uint256 _amountBabz, bytes _data) public onlyNutz whenNotPaused { allowed[_from][_sender] = allowed[_from][_sender].sub(_amountBabz); _transfer(_from, _to, _amountBabz, _data); } } contract PullPayment { modifier onlyNutz() { _; } modifier onlyOwner() { _; } modifier whenNotPaused () {_;} function balanceOf(address _owner) constant returns (uint256 value); function paymentOf(address _owner) constant returns (uint256 value, uint256 date) ; function changeDailyLimit(uint _dailyLimit) public ; function changeWithdrawalDate(address _owner, uint256 _newDate) public ; function asyncSend(address _dest) public payable ; function withdraw() public ; function isUnderLimit(uint amount) internal returns (bool); } contract Nutz { function balanceOf(address _owner) constant returns (uint); function totalSupply() constant returns (uint256); function activeSupply() constant returns (uint256); function allowance(address _owner, address _spender) constant returns (uint256); function floor() constant returns (uint256); function ceiling() constant returns (uint256); function powerPool() constant returns (uint256); function _checkDestination(address _from, address _to, uint256 _value, bytes _data) internal; function powerDown(address powerAddr, address _holder, uint256 _amountBabz) public ; function asyncSend(address _pullAddr, address _dest, uint256 _amountWei) public ; function approve(address _spender, uint256 _amountBabz) public; function transfer(address _to, uint256 _amountBabz, bytes _data) public returns (bool); function transfer(address _to, uint256 _amountBabz) public returns (bool); function transData(address _to, uint256 _amountBabz, bytes _data) public returns (bool); function transferFrom(address _from, address _to, uint256 _amountBabz, bytes _data) public returns (bool); function transferFrom(address _from, address _to, uint256 _amountBabz); function () public payable; function purchase(uint256 _price) public payable; function sell(uint256 _price, uint256 _amountBabz); function powerUp(uint256 _amountBabz) public; } contract MarketEnabled is NutzEnabled { uint256 constant INFINITY = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; address public pullAddr; uint256 internal purchasePrice; uint256 internal salePrice; function MarketEnabled(address _pullAddr, address _storageAddr, address _nutzAddr) NutzEnabled(_nutzAddr, _storageAddr) { pullAddr = _pullAddr; } function ceiling() constant returns (uint256) { return purchasePrice; } function floor() constant returns (uint256) { if (nutzAddr.balance == 0) { return INFINITY; } uint256 maxFloor = activeSupply().mul(1000000).div(nutzAddr.balance); return maxFloor >= salePrice ? maxFloor : salePrice; } function moveCeiling(uint256 _newPurchasePrice) public onlyAdmins { require(_newPurchasePrice <= salePrice); purchasePrice = _newPurchasePrice; } function moveFloor(uint256 _newSalePrice) public onlyAdmins { require(_newSalePrice >= purchasePrice); if (_newSalePrice < INFINITY) { require(nutzAddr.balance >= activeSupply().mul(1000000).div(_newSalePrice)); } salePrice = _newSalePrice; } function purchase(address _sender, uint256 _value, uint256 _price) public onlyNutz whenNotPaused returns (uint256) { require(purchasePrice > 0); require(_price == purchasePrice); uint256 amountBabz = purchasePrice.mul(_value).div(1000000); require(amountBabz > 0); uint256 activeSup = activeSupply(); uint256 powPool = powerPool(); if (powPool > 0) { uint256 powerShare = powPool.mul(amountBabz).div(activeSup.add(burnPool())); _setPowerPool(powPool.add(powerShare)); } _setActiveSupply(activeSup.add(amountBabz)); _setBabzBalanceOf(_sender, babzBalanceOf(_sender).add(amountBabz)); return amountBabz; } function sell(address _from, uint256 _price, uint256 _amountBabz) public onlyNutz whenNotPaused { uint256 effectiveFloor = floor(); require(_amountBabz != 0); require(effectiveFloor != INFINITY); require(_price == effectiveFloor); uint256 amountWei = _amountBabz.mul(1000000).div(effectiveFloor); require(amountWei > 0); uint256 powPool = powerPool(); uint256 activeSup = activeSupply(); if (powPool > 0) { uint256 powerShare = powPool.mul(_amountBabz).div(activeSup); _setPowerPool(powPool.sub(powerShare)); } _setActiveSupply(activeSup.sub(_amountBabz)); _setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz)); Nutz(nutzAddr).asyncSend(pullAddr, _from, amountWei); } function allocateEther(uint256 _amountWei, address _beneficiary) public onlyAdmins { require(_amountWei > 0); require(nutzAddr.balance.sub(_amountWei) >= activeSupply().mul(1000000).div(salePrice)); Nutz(nutzAddr).asyncSend(pullAddr, _beneficiary, _amountWei); } } contract Power { function balanceOf(address _holder) constant returns (uint256); function totalSupply() constant returns (uint256); function activeSupply() constant returns (uint256); function slashPower(address _holder, uint256 _value, bytes32 _data) public ; function powerUp(address _holder, uint256 _value) public ; function transfer(address _to, uint256 _amountPower) public returns (bool success); function downtime() public returns (uint256); function downTick(address _owner) public; function downs(address _owner) constant public returns (uint256, uint256, uint256); } contract PowerEnabled is MarketEnabled { address public powerAddr; uint256 public maxPower = 0; uint256 public downtime; modifier onlyPower() { require(msg.sender == powerAddr); _; } function PowerEnabled(address _powerAddr, address _pullAddr, address _storageAddr, address _nutzAddr) MarketEnabled(_pullAddr, _nutzAddr, _storageAddr) { powerAddr = _powerAddr; } function setMaxPower(uint256 _maxPower) public onlyAdmins { require(outstandingPower() <= _maxPower && _maxPower < authorizedPower()); maxPower = _maxPower; } function setDowntime(uint256 _downtime) public onlyAdmins { downtime = _downtime; } function dilutePower(uint256 _amountBabz, uint256 _amountPower) public onlyAdmins { uint256 authorizedPow = authorizedPower(); uint256 totalBabz = totalSupply(); if (authorizedPow == 0) { _setAuthorizedPower((_amountPower > 0) ? _amountPower : _amountBabz.add(totalBabz)); } else { _setAuthorizedPower(authorizedPow.mul(totalBabz.add(_amountBabz)).div(totalBabz)); } _setBurnPool(burnPool().add(_amountBabz)); } function _slashPower(address _holder, uint256 _value, bytes32 _data) internal { uint256 previouslyOutstanding = outstandingPower(); _setOutstandingPower(previouslyOutstanding.sub(_value)); uint256 powPool = powerPool(); uint256 slashingBabz = _value.mul(powPool).div(previouslyOutstanding); _setPowerPool(powPool.sub(slashingBabz)); Power(powerAddr).slashPower(_holder, _value, _data); } function slashPower(address _holder, uint256 _value, bytes32 _data) public onlyAdmins { _setPowerBalanceOf(_holder, powerBalanceOf(_holder).sub(_value)); _slashPower(_holder, _value, _data); } function slashDownRequest(uint256 _pos, address _holder, uint256 _value, bytes32 _data) public onlyAdmins { var (total, left, start) = downs(_holder); left = left.sub(_value); _setDownRequest(_holder, total, left, start); _slashPower(_holder, _value, _data); } function powerUp(address _sender, address _from, uint256 _amountBabz) public onlyNutz whenNotPaused { uint256 authorizedPow = authorizedPower(); require(authorizedPow != 0); require(_amountBabz != 0); uint256 totalBabz = totalSupply(); require(totalBabz != 0); uint256 amountPow = _amountBabz.mul(authorizedPow).div(totalBabz); uint256 outstandingPow = outstandingPower(); require(outstandingPow.add(amountPow) <= maxPower); if (_sender != _from) { allowed[_from][_sender] = allowed[_from][_sender].sub(_amountBabz); } _setOutstandingPower(outstandingPow.add(amountPow)); uint256 powBal = powerBalanceOf(_from).add(amountPow); require(powBal >= authorizedPow.div(10000)); _setPowerBalanceOf(_from, powBal); _setActiveSupply(activeSupply().sub(_amountBabz)); _setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz)); _setPowerPool(powerPool().add(_amountBabz)); Power(powerAddr).powerUp(_from, amountPow); } function powerTotalSupply() constant returns (uint256) { uint256 issuedPower = authorizedPower().div(2); return maxPower >= issuedPower ? maxPower : issuedPower; } function _vestedDown(uint256 _total, uint256 _left, uint256 _start, uint256 _now) internal constant returns (uint256) { if (_now <= _start) { return 0; } uint256 timePassed = _now.sub(_start); if (timePassed > downtime) { timePassed = downtime; } uint256 amountVested = _total.mul(timePassed).div(downtime); uint256 amountFrozen = _total.sub(amountVested); if (_left <= amountFrozen) { return 0; } return _left.sub(amountFrozen); } function createDownRequest(address _owner, uint256 _amountPower) public onlyPower whenNotPaused { require(_amountPower >= authorizedPower().div(10000)); _setPowerBalanceOf(_owner, powerBalanceOf(_owner).sub(_amountPower)); var (, left, ) = downs(_owner); uint256 total = _amountPower.add(left); _setDownRequest(_owner, total, total, now); } function downTick(address _holder, uint256 _now) public onlyPower whenNotPaused { var (total, left, start) = downs(_holder); uint256 amountPow = _vestedDown(total, left, start, _now); uint256 minStep = total.div(10); require(left <= minStep || minStep <= amountPow); uint256 amountBabz = amountPow.mul(totalSupply()).div(authorizedPower()); _setOutstandingPower(outstandingPower().sub(amountPow)); left = left.sub(amountPow); _setPowerPool(powerPool().sub(amountBabz)); _setActiveSupply(activeSupply().add(amountBabz)); _setBabzBalanceOf(_holder, babzBalanceOf(_holder).add(amountBabz)); if (left == 0) { start = 0; total = 0; } _setDownRequest(_holder, total, left, start); Nutz(nutzAddr).powerDown(powerAddr, _holder, amountBabz); } } contract Controller is PowerEnabled { function Controller(address _powerAddr, address _pullAddr, address _nutzAddr, address _storageAddr) PowerEnabled(_powerAddr, _pullAddr, _nutzAddr, _storageAddr) { } function setContracts(address _storageAddr, address _nutzAddr, address _powerAddr, address _pullAddr) public onlyAdmins whenPaused { storageAddr = _storageAddr; nutzAddr = _nutzAddr; powerAddr = _powerAddr; pullAddr = _pullAddr; } function changeDailyLimit(uint256 _dailyLimit) public onlyAdmins { PullPayment(pullAddr).changeDailyLimit(_dailyLimit); } function kill(address _newController) public onlyAdmins whenPaused { if (powerAddr != address(0)) { Ownable(powerAddr).transferOwnership(msg.sender); } if (pullAddr != address(0)) { Ownable(pullAddr).transferOwnership(msg.sender); } if (nutzAddr != address(0)) { Ownable(nutzAddr).transferOwnership(msg.sender); } if (storageAddr != address(0)) { Ownable(storageAddr).transferOwnership(msg.sender); } selfdestruct(_newController); } } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } }
0
pragma solidity ^0.4.16; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { string public name; string public symbol; 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 Burn(address indexed from, uint256 value); function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = tokenName; symbol = tokenSymbol; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } 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; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; emit Burn(_from, _value); return true; } } contract FERToken is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); function FERToken( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value >= balanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } function buy() payable public returns (uint amount){ amount = msg.value / buyPrice; require(balanceOf[this] >= amount); balanceOf[msg.sender] += amount; balanceOf[this] -= amount; emit Transfer(this, msg.sender, amount); return amount; } function sell(uint amount) public returns (uint revenue){ require(balanceOf[msg.sender] >= amount); balanceOf[this] += amount; balanceOf[msg.sender] -= amount; revenue = amount * sellPrice; msg.sender.transfer(revenue); emit Transfer(msg.sender, this, amount); return revenue; } }
1
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Haltable is Ownable { bool public halted; modifier stopInEmergency { if (halted) throw; _; } modifier stopNonOwnersInEmergency { if (halted && msg.sender != owner) throw; _; } modifier onlyInEmergency { if (!halted) throw; _; } function halt() external onlyOwner { halted = true; } function unhalt() external onlyOwner onlyInEmergency { halted = false; } } library SafeMathLib { function times(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function minus(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract FractionalERC20 is ERC20 { uint public decimals; } contract PricingStrategy { function isPricingStrategy() public constant returns (bool) { return true; } function isSane(address crowdsale) public constant returns (bool) { return true; } function isPresalePurchase(address purchaser) public constant returns (bool) { return false; } function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); } contract FinalizeAgent { function isFinalizeAgent() public constant returns(bool) { return true; } function isSane() public constant returns (bool); function finalizeCrowdsale(); } contract CrowdsaleBase is Haltable { uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; using SafeMathLib for uint; FractionalERC20 public token; PricingStrategy public pricingStrategy; FinalizeAgent public finalizeAgent; address public multisigWallet; uint public minimumFundingGoal; uint public startsAt; uint public endsAt; uint public tokensSold = 0; uint public weiRaised = 0; uint public presaleWeiRaised = 0; uint public investorCount = 0; uint public loadedRefund = 0; uint public weiRefunded = 0; bool public finalized; mapping (address => uint256) public investedAmountOf; mapping (address => uint256) public tokenAmountOf; mapping (address => bool) public earlyParticipantWhitelist; uint public ownerTestValue; enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); event Refund(address investor, uint weiAmount); event InvestmentPolicyChanged(bool newRequireCustomerId, bool newRequiredSignedAddress, address newSignerAddress); event Whitelisted(address addr, bool status); event EndsAtChanged(uint newEndsAt); function CrowdsaleBase(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) { owner = msg.sender; token = FractionalERC20(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if(multisigWallet == 0) { throw; } if(_start == 0) { throw; } startsAt = _start; if(_end == 0) { throw; } endsAt = _end; if(startsAt >= endsAt) { throw; } minimumFundingGoal = _minimumFundingGoal; } function() payable { throw; } function investInternal(address receiver, uint128 customerId) stopInEmergency internal returns(uint tokensBought) { if(getState() == State.PreFunding) { if(!earlyParticipantWhitelist[receiver]) { throw; } } else if(getState() == State.Funding) { } else { throw; } uint weiAmount = msg.value; uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised - presaleWeiRaised, tokensSold, msg.sender, token.decimals()); require(tokenAmount != 0); if(investedAmountOf[receiver] == 0) { investorCount++; } investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); if(pricingStrategy.isPresalePurchase(receiver)) { presaleWeiRaised = presaleWeiRaised.plus(weiAmount); } require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); assignTokens(receiver, tokenAmount); if(!multisigWallet.send(weiAmount)) throw; Invested(receiver, weiAmount, tokenAmount, customerId); return tokenAmount; } function finalize() public inState(State.Success) onlyOwner stopInEmergency { if(finalized) { throw; } if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } function setFinalizeAgent(FinalizeAgent addr) onlyOwner { finalizeAgent = addr; if(!finalizeAgent.isFinalizeAgent()) { throw; } } function setEndsAt(uint time) onlyOwner { if(now > time) { throw; } if(startsAt > time) { throw; } endsAt = time; EndsAtChanged(endsAt); } function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner { pricingStrategy = _pricingStrategy; if(!pricingStrategy.isPricingStrategy()) { throw; } } function setMultisig(address addr) public onlyOwner { if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { throw; } multisigWallet = addr; } function loadRefund() public payable inState(State.Failure) { if(msg.value == 0) throw; loadedRefund = loadedRefund.plus(msg.value); } function refund() public inState(State.Refunding) { uint256 weiValue = investedAmountOf[msg.sender]; if (weiValue == 0) throw; investedAmountOf[msg.sender] = 0; weiRefunded = weiRefunded.plus(weiValue); Refund(msg.sender, weiValue); if (!msg.sender.send(weiValue)) throw; } function isMinimumGoalReached() public constant returns (bool reached) { return weiRaised >= minimumFundingGoal; } function isFinalizerSane() public constant returns (bool sane) { return finalizeAgent.isSane(); } function isPricingSane() public constant returns (bool sane) { return pricingStrategy.isSane(address(this)); } function getState() public constant returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane(address(this))) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; else return State.Failure; } function setOwnerTestValue(uint val) onlyOwner { ownerTestValue = val; } function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } function isCrowdsale() public constant returns (bool) { return true; } modifier inState(State state) { if(getState() != state) throw; _; } function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken); function isCrowdsaleFull() public constant returns (bool); function assignTokens(address receiver, uint tokenAmount) internal; } contract AllocatedCrowdsaleMixin is CrowdsaleBase { address public beneficiary; function AllocatedCrowdsaleMixin(address _beneficiary) { beneficiary = _beneficiary; } function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) { if(tokenAmount > getTokensLeft()) { return true; } else { return false; } } function isCrowdsaleFull() public constant returns (bool) { return getTokensLeft() == 0; } function getTokensLeft() public constant returns (uint) { return token.allowance(owner, this); } function assignTokens(address receiver, uint tokenAmount) internal { if(!token.transferFrom(beneficiary, receiver, tokenAmount)) throw; } } library BytesDeserializer { function slice32(bytes b, uint offset) constant returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; } function sliceAddress(bytes b, uint offset) constant returns (address) { bytes32 out; for (uint i = 0; i < 20; i++) { out |= bytes32(b[offset + i] & 0xFF) >> ((i+12) * 8); } return address(uint(out)); } function slice16(bytes b, uint offset) constant returns (bytes16) { bytes16 out; for (uint i = 0; i < 16; i++) { out |= bytes16(b[offset + i] & 0xFF) >> (i * 8); } return out; } function slice4(bytes b, uint offset) constant returns (bytes4) { bytes4 out; for (uint i = 0; i < 4; i++) { out |= bytes4(b[offset + i] & 0xFF) >> (i * 8); } return out; } function slice2(bytes b, uint offset) constant returns (bytes2) { bytes2 out; for (uint i = 0; i < 2; i++) { out |= bytes2(b[offset + i] & 0xFF) >> (i * 8); } return out; } } contract KYCPayloadDeserializer { using BytesDeserializer for bytes; struct KYCPayload { address whitelistedAddress; uint128 customerId; uint32 minETH; uint32 maxETH; uint256 pricingInfo; } function getKYCPayload(bytes dataframe) public constant returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth) { address _whitelistedAddress = dataframe.sliceAddress(0); uint128 _customerId = uint128(dataframe.slice16(20)); uint32 _minETH = uint32(dataframe.slice4(36)); uint32 _maxETH = uint32(dataframe.slice4(40)); return (_whitelistedAddress, _customerId, _minETH, _maxETH); } function getKYCPresalePayload(bytes dataframe) public constant returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth, uint256 pricingInfo) { address _whitelistedAddress = dataframe.sliceAddress(0); uint128 _customerId = uint128(dataframe.slice16(20)); uint32 _minETH = uint32(dataframe.slice4(36)); uint32 _maxETH = uint32(dataframe.slice4(40)); uint256 _pricingInfo = uint256(dataframe.slice32(44)); return (_whitelistedAddress, _customerId, _minETH, _maxETH, _pricingInfo); } } contract KYCCrowdsale is AllocatedCrowdsaleMixin, KYCPayloadDeserializer { address public signerAddress; event SignerChanged(address signer); function KYCCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, address _beneficiary) CrowdsaleBase(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) AllocatedCrowdsaleMixin(_beneficiary) { } function buyWithKYCData(bytes dataframe, uint8 v, bytes32 r, bytes32 s) public payable returns(uint tokenAmount) { uint _tokenAmount; uint multiplier = 10 ** 18; if(earlyParticipantWhitelist[msg.sender]) { _tokenAmount = investInternal(msg.sender, 0x1000); } else { bytes32 hash = sha256(dataframe); var (whitelistedAddress, customerId, minETH, maxETH) = getKYCPayload(dataframe); require(ecrecover(hash, v, r, s) == signerAddress); require(whitelistedAddress == msg.sender); _tokenAmount = investInternal(msg.sender, customerId); } if(!earlyParticipantWhitelist[msg.sender]) { require(investedAmountOf[msg.sender] >= minETH * multiplier / 10000); require(investedAmountOf[msg.sender] <= maxETH * multiplier / 10000); } return _tokenAmount; } function setSignerAddress(address _signerAddress) onlyOwner { signerAddress = _signerAddress; SignerChanged(signerAddress); } }
0
pragma solidity ^0.4.24; library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } 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); } } function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } 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); } } } library SDDatasets { struct Player { address addr; uint256 aff; uint256 laff; uint256 planCount; mapping(uint256=>PalyerPlan) plans; uint256 aff1sum; uint256 aff2sum; uint256 aff3sum; uint256 aff4sum; } struct PalyerPlan { uint256 planId; uint256 startTime; uint256 startBlock; uint256 invested; uint256 atBlock; uint256 payEth; bool isClose; } struct Plan { uint256 interest; uint256 dayRange; uint256 min; uint256 max; } } contract PowerTokens { using SafeMath for *; address public devAddr_ = address(0xe25903C5078D01Bbea64C01DC1107f40f44141a3); address public affiAddr_ = address(0xaF9C025Ce6322A23ac00301C714f4F42895c9818); address public partnerAddr_ = address(0x4ffE17a2A72bC7422CB176bC71c04EE6D87cE329); bool public activated_ = false; uint256 ruleSum_ = 5; modifier isActivated() { require(activated_ == true, "its not active yet."); _; } function version1Invest(address addr, uint256 eth, uint256 _affCode, uint256 _planId) isAdmin() public payable { require(activated_ == false, "Only not active"); require(_planId >= 1 && _planId <= ruleSum_, "_planId error"); uint256 uid = pIDxAddr_[addr]; if (uid == 0) { if (player_[_affCode].addr != address(0x0)) { register_(addr, _affCode); } else { register_(addr, 1000); } uid = G_NowUserId; } uint256 planCount = player_[uid].planCount; player_[uid].plans[planCount].planId = _planId; player_[uid].plans[planCount].startTime = now; player_[uid].plans[planCount].startBlock = block.number; player_[uid].plans[planCount].atBlock = block.number; player_[uid].plans[planCount].invested = eth; player_[uid].plans[planCount].payEth = 0; player_[uid].plans[planCount].isClose = false; player_[uid].planCount = player_[uid].planCount.add(1); G_AllEth = G_AllEth.add(eth); } function activate() isAdmin() public { require(address(devAddr_) != address(0x0), "Must setup devAddr_."); require(address(partnerAddr_) != address(0x0), "Must setup partnerAddr_."); require(address(affiAddr_) != address(0x0), "Must setup affiAddr_."); require(activated_ == false, "Only once"); activated_ = true ; } mapping(address => uint256) private g_users ; function initUsers() private { g_users[msg.sender] = 9 ; uint256 pId = G_NowUserId; pIDxAddr_[msg.sender] = pId; player_[pId].addr = msg.sender; } modifier isAdmin() { uint256 role = g_users[msg.sender]; require((role==9), "Must be admin."); _; } uint256 public G_NowUserId = 1000; uint256 public G_AllEth = 0; uint256 G_DayBlocks = 5900; mapping (address => uint256) public pIDxAddr_; mapping (uint256 => SDDatasets.Player) public player_; mapping (uint256 => SDDatasets.Plan) private plan_; function GetIdByAddr(address addr) public view returns(uint256) { return pIDxAddr_[addr]; } function GetPlayerByUid(uint256 uid) public view returns(uint256,uint256,uint256,uint256,uint256,uint256,uint256) { SDDatasets.Player storage player = player_[uid]; return ( player.aff, player.laff, player.aff1sum, player.aff2sum, player.aff3sum, player.aff4sum, player.planCount ); } function GetPlanByUid(uint256 uid) public view returns(uint256[],uint256[],uint256[],uint256[],uint256[],bool[]) { uint256[] memory planIds = new uint256[] (player_[uid].planCount); uint256[] memory startBlocks = new uint256[] (player_[uid].planCount); uint256[] memory investeds = new uint256[] (player_[uid].planCount); uint256[] memory atBlocks = new uint256[] (player_[uid].planCount); uint256[] memory payEths = new uint256[] (player_[uid].planCount); bool[] memory isCloses = new bool[] (player_[uid].planCount); for(uint i = 0; i < player_[uid].planCount; i++) { planIds[i] = player_[uid].plans[i].planId; startBlocks[i] = player_[uid].plans[i].startBlock; investeds[i] = player_[uid].plans[i].invested; atBlocks[i] = player_[uid].plans[i].atBlock; payEths[i] = player_[uid].plans[i].payEth; isCloses[i] = player_[uid].plans[i].isClose; } return ( planIds, startBlocks, investeds, atBlocks, payEths, isCloses ); } function GetPlanTimeByUid(uint256 uid) public view returns(uint256[]) { uint256[] memory startTimes = new uint256[] (player_[uid].planCount); for(uint i = 0; i < player_[uid].planCount; i++) { startTimes[i] = player_[uid].plans[i].startTime; } return ( startTimes ); } constructor() public { plan_[1] = SDDatasets.Plan(240,60,1e16, 5e20); plan_[2] = SDDatasets.Plan(350,40,1e18, 1e21); plan_[3] = SDDatasets.Plan(470,35,1e19, 1e22); plan_[4] = SDDatasets.Plan(100,0,1e16, 1e22); plan_[5] = SDDatasets.Plan(900,12,1e18, 1e22); initUsers(); } function register_(address addr, uint256 _affCode) private{ G_NowUserId = G_NowUserId.add(1); address _addr = addr; pIDxAddr_[_addr] = G_NowUserId; player_[G_NowUserId].addr = _addr; player_[G_NowUserId].laff = _affCode; player_[G_NowUserId].planCount = 0; uint256 _affID1 = _affCode; uint256 _affID2 = player_[_affID1].laff; uint256 _affID3 = player_[_affID2].laff; uint256 _affID4 = player_[_affID3].laff; player_[_affID1].aff1sum = player_[_affID1].aff1sum.add(1); player_[_affID2].aff2sum = player_[_affID2].aff2sum.add(1); player_[_affID3].aff3sum = player_[_affID3].aff3sum.add(1); player_[_affID4].aff4sum = player_[_affID4].aff4sum.add(1); } function () isActivated() external payable { if (msg.value == 0) { withdraw(); } else { invest(1000, 1); } } function invest(uint256 _affCode, uint256 _planId) isActivated() public payable { require(_planId >= 1 && _planId <= ruleSum_, "_planId error"); uint256 uid = pIDxAddr_[msg.sender]; if (uid == 0) { if (player_[_affCode].addr != address(0x0)) { register_(msg.sender, _affCode); } else { register_(msg.sender, 1000); } uid = G_NowUserId; } require(msg.value >= plan_[_planId].min && msg.value <= plan_[_planId].max, "invest amount error, please set the exact amount"); uint256 planCount = player_[uid].planCount; player_[uid].plans[planCount].planId = _planId; player_[uid].plans[planCount].startTime = now; player_[uid].plans[planCount].startBlock = block.number; player_[uid].plans[planCount].atBlock = block.number; player_[uid].plans[planCount].invested = msg.value; player_[uid].plans[planCount].payEth = 0; player_[uid].plans[planCount].isClose = false; player_[uid].planCount = player_[uid].planCount.add(1); G_AllEth = G_AllEth.add(msg.value); if (msg.value > 1000000000) { distributeRef(msg.value, player_[uid].laff); uint256 devFee = (msg.value.mul(2)).div(100); devAddr_.transfer(devFee); uint256 partnerFee = (msg.value.mul(2)).div(100); partnerAddr_.transfer(partnerFee); } } function withdraw() isActivated() public payable { require(msg.value == 0, "withdraw fee is 0 ether, please set the exact amount"); uint256 uid = pIDxAddr_[msg.sender]; require(uid != 0, "no invest"); for(uint i = 0; i < player_[uid].planCount; i++) { if (player_[uid].plans[i].isClose) { continue; } SDDatasets.Plan plan = plan_[player_[uid].plans[i].planId]; uint256 blockNumber = block.number; bool bClose = false; if (plan.dayRange > 0) { uint256 endBlockNumber = player_[uid].plans[i].startBlock.add(plan.dayRange*G_DayBlocks); if (blockNumber > endBlockNumber){ blockNumber = endBlockNumber; bClose = true; } } uint256 amount = player_[uid].plans[i].invested * plan.interest / 10000 * (blockNumber - player_[uid].plans[i].atBlock) / G_DayBlocks; address sender = msg.sender; sender.send(amount); player_[uid].plans[i].atBlock = block.number; player_[uid].plans[i].isClose = bClose; player_[uid].plans[i].payEth += amount; } } function distributeRef(uint256 _eth, uint256 _affID) private{ uint256 _allaff = (_eth.mul(8)).div(100); uint256 _affID1 = _affID; uint256 _affID2 = player_[_affID1].laff; uint256 _affID3 = player_[_affID2].laff; uint256 _aff = 0; if (_affID1 != 0) { _aff = (_eth.mul(5)).div(100); _allaff = _allaff.sub(_aff); player_[_affID1].aff = _aff.add(player_[_affID1].aff); player_[_affID1].addr.transfer(_aff); } if (_affID2 != 0) { _aff = (_eth.mul(2)).div(100); _allaff = _allaff.sub(_aff); player_[_affID2].aff = _aff.add(player_[_affID2].aff); player_[_affID2].addr.transfer(_aff); } if (_affID3 != 0) { _aff = (_eth.mul(1)).div(100); _allaff = _allaff.sub(_aff); player_[_affID3].aff = _aff.add(player_[_affID3].aff); player_[_affID3].addr.transfer(_aff); } if(_allaff > 0 ){ affiAddr_.transfer(_allaff); } } }
1
pragma solidity ^0.4.23; interface IRegistry { function owner() external view returns (address _addr); function addressOf(bytes32 _name) external view returns (address _addr); } contract UsingRegistry { IRegistry private registry; modifier fromOwner(){ require(msg.sender == getOwner()); _; } constructor(address _registry) public { require(_registry != 0); registry = IRegistry(_registry); } function addressOf(bytes32 _name) internal view returns(address _addr) { return registry.addressOf(_name); } function getOwner() public view returns (address _addr) { return registry.owner(); } function getRegistry() public view returns (IRegistry _addr) { return registry; } } contract UsingAdmin is UsingRegistry { constructor(address _registry) UsingRegistry(_registry) public {} modifier fromAdmin(){ require(msg.sender == getAdmin()); _; } function getAdmin() public constant returns (address _addr) { return addressOf("ADMIN"); } } interface IMonarchyFactory { function lastCreatedGame() external view returns (address _game); function getCollector() external view returns (address _collector); } contract UsingMonarchyFactory is UsingRegistry { constructor(address _registry) UsingRegistry(_registry) public {} modifier fromMonarchyFactory(){ require(msg.sender == address(getMonarchyFactory())); _; } function getMonarchyFactory() public view returns (IMonarchyFactory) { return IMonarchyFactory(addressOf("MONARCHY_FACTORY")); } } interface ITreasury { function issueDividend() external returns (uint _profits); function profitsSendable() external view returns (uint _profits); } contract UsingTreasury is UsingRegistry { constructor(address _registry) UsingRegistry(_registry) public {} modifier fromTreasury(){ require(msg.sender == address(getTreasury())); _; } function getTreasury() public view returns (ITreasury) { return ITreasury(addressOf("TREASURY")); } } contract HasDailyLimit { struct DailyLimitVars { uint112 dailyLimit; uint112 usedToday; uint32 lastDay; } DailyLimitVars private vars; uint constant MAX_ALLOWED = 2**112 - 1; constructor(uint _limit) public { _setDailyLimit(_limit); } function _setDailyLimit(uint _limit) internal { require(_limit <= MAX_ALLOWED); vars.dailyLimit = uint112(_limit); } function _useFromDailyLimit(uint _amount) internal { uint _remaining = updateAndGetRemaining(); require(_amount <= _remaining); vars.usedToday += uint112(_amount); } function updateAndGetRemaining() private returns (uint _amtRemaining) { if (today() > vars.lastDay) { vars.usedToday = 0; vars.lastDay = today(); } uint112 _usedToday = vars.usedToday; uint112 _dailyLimit = vars.dailyLimit; return uint(_usedToday >= _dailyLimit ? 0 : _dailyLimit - _usedToday); } function today() private view returns (uint32) { return uint32(block.timestamp / 1 days); } function getDailyLimit() public view returns (uint) { return uint(vars.dailyLimit); } function getDailyLimitUsed() public view returns (uint) { return uint(today() > vars.lastDay ? 0 : vars.usedToday); } function getDailyLimitRemaining() public view returns (uint) { uint _used = getDailyLimitUsed(); return uint(_used >= vars.dailyLimit ? 0 : vars.dailyLimit - _used); } } contract Ledger { uint public total; struct Entry { uint balance; address next; address prev; } mapping (address => Entry) public entries; address public owner; modifier fromOwner() { require(msg.sender==owner); _; } constructor(address _owner) public { owner = _owner; } function add(address _address, uint _amt) fromOwner public { if (_address == address(0) || _amt == 0) return; Entry storage entry = entries[_address]; if (entry.balance == 0) { entry.next = entries[0x0].next; entries[entries[0x0].next].prev = _address; entries[0x0].next = _address; } total += _amt; entry.balance += _amt; } function subtract(address _address, uint _amt) fromOwner public returns (uint _amtRemoved) { if (_address == address(0) || _amt == 0) return; Entry storage entry = entries[_address]; uint _maxAmt = entry.balance; if (_maxAmt == 0) return; if (_amt >= _maxAmt) { total -= _maxAmt; entries[entry.prev].next = entry.next; entries[entry.next].prev = entry.prev; delete entries[_address]; return _maxAmt; } else { total -= _amt; entry.balance -= _amt; return _amt; } } function size() public view returns (uint _size) { Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _curEntry = entries[_curEntry.next]; _size++; } return _size; } function balanceOf(address _address) public view returns (uint _balance) { return entries[_address].balance; } function balances() public view returns (address[] _addresses, uint[] _balances) { uint _size = size(); _addresses = new address[](_size); _balances = new uint[](_size); uint _i = 0; Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _addresses[_i] = _curEntry.next; _balances[_i] = entries[_curEntry.next].balance; _curEntry = entries[_curEntry.next]; _i++; } return (_addresses, _balances); } } contract AddressSet { struct Entry { bool exists; address next; address prev; } mapping (address => Entry) public entries; address public owner; modifier fromOwner() { require(msg.sender==owner); _; } constructor(address _owner) public { owner = _owner; } function add(address _address) fromOwner public returns (bool _didCreate) { if (_address == address(0)) return; Entry storage entry = entries[_address]; if (entry.exists) return; else entry.exists = true; Entry storage HEAD = entries[0x0]; entry.next = HEAD.next; entries[HEAD.next].prev = _address; HEAD.next = _address; return true; } function remove(address _address) fromOwner public returns (bool _didExist) { if (_address == address(0)) return; Entry storage entry = entries[_address]; if (!entry.exists) return; entries[entry.prev].next = entry.next; entries[entry.next].prev = entry.prev; delete entries[_address]; return true; } function size() public view returns (uint _size) { Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _curEntry = entries[_curEntry.next]; _size++; } return _size; } function has(address _address) public view returns (bool _exists) { return entries[_address].exists; } function addresses() public view returns (address[] _addresses) { uint _size = size(); _addresses = new address[](_size); uint _i = 0; Entry memory _curEntry = entries[0x0]; while (_curEntry.next > 0) { _addresses[_i] = _curEntry.next; _curEntry = entries[_curEntry.next]; _i++; } return _addresses; } } contract Bankrollable is UsingTreasury { uint public profitsSent; Ledger public ledger; uint public bankroll; AddressSet public whitelist; modifier fromWhitelistOwner(){ require(msg.sender == getWhitelistOwner()); _; } event BankrollAdded(uint time, address indexed bankroller, uint amount, uint bankroll); event BankrollRemoved(uint time, address indexed bankroller, uint amount, uint bankroll); event ProfitsSent(uint time, address indexed treasury, uint amount); event AddedToWhitelist(uint time, address indexed addr, address indexed wlOwner); event RemovedFromWhitelist(uint time, address indexed addr, address indexed wlOwner); constructor(address _registry) UsingTreasury(_registry) public { ledger = new Ledger(this); whitelist = new AddressSet(this); } function addToWhitelist(address _addr) fromWhitelistOwner public { bool _didAdd = whitelist.add(_addr); if (_didAdd) emit AddedToWhitelist(now, _addr, msg.sender); } function removeFromWhitelist(address _addr) fromWhitelistOwner public { bool _didRemove = whitelist.remove(_addr); if (_didRemove) emit RemovedFromWhitelist(now, _addr, msg.sender); } function () public payable {} function addBankroll() public payable { require(whitelist.size()==0 || whitelist.has(msg.sender)); ledger.add(msg.sender, msg.value); bankroll = ledger.total(); emit BankrollAdded(now, msg.sender, msg.value, bankroll); } function removeBankroll(uint _amount, string _callbackFn) public returns (uint _recalled) { address _bankroller = msg.sender; uint _collateral = getCollateral(); uint _balance = address(this).balance; uint _available = _balance > _collateral ? _balance - _collateral : 0; if (_amount > _available) _amount = _available; _amount = ledger.subtract(_bankroller, _amount); bankroll = ledger.total(); if (_amount == 0) return; bytes4 _sig = bytes4(keccak256(_callbackFn)); require(_bankroller.call.value(_amount)(_sig)); emit BankrollRemoved(now, _bankroller, _amount, bankroll); return _amount; } function sendProfits() public returns (uint _profits) { int _p = profits(); if (_p <= 0) return; _profits = uint(_p); profitsSent += _profits; address _tr = getTreasury(); require(_tr.call.value(_profits)()); emit ProfitsSent(now, _tr, _profits); } function getCollateral() public view returns (uint _amount); function getWhitelistOwner() public view returns (address _addr); function profits() public view returns (int _profits) { int _balance = int(address(this).balance); int _threshold = int(bankroll + getCollateral()); return _balance - _threshold; } function profitsTotal() public view returns (int _profits) { return int(profitsSent) + profits(); } function bankrollAvailable() public view returns (uint _amount) { uint _balance = address(this).balance; uint _bankroll = bankroll; uint _collat = getCollateral(); if (_balance <= _collat) return 0; else if (_balance < _collat + _bankroll) return _balance - _collat; else return _bankroll; } function bankrolledBy(address _addr) public view returns (uint _amount) { return ledger.balanceOf(_addr); } function bankrollerTable() public view returns (address[], uint[]) { return ledger.balances(); } } interface IMonarchyGame { function sendPrize(uint _gasLimit) external returns (bool _success, uint _prizeSent); function sendFees() external returns (uint _feesSent); function prize() external view returns(uint); function numOverthrows() external view returns(uint); function fees() external view returns (uint _fees); function monarch() external view returns (address _addr); function isEnded() external view returns (bool _bool); function isPaid() external view returns (bool _bool); } contract MonarchyController is HasDailyLimit, Bankrollable, UsingAdmin, UsingMonarchyFactory { uint constant public version = 1; uint public totalFees; uint public totalPrizes; uint public totalOverthrows; IMonarchyGame[] public endedGames; uint public numDefinedGames; mapping (uint => DefinedGame) public definedGames; struct DefinedGame { IMonarchyGame game; bool isEnabled; string summary; uint initialPrize; uint fee; int prizeIncr; uint reignBlocks; uint initialBlocks; } event Created(uint time); event DailyLimitChanged(uint time, address indexed owner, uint newValue); event Error(uint time, string msg); event DefinedGameEdited(uint time, uint index); event DefinedGameEnabled(uint time, uint index, bool isEnabled); event DefinedGameFailedCreation(uint time, uint index); event GameStarted(uint time, uint indexed index, address indexed addr, uint initialPrize); event GameEnded(uint time, uint indexed index, address indexed addr, address indexed winner); event FeesCollected(uint time, uint amount); constructor(address _registry) HasDailyLimit(10 ether) Bankrollable(_registry) UsingAdmin(_registry) UsingMonarchyFactory(_registry) public { emit Created(now); } function setDailyLimit(uint _amount) public fromOwner { _setDailyLimit(_amount); emit DailyLimitChanged(now, msg.sender, _amount); } function editDefinedGame( uint _index, string _summary, uint _initialPrize, uint _fee, int _prizeIncr, uint _reignBlocks, uint _initialBlocks ) public fromAdmin returns (bool _success) { if (_index-1 > numDefinedGames || _index > 20) { emit Error(now, "Index out of bounds."); return; } if (_index-1 == numDefinedGames) numDefinedGames++; definedGames[_index].summary = _summary; definedGames[_index].initialPrize = _initialPrize; definedGames[_index].fee = _fee; definedGames[_index].prizeIncr = _prizeIncr; definedGames[_index].reignBlocks = _reignBlocks; definedGames[_index].initialBlocks = _initialBlocks; emit DefinedGameEdited(now, _index); return true; } function enableDefinedGame(uint _index, bool _bool) public fromAdmin returns (bool _success) { if (_index-1 >= numDefinedGames) { emit Error(now, "Index out of bounds."); return; } definedGames[_index].isEnabled = _bool; emit DefinedGameEnabled(now, _index, _bool); return true; } function () public payable { totalFees += msg.value; } function startDefinedGame(uint _index) public returns (address _game) { DefinedGame memory dGame = definedGames[_index]; if (_index-1 >= numDefinedGames) { _error("Index out of bounds."); return; } if (dGame.isEnabled == false) { _error("DefinedGame is not enabled."); return; } if (dGame.game != IMonarchyGame(0)) { _error("Game is already started."); return; } if (address(this).balance < dGame.initialPrize) { _error("Not enough funds to start this game."); return; } if (getDailyLimitRemaining() < dGame.initialPrize) { _error("Starting game would exceed daily limit."); return; } IMonarchyFactory _mf = getMonarchyFactory(); if (_mf.getCollector() != address(this)){ _error("MonarchyFactory.getCollector() points to a different contract."); return; } bool _success = address(_mf).call.value(dGame.initialPrize)( bytes4(keccak256("createGame(uint256,uint256,int256,uint256,uint256)")), dGame.initialPrize, dGame.fee, dGame.prizeIncr, dGame.reignBlocks, dGame.initialBlocks ); if (!_success) { emit DefinedGameFailedCreation(now, _index); _error("MonarchyFactory could not create game (invalid params?)"); return; } _useFromDailyLimit(dGame.initialPrize); _game = _mf.lastCreatedGame(); definedGames[_index].game = IMonarchyGame(_game); emit GameStarted(now, _index, _game, dGame.initialPrize); return _game; } function _error(string _msg) private { emit Error(now, _msg); } function startDefinedGameManually(uint _index) public payable returns (address _game) { DefinedGame memory dGame = definedGames[_index]; if (msg.value != dGame.initialPrize) { _error("Value sent does not match initialPrize."); require(msg.sender.call.value(msg.value)()); return; } _game = startDefinedGame(_index); if (_game == address(0)) { require(msg.sender.call.value(msg.value)()); } } function refreshGames() public returns (uint _numGamesEnded, uint _feesCollected) { for (uint _i = 1; _i <= numDefinedGames; _i++) { IMonarchyGame _game = definedGames[_i].game; if (_game == IMonarchyGame(0)) continue; uint _fees = _game.sendFees(); _feesCollected += _fees; if (_game.isEnded()) { if (!_game.isPaid()) _game.sendPrize(2300); totalPrizes += _game.prize(); totalOverthrows += _game.numOverthrows(); definedGames[_i].game = IMonarchyGame(0); endedGames.push(_game); _numGamesEnded++; emit GameEnded(now, _i, address(_game), _game.monarch()); } } if (_feesCollected > 0) emit FeesCollected(now, _feesCollected); return (_numGamesEnded, _feesCollected); } function getCollateral() public view returns (uint) { return 0; } function getWhitelistOwner() public view returns (address){ return getAdmin(); } function numEndedGames() public view returns (uint) { return endedGames.length; } function numActiveGames() public view returns (uint _count) { for (uint _i = 1; _i <= numDefinedGames; _i++) { if (definedGames[_i].game != IMonarchyGame(0)) _count++; } } function getNumEndableGames() public view returns (uint _count) { for (uint _i = 1; _i <= numDefinedGames; _i++) { IMonarchyGame _game = definedGames[_i].game; if (_game == IMonarchyGame(0)) continue; if (_game.isEnded()) _count++; } return _count; } function getFirstStartableIndex() public view returns (uint _index) { for (uint _i = 1; _i <= numDefinedGames; _i++) { if (getIsStartable(_i)) return _i; } } function getAvailableFees() public view returns (uint _feesAvailable) { for (uint _i = 1; _i <= numDefinedGames; _i++) { if (definedGames[_i].game == IMonarchyGame(0)) continue; _feesAvailable += definedGames[_i].game.fees(); } return _feesAvailable; } function recentlyEndedGames(uint _num) public view returns (address[] _addresses) { uint _len = endedGames.length; if (_num > _len) _num = _len; _addresses = new address[](_num); uint _i = 1; while (_i <= _num) { _addresses[_i - 1] = endedGames[_len - _i]; _i++; } } function getGame(uint _index) public view returns (address) { return address(definedGames[_index].game); } function getIsEnabled(uint _index) public view returns (bool) { return definedGames[_index].isEnabled; } function getInitialPrize(uint _index) public view returns (uint) { return definedGames[_index].initialPrize; } function getIsStartable(uint _index) public view returns (bool _isStartable) { DefinedGame memory dGame = definedGames[_index]; if (_index >= numDefinedGames) return; if (dGame.isEnabled == false) return; if (dGame.game != IMonarchyGame(0)) return; if (dGame.initialPrize > address(this).balance) return; if (dGame.initialPrize > getDailyLimitRemaining()) return; return true; } }
0
pragma solidity ^0.4.8; contract Token { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { uint256 constant MAX_UINT256 = 2**256 - 1; function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract BAOToken is StandardToken { function BAOToken() public { balances[msg.sender] = initialAmount; totalSupply = initialAmount; } function() public { } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } string public name = "BAO"; uint8 public decimals = 18; string public symbol = "BAO"; string public version = "v1.1"; uint256 public initialAmount = 800 * (10 ** 8) * (10 ** 18); }
1
pragma solidity ^0.4.19; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} } contract WhiteList { function checkMemberLevel (address addr) view public returns (uint) {} } contract PresalePool { using SafeMath for uint; uint8 public contractStage = 1; address public owner; uint[] public contributionCaps; uint public feePct; address public receiverAddress; uint constant public contributionMin = 100000000000000000; uint constant public maxGasPrice = 50000000000; WhiteList constant public whitelistContract = WhiteList(0x8D95B038cA80A986425FA240C3C17Fb2B6e9bc63); uint public nextCapTime; uint [] public nextContributionCaps; uint public addressChangeBlock; uint public finalBalance; uint[] public ethRefundAmount; address public activeToken; struct Contributor { bool authorized; uint ethRefund; uint balance; uint cap; mapping (address => uint) tokensClaimed; } mapping (address => Contributor) whitelist; struct TokenAllocation { ERC20 token; uint[] pct; uint balanceRemaining; } mapping (address => TokenAllocation) distributionMap; modifier onlyOwner () { require (msg.sender == owner); _; } bool locked; modifier noReentrancy() { require(!locked); locked = true; _; locked = false; } event ContributorBalanceChanged (address contributor, uint totalBalance); event ReceiverAddressSet ( address _addr); event PoolSubmitted (address receiver, uint amount); event WithdrawalsOpen (address tokenAddr); event TokensWithdrawn (address receiver, uint amount); event EthRefundReceived (address sender, uint amount); event EthRefunded (address receiver, uint amount); event ERC223Received (address token, uint value); function _toPct (uint numerator, uint denominator ) internal pure returns (uint) { return numerator.mul(10 ** 20) / denominator; } function _applyPct (uint numerator, uint pct) internal pure returns (uint) { return numerator.mul(pct) / (10 ** 20); } function PresalePool(address receiverAddr, uint[] capAmounts, uint fee) public { require (fee < 100); require (capAmounts.length>1 && capAmounts.length<256); for (uint8 i=1; i<capAmounts.length; i++) { require (capAmounts[i] <= capAmounts[0]); } owner = msg.sender; receiverAddress = receiverAddr; contributionCaps = capAmounts; feePct = _toPct(fee,100); whitelist[msg.sender].authorized = true; } function () payable public { if (contractStage == 1) { _ethDeposit(); } else if (contractStage == 3) { _ethRefund(); } else revert(); } function _ethDeposit () internal { assert (contractStage == 1); require (tx.gasprice <= maxGasPrice); require (this.balance <= contributionCaps[0]); var c = whitelist[msg.sender]; uint newBalance = c.balance.add(msg.value); require (newBalance >= contributionMin); require (newBalance <= _checkCap(msg.sender)); c.balance = newBalance; ContributorBalanceChanged(msg.sender, newBalance); } function _ethRefund () internal { assert (contractStage == 3); require (msg.sender == owner || msg.sender == receiverAddress); require (msg.value >= contributionMin); ethRefundAmount.push(msg.value); EthRefundReceived(msg.sender, msg.value); } function withdraw (address tokenAddr) public { var c = whitelist[msg.sender]; require (c.balance > 0); if (contractStage < 3) { uint amountToTransfer = c.balance; c.balance = 0; msg.sender.transfer(amountToTransfer); ContributorBalanceChanged(msg.sender, 0); } else { _withdraw(msg.sender,tokenAddr); } } function withdrawFor (address contributor, address tokenAddr) public onlyOwner { require (contractStage == 3); require (whitelist[contributor].balance > 0); _withdraw(contributor,tokenAddr); } function _withdraw (address receiver, address tokenAddr) internal { assert (contractStage == 3); var c = whitelist[receiver]; if (tokenAddr == 0x00) { tokenAddr = activeToken; } var d = distributionMap[tokenAddr]; require ( (ethRefundAmount.length > c.ethRefund) || d.pct.length > c.tokensClaimed[tokenAddr] ); if (ethRefundAmount.length > c.ethRefund) { uint pct = _toPct(c.balance,finalBalance); uint ethAmount = 0; for (uint i=c.ethRefund; i<ethRefundAmount.length; i++) { ethAmount = ethAmount.add(_applyPct(ethRefundAmount[i],pct)); } c.ethRefund = ethRefundAmount.length; if (ethAmount > 0) { receiver.transfer(ethAmount); EthRefunded(receiver,ethAmount); } } if (d.pct.length > c.tokensClaimed[tokenAddr]) { uint tokenAmount = 0; for (i=c.tokensClaimed[tokenAddr]; i<d.pct.length; i++) { tokenAmount = tokenAmount.add(_applyPct(c.balance,d.pct[i])); } c.tokensClaimed[tokenAddr] = d.pct.length; if (tokenAmount > 0) { require(d.token.transfer(receiver,tokenAmount)); d.balanceRemaining = d.balanceRemaining.sub(tokenAmount); TokensWithdrawn(receiver,tokenAmount); } } } function authorize (address addr, uint cap) public onlyOwner { require (contractStage == 1); _checkWhitelistContract(addr); require (!whitelist[addr].authorized); require ((cap > 0 && cap < contributionCaps.length) || (cap >= contributionMin && cap <= contributionCaps[0]) ); uint size; assembly { size := extcodesize(addr) } require (size == 0); whitelist[addr].cap = cap; whitelist[addr].authorized = true; } function authorizeMany (address[] addr, uint cap) public onlyOwner { require (addr.length < 255); require (cap > 0 && cap < contributionCaps.length); for (uint8 i=0; i<addr.length; i++) { authorize(addr[i], cap); } } function revoke (address addr) public onlyOwner { require (contractStage < 3); require (whitelist[addr].authorized); require (whitelistContract.checkMemberLevel(addr) == 0); whitelist[addr].authorized = false; if (whitelist[addr].balance > 0) { uint amountToTransfer = whitelist[addr].balance; whitelist[addr].balance = 0; addr.transfer(amountToTransfer); ContributorBalanceChanged(addr, 0); } } function modifyIndividualCap (address addr, uint cap) public onlyOwner { require (contractStage < 3); require (cap < contributionCaps.length || (cap >= contributionMin && cap <= contributionCaps[0]) ); _checkWhitelistContract(addr); var c = whitelist[addr]; require (c.authorized); uint amount = c.balance; c.cap = cap; uint capAmount = _checkCap(addr); if (amount > capAmount) { c.balance = capAmount; addr.transfer(amount.sub(capAmount)); ContributorBalanceChanged(addr, capAmount); } } function modifyLevelCap (uint level, uint cap) public onlyOwner { require (contractStage < 3); require (level > 0 && level < contributionCaps.length); require (this.balance <= cap && contributionCaps[0] >= cap); contributionCaps[level] = cap; nextCapTime = 0; } function modifyAllLevelCaps (uint[] cap, uint time) public onlyOwner { require (contractStage < 3); require (cap.length == contributionCaps.length-1); require (time == 0 || time>block.timestamp); if (time == 0) { for (uint8 i = 0; i < cap.length; i++) { modifyLevelCap(i+1, cap[i]); } } else { nextContributionCaps = contributionCaps; nextCapTime = time; for (i = 0; i < cap.length; i++) { require (contributionCaps[i+1] <= cap[i] && contributionCaps[0] >= cap[i]); nextContributionCaps[i+1] = cap[i]; } } } function modifyMaxContractBalance (uint amount) public onlyOwner { require (contractStage < 3); require (amount >= contributionMin); require (amount >= this.balance); contributionCaps[0] = amount; nextCapTime = 0; for (uint8 i=1; i<contributionCaps.length; i++) { if (contributionCaps[i]>amount) contributionCaps[i]=amount; } } function _checkCap (address addr) internal returns (uint) { _checkWhitelistContract(addr); var c = whitelist[addr]; if (!c.authorized) return 0; if (nextCapTime>0 && block.timestamp>nextCapTime) { contributionCaps = nextContributionCaps; nextCapTime = 0; } if (c.cap<contributionCaps.length) return contributionCaps[c.cap]; return c.cap; } function _checkWhitelistContract (address addr) internal { var c = whitelist[addr]; if (!c.authorized) { var level = whitelistContract.checkMemberLevel(addr); if (level == 0 || level >= contributionCaps.length) return; c.cap = level; c.authorized = true; } } function checkPoolBalance () view public returns (uint poolCap, uint balance, uint remaining) { if (contractStage == 1) { remaining = contributionCaps[0].sub(this.balance); } else { remaining = 0; } return (contributionCaps[0],this.balance,remaining); } function checkContributorBalance (address addr) view public returns (uint balance, uint cap, uint remaining) { var c = whitelist[addr]; if (!c.authorized) { cap = whitelistContract.checkMemberLevel(addr); if (cap == 0) return (0,0,0); } else { cap = c.cap; } balance = c.balance; if (contractStage == 1) { if (cap<contributionCaps.length) { if (nextCapTime == 0 || nextCapTime > block.timestamp) { cap = contributionCaps[cap]; } else { cap = nextContributionCaps[cap]; } } remaining = cap.sub(balance); if (contributionCaps[0].sub(this.balance) < remaining) remaining = contributionCaps[0].sub(this.balance); } else { remaining = 0; } return (balance, cap, remaining); } function checkAvailableTokens (address addr, address tokenAddr) view public returns (uint tokenAmount) { var c = whitelist[addr]; var d = distributionMap[tokenAddr]; for (uint i = c.tokensClaimed[tokenAddr]; i < d.pct.length; i++) { tokenAmount = tokenAmount.add(_applyPct(c.balance, d.pct[i])); } return tokenAmount; } function closeContributions () public onlyOwner { require (contractStage == 1); contractStage = 2; } function reopenContributions () public onlyOwner { require (contractStage == 2); contractStage = 1; } function setReceiverAddress (address addr) public onlyOwner { require (addr != 0x00 && receiverAddress == 0x00); require (contractStage < 3); receiverAddress = addr; addressChangeBlock = block.number; ReceiverAddressSet(addr); } function submitPool (uint amountInWei) public onlyOwner noReentrancy { require (contractStage < 3); require (receiverAddress != 0x00); require (block.number >= addressChangeBlock.add(6000)); require (contributionMin <= amountInWei && amountInWei <= this.balance); finalBalance = this.balance; require (receiverAddress.call.value(amountInWei).gas(msg.gas.sub(5000))()); ethRefundAmount.push(this.balance); contractStage = 3; PoolSubmitted(receiverAddress, amountInWei); } function enableTokenWithdrawals (address tokenAddr, bool notDefault) public onlyOwner noReentrancy { require (contractStage == 3); if (notDefault) { require (activeToken != 0x00); } else { activeToken = tokenAddr; } var d = distributionMap[tokenAddr]; if (d.pct.length==0) d.token = ERC20(tokenAddr); uint amount = d.token.balanceOf(this).sub(d.balanceRemaining); require (amount > 0); if (feePct > 0) { require (d.token.transfer(owner,_applyPct(amount,feePct))); } amount = d.token.balanceOf(this).sub(d.balanceRemaining); d.balanceRemaining = d.token.balanceOf(this); d.pct.push(_toPct(amount,finalBalance)); } function tokenFallback (address from, uint value, bytes data) public { ERC223Received (from, value); } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 27907200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xbC4B5CC0AA32b8B30eD6Ec78cBe88c63fB3963c8; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 30412800; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xF2C7722774D5FbF0A630Fbd12cF3C78b70441e84; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintBurnableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } } contract DLH is MintBurnableToken { string public constant name = "Depositor-investor L&H"; string public constant symbol = "DLH"; uint8 public constant decimals = 18; } contract ReentrancyGuard { bool private rentrancy_lock = false; modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } } contract Stateful { enum State { Private, PreSale, sellIsOver } State public state = State.Private; event StateChanged(State oldState, State newState); function setState(State newState) internal { State oldState = state; state = newState; StateChanged(oldState, newState); } } contract PreICO is ReentrancyGuard, Ownable, Stateful { using SafeMath for uint256; DLH public token; address public wallet; uint256 public startPreICOTime; uint256 public endPreICOTime; uint256 public rate; uint256 public priceUSD; uint256 public centRaised; uint256 public minimumInvest; uint256 public softCapPreSale; uint256 public hardCapPreSale; uint256 public hardCapPrivate; address public oracle; address public manager; mapping(address => uint) public balances; mapping(address => uint) public balancesInCent; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function PreICO( address _wallet, address _token, uint256 _priceUSD, uint256 _minimumInvest) public { require(_priceUSD != 0); require(_wallet != address(0)); require(_token != address(0)); priceUSD = _priceUSD; rate = 250000000000000000; wallet = _wallet; token = DLH(_token); hardCapPrivate = 40000000; minimumInvest = _minimumInvest; } modifier saleIsOn() { bool withinPeriod = now >= startPreICOTime && now <= endPreICOTime; require(withinPeriod && state == State.PreSale || state == State.Private); _; } modifier isUnderHardCap() { bool underHardCap; if (state == State.Private){ underHardCap = centRaised < hardCapPrivate; } else { underHardCap = centRaised < hardCapPreSale; } require(underHardCap); _; } modifier onlyOracle(){ require(msg.sender == oracle); _; } modifier onlyOwnerOrManager(){ require(msg.sender == manager || msg.sender == owner); _; } function hasEnded() public view returns (bool) { return now > endPreICOTime; } function getTokenAmount(uint256 centValue) internal view returns(uint256) { return centValue.mul(rate); } function forwardFunds(uint256 value) internal { wallet.transfer(value); } function startPreSale(uint256 _softCapPreSale, uint256 _hardCapPreSale, uint256 period, uint256 _start) public onlyOwner { startPreICOTime = _start; endPreICOTime = startPreICOTime.add(period * 1 days); softCapPreSale = _softCapPreSale; hardCapPreSale = _hardCapPreSale; setState(State.PreSale); } function finishPreSale() public onlyOwner { require(centRaised > softCapPreSale); setState(State.sellIsOver); token.transferOwnership(owner); forwardFunds(this.balance); } function setOracle(address _oracle) public onlyOwner { require(_oracle != address(0)); oracle = _oracle; } function setManager(address _manager) public onlyOwner { require(_manager != address(0)); manager = _manager; } function changePriceUSD(uint256 _priceUSD) public onlyOracle { require(_priceUSD != 0); priceUSD = _priceUSD; } modifier refundAllowed() { require(state != State.Private && centRaised < softCapPreSale && now > endPreICOTime); _; } function refund() public refundAllowed nonReentrant { uint valueToReturn = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(valueToReturn); } function manualTransfer(address _to, uint _valueUSD) public saleIsOn isUnderHardCap onlyOwnerOrManager { uint256 centValue = _valueUSD.mul(100); uint256 tokensAmount = getTokenAmount(centValue); centRaised = centRaised.add(centValue); token.mint(_to, tokensAmount); balancesInCent[_to] = balancesInCent[_to].add(centValue); } function buyTokens(address beneficiary) saleIsOn isUnderHardCap nonReentrant public payable { require(beneficiary != address(0) && msg.value.div(priceUSD) >= minimumInvest); uint256 weiAmount = msg.value; uint256 centValue = weiAmount.div(priceUSD); uint256 tokens = getTokenAmount(centValue); centRaised = centRaised.add(centValue); token.mint(beneficiary, tokens); balances[msg.sender] = balances[msg.sender].add(weiAmount); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); if (centRaised > softCapPreSale || state == State.Private) { forwardFunds(weiAmount); } } function () external payable { buyTokens(msg.sender); } }
0
pragma solidity ^0.4.15; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract StandardToken is ERC20 { using SafeMath for uint; event Minted(address receiver, uint amount); mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; function isToken() public constant returns (bool weAre) { return true; } function transfer(address _to, uint _value) returns (bool success) { balances[msg.sender] = balances[msg.sender].sub( _value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { uint _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract UpgradeableToken is StandardToken { using SafeMath for uint256; address public upgradeMaster; UpgradeAgent public upgradeAgent; uint256 public totalUpgraded; enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} event Upgrade(address indexed _from, address indexed _to, uint256 _value); event UpgradeAgentSet(address agent); function UpgradeableToken(address _upgradeMaster) { upgradeMaster = _upgradeMaster; } function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); if (!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { revert(); } if (value == 0) revert(); balances[msg.sender] = balances[msg.sender].sub(value); totalSupply = totalSupply.sub(value); totalUpgraded = totalUpgraded.add(value); upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } function setUpgradeAgent(address agent) external { if(!canUpgrade()) { revert(); } if (agent == 0x0) revert(); if (msg.sender != upgradeMaster) revert(); if (getUpgradeState() == UpgradeState.Upgrading) revert(); upgradeAgent = UpgradeAgent(agent); if(!upgradeAgent.isUpgradeAgent()) revert(); if (upgradeAgent.originalSupply() != totalSupply) revert(); UpgradeAgentSet(upgradeAgent); } function getUpgradeState() public constant returns(UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } function setUpgradeMaster(address master) public { if (master == 0x0) revert(); if (msg.sender != upgradeMaster) revert(); upgradeMaster = master; } function canUpgrade() public constant returns(bool) { return true; } } contract UpgradeAgent { uint public originalSupply; function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } contract ReleasableToken is ERC20, Ownable { address public releaseAgent; bool public released = false; mapping (address => bool) public transferAgents; modifier canTransfer(address _sender) { if(!released) { if(!transferAgents[_sender]) { revert(); } } _; } function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { releaseAgent = addr; } function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } function releaseTokenTransfer() public onlyReleaseAgent { released = true; } modifier inReleaseState(bool releaseState) { if(releaseState != released) { revert(); } _; } modifier onlyReleaseAgent() { if(msg.sender != releaseAgent) { revert(); } _; } function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { return super.transferFrom(_from, _to, _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint _value) whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract CentrallyIssuedToken is UpgradeableToken, ReleasableToken, PausableToken { string public name; string public symbol; uint public decimals; function CentrallyIssuedToken(address _owner, string _name, string _symbol, uint _totalSupply, uint _decimals) UpgradeableToken(_owner) { name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; balances[_owner] = _totalSupply; } }
1
pragma solidity ^0.4.16; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { string public name; string public symbol; 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); event Burn(address indexed from, uint256 value); function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = tokenName; symbol = tokenSymbol; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } 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; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; emit Burn(_from, _value); return true; } } contract RodCoin is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); function RodCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value >= balanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); } function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } function buy() payable public { uint amount = msg.value / buyPrice; _transfer(this, msg.sender, amount); } function sell(uint256 amount) public { address myAddress = this; require(myAddress.balance >= amount * sellPrice); _transfer(msg.sender, this, amount); msg.sender.transfer(amount * sellPrice); } }
1
pragma solidity 0.4.25; library LinkedListLib { uint256 constant NULL = 0; uint256 constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct LinkedList{ mapping (uint256 => mapping (bool => uint256)) list; } function listExists(LinkedList storage self) public view returns (bool) { if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) { return true; } else { return false; } } function nodeExists(LinkedList storage self, uint256 _node) public view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } function sizeOf(LinkedList storage self) public view returns (uint256 numElements) { bool exists; uint256 i; (exists,i) = getAdjacent(self, HEAD, NEXT); while (i != HEAD) { (exists,i) = getAdjacent(self, i, NEXT); numElements++; } return; } function getNode(LinkedList storage self, uint256 _node) public view returns (bool,uint256,uint256) { if (!nodeExists(self,_node)) { return (false,0,0); } else { return (true,self.list[_node][PREV], self.list[_node][NEXT]); } } function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) public view returns (bool,uint256) { if (!nodeExists(self,_node)) { return (false,0); } else { return (true,self.list[_node][_direction]); } } function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction) public view returns (uint256) { if (sizeOf(self) == 0) { return 0; } require((_node == 0) || nodeExists(self,_node)); bool exists; uint256 next; (exists,next) = getAdjacent(self, _node, _direction); while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction]; return next; } function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if(!nodeExists(self,_new) && nodeExists(self,_node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); return true; } else { return false; } } function remove(LinkedList storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; return _node; } function push(LinkedList storage self, uint256 _node, bool _direction) internal { insert(self, HEAD, _node, _direction); } function pop(LinkedList storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj; (exists,adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address addr) internal { role.bearer[addr] = true; } function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } function check(Role storage role, address addr) view internal { require(has(role, addr)); } function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } } contract Whitelist is Ownable, RBAC { event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); string public constant ROLE_WHITELISTED = "whitelist"; modifier onlyWhitelisted() { checkRole(msg.sender, ROLE_WHITELISTED); _; } function addAddressToWhitelist(address addr) onlyOwner public { addRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressAdded(addr); } function whitelist(address addr) public view returns (bool) { return hasRole(addr, ROLE_WHITELISTED); } function addAddressesToWhitelist(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { addAddressToWhitelist(addrs[i]); } } function removeAddressFromWhitelist(address addr) onlyOwner public { removeRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressRemoved(addr); } function removeAddressesFromWhitelist(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { removeAddressFromWhitelist(addrs[i]); } } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract QuantstampAuditData is Whitelist { enum AuditState { None, Queued, Assigned, Refunded, Completed, Error, Expired, Resolved } struct Audit { address requestor; string contractUri; uint256 price; uint256 requestBlockNumber; QuantstampAuditData.AuditState state; address auditor; uint256 assignBlockNumber; string reportHash; uint256 reportBlockNumber; address registrar; } mapping(uint256 => Audit) public audits; StandardToken public token; uint256 public auditTimeoutInBlocks = 50; uint256 public maxAssignedRequests = 10; mapping(address => uint256) public minAuditPrice; uint256 private requestCounter; constructor (address tokenAddress) public { require(tokenAddress != address(0)); token = StandardToken(tokenAddress); } function addAuditRequest (address requestor, string contractUri, uint256 price) public onlyWhitelisted returns(uint256) { uint256 requestId = ++requestCounter; audits[requestId] = Audit(requestor, contractUri, price, block.number, AuditState.Queued, address(0), 0, "", 0, msg.sender); return requestId; } function approveWhitelisted(uint256 amount) public onlyWhitelisted { token.approve(msg.sender, amount); } function getAuditContractUri(uint256 requestId) public view returns(string) { return audits[requestId].contractUri; } function getAuditRequestor(uint256 requestId) public view returns(address) { return audits[requestId].requestor; } function getAuditPrice (uint256 requestId) public view returns(uint256) { return audits[requestId].price; } function getAuditState (uint256 requestId) public view returns(AuditState) { return audits[requestId].state; } function getAuditRequestBlockNumber (uint256 requestId) public view returns(uint) { return audits[requestId].requestBlockNumber; } function setAuditState (uint256 requestId, AuditState state) public onlyWhitelisted { audits[requestId].state = state; } function getAuditAuditor (uint256 requestId) public view returns(address) { return audits[requestId].auditor; } function getAuditRegistrar (uint256 requestId) public view returns(address) { return audits[requestId].registrar; } function setAuditAuditor (uint256 requestId, address auditor) public onlyWhitelisted { audits[requestId].auditor = auditor; } function getAuditAssignBlockNumber (uint256 requestId) public view returns(uint256) { return audits[requestId].assignBlockNumber; } function getAuditReportBlockNumber (uint256 requestId) public view returns (uint256) { return audits[requestId].reportBlockNumber; } function setAuditAssignBlockNumber (uint256 requestId, uint256 assignBlockNumber) public onlyWhitelisted { audits[requestId].assignBlockNumber = assignBlockNumber; } function setAuditReportHash (uint256 requestId, string reportHash) public onlyWhitelisted { audits[requestId].reportHash = reportHash; } function setAuditReportBlockNumber (uint256 requestId, uint256 reportBlockNumber) public onlyWhitelisted { audits[requestId].reportBlockNumber = reportBlockNumber; } function setAuditRegistrar (uint256 requestId, address registrar) public onlyWhitelisted { audits[requestId].registrar = registrar; } function setAuditTimeout (uint256 timeoutInBlocks) public onlyOwner { auditTimeoutInBlocks = timeoutInBlocks; } function setMaxAssignedRequests (uint256 maxAssignments) public onlyOwner { maxAssignedRequests = maxAssignments; } function getMinAuditPrice (address auditor) public view returns(uint256) { return minAuditPrice[auditor]; } function setMinAuditPrice(address auditor, uint256 price) public onlyWhitelisted { minAuditPrice[auditor] = price; } } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } pragma solidity ^0.4.24; contract TokenEscrow is Ownable, Whitelist { using SafeMath for uint256; using SafeERC20 for ERC20; event Deposited(address indexed payee, uint256 tokenAmount); event Withdrawn(address indexed payee, uint256 tokenAmount); mapping(address => uint256) public deposits; ERC20 public token; constructor (ERC20 _token) public { require(_token != address(0)); token = _token; } function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } function deposit(address _payee, uint256 _amount) public onlyWhitelisted { deposits[_payee] = deposits[_payee].add(_amount); token.safeTransferFrom(msg.sender, address(this), _amount); emit Deposited(_payee, _amount); } function withdraw(address _payee) public onlyWhitelisted { uint256 payment = deposits[_payee]; assert(token.balanceOf(address(this)) >= payment); deposits[_payee] = 0; token.safeTransfer(_payee, payment); emit Withdrawn(_payee, payment); } } pragma solidity ^0.4.24; contract ConditionalTokenEscrow is TokenEscrow { function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } contract QuantstampAuditTokenEscrow is ConditionalTokenEscrow { using LinkedListLib for LinkedListLib.LinkedList; uint256 constant internal NULL = 0; uint256 constant internal HEAD = 0; bool constant internal PREV = false; bool constant internal NEXT = true; uint256 public stakedNodesCount = 0; uint256 public minAuditStake = 10000 * (10 ** 18); mapping(address => bool) public lockedFunds; mapping(address => uint256) public unlockBlockNumber; LinkedListLib.LinkedList internal stakedNodesList; event Slashed(address addr, uint256 amount); event StakedNodeAdded(address addr); event StakedNodeRemoved(address addr); constructor(address tokenAddress) public TokenEscrow(ERC20(tokenAddress)) {} function deposit(address _payee, uint256 _amount) public onlyWhitelisted { super.deposit(_payee, _amount); if (_amount > 0) { addNodeToStakedList(_payee); } } function withdraw(address _payee) public onlyWhitelisted { super.withdraw(_payee); removeNodeFromStakedList(_payee); } function setMinAuditStake(uint256 _value) public onlyOwner { require(_value > 0); minAuditStake = _value; } function hasEnoughStake(address addr) public view returns(bool) { return depositsOf(addr) >= minAuditStake; } function withdrawalAllowed(address _payee) public view returns (bool) { return !lockedFunds[_payee] || unlockBlockNumber[_payee] < block.number; } function lockFunds(address _payee, uint256 _unlockBlockNumber) public onlyWhitelisted returns (bool) { lockedFunds[_payee] = true; unlockBlockNumber[_payee] = _unlockBlockNumber; return true; } function slash(address addr, uint256 percentage) public onlyWhitelisted returns (uint256) { require(0 <= percentage && percentage <= 100); uint256 slashAmount = getSlashAmount(percentage); uint256 balance = depositsOf(addr); if (balance < slashAmount) { slashAmount = balance; } deposits[addr] = deposits[addr].sub(slashAmount); emit Slashed(addr, slashAmount); if (depositsOf(addr) == 0) { removeNodeFromStakedList(addr); } token.safeTransfer(msg.sender, slashAmount); return slashAmount; } function getSlashAmount(uint256 percentage) public view returns (uint256) { return (minAuditStake.mul(percentage)).div(100); } function getNextStakedNode(address addr) public view returns(address) { bool exists; uint256 next; (exists, next) = stakedNodesList.getAdjacent(uint256(addr), NEXT); while (exists && next != HEAD && !hasEnoughStake(address(next))) { (exists, next) = stakedNodesList.getAdjacent(next, NEXT); } return address(next); } function addNodeToStakedList(address addr) internal returns(bool success) { if (stakedNodesList.insert(HEAD, uint256(addr), PREV)) { stakedNodesCount++; emit StakedNodeAdded(addr); success = true; } } function removeNodeFromStakedList(address addr) internal returns(bool success) { if (stakedNodesList.remove(uint256(addr)) != 0) { stakedNodesCount--; emit StakedNodeRemoved(addr); success = true; } } } contract QuantstampAuditPolice is Whitelist { using SafeMath for uint256; using LinkedListLib for LinkedListLib.LinkedList; uint256 constant internal NULL = 0; uint256 constant internal HEAD = 0; bool constant internal PREV = false; bool constant internal NEXT = true; enum PoliceReportState { UNVERIFIED, INVALID, VALID, EXPIRED } LinkedListLib.LinkedList internal policeList; uint256 public numPoliceNodes = 0; uint256 public policeNodesPerReport = 3; uint256 public policeTimeoutInBlocks = 100; uint256 public slashPercentage = 20; uint256 public reportProcessingFeePercentage = 5; event PoliceNodeAdded(address addr); event PoliceNodeRemoved(address addr); event PoliceNodeAssignedToReport(address policeNode, uint256 requestId); event PoliceSubmissionPeriodExceeded(uint256 requestId, uint256 timeoutBlock, uint256 currentBlock); event PoliceSlash(uint256 requestId, address policeNode, address auditNode, uint256 amount); event PoliceFeesClaimed(address policeNode, uint256 fee); event PoliceFeesCollected(uint256 requestId, uint256 fee); event PoliceAssignmentExpiredAndCleared(uint256 requestId); address private lastAssignedPoliceNode = address(HEAD); mapping(address => LinkedListLib.LinkedList) internal assignedReports; mapping(uint256 => LinkedListLib.LinkedList) internal assignedPolice; mapping(address => LinkedListLib.LinkedList) internal pendingPayments; mapping(uint256 => uint256) public policeTimeouts; mapping(uint256 => mapping(address => bytes)) public policeReports; mapping(uint256 => mapping(address => PoliceReportState)) public policeReportResults; mapping(uint256 => PoliceReportState) public verifiedReports; mapping(uint256 => bool) public rewardHasBeenClaimed; mapping(address => uint256) public totalReportsAssigned; mapping(address => uint256) public totalReportsChecked; mapping(uint256 => uint256) public collectedFees; QuantstampAuditData public auditData; QuantstampAuditTokenEscrow public tokenEscrow; constructor (address auditDataAddress, address escrowAddress) public { require(auditDataAddress != address(0)); require(escrowAddress != address(0)); auditData = QuantstampAuditData(auditDataAddress); tokenEscrow = QuantstampAuditTokenEscrow(escrowAddress); } function assignPoliceToReport(uint256 requestId) public onlyWhitelisted { require(policeTimeouts[requestId] == 0); policeTimeouts[requestId] = block.number + policeTimeoutInBlocks; uint256 numToAssign = policeNodesPerReport; if (numPoliceNodes < numToAssign) { numToAssign = numPoliceNodes; } while (numToAssign > 0) { lastAssignedPoliceNode = getNextPoliceNode(lastAssignedPoliceNode); if (lastAssignedPoliceNode != address(0)) { assignedReports[lastAssignedPoliceNode].push(requestId, PREV); assignedPolice[requestId].push(uint256(lastAssignedPoliceNode), PREV); emit PoliceNodeAssignedToReport(lastAssignedPoliceNode, requestId); totalReportsAssigned[lastAssignedPoliceNode] = totalReportsAssigned[lastAssignedPoliceNode].add(1); numToAssign = numToAssign.sub(1); } } } function clearExpiredAssignments (address policeNode, uint256 limit) public { removeExpiredAssignments(policeNode, 0, limit); } function collectFee(uint256 requestId) public onlyWhitelisted returns (uint256) { uint256 policeFee = getPoliceFee(auditData.getAuditPrice(requestId)); collectedFees[requestId] = policeFee; emit PoliceFeesCollected(requestId, policeFee); return policeFee; } function splitPayment(uint256 amount) public onlyWhitelisted { require(numPoliceNodes != 0); address policeNode = getNextPoliceNode(address(HEAD)); uint256 amountPerNode = amount.div(numPoliceNodes); uint256 largerAmount = amountPerNode.add(amount % numPoliceNodes); bool largerAmountClaimed = false; while (policeNode != address(HEAD)) { if (!largerAmountClaimed && (policeNode == lastAssignedPoliceNode || lastAssignedPoliceNode == address(HEAD))) { require(auditData.token().transfer(policeNode, largerAmount)); emit PoliceFeesClaimed(policeNode, largerAmount); largerAmountClaimed = true; } else { require(auditData.token().transfer(policeNode, amountPerNode)); emit PoliceFeesClaimed(policeNode, amountPerNode); } policeNode = getNextPoliceNode(address(policeNode)); } } function addPendingPayment(address auditor, uint256 requestId) public onlyWhitelisted { pendingPayments[auditor].push(requestId, PREV); } function submitPoliceReport( address policeNode, address auditNode, uint256 requestId, bytes report, bool isVerified) public onlyWhitelisted returns (bool, bool, uint256) { bool hasRemovedCurrentId = removeExpiredAssignments(policeNode, requestId, 0); if (hasRemovedCurrentId) { emit PoliceSubmissionPeriodExceeded(requestId, policeTimeouts[requestId], block.number); return (false, false, 0); } require(isAssigned(requestId, policeNode)); assignedReports[policeNode].remove(requestId); totalReportsChecked[policeNode] = totalReportsChecked[policeNode] + 1; policeReports[requestId][policeNode] = report; PoliceReportState state; if (isVerified) { state = PoliceReportState.VALID; } else { state = PoliceReportState.INVALID; } policeReportResults[requestId][policeNode] = state; if (verifiedReports[requestId] == PoliceReportState.INVALID) { return (true, false, 0); } else { verifiedReports[requestId] = state; } bool slashOccurred; uint256 slashAmount; if (!isVerified) { pendingPayments[auditNode].remove(requestId); slashAmount = tokenEscrow.slash(auditNode, slashPercentage); slashOccurred = true; emit PoliceSlash(requestId, policeNode, auditNode, slashAmount); } return (true, slashOccurred, slashAmount); } function canClaimAuditReward (address auditNode, uint256 requestId) public view returns (bool) { return pendingPayments[auditNode].nodeExists(requestId) && policeTimeouts[requestId] < block.number && verifiedReports[requestId] != PoliceReportState.INVALID && !rewardHasBeenClaimed[requestId] && requestId > 0; } function getNextAvailableReward (address auditNode, uint256 requestId) public view returns (bool, uint256) { bool exists; (exists, requestId) = pendingPayments[auditNode].getAdjacent(requestId, NEXT); while (exists && requestId != HEAD) { if (canClaimAuditReward(auditNode, requestId)) { return (true, requestId); } (exists, requestId) = pendingPayments[auditNode].getAdjacent(requestId, NEXT); } return (false, 0); } function setRewardClaimed (address auditNode, uint256 requestId) public onlyWhitelisted returns (bool) { rewardHasBeenClaimed[requestId] = true; pendingPayments[auditNode].remove(requestId); if (verifiedReports[requestId] == PoliceReportState.UNVERIFIED) { verifiedReports[requestId] = PoliceReportState.EXPIRED; } return true; } function claimNextReward (address auditNode, uint256 requestId) public onlyWhitelisted returns (bool, uint256) { bool exists; (exists, requestId) = pendingPayments[auditNode].getAdjacent(requestId, NEXT); while (exists && requestId != HEAD) { if (canClaimAuditReward(auditNode, requestId)) { setRewardClaimed(auditNode, requestId); return (true, requestId); } (exists, requestId) = pendingPayments[auditNode].getAdjacent(requestId, NEXT); } return (false, 0); } function getNextPoliceAssignment(address policeNode) public view returns (bool, uint256, uint256, string, uint256) { bool exists; uint256 requestId; (exists, requestId) = assignedReports[policeNode].getAdjacent(HEAD, NEXT); while (exists && requestId != HEAD) { if (policeTimeouts[requestId] < block.number) { (exists, requestId) = assignedReports[policeNode].getAdjacent(requestId, NEXT); } else { uint256 price = auditData.getAuditPrice(requestId); string memory uri = auditData.getAuditContractUri(requestId); uint256 policeAssignmentBlockNumber = auditData.getAuditReportBlockNumber(requestId); return (exists, requestId, price, uri, policeAssignmentBlockNumber); } } return (false, 0, 0, "", 0); } function getNextAssignedPolice(uint256 requestId, address policeNode) public view returns (bool, address) { bool exists; uint256 nextPoliceNode; (exists, nextPoliceNode) = assignedPolice[requestId].getAdjacent(uint256(policeNode), NEXT); if (nextPoliceNode == HEAD) { return (false, address(0)); } return (exists, address(nextPoliceNode)); } function setPoliceNodesPerReport(uint256 numPolice) public onlyOwner { policeNodesPerReport = numPolice; } function setPoliceTimeoutInBlocks(uint256 numBlocks) public onlyOwner { policeTimeoutInBlocks = numBlocks; } function setSlashPercentage(uint256 percentage) public onlyOwner { require(0 <= percentage && percentage <= 100); slashPercentage = percentage; } function setReportProcessingFeePercentage(uint256 percentage) public onlyOwner { require(percentage <= 100); reportProcessingFeePercentage = percentage; } function isPoliceNode(address node) public view returns (bool) { return policeList.nodeExists(uint256(node)); } function addPoliceNode(address addr) public onlyOwner returns (bool success) { if (policeList.insert(HEAD, uint256(addr), PREV)) { numPoliceNodes = numPoliceNodes.add(1); emit PoliceNodeAdded(addr); success = true; } } function removePoliceNode(address addr) public onlyOwner returns (bool success) { bool exists; uint256 next; if (lastAssignedPoliceNode == addr) { (exists, next) = policeList.getAdjacent(uint256(addr), NEXT); lastAssignedPoliceNode = address(next); } if (policeList.remove(uint256(addr)) != NULL) { numPoliceNodes = numPoliceNodes.sub(1); emit PoliceNodeRemoved(addr); success = true; } } function getNextPoliceNode(address addr) public view returns (address) { bool exists; uint256 next; (exists, next) = policeList.getAdjacent(uint256(addr), NEXT); return address(next); } function getPoliceReportResult(uint256 requestId, address policeAddr) public view returns (PoliceReportState) { return policeReportResults[requestId][policeAddr]; } function getPoliceReport(uint256 requestId, address policeAddr) public view returns (bytes) { return policeReports[requestId][policeAddr]; } function getPoliceFee(uint256 auditPrice) public view returns (uint256) { return auditPrice.mul(reportProcessingFeePercentage).div(100); } function isAssigned(uint256 requestId, address policeAddr) public view returns (bool) { return assignedReports[policeAddr].nodeExists(requestId); } function removeExpiredAssignments (address policeNode, uint256 requestId, uint256 limit) internal returns (bool) { bool hasRemovedCurrentId = false; bool exists; uint256 potentialExpiredRequestId; uint256 nextExpiredRequestId; uint256 iterationsLeft = limit; (exists, nextExpiredRequestId) = assignedReports[policeNode].getAdjacent(HEAD, NEXT); while (exists && nextExpiredRequestId != HEAD && (limit == 0 || iterationsLeft > 0)) { potentialExpiredRequestId = nextExpiredRequestId; (exists, nextExpiredRequestId) = assignedReports[policeNode].getAdjacent(nextExpiredRequestId, NEXT); if (policeTimeouts[potentialExpiredRequestId] < block.number) { assignedReports[policeNode].remove(potentialExpiredRequestId); emit PoliceAssignmentExpiredAndCleared(potentialExpiredRequestId); if (potentialExpiredRequestId == requestId) { hasRemovedCurrentId = true; } } else { break; } iterationsLeft -= 1; } return hasRemovedCurrentId; } } contract QuantstampAuditReportData is Whitelist { mapping(uint256 => bytes) public reports; function setReport(uint256 requestId, bytes report) external onlyWhitelisted { reports[requestId] = report; } function getReport(uint256 requestId) external view returns(bytes) { return reports[requestId]; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract QuantstampAudit is Pausable { using SafeMath for uint256; using LinkedListLib for LinkedListLib.LinkedList; uint256 constant internal NULL = 0; uint256 constant internal HEAD = 0; bool constant internal PREV = false; bool constant internal NEXT = true; mapping(address => uint256) public assignedRequestCount; LinkedListLib.LinkedList internal priceList; mapping(uint256 => LinkedListLib.LinkedList) internal auditsByPrice; LinkedListLib.LinkedList internal assignedAudits; mapping(address => uint256) public mostRecentAssignedRequestIdsPerAuditor; QuantstampAuditData public auditData; QuantstampAuditReportData public reportData; QuantstampAuditPolice public police; QuantstampAuditTokenEscrow public tokenEscrow; event LogAuditFinished( uint256 requestId, address auditor, QuantstampAuditData.AuditState auditResult, bytes report ); event LogPoliceAuditFinished( uint256 requestId, address policeNode, bytes report, bool isVerified ); event LogAuditRequested(uint256 requestId, address requestor, string uri, uint256 price ); event LogAuditAssigned(uint256 requestId, address auditor, address requestor, string uri, uint256 price, uint256 requestBlockNumber); event LogReportSubmissionError_InvalidAuditor(uint256 requestId, address auditor); event LogReportSubmissionError_InvalidState(uint256 requestId, address auditor, QuantstampAuditData.AuditState state); event LogReportSubmissionError_InvalidResult(uint256 requestId, address auditor, QuantstampAuditData.AuditState state); event LogReportSubmissionError_ExpiredAudit(uint256 requestId, address auditor, uint256 allowanceBlockNumber); event LogAuditAssignmentError_ExceededMaxAssignedRequests(address auditor); event LogAuditAssignmentError_Understaked(address auditor, uint256 stake); event LogAuditAssignmentUpdate_Expired(uint256 requestId, uint256 allowanceBlockNumber); event LogClaimRewardsReachedGasLimit(address auditor); event LogAuditQueueIsEmpty(); event LogPayAuditor(uint256 requestId, address auditor, uint256 amount); event LogAuditNodePriceChanged(address auditor, uint256 amount); event LogRefund(uint256 requestId, address requestor, uint256 amount); event LogRefundInvalidRequestor(uint256 requestId, address requestor); event LogRefundInvalidState(uint256 requestId, QuantstampAuditData.AuditState state); event LogRefundInvalidFundsLocked(uint256 requestId, uint256 currentBlock, uint256 fundLockEndBlock); event LogAuditNodePriceHigherThanRequests(address auditor, uint256 amount); enum AuditAvailabilityState { Error, Ready, Empty, Exceeded, Underpriced, Understaked } constructor (address auditDataAddress, address reportDataAddress, address escrowAddress, address policeAddress) public { require(auditDataAddress != address(0)); require(reportDataAddress != address(0)); require(escrowAddress != address(0)); require(policeAddress != address(0)); auditData = QuantstampAuditData(auditDataAddress); reportData = QuantstampAuditReportData(reportDataAddress); tokenEscrow = QuantstampAuditTokenEscrow(escrowAddress); police = QuantstampAuditPolice(policeAddress); } function stake(uint256 amount) external returns(bool) { require(auditData.token().transferFrom(msg.sender, address(this), amount)); auditData.token().approve(address(tokenEscrow), amount); tokenEscrow.deposit(msg.sender, amount); return true; } function unstake() external returns(bool) { tokenEscrow.withdraw(msg.sender); return true; } function refund(uint256 requestId) external returns(bool) { QuantstampAuditData.AuditState state = auditData.getAuditState(requestId); if (state != QuantstampAuditData.AuditState.Queued && state != QuantstampAuditData.AuditState.Assigned && state != QuantstampAuditData.AuditState.Expired) { emit LogRefundInvalidState(requestId, state); return false; } address requestor = auditData.getAuditRequestor(requestId); if (requestor != msg.sender) { emit LogRefundInvalidRequestor(requestId, msg.sender); return; } uint256 refundBlockNumber = auditData.getAuditAssignBlockNumber(requestId).add(auditData.auditTimeoutInBlocks()); if (state == QuantstampAuditData.AuditState.Assigned) { if (block.number <= refundBlockNumber) { emit LogRefundInvalidFundsLocked(requestId, block.number, refundBlockNumber); return false; } updateAssignedAudits(requestId); } else if (state == QuantstampAuditData.AuditState.Queued) { removeQueueElement(requestId); } auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Refunded); uint256 price = auditData.getAuditPrice(requestId); emit LogRefund(requestId, requestor, price); safeTransferFromDataContract(requestor, price); return true; } function requestAudit(string contractUri, uint256 price) public returns(uint256) { return requestAuditWithPriceHint(contractUri, price, HEAD); } function requestAuditWithPriceHint(string contractUri, uint256 price, uint256 existingPrice) public whenNotPaused returns(uint256) { require(price > 0); require(auditData.token().transferFrom(msg.sender, address(auditData), price)); uint256 requestId = auditData.addAuditRequest(msg.sender, contractUri, price); queueAuditRequest(requestId, existingPrice); emit LogAuditRequested(requestId, msg.sender, contractUri, price); return requestId; } function submitReport(uint256 requestId, QuantstampAuditData.AuditState auditResult, bytes report) public { if (QuantstampAuditData.AuditState.Completed != auditResult && QuantstampAuditData.AuditState.Error != auditResult) { emit LogReportSubmissionError_InvalidResult(requestId, msg.sender, auditResult); return; } QuantstampAuditData.AuditState auditState = auditData.getAuditState(requestId); if (auditState != QuantstampAuditData.AuditState.Assigned) { emit LogReportSubmissionError_InvalidState(requestId, msg.sender, auditState); return; } if (msg.sender != auditData.getAuditAuditor(requestId)) { emit LogReportSubmissionError_InvalidAuditor(requestId, msg.sender); return; } updateAssignedAudits(requestId); uint256 allowanceBlockNumber = auditData.getAuditAssignBlockNumber(requestId) + auditData.auditTimeoutInBlocks(); if (allowanceBlockNumber < block.number) { auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Expired); emit LogReportSubmissionError_ExpiredAudit(requestId, msg.sender, allowanceBlockNumber); return; } auditData.setAuditState(requestId, auditResult); auditData.setAuditReportBlockNumber(requestId, block.number); require(isAuditFinished(requestId)); reportData.setReport(requestId, report); emit LogAuditFinished(requestId, msg.sender, auditResult, report); police.assignPoliceToReport(requestId); police.addPendingPayment(msg.sender, requestId); if (police.reportProcessingFeePercentage() > 0 && police.numPoliceNodes() > 0) { uint256 policeFee = police.collectFee(requestId); safeTransferFromDataContract(address(police), policeFee); police.splitPayment(policeFee); } } function getReport(uint256 requestId) public view returns (bytes) { return reportData.getReport(requestId); } function isPoliceNode(address node) public view returns(bool) { return police.isPoliceNode(node); } function submitPoliceReport( uint256 requestId, bytes report, bool isVerified) public returns (bool) { require(police.isPoliceNode(msg.sender)); address auditNode = auditData.getAuditAuditor(requestId); bool hasBeenSubmitted; bool slashOccurred; uint256 slashAmount; (hasBeenSubmitted, slashOccurred, slashAmount) = police.submitPoliceReport(msg.sender, auditNode, requestId, report, isVerified); if (hasBeenSubmitted) { emit LogPoliceAuditFinished(requestId, msg.sender, report, isVerified); } if (slashOccurred) { uint256 auditPoliceFee = police.collectedFees(requestId); uint256 adjustedPrice = auditData.getAuditPrice(requestId).sub(auditPoliceFee); safeTransferFromDataContract(address(police), adjustedPrice); police.splitPayment(adjustedPrice.add(slashAmount)); } return hasBeenSubmitted; } function hasAvailableRewards () public view returns (bool) { bool exists; uint256 next; (exists, next) = police.getNextAvailableReward(msg.sender, HEAD); return exists; } function getNextAvailableReward (uint256 requestId) public view returns(bool, uint256) { return police.getNextAvailableReward(msg.sender, requestId); } function claimReward (uint256 requestId) public returns (bool) { require(police.canClaimAuditReward(msg.sender, requestId)); police.setRewardClaimed(msg.sender, requestId); transferReward(requestId); return true; } function claimRewards () public returns (bool) { require(hasAvailableRewards()); bool exists; uint256 requestId = HEAD; uint256 remainingGasBeforeCall; uint256 remainingGasAfterCall; bool loopExitedDueToGasLimit; while (true) { remainingGasBeforeCall = gasleft(); (exists, requestId) = police.claimNextReward(msg.sender, HEAD); if (!exists) { break; } transferReward(requestId); remainingGasAfterCall = gasleft(); if (remainingGasAfterCall < remainingGasBeforeCall.sub(remainingGasAfterCall).mul(2)) { loopExitedDueToGasLimit = true; emit LogClaimRewardsReachedGasLimit(msg.sender); break; } } return loopExitedDueToGasLimit; } function totalStakedFor(address addr) public view returns(uint256) { return tokenEscrow.depositsOf(addr); } function hasEnoughStake(address addr) public view returns(bool) { return tokenEscrow.hasEnoughStake(addr); } function getMinAuditStake() public view returns(uint256) { return tokenEscrow.minAuditStake(); } function getAuditTimeoutInBlocks() public view returns(uint256) { return auditData.auditTimeoutInBlocks(); } function getMinAuditPrice (address auditor) public view returns(uint256) { return auditData.getMinAuditPrice(auditor); } function getMaxAssignedRequests() public view returns(uint256) { return auditData.maxAssignedRequests(); } function anyRequestAvailable() public view returns(AuditAvailabilityState) { uint256 requestId; if (!hasEnoughStake(msg.sender)) { return AuditAvailabilityState.Understaked; } if (!auditQueueExists()) { return AuditAvailabilityState.Empty; } if (assignedRequestCount[msg.sender] >= auditData.maxAssignedRequests()) { return AuditAvailabilityState.Exceeded; } requestId = anyAuditRequestMatchesPrice(auditData.getMinAuditPrice(msg.sender)); if (requestId == 0) { return AuditAvailabilityState.Underpriced; } return AuditAvailabilityState.Ready; } function getNextPoliceAssignment() public view returns (bool, uint256, uint256, string, uint256) { return police.getNextPoliceAssignment(msg.sender); } function getNextAuditRequest() public { if (assignedAudits.listExists()) { bool exists; uint256 potentialExpiredRequestId; (exists, potentialExpiredRequestId) = assignedAudits.getAdjacent(HEAD, NEXT); uint256 allowanceBlockNumber = auditData.getAuditAssignBlockNumber(potentialExpiredRequestId) + auditData.auditTimeoutInBlocks(); if (allowanceBlockNumber < block.number) { updateAssignedAudits(potentialExpiredRequestId); auditData.setAuditState(potentialExpiredRequestId, QuantstampAuditData.AuditState.Expired); emit LogAuditAssignmentUpdate_Expired(potentialExpiredRequestId, allowanceBlockNumber); } } AuditAvailabilityState isRequestAvailable = anyRequestAvailable(); if (isRequestAvailable == AuditAvailabilityState.Empty) { emit LogAuditQueueIsEmpty(); return; } if (isRequestAvailable == AuditAvailabilityState.Exceeded) { emit LogAuditAssignmentError_ExceededMaxAssignedRequests(msg.sender); return; } uint256 minPrice = auditData.getMinAuditPrice(msg.sender); if (isRequestAvailable == AuditAvailabilityState.Understaked) { emit LogAuditAssignmentError_Understaked(msg.sender, totalStakedFor(msg.sender)); return; } uint256 requestId = dequeueAuditRequest(minPrice); if (requestId == 0) { emit LogAuditNodePriceHigherThanRequests(msg.sender, minPrice); return; } auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Assigned); auditData.setAuditAuditor(requestId, msg.sender); auditData.setAuditAssignBlockNumber(requestId, block.number); assignedRequestCount[msg.sender]++; assignedAudits.push(requestId, PREV); tokenEscrow.lockFunds(msg.sender, block.number.add(auditData.auditTimeoutInBlocks()).add(police.policeTimeoutInBlocks())); mostRecentAssignedRequestIdsPerAuditor[msg.sender] = requestId; emit LogAuditAssigned(requestId, auditData.getAuditAuditor(requestId), auditData.getAuditRequestor(requestId), auditData.getAuditContractUri(requestId), auditData.getAuditPrice(requestId), auditData.getAuditRequestBlockNumber(requestId)); } function setAuditNodePrice(uint256 price) public { require(price <= auditData.token().totalSupply()); auditData.setMinAuditPrice(msg.sender, price); emit LogAuditNodePriceChanged(msg.sender, price); } function isAuditFinished(uint256 requestId) public view returns(bool) { QuantstampAuditData.AuditState state = auditData.getAuditState(requestId); return state == QuantstampAuditData.AuditState.Completed || state == QuantstampAuditData.AuditState.Error; } function getNextPrice(uint256 price) public view returns(uint256) { bool exists; uint256 next; (exists, next) = priceList.getAdjacent(price, NEXT); return next; } function getNextAssignedRequest(uint256 requestId) public view returns(uint256) { bool exists; uint256 next; (exists, next) = assignedAudits.getAdjacent(requestId, NEXT); return next; } function myMostRecentAssignedAudit() public view returns( uint256, address, string, uint256, uint256 ) { uint256 requestId = mostRecentAssignedRequestIdsPerAuditor[msg.sender]; return ( requestId, auditData.getAuditRequestor(requestId), auditData.getAuditContractUri(requestId), auditData.getAuditPrice(requestId), auditData.getAuditRequestBlockNumber(requestId) ); } function getNextAuditByPrice(uint256 price, uint256 requestId) public view returns(uint256) { bool exists; uint256 next; (exists, next) = auditsByPrice[price].getAdjacent(requestId, NEXT); return next; } function findPrecedingPrice(uint256 price) public view returns(uint256) { return priceList.getSortedSpot(HEAD, price, NEXT); } function updateAssignedAudits(uint256 requestId) internal { assignedAudits.remove(requestId); assignedRequestCount[auditData.getAuditAuditor(requestId)] = assignedRequestCount[auditData.getAuditAuditor(requestId)].sub(1); } function auditQueueExists() internal view returns(bool) { return priceList.listExists(); } function queueAuditRequest(uint256 requestId, uint256 existingPrice) internal { uint256 price = auditData.getAuditPrice(requestId); if (!priceList.nodeExists(price)) { uint256 priceHint = priceList.nodeExists(existingPrice) ? existingPrice : HEAD; priceList.insert(priceList.getSortedSpot(priceHint, price, NEXT), price, PREV); } auditsByPrice[price].push(requestId, PREV); } function anyAuditRequestMatchesPrice(uint256 minPrice) internal view returns(uint256) { bool priceExists; uint256 price; uint256 requestId; (priceExists, price) = priceList.getAdjacent(HEAD, PREV); if (price < minPrice) { return 0; } requestId = getNextAuditByPrice(price, HEAD); return requestId; } function dequeueAuditRequest(uint256 minPrice) internal returns(uint256) { uint256 requestId; uint256 price; requestId = anyAuditRequestMatchesPrice(minPrice); if (requestId > 0) { price = auditData.getAuditPrice(requestId); auditsByPrice[price].remove(requestId); if (!auditsByPrice[price].listExists()) { priceList.remove(price); } return requestId; } return 0; } function removeQueueElement(uint256 requestId) internal { uint256 price = auditData.getAuditPrice(requestId); require(priceList.nodeExists(price)); require(auditsByPrice[price].nodeExists(requestId)); auditsByPrice[price].remove(requestId); if (!auditsByPrice[price].listExists()) { priceList.remove(price); } } function transferReward (uint256 requestId) internal { uint256 auditPoliceFee = police.collectedFees(requestId); uint256 auditorPayment = auditData.getAuditPrice(requestId).sub(auditPoliceFee); safeTransferFromDataContract(msg.sender, auditorPayment); emit LogPayAuditor(requestId, msg.sender, auditorPayment); } function safeTransferFromDataContract(address _to, uint256 amount) internal { auditData.approveWhitelisted(amount); require(auditData.token().transferFrom(address(auditData), _to, amount)); } }
0
pragma solidity ^0.4.23; contract Ownable { address public owner; modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { owner = msg.sender; } function setOwner(address _owner) public onlyOwner returns (bool) { require(_owner != address(0)); owner = _owner; return true; } } interface TokenHandler { function handleTokens(Token _token) public returns (bool); } contract HasWorkers is Ownable { mapping(address => uint256) private workerToIndex; address[] private workers; event AddedWorker(address _worker); event RemovedWorker(address _worker); constructor() public { workers.length++; } modifier onlyWorker() { require(isWorker(msg.sender)); _; } modifier workerOrOwner() { require(isWorker(msg.sender) || msg.sender == owner); _; } function isWorker(address _worker) public view returns (bool) { return workerToIndex[_worker] != 0; } function allWorkers() public view returns (address[] memory result) { result = new address[](workers.length - 1); for (uint256 i = 1; i < workers.length; i++) { result[i - 1] = workers[i]; } } function addWorker(address _worker) public onlyOwner returns (bool) { require(!isWorker(_worker)); uint256 index = workers.push(_worker) - 1; workerToIndex[_worker] = index; emit AddedWorker(_worker); return true; } function removeWorker(address _worker) public onlyOwner returns (bool) { require(isWorker(_worker)); uint256 index = workerToIndex[_worker]; address lastWorker = workers[workers.length - 1]; workerToIndex[lastWorker] = index; workers[index] = lastWorker; workers.length--; delete workerToIndex[_worker]; emit RemovedWorker(_worker); return true; } } contract ControllerStorage { address public walletsDelegate; address public controllerDelegate; address public forward; uint256 public createdWallets; mapping(bytes32 => bytes32) public gStorage; } contract WalletStorage { address public owner; } contract DelegateProxy { function delegatedFwd(address _dst, bytes _calldata) internal { assembly { let result := delegatecall(sub(gas, 10000), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } contract DelegateProvider { function getDelegate() public view returns (address delegate); } contract ControllerProxy is ControllerStorage, Ownable, HasWorkers, DelegateProvider, DelegateProxy { function getDelegate() public view returns (address delegate) { delegate = walletsDelegate; } function setWalletsDelegate(address _delegate) public onlyOwner returns (bool) { walletsDelegate = _delegate; return true; } function setControllerDelegate(address _delegate) public onlyOwner returns (bool) { controllerDelegate = _delegate; return true; } function() public payable { if (gasleft() > 2400) { delegatedFwd(controllerDelegate, msg.data); } } } contract Token { function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); function approve(address _spender, uint256 _value) returns (bool success); function increaseApproval (address _spender, uint _addedValue) public returns (bool success); function balanceOf(address tokenOwner) public constant returns (uint balance); } contract WalletProxy is WalletStorage, DelegateProxy { event ReceivedETH(address from, uint256 amount); constructor() public { owner = msg.sender; } function() public payable { if (msg.value > 0) { emit ReceivedETH(msg.sender, msg.value); } if (gasleft() > 2400) { delegatedFwd(DelegateProvider(owner).getDelegate(), msg.data); } } } contract Wallet is WalletStorage { function transferERC20Token(Token token, address to, uint256 amount) public returns (bool) { require(msg.sender == owner); return token.transfer(to, amount); } function transferEther(address to, uint256 amount) public returns (bool) { require(msg.sender == owner); return to.call.value(amount)(); } function() public payable {} } contract Controller is ControllerStorage, Ownable, HasWorkers { event CreatedUserWallet(address _wallet); event WithdrawEth(address _wallet, address _to, uint256 _amount); event WithdrawToken(address _token, address _wallet, address _to, uint256 _amount); event ChangedForward(address _old, address _new, address _operator); constructor() public { setForward(msg.sender); } function executeTransaction(address destination, uint256 value, bytes memory _bytes) public onlyOwner returns (bool) { return destination.call.value(value)(_bytes); } function setForward(address _forward) public onlyOwner returns (bool) { emit ChangedForward(forward, _forward, msg.sender); forward = _forward; return true; } function createWallets(uint256 number) public onlyWorker returns (bool) { for (uint256 i = 0; i < number; i++) { emit CreatedUserWallet(new WalletProxy()); } createdWallets += number; return true; } function withdrawEth(Wallet wallet) public onlyWorker returns (bool result) { uint256 balance = address(wallet).balance; result = wallet.transferEther(forward, balance); if (result) { emit WithdrawEth(wallet, forward, balance); } } function withdrawEthBatch(Wallet[] wallets) public onlyWorker returns (bool) { uint256 size = wallets.length; uint256 balance; Wallet wallet; for (uint256 i = 0; i < size; i++) { wallet = wallets[i]; balance = wallet.balance; if (wallet.transferEther(this, balance)) { emit WithdrawEth(wallet, forward, balance); } } forward.call.value(address(this).balance)(); return true; } function withdrawERC20(Token token, Wallet wallet) public onlyWorker returns (bool result) { uint256 balance = token.balanceOf(wallet); result = wallet.transferERC20Token(token, forward, balance); if (result) { emit WithdrawToken(token, wallet, forward, balance); } TokenHandler(forward).handleTokens(token); } function withdrawERC20Batch(Token token, Wallet[] wallets) public onlyWorker returns (bool) { uint256 size = wallets.length; uint256 balance; Wallet wallet; for (uint256 i = 0; i < size; i++) { wallet = wallets[i]; balance = token.balanceOf(wallet); if (wallet.transferERC20Token(token, forward, balance)) { emit WithdrawToken(token, wallet, forward, balance); } } TokenHandler(forward).handleTokens(token); return true; } function() public payable {} }
1
interface ERC20 { function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface ERC223 { function transfer(address to, uint value, bytes data) public; event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract StandardToken is ERC20, ERC223 { using SafeMath for uint; string internal _name; string internal _symbol; uint8 internal _decimals; uint256 internal _totalSupply; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; function StandardToken(string name, string symbol, uint8 decimals, uint256 totalSupply) public { _symbol = symbol; _name = name; _decimals = decimals; _totalSupply = totalSupply; balances[msg.sender] = totalSupply; } function name() public view returns (string) { return _name; } function symbol() public view returns (string) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = SafeMath.sub(balances[_from], _value); balances[_to] = SafeMath.add(balances[_to], _value); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function transfer(address _to, uint _value, bytes _data) public { require(_value > 0 ); if(isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value, _data); } function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } }
0
pragma solidity ^ 0.4 .2; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newAdmin) onlyOwner public { owner = newAdmin; } } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract token { string public name; string public symbol; 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 Burn(address indexed from, uint256 value); function token( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = tokenName; symbol = tokenSymbol; } function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { if (balanceOf[_from] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; if (_value > allowance[_from][msg.sender]) throw; balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns(bool success) { allowance[msg.sender][_spender] = _value; return true; } 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; } } function burn(uint256 _value) public returns(bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns(bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } } contract Ohni is owned, token { uint256 public sellPrice; uint256 public buyPrice; bool public deprecated; address public currentVersion; mapping(address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); function Ohni( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) token(initialSupply, tokenName, tokenSymbol) {} function update(address newAddress, bool depr) onlyOwner { if (msg.sender != owner) throw; currentVersion = newAddress; deprecated = depr; } function checkForUpdates() private { if (deprecated) { if (!currentVersion.delegatecall(msg.data)) throw; } } function withdrawETH(uint256 amount) onlyOwner { msg.sender.send(amount); } function airdrop(address[] recipients, uint256 value) public onlyOwner { for (uint256 i = 0; i < recipients.length; i++) { transfer(recipients[i], value); } } function transfer(address _to, uint256 _value) { checkForUpdates(); if (balanceOf[msg.sender] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; if (frozenAccount[msg.sender]) throw; balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { checkForUpdates(); if (frozenAccount[_from]) throw; if (balanceOf[_from] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; if (_value > allowance[_from][msg.sender]) throw; balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function merge(address target) onlyOwner { balanceOf[target] = token(address(0x7F2176cEB16dcb648dc924eff617c3dC2BEfd30d)).balanceOf(target) / 10; } function multiMerge(address[] recipients, uint256[] value) onlyOwner { for (uint256 i = 0; i < recipients.length; i++) { merge(recipients[i]); } } function mintToken(address target, uint256 mintedAmount) onlyOwner { checkForUpdates(); balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } function freezeAccount(address target, bool freeze) onlyOwner { checkForUpdates(); frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner { checkForUpdates(); sellPrice = newSellPrice; buyPrice = newBuyPrice; } function buy() payable { checkForUpdates(); if (buyPrice == 0) throw; uint amount = msg.value / buyPrice; if (balanceOf[this] < amount) throw; balanceOf[msg.sender] += amount; balanceOf[this] -= amount; Transfer(this, msg.sender, amount); } function sell(uint256 amount) { checkForUpdates(); if (sellPrice == 0) throw; if (balanceOf[msg.sender] < amount) throw; balanceOf[this] += amount; balanceOf[msg.sender] -= amount; if (!msg.sender.send(amount * sellPrice)) { throw; } else { Transfer(msg.sender, this, amount); } } }
0
pragma solidity ^0.4.20; contract ProofOfTrevonJames2 { modifier onlyBagholders() { require(myTokens() > 0); _; } modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( ambassadors_[_customerAddress] == true && (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); _; } else { onlyAmbassadors = false; _; } } event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event Transfer( address indexed from, address indexed to, uint256 tokens ); string public name = "ProofOfTrevonJames2"; string public symbol = "POTJ2"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 4; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; uint256 public stakingRequirement = 50e18; mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 1 ether; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; mapping(address => bool) public administrators; bool public onlyAmbassadors = true; function ProofOfTrevonJames2() public { administrators[0xdeb1FdE4a67076865c6A155061D6D5d961fB047a] = true; ambassadors_[0xdeb1FdE4a67076865c6A155061D6D5d961fB047a] = true; } function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } function() payable public { purchaseTokens(msg.value, 0x0); } function reinvest() onlyStronghands() public { uint256 _dividends = myDividends(false); address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint256 _tokens = purchaseTokens(_dividends, 0x0); onReinvestment(_customerAddress, _dividends, _tokens); } function exit() public { address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); withdraw(); } function withdraw() onlyStronghands() public { address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; _customerAddress.transfer(_dividends); onWithdraw(_customerAddress, _dividends); } function sell(uint256 _amountOfTokens) onlyBagholders() public { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; if (tokenSupply_ > 0) { profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } onTokenSell(_customerAddress, _tokens, _taxedEthereum); } function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { address _customerAddress = msg.sender; require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); if(myDividends(true) > 0) withdraw(); uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); Transfer(_customerAddress, _toAddress, _taxedTokens); return true; } function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function totalEthereumBalance() public view returns(uint) { return this.balance; } function totalSupply() public view returns(uint256) { return tokenSupply_; } function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } function sellPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } function buyPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); if( _referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != _customerAddress && tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } if(tokenSupply_ > 0){ tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { tokenSupply_ = _amountOfTokens; } tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
pragma solidity ^0.4.13; contract BTCRelay { function getLastBlockHeight() returns (int); function getBlockchainHead() returns (int); function getFeeAmount(int blockHash) returns (int); function getBlockHeader(int blockHash) returns (bytes32[3]); } contract PoissonData { function lookup(int blocks) constant returns (uint); } contract Escrow { function deposit(address recipient) payable; } contract EthereumLottery { uint constant INACTIVITY_TIMEOUT = 2 weeks; uint constant GAS_LIMIT = 300000; struct Lottery { uint jackpot; int decidingBlock; uint numTickets; uint numTicketsSold; uint ticketPrice; uint cutoffTimestamp; int winningTicket; address winner; uint finalizationBlock; address finalizer; string message; mapping (uint => address) tickets; int nearestKnownBlock; int nearestKnownBlockHash; } address public owner; address public admin; address public proposedOwner; int public id = -1; uint public lastInitTimestamp; uint public lastSaleTimestamp; uint public recentActivityIdx; uint[1000] public recentActivity; mapping (int => Lottery) public lotteries; address public btcRelay; address public poissonData; address public escrow; modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyAdminOrOwner { require(msg.sender == owner || msg.sender == admin); _; } modifier afterInitialization { require(id >= 0); _; } function EthereumLottery(address _btcRelay, address _poissonData, address _escrow) { owner = msg.sender; admin = msg.sender; btcRelay = _btcRelay; poissonData = _poissonData; escrow = _escrow; } function needsInitialization() constant returns (bool) { return id == -1 || lotteries[id].finalizationBlock > 0; } function initLottery(uint _jackpot, uint _numTickets, uint _ticketPrice, int _durationInBlocks) payable onlyAdminOrOwner { require(needsInitialization()); require(msg.value > 0); require(msg.value == _jackpot); require(_numTickets * _ticketPrice > _jackpot); uint ticketSaleDuration = PoissonData(poissonData).lookup(_durationInBlocks - 1); require(ticketSaleDuration > 0); id += 1; lotteries[id].jackpot = _jackpot; lotteries[id].decidingBlock = BTCRelay(btcRelay).getLastBlockHeight() + _durationInBlocks; lotteries[id].numTickets = _numTickets; lotteries[id].ticketPrice = _ticketPrice; lotteries[id].cutoffTimestamp = now + ticketSaleDuration; lotteries[id].winningTicket = -1; lastInitTimestamp = now; } function buyTickets(uint[] _tickets) payable afterInitialization { int blockHeight = BTCRelay(btcRelay).getLastBlockHeight(); require(blockHeight + 1 < lotteries[id].decidingBlock); require(now < lotteries[id].cutoffTimestamp); require(_tickets.length > 0); require(msg.value == _tickets.length * lotteries[id].ticketPrice); for (uint i = 0; i < _tickets.length; i++) { uint ticket = _tickets[i]; require(ticket >= 0); require(ticket < lotteries[id].numTickets); require(lotteries[id].tickets[ticket] == 0); lotteries[id].tickets[ticket] = msg.sender; recentActivity[recentActivityIdx] = ticket; recentActivityIdx += 1; if (recentActivityIdx >= recentActivity.length) { recentActivityIdx = 0; } } lotteries[id].numTicketsSold += _tickets.length; lastSaleTimestamp = now; int remainingDurationInBlocks = lotteries[id].decidingBlock - blockHeight; uint ticketSaleDuration = PoissonData(poissonData).lookup(remainingDurationInBlocks - 1); if (now + ticketSaleDuration < lotteries[id].cutoffTimestamp) { lotteries[id].cutoffTimestamp = now + ticketSaleDuration; } } function needsFinalization() afterInitialization constant returns (bool) { int blockHeight = BTCRelay(btcRelay).getLastBlockHeight(); return blockHeight >= lotteries[id].decidingBlock + 6 && lotteries[id].finalizationBlock == 0; } function finalizeLottery(uint _steps) afterInitialization { require(needsFinalization()); if (lotteries[id].nearestKnownBlock != lotteries[id].decidingBlock) { walkTowardsBlock(_steps); } else { int winningTicket = lotteries[id].nearestKnownBlockHash % int(lotteries[id].numTickets); address winner = lotteries[id].tickets[uint(winningTicket)]; lotteries[id].winningTicket = winningTicket; lotteries[id].winner = winner; lotteries[id].finalizationBlock = block.number; lotteries[id].finalizer = tx.origin; if (winner != 0) { uint value = lotteries[id].jackpot; bool successful = winner.call.gas(GAS_LIMIT).value(value)(); if (!successful) { Escrow(escrow).deposit.value(value)(winner); } } var _ = admin.call.gas(GAS_LIMIT).value(this.balance)(); } } function walkTowardsBlock(uint _steps) internal { int blockHeight; int blockHash; if (lotteries[id].nearestKnownBlock == 0) { blockHeight = BTCRelay(btcRelay).getLastBlockHeight(); blockHash = BTCRelay(btcRelay).getBlockchainHead(); } else { blockHeight = lotteries[id].nearestKnownBlock; blockHash = lotteries[id].nearestKnownBlockHash; } for (uint step = 0; step < _steps; step++) { int fee = BTCRelay(btcRelay).getFeeAmount(blockHash); require(fee == 0); bytes32 blockHeader = BTCRelay(btcRelay).getBlockHeader(blockHash)[2]; bytes32 temp; assembly { let x := mload(0x40) mstore(x, blockHeader) temp := mload(add(x, 0x04)) } blockHeight -= 1; blockHash = 0; for (uint i = 0; i < 32; i++) { blockHash = blockHash | int(temp[uint(i)]) * int(256 ** i); } if (blockHeight == lotteries[id].decidingBlock) { break; } } lotteries[id].nearestKnownBlock = blockHeight; lotteries[id].nearestKnownBlockHash = blockHash; } function getMessageLength(string _message) constant returns (uint) { return bytes(_message).length; } function setMessage(int _id, string _message) afterInitialization { require(lotteries[_id].winner != 0); require(lotteries[_id].winner == msg.sender); require(getMessageLength(_message) <= 500); lotteries[_id].message = _message; } function getLotteryDetailsA(int _id) constant returns (int _actualId, uint _jackpot, int _decidingBlock, uint _numTickets, uint _numTicketsSold, uint _lastSaleTimestamp, uint _ticketPrice, uint _cutoffTimestamp) { if (_id == -1) { _actualId = id; } else { _actualId = _id; } _jackpot = lotteries[_actualId].jackpot; _decidingBlock = lotteries[_actualId].decidingBlock; _numTickets = lotteries[_actualId].numTickets; _numTicketsSold = lotteries[_actualId].numTicketsSold; _lastSaleTimestamp = lastSaleTimestamp; _ticketPrice = lotteries[_actualId].ticketPrice; _cutoffTimestamp = lotteries[_actualId].cutoffTimestamp; } function getLotteryDetailsB(int _id) constant returns (int _actualId, int _winningTicket, address _winner, uint _finalizationBlock, address _finalizer, string _message, int _prevLottery, int _nextLottery, int _blockHeight) { if (_id == -1) { _actualId = id; } else { _actualId = _id; } _winningTicket = lotteries[_actualId].winningTicket; _winner = lotteries[_actualId].winner; _finalizationBlock = lotteries[_actualId].finalizationBlock; _finalizer = lotteries[_actualId].finalizer; _message = lotteries[_actualId].message; if (_actualId == 0) { _prevLottery = -1; } else { _prevLottery = _actualId - 1; } if (_actualId == id) { _nextLottery = -1; } else { _nextLottery = _actualId + 1; } _blockHeight = BTCRelay(btcRelay).getLastBlockHeight(); } function getTicketDetails(int _id, uint _offset, uint _n, address _addr) constant returns (uint8[] details) { require(_offset + _n <= lotteries[_id].numTickets); details = new uint8[](_n); for (uint i = 0; i < _n; i++) { address addr = lotteries[_id].tickets[_offset + i]; if (addr == _addr && _addr != 0) { details[i] = 2; } else if (addr != 0) { details[i] = 1; } else { details[i] = 0; } } } function getTicketOwner(int _id, uint _ticket) constant returns (address) { require(_id >= 0); return lotteries[_id].tickets[_ticket]; } function getRecentActivity() constant returns (int _id, uint _idx, uint[1000] _recentActivity) { _id = id; _idx = recentActivityIdx; for (uint i = 0; i < recentActivity.length; i++) { _recentActivity[i] = recentActivity[i]; } } function setAdmin(address _admin) onlyOwner { admin = _admin; } function proposeOwner(address _owner) onlyOwner { proposedOwner = _owner; } function acceptOwnership() { require(proposedOwner != 0); require(msg.sender == proposedOwner); owner = proposedOwner; } function destruct() onlyOwner { require(now - lastInitTimestamp > INACTIVITY_TIMEOUT); selfdestruct(owner); } }
0
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract B2ANDcoin is Ownable { string public name; string public symbol; 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 Burn(address indexed from, uint256 value); function B2ANDcoin( ) public { totalSupply = 100000000 * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = "B2ANDcoin"; symbol = "B2C"; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } 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; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
1
pragma solidity ^0.4.19; contract ERC721 { function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function takeOwnership(uint256 _tokenId) public; function implementsERC721() public pure returns (bool); event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); function supportsInterface(bytes4 _interfaceID) external view returns (bool); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a; } else { return b; } } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } } contract ClockAuctionBase { struct Auction { address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; } ERC721 public nonFungibleContract; uint256 public ownerCut; mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _transfer(address _receiver, uint256 _tokenId) internal { nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal { require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } uint256 bidExcess = _bidAmount - price; msg.sender.transfer(bidExcess); AuctionSuccessful(_tokenId, price, msg.sender); return price; } function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256) { return SafeMath.mul(_price, SafeMath.div(ownerCut,10000)); } } contract EthernautsBase { bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); uint8 public constant STATS_SIZE = 10; uint8 public constant SHIP_SLOTS = 5; enum AssetState { Available, UpForLease, Used } enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember } enum ShipStats {Level, Attack, Defense, Speed, Range, Luck} bytes2 public ATTR_SEEDED = bytes2(2**0); bytes2 public ATTR_PRODUCIBLE = bytes2(2**1); bytes2 public ATTR_EXPLORABLE = bytes2(2**2); bytes2 public ATTR_LEASABLE = bytes2(2**3); bytes2 public ATTR_PERMANENT = bytes2(2**4); bytes2 public ATTR_CONSUMABLE = bytes2(2**5); bytes2 public ATTR_TRADABLE = bytes2(2**6); bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7); } contract EthernautsAccessControl is EthernautsBase { event ContractUpgrade(address newContract); address public ceoAddress; address public ctoAddress; address public cooAddress; address public oracleAddress; bool public paused = false; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCTO() { require(msg.sender == ctoAddress); _; } modifier onlyOracle() { require(msg.sender == oracleAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == ctoAddress || msg.sender == cooAddress ); _; } function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCTO(address _newCTO) external { require( msg.sender == ceoAddress || msg.sender == ctoAddress ); require(_newCTO != address(0)); ctoAddress = _newCTO; } function setCOO(address _newCOO) external { require( msg.sender == ceoAddress || msg.sender == cooAddress ); require(_newCOO != address(0)); cooAddress = _newCOO; } function setOracle(address _newOracle) external { require(msg.sender == ctoAddress); require(_newOracle != address(0)); oracleAddress = _newOracle; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() external onlyCLevel whenNotPaused { paused = true; } function unpause() public onlyCEO whenPaused { paused = false; } } contract EthernautsStorage is EthernautsAccessControl { function EthernautsStorage() public { ceoAddress = msg.sender; ctoAddress = msg.sender; cooAddress = msg.sender; oracleAddress = msg.sender; } function() external payable { require(msg.sender == address(this)); } mapping (address => bool) public contractsGrantedAccess; function grantAccess(address _v2Address) public onlyCTO { contractsGrantedAccess[_v2Address] = true; } function removeAccess(address _v2Address) public onlyCTO { delete contractsGrantedAccess[_v2Address]; } modifier onlyGrantedContracts() { require(contractsGrantedAccess[msg.sender] == true); _; } modifier validAsset(uint256 _tokenId) { require(assets[_tokenId].ID > 0); _; } struct Asset { uint16 ID; uint8 category; uint8 state; bytes2 attributes; uint64 createdAt; uint64 cooldownEndBlock; uint8[STATS_SIZE] stats; uint256 cooldown; uint256 builtBy; } bool public isEthernautsStorage = true; Asset[] public assets; mapping (uint256 => uint256) internal assetIndexToPrice; mapping (uint256 => address) internal assetIndexToOwner; mapping (address => uint256) internal ownershipTokenCount; mapping (uint256 => address) internal assetIndexToApproved; function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts { assetIndexToPrice[_tokenId] = _price; } function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts { assetIndexToApproved[_tokenId] = _approved; } function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts { ownershipTokenCount[_to]++; assetIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete assetIndexToApproved[_tokenId]; } } function createAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) public onlyGrantedContracts returns (uint256) { require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); Asset memory asset = Asset({ ID: _ID, category: _category, builtBy: _creatorTokenID, attributes: bytes2(_attributes), stats: _stats, state: _state, createdAt: uint64(now), cooldownEndBlock: _cooldownEndBlock, cooldown: _cooldown }); uint256 newAssetUniqueId = assets.push(asset) - 1; require(newAssetUniqueId == uint256(uint32(newAssetUniqueId))); assetIndexToPrice[newAssetUniqueId] = _price; transfer(address(0), _owner, newAssetUniqueId); return newAssetUniqueId; } function editAsset( uint256 _tokenId, uint256 _creatorTokenID, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint16 _cooldown ) external validAsset(_tokenId) onlyCLevel returns (uint256) { require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); assetIndexToPrice[_tokenId] = _price; Asset storage asset = assets[_tokenId]; asset.ID = _ID; asset.category = _category; asset.builtBy = _creatorTokenID; asset.attributes = bytes2(_attributes); asset.stats = _stats; asset.state = _state; asset.cooldown = _cooldown; } function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].stats = _stats; } function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].state = _state; } function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].cooldown = _cooldown; assets[_tokenId].cooldownEndBlock = _cooldownEndBlock; } function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) { return assets[_tokenId].stats; } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return assetIndexToPrice[_tokenId]; } function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes == _attributes; } function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes != 0x0; } function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) { return assets[_tokenId].category == _category; } function isState(uint256 _tokenId, uint8 _state) public view returns (bool) { return assets[_tokenId].state == _state; } function ownerOf(uint256 _tokenId) public view returns (address owner) { return assetIndexToOwner[_tokenId]; } function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) { return assetIndexToApproved[_tokenId]; } function totalSupply() public view returns (uint256) { return assets.length; } function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns( uint256[6][] ) { uint256 totalAssets = assets.length; if (totalAssets == 0) { return new uint256[6][](0); } else { uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets); uint256 resultIndex = 0; bytes2 hasAttributes = bytes2(_withAttributes); Asset memory asset; for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) { asset = assets[tokenId]; if ( (asset.state != uint8(AssetState.Used)) && (assetIndexToOwner[tokenId] == _owner || _owner == address(0)) && (asset.attributes & hasAttributes == hasAttributes) ) { result[resultIndex][0] = tokenId; result[resultIndex][1] = asset.ID; result[resultIndex][2] = asset.category; result[resultIndex][3] = uint256(asset.attributes); result[resultIndex][4] = asset.cooldown; result[resultIndex][5] = assetIndexToPrice[tokenId]; resultIndex++; } } return result; } } } contract EthernautsOwnership is EthernautsAccessControl, ERC721 { EthernautsStorage public ethernautsStorage; string public constant name = "Ethernauts"; string public constant symbol = "ETNT"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed owner, address indexed approved, uint256 tokens); event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price); function implementsERC721() public pure returns (bool) { return true; } function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.ownerOf(_tokenId) == _claimant; } function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.approvedFor(_tokenId) == _claimant; } function _approve(uint256 _tokenId, address _approved) internal { ethernautsStorage.approve(_tokenId, _approved); } function balanceOf(address _owner) public view returns (uint256 count) { return ethernautsStorage.balanceOf(_owner); } function transfer( address _to, uint256 _tokenId ) external whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_to != address(ethernautsStorage)); require(_owns(msg.sender, _tokenId)); ethernautsStorage.transfer(msg.sender, _to, _tokenId); } function approve( address _to, uint256 _tokenId ) external whenNotPaused { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } function _transferFrom( address _from, address _to, uint256 _tokenId ) internal { require(_to != address(0)); require(_owns(_from, _tokenId)); require(_approvedFor(_to, _tokenId)); ethernautsStorage.transfer(_from, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { _transferFrom(_from, _to, _tokenId); } function takeOwnership(uint256 _tokenId) public { address _from = ethernautsStorage.ownerOf(_tokenId); require(_from != address(0)); _transferFrom(_from, msg.sender, _tokenId); } function totalSupply() public view returns (uint256) { return ethernautsStorage.totalSupply(); } function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ethernautsStorage.ownerOf(_tokenId); require(owner != address(0)); } function createNewAsset( uint256 _creatorTokenID, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats ) external onlyCLevel returns (uint256) { require(msg.sender != address(0)); uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, msg.sender, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, 0, 0 ); Build( msg.sender, tokenID, _assetID, _price ); return tokenID; } function isExploring(uint256 _tokenId) public view returns (bool) { uint256 cooldown; uint64 cooldownEndBlock; (,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId); return (cooldown > now) || (cooldownEndBlock > uint64(block.number)); } } contract EthernautsLogic is EthernautsOwnership { address public newContractAddress; function EthernautsLogic() public { ceoAddress = msg.sender; ctoAddress = msg.sender; cooAddress = msg.sender; oracleAddress = msg.sender; paused = true; } function setNewAddress(address _v2Address) external onlyCTO whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused { EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress); require(candidateContract.isEthernautsStorage()); ethernautsStorage = candidateContract; } function unpause() public onlyCEO whenPaused { require(ethernautsStorage != address(0)); require(newContractAddress == address(0)); require(ethernautsStorage.contractsGrantedAccess(address(this)) == true); super.unpause(); } function withdrawBalances(address _to) public onlyCLevel { _to.transfer(this.balance); } function getBalance() public view onlyCLevel returns (uint256) { return this.balance; } } contract EthernautsMarket is EthernautsLogic, ClockAuctionBase { function EthernautsMarket(uint256 _cut) public EthernautsLogic() { require(_cut <= 10000); ownerCut = _cut; nonFungibleContract = this; } event Purchase(uint256 indexed tokenId, uint256 oldPrice, uint256 newPrice, address indexed prevOwner, address indexed winner); uint8 private percentageFee1Step = 95; uint8 private percentageFee2Step = 95; uint8 private percentageFeeSteps = 98; uint8 private percentageBase = 100; uint8 private percentage1Step = 200; uint8 private percentage2Step = 125; uint8 private percentageSteps = 115; uint256 private firstStepLimit = 0.05 ether; uint256 private secondStepLimit = 5 ether; function bid(uint256 _tokenId) external payable whenNotPaused { uint256 newPrice = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); ethernautsStorage.setPrice(_tokenId, newPrice); } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyCLevel external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } function createSaleAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); require(ethernautsStorage.hasAllAttrs(_tokenId, ATTR_TRADABLE)); require(!ethernautsStorage.hasAllAttrs(_tokenId, ATTR_GOLDENGOOSE)); require(ethernautsStorage.isState(_tokenId, uint8(AssetState.Available))); require(!isExploring(_tokenId)); ethernautsStorage.approve(_tokenId, address(this)); _transferFrom(msg.sender, this, _tokenId); Auction memory auction = Auction( msg.sender, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } function setOwnerCut(uint256 _ownerCut) public onlyCLevel { ownerCut = _ownerCut; } function purchase(uint256 _tokenId) external payable whenNotPaused { require(ethernautsStorage.hasAnyAttrs(_tokenId, ATTR_GOLDENGOOSE)); require(!isExploring(_tokenId)); address oldOwner = ethernautsStorage.ownerOf(_tokenId); address newOwner = msg.sender; uint256 sellingPrice = ethernautsStorage.priceOf(_tokenId); require(oldOwner != newOwner); require(newOwner != address(0)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, percentageFee1Step), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); uint256 newPrice = sellingPrice; if (sellingPrice < firstStepLimit) { newPrice = SafeMath.div(SafeMath.mul(sellingPrice, percentage1Step), percentageBase); } else if (sellingPrice < secondStepLimit) { payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, percentageFee2Step), 100)); newPrice = SafeMath.div(SafeMath.mul(sellingPrice, percentage2Step), percentageBase); } else { payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, percentageFeeSteps), 100)); newPrice = SafeMath.div(SafeMath.mul(sellingPrice, percentageSteps), percentageBase); } if (oldOwner != address(this)) { oldOwner.transfer(payment); } ethernautsStorage.transfer(oldOwner, newOwner, _tokenId); ethernautsStorage.setPrice(_tokenId, newPrice); Purchase(_tokenId, sellingPrice, newPrice, oldOwner, newOwner); msg.sender.transfer(purchaseExcess); } function setStepLimits( uint256 _firstStepLimit, uint256 _secondStepLimit ) public onlyCLevel { firstStepLimit = _firstStepLimit; secondStepLimit = _secondStepLimit; } function setPercentages( uint8 _Fee1, uint8 _Fee2, uint8 _Fees, uint8 _1Step, uint8 _2Step, uint8 _Steps ) public onlyCLevel { percentageFee1Step = _Fee1; percentageFee2Step = _Fee2; percentageFeeSteps = _Fees; percentage1Step = _1Step; percentage2Step = _2Step; percentageSteps = _Steps; } }
0
pragma solidity ^0.4.24; library ExtendedMath { function limitLessThan(uint a, uint b) internal pure returns(uint c) { if (a > b) return b; return a; } } library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns(uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns(uint256) { require(_b > 0); uint256 c = _a / _b; return c; } function sub(uint256 _a, uint256 _b) internal pure returns(uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } function add(uint256 _a, uint256 _b) internal pure returns(uint256) { uint256 c = _a + _b; require(c >= _a); return c; } function mod(uint256 a, uint256 b) internal pure returns(uint256) { require(b != 0); return a % b; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ERC20Basic { function totalSupply() public view returns(uint256); function balanceOf(address _who) public view returns(uint256); function transfer(address _to, uint256 _value) public returns(bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns(uint256); function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function approve(address _spender, uint256 _value) public returns(bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; function totalSupply() public view returns(uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns(bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns(bool) { require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns(uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint256 _addedValue ) public returns(bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns(bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } interface IRemoteFunctions { function _externalAddMasternode(address) external; function _externalStopMasternode(address) external; } interface IcaelumVoting { function getTokenProposalDetails() external view returns(address, uint, uint, uint); function getExpiry() external view returns (uint); function getContractType () external view returns (uint); } interface EIP918Interface { function mint(uint256 nonce, bytes32 challenge_digest) external returns (bool success); function getChallengeNumber() external constant returns (bytes32); function getMiningDifficulty() external constant returns (uint); function getMiningTarget() external constant returns (uint); function getMiningReward() external constant returns (uint); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); } contract NewMinerProposal is IcaelumVoting { enum VOTE_TYPE {MINER, MASTER, TOKEN} VOTE_TYPE public contractType = VOTE_TYPE.TOKEN; address contractAddress; uint validUntil; uint votingDurationInDays; constructor(address _contract, uint _valid, uint _voteDuration) public { require(_voteDuration >= 14 && _voteDuration <= 50, "Proposed voting duration does not meet requirements"); contractAddress = _contract; validUntil = _valid; votingDurationInDays = _voteDuration; } function getTokenProposalDetails() public view returns(address, uint, uint, uint) { return (contractAddress, 0, validUntil, uint(contractType)); } function getExpiry() external view returns (uint) { return votingDurationInDays; } function getContractType () external view returns (uint){ return uint(contractType); } } contract CaelumVotings is Ownable { using SafeMath for uint; enum VOTE_TYPE {MINER, MASTER, TOKEN} struct Proposals { address tokenContract; uint totalVotes; uint proposedOn; uint acceptedOn; VOTE_TYPE proposalType; } struct Voters { bool isVoter; address owner; uint[] votedFor; } uint MAJORITY_PERCENTAGE_NEEDED = 60; uint MINIMUM_VOTERS_NEEDED = 1; bool public proposalPending; mapping(uint => Proposals) public proposalList; mapping (address => Voters) public voterMap; mapping(uint => address) public voterProposals; uint public proposalCounter; uint public votersCount; uint public votersCountTeam; function setMasternodeContractFromVote(address _t) internal ; function setTokenContractFromVote(address _t) internal; function setMiningContractFromVote (address _t) internal; event NewProposal(uint ProposalID); event ProposalAccepted(uint ProposalID); address _CaelumMasternodeContract; CaelumMasternode public MasternodeContract; function setMasternodeContractForData(address _t) onlyOwner public { MasternodeContract = CaelumMasternode(_t); _CaelumMasternodeContract = (_t); } function setVotingMinority(uint _total) onlyOwner public { require(_total > MINIMUM_VOTERS_NEEDED); MINIMUM_VOTERS_NEEDED = _total; } function pushProposal(address _contract) onlyOwner public returns (uint) { if(proposalCounter != 0) require (pastProposalTimeRules (), "You need to wait 90 days before submitting a new proposal."); require (!proposalPending, "Another proposal is pending."); uint _contractType = IcaelumVoting(_contract).getContractType(); proposalList[proposalCounter] = Proposals(_contract, 0, now, 0, VOTE_TYPE(_contractType)); emit NewProposal(proposalCounter); proposalCounter++; proposalPending = true; return proposalCounter.sub(1); } function handleLastProposal () internal returns (uint) { uint _ID = proposalCounter.sub(1); proposalList[_ID].acceptedOn = now; proposalPending = false; address _address; uint _required; uint _valid; uint _type; (_address, _required, _valid, _type) = getTokenProposalDetails(_ID); if(_type == uint(VOTE_TYPE.MINER)) { setMiningContractFromVote(_address); } if(_type == uint(VOTE_TYPE.MASTER)) { setMasternodeContractFromVote(_address); } if(_type == uint(VOTE_TYPE.TOKEN)) { setTokenContractFromVote(_address); } emit ProposalAccepted(_ID); return _ID; } function discardRejectedProposal() onlyOwner public returns (bool) { require(proposalPending); require (LastProposalCanDiscard()); proposalPending = false; return (true); } function LastProposalCanDiscard () public view returns (bool) { uint daysBeforeDiscard = IcaelumVoting(proposalList[proposalCounter - 1].tokenContract).getExpiry(); uint entryDate = proposalList[proposalCounter - 1].proposedOn; uint expiryDate = entryDate + (daysBeforeDiscard * 1 days); if (now >= expiryDate) return true; } function getTokenProposalDetails(uint proposalID) public view returns(address, uint, uint, uint) { return IcaelumVoting(proposalList[proposalID].tokenContract).getTokenProposalDetails(); } function pastProposalTimeRules() public view returns (bool) { uint lastProposal = proposalList[proposalCounter - 1].proposedOn; if (now >= lastProposal + 90 days) return true; } function becomeVoter() public { require (MasternodeContract.isMasternodeOwner(msg.sender), "User has no masternodes"); require (!voterMap[msg.sender].isVoter, "User Already voted for this proposal"); voterMap[msg.sender].owner = msg.sender; voterMap[msg.sender].isVoter = true; votersCount = votersCount + 1; if (MasternodeContract.isTeamMember(msg.sender)) votersCountTeam = votersCountTeam + 1; } function voteProposal(uint proposalID) public returns (bool success) { require(voterMap[msg.sender].isVoter, "Sender not listed as voter"); require(proposalID >= 0, "No proposal was selected."); require(proposalID <= proposalCounter, "Proposal out of limits."); require(voterProposals[proposalID] != msg.sender, "Already voted."); require(votersCount >= MINIMUM_VOTERS_NEEDED, "Not enough voters in existence to push a proposal"); voterProposals[proposalID] = msg.sender; proposalList[proposalID].totalVotes++; if(reachedMajority(proposalID)) { handleLastProposal(); return true; } } function reachedMajority (uint proposalID) public view returns (bool) { uint getProposalVotes = proposalList[proposalID].totalVotes; if (getProposalVotes >= majority()) return true; } function majority () internal view returns (uint) { uint a = (votersCount * MAJORITY_PERCENTAGE_NEEDED ); return a / 100; } function reachedMajorityForTeam (uint proposalID) public view returns (bool) { uint getProposalVotes = proposalList[proposalID].totalVotes; if (getProposalVotes >= majorityForTeam()) return true; } function majorityForTeam () internal view returns (uint) { uint a = (votersCountTeam * MAJORITY_PERCENTAGE_NEEDED ); return a / 100; } } contract CaelumAcceptERC20 is Ownable { using SafeMath for uint; IRemoteFunctions public DataVault; address[] public tokensList; bool setOwnContract = true; struct _whitelistTokens { address tokenAddress; bool active; uint requiredAmount; uint validUntil; uint timestamp; } mapping(address => mapping(address => uint)) public tokens; mapping(address => _whitelistTokens) acceptedTokens; event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); function addOwnToken() onlyOwner public returns (bool) { require(setOwnContract); addToWhitelist(this, 5000 * 1e8, 36500); setOwnContract = false; return true; } function addToWhitelist(address _token, uint _amount, uint daysAllowed) internal { _whitelistTokens storage newToken = acceptedTokens[_token]; newToken.tokenAddress = _token; newToken.requiredAmount = _amount; newToken.timestamp = now; newToken.validUntil = now + (daysAllowed * 1 days); newToken.active = true; tokensList.push(_token); } function isAcceptedToken(address _ad) internal view returns(bool) { return acceptedTokens[_ad].active; } function getAcceptedTokenAmount(address _ad) internal view returns(uint) { return acceptedTokens[_ad].requiredAmount; } function isValid(address _ad) internal view returns(bool) { uint endTime = acceptedTokens[_ad].validUntil; if (block.timestamp < endTime) return true; return false; } function listAcceptedTokens() public view returns(address[]) { return tokensList; } function getTokenDetails(address token) public view returns(address ad,uint required, bool active, uint valid) { return (acceptedTokens[token].tokenAddress, acceptedTokens[token].requiredAmount,acceptedTokens[token].active, acceptedTokens[token].validUntil); } function depositCollateral(address token, uint amount) public { require(isAcceptedToken(token), "ERC20 not authorised"); require(amount == getAcceptedTokenAmount(token)); require(isValid(token)); tokens[token][msg.sender] = tokens[token][msg.sender].add(amount); require(StandardToken(token).transferFrom(msg.sender, this, amount), "error with token"); emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]); DataVault._externalAddMasternode(msg.sender); } function withdrawCollateral(address token, uint amount) public { require(token != 0); require(isAcceptedToken(token), "ERC20 not authorised"); require(amount == getAcceptedTokenAmount(token)); require(tokens[token][msg.sender] >= amount); uint amountToWithdraw = tokens[token][msg.sender]; tokens[token][msg.sender] = 0; DataVault._externalStopMasternode(msg.sender); if (!StandardToken(token).transfer(msg.sender, amountToWithdraw)) revert(); emit Withdraw(token, msg.sender, amountToWithdraw, amountToWithdraw); } function setDataStorage (address _masternodeContract) onlyOwner public { DataVault = IRemoteFunctions(_masternodeContract); } } contract CaelumAbstractMasternode is Ownable{ using SafeMath for uint; bool onTestnet = false; bool genesisAdded = false; uint public masternodeRound; uint public masternodeCandidate; uint public masternodeCounter; uint public masternodeEpoch; uint public miningEpoch; uint public rewardsProofOfWork; uint public rewardsMasternode; uint rewardsGlobal = 50 * 1e8; uint public MINING_PHASE_DURATION_BLOCKS = 4500; struct MasterNode { address accountOwner; bool isActive; bool isTeamMember; uint storedIndex; uint startingRound; uint[] indexcounter; } uint[] userArray; address[] userAddressArray; mapping(uint => MasterNode) userByIndex; mapping(address => MasterNode) userByAddress; mapping(address => uint) userAddressIndex; event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); event NewMasternode(address candidateAddress, uint timeStamp); event RemovedMasternode(address candidateAddress, uint timeStamp); function addGenesis(address _genesis, bool _team) onlyOwner public { require(!genesisAdded); addMasternode(_genesis); if (_team) { updateMasternodeAsTeamMember(msg.sender); } } function closeGenesis() onlyOwner public { genesisAdded = true; } function addMasternode(address _candidate) internal returns(uint) { userByIndex[masternodeCounter].accountOwner = _candidate; userByIndex[masternodeCounter].isActive = true; userByIndex[masternodeCounter].startingRound = masternodeRound + 1; userByIndex[masternodeCounter].storedIndex = masternodeCounter; userByAddress[_candidate].accountOwner = _candidate; userByAddress[_candidate].indexcounter.push(masternodeCounter); userArray.push(userArray.length); masternodeCounter++; emit NewMasternode(_candidate, now); return masternodeCounter - 1; } function updateMasternode(uint _candidate) internal returns(bool) { userByIndex[_candidate].startingRound++; return true; } function updateMasternodeAsTeamMember(address _member) internal returns (bool) { userByAddress[_member].isTeamMember = true; return (true); } function isTeamMember (address _member) public view returns (bool) { if (userByAddress[_member].isTeamMember) return true; } function deleteMasternode(uint _masternodeID) internal returns(bool success) { uint rowToDelete = userByIndex[_masternodeID].storedIndex; uint keyToMove = userArray[userArray.length - 1]; userByIndex[_masternodeID].isActive = userByIndex[_masternodeID].isActive = (false); userArray[rowToDelete] = keyToMove; userByIndex[keyToMove].storedIndex = rowToDelete; userArray.length = userArray.length - 1; removeFromUserCounter(_masternodeID); emit RemovedMasternode(userByIndex[_masternodeID].accountOwner, now); return true; } function isPartOf(uint mnid) public view returns (address) { return userByIndex[mnid].accountOwner; } function removeFromUserCounter(uint index) internal returns(uint[]) { address belong = isPartOf(index); if (index >= userByAddress[belong].indexcounter.length) return; for (uint i = index; i<userByAddress[belong].indexcounter.length-1; i++){ userByAddress[belong].indexcounter[i] = userByAddress[belong].indexcounter[i+1]; } delete userByAddress[belong].indexcounter[userByAddress[belong].indexcounter.length-1]; userByAddress[belong].indexcounter.length--; return userByAddress[belong].indexcounter; } function setMasternodeCandidate() internal returns(address) { uint hardlimitCounter = 0; while (getFollowingCandidate() == 0x0) { require(hardlimitCounter < 6, "Failsafe switched on"); if (hardlimitCounter == 5) return (0); masternodeRound = masternodeRound + 1; masternodeCandidate = 0; hardlimitCounter++; } if (masternodeCandidate == masternodeCounter - 1) { masternodeRound = masternodeRound + 1; masternodeCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeCounter; i++) { if (userByIndex[i].isActive) { if (userByIndex[i].startingRound == masternodeRound) { updateMasternode(i); masternodeCandidate = i; return (userByIndex[i].accountOwner); } } } masternodeRound = masternodeRound + 1; return (0); } function getFollowingCandidate() internal view returns(address _address) { uint tmpRound = masternodeRound; uint tmpCandidate = masternodeCandidate; if (tmpCandidate == masternodeCounter - 1) { tmpRound = tmpRound + 1; tmpCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeCounter; i++) { if (userByIndex[i].isActive) { if (userByIndex[i].startingRound == tmpRound) { tmpCandidate = i; return (userByIndex[i].accountOwner); } } } tmpRound = tmpRound + 1; return (0); } function belongsToUser(address userAddress) public view returns(uint[]) { return (userByAddress[userAddress].indexcounter); } function isMasternodeOwner(address _candidate) public view returns(bool) { if(userByAddress[_candidate].indexcounter.length <= 0) return false; if (userByAddress[_candidate].accountOwner == _candidate) return true; } function getLastPerUser(address _candidate) public view returns (uint) { return userByAddress[_candidate].indexcounter[userByAddress[_candidate].indexcounter.length - 1]; } function getMiningReward() public view returns(uint) { return 50 * 1e8; } function calculateRewardStructures() internal { uint _global_reward_amount = getMiningReward(); uint getStageOfMining = miningEpoch / MINING_PHASE_DURATION_BLOCKS * 10; if (getStageOfMining < 10) { rewardsProofOfWork = _global_reward_amount / 100 * 5; rewardsMasternode = 0; return; } if (getStageOfMining > 90) { rewardsProofOfWork = _global_reward_amount / 100 * 2; rewardsMasternode = _global_reward_amount / 100 * 98; return; } uint _mnreward = (_global_reward_amount / 100) * getStageOfMining; uint _powreward = (_global_reward_amount - _mnreward); setBaseRewards(_powreward, _mnreward); } function setBaseRewards(uint _pow, uint _mn) internal { rewardsMasternode = _mn; rewardsProofOfWork = _pow; } function _arrangeMasternodeFlow() internal { calculateRewardStructures(); setMasternodeCandidate(); miningEpoch++; } function _emergencyLoop() onlyOwner public { calculateRewardStructures(); setMasternodeCandidate(); miningEpoch++; } function masternodeInfo(uint index) public view returns ( address, bool, uint, uint ) { return ( userByIndex[index].accountOwner, userByIndex[index].isActive, userByIndex[index].storedIndex, userByIndex[index].startingRound ); } function contractProgress() public view returns ( uint epoch, uint candidate, uint round, uint miningepoch, uint globalreward, uint powreward, uint masternodereward, uint usercounter ) { return ( masternodeEpoch, masternodeCandidate, masternodeRound, miningEpoch, getMiningReward(), rewardsProofOfWork, rewardsMasternode, masternodeCounter ); } } contract CaelumMasternode is CaelumVotings, CaelumAbstractMasternode { address public miningContract; address public tokenContract; bool minerSet = false; bool tokenSet = false; function setMiningContract(address _t) onlyOwner public { require(!minerSet); miningContract = _t; minerSet = true; } function setTokenContract(address _t) onlyOwner public { require(!tokenSet); tokenContract = _t; tokenSet = true; } function setMasternodeContractFromVote(address _t) internal { } function setTokenContractFromVote(address _t) internal{ tokenContract = _t; } function setMiningContractFromVote (address _t) internal { miningContract = _t; } modifier onlyMiningContract() { require(msg.sender == miningContract); _; } modifier onlyTokenContract() { require(msg.sender == tokenContract); _; } modifier bothRemoteContracts() { require(msg.sender == tokenContract || msg.sender == miningContract); _; } function _externalArrangeFlow() onlyMiningContract external { _arrangeMasternodeFlow(); } function _externalAddMasternode(address _received) onlyMiningContract external { addMasternode(_received); } function _externalStopMasternode(address _received) onlyMiningContract external { deleteMasternode(getLastPerUser(_received)); } function getMiningReward() public view returns(uint) { return CaelumMiner(miningContract).getMiningReward(); } address cloneDataFrom = 0x7600bF5112945F9F006c216d5d6db0df2806eDc6; function getDataFromContract () onlyOwner public returns(uint) { CaelumMasternode prev = CaelumMasternode(cloneDataFrom); (uint epoch, uint candidate, uint round, uint miningepoch, uint globalreward, uint powreward, uint masternodereward, uint usercounter) = prev.contractProgress(); masternodeEpoch = epoch; masternodeRound = round; miningEpoch = miningepoch; rewardsProofOfWork = powreward; rewardsMasternode = masternodereward; } } contract CaelumToken is Ownable, StandardToken, CaelumVotings, CaelumAcceptERC20 { using SafeMath for uint; ERC20 previousContract; bool contractSet = false; bool public swapClosed = false; uint public swapCounter; string public symbol = "CLM"; string public name = "Caelum Token"; uint8 public decimals = 8; uint256 public totalSupply = 2100000000000000; address public miningContract = 0x0; modifier onlyMiningContract() { require(msg.sender == miningContract); _; } constructor(address _previousContract) public { previousContract = ERC20(_previousContract); swapClosed = false; swapCounter = 0; } function setMiningContract (address _t) onlyOwner public { require(!contractSet); miningContract = _t; contractSet = true; } function setMasternodeContractFromVote(address _t) internal { return; } function setTokenContractFromVote(address _t) internal{ return; } function setMiningContractFromVote (address _t) internal { miningContract = _t; } function changeSwapState (bool _state) onlyOwner public { require(swapCounter <= 9); swapClosed = _state; swapCounter++; } function rewardExternal(address _receiver, uint _amount) onlyMiningContract external { balances[_receiver] = balances[_receiver].add(_amount); emit Transfer(this, _receiver, _amount); } function upgradeTokens() public{ require(!swapClosed); uint amountToUpgrade = previousContract.balanceOf(msg.sender); require(amountToUpgrade <= previousContract.allowance(msg.sender, this)); if(previousContract.transferFrom(msg.sender, this, amountToUpgrade)){ balances[msg.sender] = balances[msg.sender].add(amountToUpgrade); emit Transfer(this, msg.sender, amountToUpgrade); } require(previousContract.balanceOf(msg.sender) == 0); } } contract AbstractERC918 is EIP918Interface { bytes32 public challengeNumber; uint public difficulty; uint public tokensMinted; struct Statistics { address lastRewardTo; uint lastRewardAmount; uint lastRewardEthBlockNumber; uint lastRewardTimestamp; } Statistics public statistics; function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success); function _hash(uint256 nonce, bytes32 challenge_digest) internal returns (bytes32 digest); function _reward() internal returns (uint); function _newEpoch(uint256 nonce) internal returns (uint); function _adjustDifficulty() internal returns (uint); } contract CaelumAbstractMiner is AbstractERC918 { using SafeMath for uint; using ExtendedMath for uint; uint256 public totalSupply = 2100000000000000; uint public latestDifficultyPeriodStarted; uint public epochCount; uint public baseMiningReward = 50; uint public blocksPerReadjustment = 512; uint public _MINIMUM_TARGET = 2 ** 16; uint public _MAXIMUM_TARGET = 2 ** 234; uint public rewardEra = 0; uint public maxSupplyForEra; uint public MAX_REWARD_ERA = 39; uint public MINING_RATE_FACTOR = 60; uint public MAX_ADJUSTMENT_PERCENT = 100; uint public TARGET_DIVISOR = 2000; uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2); mapping(bytes32 => bytes32) solutionForChallenge; mapping(address => mapping(address => uint)) allowed; bytes32 public challengeNumber; uint public difficulty; uint public tokensMinted; Statistics public statistics; event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); event RewardMasternode(address candidate, uint amount); constructor() public { tokensMinted = 0; maxSupplyForEra = totalSupply.div(2); difficulty = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; _newEpoch(0); } function _newEpoch(uint256 nonce) internal returns(uint) { if (tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA) { rewardEra = rewardEra + 1; } maxSupplyForEra = totalSupply - totalSupply.div(2 ** (rewardEra + 1)); epochCount = epochCount.add(1); challengeNumber = blockhash(block.number - 1); return (epochCount); } function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success); function _hash(uint256 nonce, bytes32 challenge_digest) internal returns(bytes32 digest) { digest = keccak256(challengeNumber, msg.sender, nonce); if (digest != challenge_digest) revert(); if (uint256(digest) > difficulty) revert(); bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if (solution != 0x0) revert(); } function _reward() internal returns(uint); function _reward_masternode() internal returns(uint); function _adjustDifficulty() internal returns(uint) { if (epochCount % blocksPerReadjustment != 0) { return difficulty; } uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; uint epochsMined = blocksPerReadjustment; uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR; if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(ethBlocksSinceLastDifficultyPeriod); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra)); } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(targetEthBlocksPerDiffPeriod); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra)); } latestDifficultyPeriodStarted = block.number; if (difficulty < _MINIMUM_TARGET) { difficulty = _MINIMUM_TARGET; } if (difficulty > _MAXIMUM_TARGET) { difficulty = _MAXIMUM_TARGET; } } function getChallengeNumber() public view returns(bytes32) { return challengeNumber; } function getMiningDifficulty() public view returns(uint) { return _MAXIMUM_TARGET.div(difficulty); } function getMiningTarget() public view returns(uint) { return difficulty; } function getMiningReward() public view returns(uint) { return (baseMiningReward * 1e8).div(2 ** rewardEra); } function getMintDigest( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number ) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); return digest; } function checkMintSolution( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget ) public view returns(bool success) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); if (uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } } contract CaelumMiner is CaelumVotings, CaelumAbstractMiner { address cloneDataFrom = 0x7600bF5112945F9F006c216d5d6db0df2806eDc6; bool ACTIVE_CONTRACT_STATE = true; bool MasternodeSet = false; bool TokenSet = false; address _CaelumMasternodeContract; address _CaelumTokenContract; CaelumMasternode public MasternodeContract; CaelumToken public tokenContract; function setMasternodeContract(address _t) onlyOwner public { require(!MasternodeSet); MasternodeContract = CaelumMasternode(_t); _CaelumMasternodeContract = (_t); MasternodeSet = true; } function setTokenContract(address _t) onlyOwner public { require(!TokenSet); tokenContract = CaelumToken(_t); _CaelumTokenContract = (_t); TokenSet = true; } function setMiningContract (address _t) onlyOwner public { return; } function setMasternodeContractFromVote(address _t) internal { MasternodeContract = CaelumMasternode(_t); _CaelumMasternodeContract = (_t); } function setTokenContractFromVote(address _t) internal{ tokenContract = CaelumToken(_t); _CaelumTokenContract = (_t); } function setMiningContractFromVote (address _t) internal { return; } function lockMiningContract () onlyOwner public { ACTIVE_CONTRACT_STATE = false; } function getDataFromContract () onlyOwner public { require(_CaelumTokenContract != 0); require(_CaelumMasternodeContract != 0); CaelumMiner prev = CaelumMiner(cloneDataFrom); difficulty = prev.difficulty(); rewardEra = prev.rewardEra(); MINING_RATE_FACTOR = prev.MINING_RATE_FACTOR(); maxSupplyForEra = prev.maxSupplyForEra(); tokensMinted = prev.tokensMinted(); epochCount = prev.epochCount(); latestDifficultyPeriodStarted = prev.latestDifficultyPeriodStarted(); ACTIVE_CONTRACT_STATE = true; } function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) { require(ACTIVE_CONTRACT_STATE); _hash(nonce, challenge_digest); MasternodeContract._externalArrangeFlow(); uint rewardAmount =_reward(); uint rewardMasternode = _reward_masternode(); tokensMinted += rewardAmount.add(rewardMasternode); uint epochCounter = _newEpoch(nonce); _adjustDifficulty(); statistics = Statistics(msg.sender, rewardAmount, block.number, now); emit Mint(msg.sender, rewardAmount, epochCounter, challengeNumber); return true; } function _reward() internal returns(uint) { uint _pow = MasternodeContract.rewardsProofOfWork(); tokenContract.rewardExternal(msg.sender, _pow); return _pow; } function _reward_masternode() internal returns(uint) { uint _mnReward = MasternodeContract.rewardsMasternode(); if (MasternodeContract.masternodeCounter() == 0) return 0; uint getCandidate = MasternodeContract.masternodeCandidate(); address _mnCandidate = MasternodeContract.isPartOf(getCandidate); if (_mnCandidate == 0x0) return 0; tokenContract.rewardExternal(_mnCandidate, _mnReward); emit RewardMasternode(_mnCandidate, _mnReward); return _mnReward; } function getMiningReward() public view returns(uint) { return MasternodeContract.rewardsProofOfWork(); } } contract caelumFactory { CaelumMiner public MINER; CaelumMasternode public MASTER; CaelumToken public TOKEN; function newCookie() public { MINER = new CaelumMiner(); MASTER = new CaelumMasternode(); TOKEN = new CaelumToken(0x0); MASTER.setMiningContract(MINER); MASTER.setTokenContract(TOKEN); MINER.setMasternodeContract(MASTER); MINER.setTokenContract(TOKEN); TOKEN.setMiningContract(MINER); TOKEN.setDataStorage(MASTER); MASTER.transferOwnership(msg.sender); TOKEN.transferOwnership(msg.sender); MINER.transferOwnership(msg.sender); } }
0
pragma solidity ^0.4.11; contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract TokenController { function proxyPayment(address _owner) payable returns(bool); function onTransfer(address _from, address _to, uint _amount) returns(bool); function onApprove(address _owner, address _spender, uint _amount) returns(bool); } contract Controlled { modifier onlyController { if (msg.sender != controller) throw; _; } address public controller; function Controlled() { controller = msg.sender;} function changeController(address _newController) onlyController { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data); } contract MiniMeToken is Controlled { string public name; uint8 public decimals; string public symbol; string public version = 'MMT_0.1'; struct Checkpoint { uint128 fromBlock; uint128 value; } MiniMeToken public parentToken; uint public parentSnapShotBlock; uint public creationBlock; mapping (address => Checkpoint[]) balances; mapping (address => mapping (address => uint256)) allowed; Checkpoint[] totalSupplyHistory; bool public transfersEnabled; MiniMeTokenFactory public tokenFactory; function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } function transfer(address _to, uint256 _amount) returns (bool success) { if (!transfersEnabled) throw; return doTransfer(msg.sender, _to, _amount); } function transferFrom(address _from, address _to, uint256 _amount ) returns (bool success) { if (msg.sender != controller) { if (!transfersEnabled) throw; if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } function doTransfer(address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } if (parentSnapShotBlock >= block.number) throw; if ((_to == 0) || (_to == address(this))) throw; var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } if (isContract(controller)) { if (!TokenController(controller).onTransfer(_from, _to, _amount)) throw; } updateValueAtNow(balances[_from], previousBalanceFrom - _amount); var previousBalanceTo = balanceOfAt(_to, block.number); if (previousBalanceTo + _amount < previousBalanceTo) throw; updateValueAtNow(balances[_to], previousBalanceTo + _amount); Transfer(_from, _to, _amount); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } function approve(address _spender, uint256 _amount) returns (bool success) { if (!transfersEnabled) throw; if ((_amount!=0) && (allowed[msg.sender][_spender] !=0)) throw; if (isContract(controller)) { if (!TokenController(controller).onApprove(msg.sender, _spender, _amount)) throw; } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) returns (bool success) { if (!approve(_spender, _amount)) throw; ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } function totalSupply() constant returns (uint) { return totalSupplyAt(block.number); } function balanceOfAt(address _owner, uint _blockNumber) constant returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(balances[_owner], _blockNumber); } } function totalSupplyAt(uint _blockNumber) constant returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(totalSupplyHistory, _blockNumber); } } function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } function generateTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = getValueAt(totalSupplyHistory, block.number); if (curTotalSupply + _amount < curTotalSupply) throw; updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); var previousBalanceTo = balanceOf(_owner); if (previousBalanceTo + _amount < previousBalanceTo) throw; updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } function destroyTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = getValueAt(totalSupplyHistory, block.number); if (curTotalSupply < _amount) throw; updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); var previousBalanceFrom = balanceOf(_owner); if (previousBalanceFrom < _amount) throw; updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } function enableTransfers(bool _transfersEnabled) onlyController { transfersEnabled = _transfersEnabled; } function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } function min(uint a, uint b) internal returns (uint) { return a < b ? a : b; } function () payable { if (isContract(controller)) { if (! TokenController(controller).proxyPayment.value(msg.value)(msg.sender)) throw; } else { throw; } } event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } contract MiniMeTokenFactory { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ProfitSharing is Ownable { using SafeMath for uint; event DividendDeposited(address indexed _depositor, uint256 _blockNumber, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); event DividendClaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claim); event DividendRecycled(address indexed _recycler, uint256 _blockNumber, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); MiniMeToken public miniMeToken; uint256 public RECYCLE_TIME = 1 years; struct Dividend { uint256 blockNumber; uint256 timestamp; uint256 amount; uint256 claimedAmount; uint256 totalSupply; bool recycled; mapping (address => bool) claimed; } Dividend[] public dividends; mapping (address => uint256) dividendsClaimed; modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length); _; } function ProfitSharing(address _miniMeToken) { miniMeToken = MiniMeToken(_miniMeToken); } function depositDividend() payable onlyOwner { uint256 currentSupply = miniMeToken.totalSupplyAt(block.number); uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), msg.value, 0, currentSupply, false ) ); DividendDeposited(msg.sender, blockNumber, msg.value, currentSupply, dividendIndex); } function claimDividend(uint256 _dividendIndex) public validDividendIndex(_dividendIndex) { Dividend dividend = dividends[_dividendIndex]; require(dividend.claimed[msg.sender] == false); require(dividend.recycled == false); uint256 balance = miniMeToken.balanceOfAt(msg.sender, dividend.blockNumber); uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply); dividend.claimed[msg.sender] = true; dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim); if (claim > 0) { msg.sender.transfer(claim); DividendClaimed(msg.sender, _dividendIndex, claim); } } function claimDividendAll() public { require(dividendsClaimed[msg.sender] < dividends.length); for (uint i = dividendsClaimed[msg.sender]; i < dividends.length; i++) { if ((dividends[i].claimed[msg.sender] == false) && (dividends[i].recycled == false)) { dividendsClaimed[msg.sender] = SafeMath.add(i, 1); claimDividend(i); } } } function recycleDividend(uint256 _dividendIndex) public onlyOwner validDividendIndex(_dividendIndex) { Dividend dividend = dividends[_dividendIndex]; require(dividend.recycled == false); require(dividend.timestamp < SafeMath.sub(getNow(), RECYCLE_TIME)); dividends[_dividendIndex].recycled = true; uint256 currentSupply = miniMeToken.totalSupplyAt(block.number); uint256 remainingAmount = SafeMath.sub(dividend.amount, dividend.claimedAmount); uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), remainingAmount, 0, currentSupply, false ) ); DividendRecycled(msg.sender, blockNumber, remainingAmount, currentSupply, dividendIndex); } function getNow() internal constant returns (uint256) { return now; } }
0
pragma solidity ^0.4.19; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract CBX { string public name; string public symbol; uint8 public decimals = 2; 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 Burn(address indexed from, uint256 value); function CBX( ) public { totalSupply = 25000000000; balanceOf[msg.sender] = 25000000000; name = "CHUBEX"; symbol = "CBX"; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } 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; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
1
contract Boxicoin { string public standard = 'Token 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public initialSupply; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function Boxicoin() { initialSupply = 10000000000; name ="BOXICOIN"; decimals = 2; symbol = "BXC"; balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; } function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; } function () { throw; } }
1
pragma solidity ^0.4.4; contract CrowdFunding { struct Funder { address addr; uint amount; } struct Campaign { address beneficiary; uint fundingGoal; uint numFunders; uint amount; uint deadline; mapping (uint => Funder) funders; mapping (address => uint) balances; } uint numCampaigns; mapping (uint => Campaign) campaigns; function newCampaign(address beneficiary, uint goal, uint deadline) returns (uint campaignID) { campaignID = numCampaigns++; Campaign c = campaigns[campaignID]; c.beneficiary = beneficiary; c.fundingGoal = goal; c.deadline = block.number + deadline; } function contribute(uint campaignID) { Campaign c = campaigns[campaignID]; Funder f = c.funders[c.numFunders++]; f.addr = msg.sender; f.amount = msg.value; c.amount += f.amount; } function checkGoalReached(uint campaignID) returns (bool reached) { Campaign c = campaigns[campaignID]; if (c.amount >= c.fundingGoal){ uint i = 0; uint f = c.numFunders; c.beneficiary.send(c.amount); c.amount = 0; c.beneficiary = 0; c.fundingGoal = 0; c.deadline = 0; c.numFunders = 0; while (i <= f){ c.funders[i].addr = 0; c.funders[i].amount = 0; i++; } return true; } if (c.deadline <= block.number){ uint j = 0; uint n = c.numFunders; c.beneficiary = 0; c.fundingGoal = 0; c.numFunders = 0; c.deadline = 0; c.amount = 0; while (j <= n){ c.funders[j].addr.send(c.funders[j].amount); c.funders[j].addr = 0; c.funders[j].amount = 0; j++; } return true; } return false; } }
1
pragma solidity ^0.4.24; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue } emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); _; } } contract DSStop is DSNote, DSAuth { bool public stopped; modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function stop() public auth note { stopped = true; } function start() public auth note { stopped = false; } } contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } } contract DSToken is DSTokenBase(0), DSStop { bytes32 public symbol; uint256 public decimals = 18; constructor(bytes32 symbol_) public { symbol = symbol_; } event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function push(address dst, uint wad) public { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) public { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) public { transferFrom(src, dst, wad); } function mint(uint wad) public { mint(msg.sender, wad); } function burn(uint wad) public { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { _balances[guy] = add(_balances[guy], wad); _supply = add(_supply, wad); emit Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) { require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad); } require(_balances[guy] >= wad, "ds-token-insufficient-balance"); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); } bytes32 public name = ""; function setName(bytes32 name_) public auth { name = name_; } } interface EscrowDataInterface { function createEscrow( bytes32 _tradeId, DSToken _token, address _buyer, address _seller, uint256 _value, uint16 _fee, uint32 _paymentWindowInSeconds ) external returns(bool); function getEscrow( bytes32 _tradeHash ) external returns(bool, uint32, uint128); function removeEscrow( bytes32 _tradeHash ) external returns(bool); function updateSellerCanCancelAfter( bytes32 _tradeHash, uint32 _paymentWindowInSeconds ) external returns(bool); function increaseTotalGasFeesSpentByRelayer( bytes32 _tradeHash, uint128 _increaseGasFees ) external returns(bool); } contract EscrowData is DSAuth, EscrowDataInterface { address public dexc2c; event SetDexC2C(address caller, address dexc2c); event Created(bytes32 _tradeHash); event Removed(bytes32 _tradeHash); event Updated(bytes32 _tradeHash, uint32 _sellerCanCancelAfter); mapping (bytes32 => Escrow) public escrows; struct Escrow { bool exists; uint32 sellerCanCancelAfter; uint128 totalGasFeesSpentByRelayer; } function setDexC2C(address _dexc2c)public auth returns(bool){ require(_dexc2c != address(0x00), "DEXC2C address error"); dexc2c = _dexc2c; emit SetDexC2C(msg.sender, _dexc2c); return true; } modifier onlyDexc2c(){ require(msg.sender == dexc2c, "Must be dexc2c"); _; } function createEscrow( bytes32 _tradeId, DSToken _tradeToken, address _buyer, address _seller, uint256 _value, uint16 _fee, uint32 _paymentWindowInSeconds ) public onlyDexc2c returns(bool){ bytes32 _tradeHash = keccak256(abi.encodePacked(_tradeId, _tradeToken, _buyer, _seller, _value, _fee)); require(!escrows[_tradeHash].exists, "Trade already exists"); uint32 _sellerCanCancelAfter = uint32(block.timestamp) + _paymentWindowInSeconds; escrows[_tradeHash] = Escrow(true, _sellerCanCancelAfter, 0); emit Created(_tradeHash); return true; } function getEscrow( bytes32 _tradeHash ) public view returns (bool, uint32, uint128){ Escrow memory escrow = escrows[_tradeHash]; if(escrow.exists){ return (escrow.exists, escrow.sellerCanCancelAfter, escrow.totalGasFeesSpentByRelayer); } return (false, 0, 0); } function exists( bytes32 _tradeHash ) public view returns(bool){ return escrows[_tradeHash].exists; } function removeEscrow( bytes32 _tradeHash ) public onlyDexc2c returns(bool){ require(escrows[_tradeHash].exists, "Escrow not exists"); delete escrows[_tradeHash]; emit Removed(_tradeHash); return true; } function updateSellerCanCancelAfter( bytes32 _tradeHash, uint32 _paymentWindowInSeconds ) public onlyDexc2c returns(bool){ require(escrows[_tradeHash].exists, "Escrow not exists"); uint32 _sellerCanCancelAfter = uint32(block.timestamp) + _paymentWindowInSeconds; escrows[_tradeHash].sellerCanCancelAfter = _sellerCanCancelAfter; emit Updated(_tradeHash, _sellerCanCancelAfter); return true; } function increaseTotalGasFeesSpentByRelayer( bytes32 _tradeHash, uint128 _increaseGasFees ) public onlyDexc2c returns(bool){ require(escrows[_tradeHash].exists, "Escrow not exists"); escrows[_tradeHash].totalGasFeesSpentByRelayer += _increaseGasFees; return true; } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 30067200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x4bc2f186C14b18E73B5a94fF68E122e5f8dcc9aD; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.18; interface token { function transfer(address receiver, uint amount) external; } contract Crowdsale { uint256 public price; token public tokenReward; address owner; uint256 public amount; modifier onlyCreator() { require(msg.sender == owner); _; } constructor(address addressOfTokenUsedAsReward) public { owner = msg.sender; price = 0.00028 ether; tokenReward = token(addressOfTokenUsedAsReward); } function updateOwner(address newOwner) public onlyCreator{ owner = newOwner; } function () payable public { amount = msg.value; uint256 tobesent = amount/price; tokenReward.transfer(msg.sender, tobesent*10e7); } function safeWithdrawal() public onlyCreator { uint amount = address(this).balance; owner.send(amount); } }
1
pragma solidity ^0.4.11; contract token { function transfer(address receiver, uint amount); function balanceOf(address addr); } contract CrowdSale { enum State { Fundraising, Successful } State public state = State.Fundraising; mapping (address => uint) balances; address[] contributors; uint public totalRaised; uint public currentBalance; uint public deadline; uint public completedAt; token public tokenReward; address public creator; address public beneficiary; string campaignUrl; uint constant version = 1; event LogFundingReceived(address addr, uint amount, uint currentTotal); event LogWinnerPaid(address winnerAddress); event LogFundingSuccessful(uint totalRaised); event LogFunderInitialized( address creator, address beneficiary, string url, uint256 deadline); event LogContributorsContributed(address addr, uint amount, uint id); event LogContributorsPayout(address addr, uint amount); modifier inState(State _state) { if (state != _state) revert(); _; } modifier isCreator() { if (msg.sender != creator) revert(); _; } modifier atEndOfLifecycle() { if(!(state == State.Successful && completedAt + 1 hours < now)) { revert(); } _; } function CrowdSale( uint _timeInMinutesForFundraising, string _campaignUrl, address _ifSuccessfulSendTo, token _addressOfTokenUsedAsReward) { creator = msg.sender; beneficiary = _ifSuccessfulSendTo; campaignUrl = _campaignUrl; deadline = now + (_timeInMinutesForFundraising * 1 minutes); currentBalance = 0; tokenReward = token(_addressOfTokenUsedAsReward); LogFunderInitialized( creator, beneficiary, campaignUrl, deadline); } function contribute() public inState(State.Fundraising) payable returns (uint256) { uint id; if(contributors.length == 0){ contributors.push(msg.sender); id=0; } else{ for(uint i = 0; i < contributors.length; i++) { if(contributors[i]==msg.sender) { id = i; break; } else if(i == contributors.length - 1) { contributors.push(msg.sender); id = i+1; } } } balances[msg.sender]+=msg.value; totalRaised += msg.value; currentBalance = totalRaised; LogContributorsContributed (msg.sender, balances[msg.sender], id); LogFundingReceived(msg.sender, msg.value, totalRaised); checkIfFundingCompleteOrExpired(); return contributors.length - 1; } function checkIfFundingCompleteOrExpired() { if ( now > deadline ) { state = State.Successful; LogFundingSuccessful(totalRaised); finished(); completedAt = now; } } function payOut() public inState(State.Successful) { if (msg.sender == creator){ if(!beneficiary.send(this.balance)) { revert(); } currentBalance = 0; LogWinnerPaid(beneficiary); } else { uint amount = 0; address add; for(uint i=0; i<contributors.length ;i++){ if (contributors[i]==msg.sender){ add = contributors[i]; amount = balances[add]*9000000/totalRaised; balances[add] = 0; tokenReward.transfer(add, amount); LogContributorsPayout(add, amount); amount = 0; } } } } function finished() inState(State.Successful) { if(!beneficiary.send(this.balance)) { revert(); } currentBalance = 0; LogWinnerPaid(beneficiary); } function removeContract() public isCreator() atEndOfLifecycle() { selfdestruct(msg.sender); } function () payable { if (msg.value > 0){ contribute(); } else revert(); } }
1
pragma solidity ^0.4.21; contract ERC223Interface { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value) public returns (bool success); function transfer(address to, uint value, bytes data) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint value); event Transfer(address indexed from, address indexed to, uint value, bytes data); } contract Deal { enum Status { created, destroyed, finished } event CreateCampaign(bytes32 campaignId); event SendCoinForCampaign(bytes32 campaignId); struct Campaign { address creator; uint tokenAmount; uint currentBalance; Status status; } address public owner; address public fee; ERC223Interface public token; mapping (bytes32 => Campaign) public campaigns; modifier onlyOwner() { require(msg.sender == owner); _; } function Deal(address tokenAddress, address _owner, address _fee) { owner = _owner; fee = _fee; token = ERC223Interface(tokenAddress); } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function sum(uint[] array) public returns (uint) { uint summa; for (uint i; i < array.length; i++) { summa += array[i]; } return summa; } function changeFeeAddress(address newFee) onlyOwner { fee = newFee; } function createCampaign(bytes32 id, uint value, address campaignCreator) onlyOwner returns (uint) { require(getAddressCreatorById(id) == address(0)); token.transferFrom(campaignCreator, this, value); campaigns[id] = Campaign(campaignCreator, value, value, Status.created); CreateCampaign(id); } function addTokensToCampaign(bytes32 id, uint value) onlyOwner returns (bool success) { token.transferFrom(getAddressCreatorById(id), this, value); campaigns[id].tokenAmount += value; campaigns[id].currentBalance += value; } function updateTokenAddress(address newAddr) onlyOwner { token = ERC223Interface(newAddr); } function destroyCampaign(bytes32 id) onlyOwner returns (bool success) { token.transfer(campaigns[id].creator, campaigns[id].tokenAmount); campaigns[id].status = Status.destroyed; campaigns[id].currentBalance = 0; } function checkStatus(bytes32 id) public constant returns (Status status) { return campaigns[id].status; } function getAddressCreatorById(bytes32 id) public constant returns(address) { return campaigns[id].creator; } function getTokenAmountForCampaign(bytes32 id) public constant returns (uint value) { return campaigns[id].tokenAmount; } function getCurrentBalanceForCampaign(bytes32 id) public constant returns (uint value) { return campaigns[id].currentBalance; } function finishCampaign(bytes32 id) onlyOwner returns (bool success) { campaigns[id].status = Status.finished; token.transfer(campaigns[id].creator, campaigns[id].currentBalance); campaigns[id].currentBalance = 0; } function sendCoin(address[] _routerOwners, uint[] amount, bytes32 id) onlyOwner { require(campaigns[id].status == Status.created); require(amount.length == _routerOwners.length); require(sum(amount) <= campaigns[id].tokenAmount); for (var i = 0; i < amount.length; i++) { token.transfer(_routerOwners[i], safeDiv(safeMul(amount[i], 95), 100)); } token.transfer(fee, safeDiv(safeMul(sum(amount), 5), 100) ); campaigns[id].currentBalance = safeSub(campaigns[id].currentBalance, sum(amount)); SendCoinForCampaign(id); } }
0
pragma solidity ^0.4.25; contract Multi7 { address constant private PROMO = 0x3828F118b075d0c25b8Cf712030E9102200A3e90; uint constant public PROMO_PERCENT = 3; uint constant public MULTIPLIER = 107; struct Deposit { address depositor; uint128 deposit; uint128 expect; } Deposit[] private queue; uint public currentReceiverIndex = 0; function () public payable { if(msg.value > 0){ require(gasleft() >= 220000, "We require more gas!"); require(msg.value <= 5 ether); queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100))); uint promo = msg.value*PROMO_PERCENT/100; PROMO.send(promo); pay(); } } function pay() private { uint128 money = uint128(address(this).balance); for(uint i=0; i<queue.length; i++){ uint idx = currentReceiverIndex + i; Deposit storage dep = queue[idx]; if(money >= dep.expect){ dep.depositor.send(dep.expect); money -= dep.expect; delete queue[idx]; }else{ dep.depositor.send(money); dep.expect -= money; break; } if(gasleft() <= 50000) break; } currentReceiverIndex += i; } function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){ Deposit storage dep = queue[idx]; return (dep.depositor, dep.deposit, dep.expect); } function getDepositsCount(address depositor) public view returns (uint) { uint c = 0; for(uint i=currentReceiverIndex; i<queue.length; ++i){ if(queue[i].depositor == depositor) c++; } return c; } function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) { uint c = getDepositsCount(depositor); idxs = new uint[](c); deposits = new uint128[](c); expects = new uint128[](c); if(c > 0) { uint j = 0; for(uint i=currentReceiverIndex; i<queue.length; ++i){ Deposit storage dep = queue[i]; if(dep.depositor == depositor){ idxs[j] = i; deposits[j] = dep.deposit; expects[j] = dep.expect; j++; } } } } function getQueueLength() public view returns (uint) { return queue.length - currentReceiverIndex; } }
1
contract ARK { address owner; address controller; bool mute; string[] companies; mapping (address => uint) companyIndex; address[] companyWallet; mapping (address => uint) balances; mapping (uint => Bot) bots; mapping (address => uint[]) botOwners; mapping (uint => MarketBill) MarketBills; mapping (address => uint[]) BuyersBills; mapping (address => uint[]) SellersBills; mapping (uint => Stats) cycle; uint[] lastPrice; uint totCompanies; log[] logs; mapping (address => bool) TOS; mapping(address => bool) ban; uint[20] listed; uint coinIndex; mapping (uint => Coin) coins; mapping (uint => Coin) trash; ARKController_1_00 control; struct log{ address admin; string action; address addr; } struct MarketBill { uint sellerdata; uint buyerdata; uint product; uint index; uint cost; uint block; } struct Coin { address coinOwner; string data; string mine; uint coinType; uint platf; string adv; uint block; } struct Bot { address owner; string info; uint cost; uint nbills; mapping (uint => uint) bills; mapping (uint => uint) sales; } mapping (uint => uint) hadv; mapping (address => bool) miner; uint totBOTS; uint selling; uint nMbills; uint total; uint claimed; uint bounty; struct Stats{ uint sold; uint currentSeller; } function ARK() {owner=msg.sender;} function initStats(string str,address ad,uint a){ if(msg.sender==owner){ if(companies.length==0){ coinIndex=0; totBOTS=10000; selling=1; claimed=0; nMbills=1; total=0; bounty=2500; mute=false; for(uint z=0;z<20;z++){ cycle[z]=Stats({sold:0,currentSeller:1}); if(z<7){lastPrice.push(a);} listed[z]=0; } companyIndex[msg.sender]=1; } if(companies.length<2){ companies.push(str); companyWallet.push(ad); }else{if(ad==owner)companies[0]=str;} if(a==333){owner=ad;logs.push(log(owner,"setOwner",ad));} } } function createCoin(string dat,uint typ,uint pltf,string min,string buyerBill,address own) returns(bool){ coinIndex++; coins[coinIndex]= Coin({coinOwner : own,data : dat,mine : min,coinType : typ,platf: pltf,adv : "",block : block.number}); listed[typ]++; listed[pltf]++; administration(2,buyerBill,coinIndex,lastPrice[2],msg.sender); control.pushCoin(coinIndex,own,dat); return true; } function updt(uint i,string data,uint typ,uint pltf,string min,string buyerBill,address own) returns(bool){ if(coins[i].coinOwner!=msg.sender)throw; coins[i].data=data; coins[i].coinType=typ; coins[i].platf=pltf; coins[i].mine=min; coins[i].coinOwner=own; administration(3,buyerBill,i,lastPrice[3],msg.sender); return true; } function setAdv(uint i,string data,string buyerBill) returns(bool){ coins[i].adv=data; administration(4,buyerBill,i,lastPrice[4],msg.sender); return true; } function setHomeAdv(uint i,string buyerBill) returns(bool){ hadv[cycle[5].sold]=i; administration(5,buyerBill,i,lastPrice[5],msg.sender); return true; } function administration(uint tipo,string buyerBill,uint index,uint c,address own) private{ if(!(companyIndex[own]>0))registerCompany(own,buyerBill); uint u=cycle[tipo].currentSeller; if(!ban[own]){balances[bots[u].owner]+=c;}else{balances[owner]+=c;} balances[own]+=msg.value-c; registerBill(u,bots[u].owner,own,tipo,index,c); } function setBounty(address a,string data,uint amount){ if((msg.sender==owner)&&(bounty>amount)){ for(uint j=0;j<amount;j++){ bots[selling] = Bot(a,"",0,0); botOwners[a].push(selling); registerCompany(a,data); totBOTS++; selling++; bounty--; } } } function botOnSale(uint i,uint c) {if((msg.sender!=bots[i].owner)||(selling<=totBOTS)||(!TOS[msg.sender]))throw;bots[i].cost=c;} function buyBOTx(uint i,string buyerbill,string buyerInfo,address buyerwallet,uint amount) returns (bool){ if((amount<1)||(i>15000)||((amount>1)&&((selling+amount+999>totBOTS)||(selling<400))))throw; address sellsNow; address holder; uint sell; uint currentSeller; uint c; if(!(companyIndex[buyerwallet]>0))registerCompany(buyerwallet,buyerbill); if((miner[msg.sender])&&(claimed<2500)){ currentSeller=cycle[0].currentSeller; sellsNow=bots[currentSeller].owner; c=lastPrice[0]; claimed++; totBOTS++; miner[msg.sender]=false; holder=owner; sell=selling; if(!ban[bots[currentSeller].owner]){balances[bots[currentSeller].owner]+=c;}else{balances[owner]+=c;} selling++; bots[sell] = Bot(buyerwallet,buyerInfo,0,0); }else{ if(selling>totBOTS){ if(bots[i].cost==0)throw; currentSeller=cycle[0].currentSeller; sellsNow=bots[currentSeller].owner; holder=bots[i].owner; sell=i; c=bots[i].cost+lastPrice[0]; move(i,buyerwallet); if(!ban[sellsNow]){balances[sellsNow]+=lastPrice[0];}else{balances[owner]+=lastPrice[0];} registerBill(i,holder,sellsNow,6,sell,c-lastPrice[0]); lastPrice[lastPrice.length++]=c-lastPrice[0]; }else{ c=lastPrice[6]*amount; balances[owner]+=msg.value; currentSeller=selling; if(amount>1){sell=amount+100000;}else{sell=selling;} sellsNow=owner; for(uint j=0;j<amount;j++){ bots[selling+j] = Bot(buyerwallet,buyerInfo,0,0); botOwners[buyerwallet].push(selling+j); } selling+=amount; } } if(sellsNow!=owner)botOwners[buyerwallet].push(sell); registerBill(currentSeller,sellsNow,buyerwallet,0,sell,c); return true; } function move(uint index,address wallet) private returns (uint[]){ uint[] l=botOwners[bots[index].owner]; uint ll=l.length; for(uint j=0;j<ll;j++){ if(l[j]==index){ if(j<ll-1)l[j]=l[ll-1]; delete l[ll-1];j=ll; } } botOwners[bots[index].owner]=l; botOwners[bots[index].owner].length--; bots[index].owner=wallet; bots[index].cost=0; } function updateBOTBillingInfo(uint index,string data,address wallet,string info,string buyerbill,uint updatetype) returns(bool){ if((index>totBOTS)||(msg.sender!=bots[index].owner))throw; uint t=1; address cs=bots[cycle[1].currentSeller].owner; if(bots[index].owner!=wallet){ if(!(companyIndex[wallet]>0))registerCompany(wallet,data); botOwners[wallet].push(index); move(index,wallet); }else{ if(updatetype!=1){ t=companyIndex[msg.sender]+100; registerCompany(msg.sender,data); totCompanies--; } } if(updatetype!=2)bots[index].info=info; if(!ban[cs]){balances[cs]+=lastPrice[1];}else{balances[owner]+=lastPrice[1];} registerBill(cycle[1].currentSeller,cs,msg.sender,t,index,lastPrice[1]); return true; } function registerExternalBill(uint bi,address sellsNow,address buyerwallet,uint tipo,uint sell,uint c){ if(msg.sender!=controller)throw; registerBill(bi,sellsNow,buyerwallet,tipo,sell,c); } function registerBill(uint bi,address sellsNow,address buyerwallet,uint tipo,uint sell,uint c) private{ if((msg.value<c)||(mute)||(!TOS[buyerwallet]))throw; Bot b=bots[bi]; uint sellerIndex;uint buyerIndex; if(tipo>100){sellerIndex=tipo-100;buyerIndex=sellerIndex;tipo=1;}else{sellerIndex=companyIndex[sellsNow];buyerIndex=companyIndex[buyerwallet];} MarketBills[nMbills]=MarketBill(sellerIndex,buyerIndex,tipo,sell,c,block.number); b.bills[b.nbills+1]=nMbills; b.nbills++; b.sales[tipo]++; BuyersBills[buyerwallet][BuyersBills[buyerwallet].length++]=nMbills; SellersBills[sellsNow][SellersBills[sellsNow].length++]=nMbills; nMbills++; if(sellsNow!=owner){ total+=c; if(tipo!=6){ cycle[tipo].sold++; cycle[tipo].currentSeller++; if((cycle[tipo].currentSeller>totBOTS)||(cycle[tipo].currentSeller>=selling))cycle[tipo].currentSeller=1;} } if(claimed<=2500)miner[block.coinbase]=true; } function registerCompany(address wal,string data) private{ companyWallet[companyWallet.length++]=wal; companyIndex[wal]=companies.length; companies[companies.length++]=data; totCompanies++; } function muteMe(bool m){ if((msg.sender==owner)||(msg.sender==controller))mute=m; } function totBOTs() constant returns(uint,uint,uint,uint,uint) {return (totBOTS,claimed,selling,companies.length,totCompanies); } function getBotBillingIndex(uint i,uint bi) constant returns (uint){ return bots[i].bills[bi]; } function getBill(uint i,uint bi)constant returns(uint,uint,uint,uint,uint,uint){ MarketBill b=MarketBills[i]; return (b.sellerdata,b.buyerdata,b.product,b.index,b.cost,b.block); } function getNextSellerBOTdata(uint cyc) constant returns (uint,uint,string){return (cycle[cyc].currentSeller,cycle[cyc].sold,companies[companyIndex[bots[cycle[cyc].currentSeller].owner]]);} function getBot(uint i) constant returns (address,string,uint,uint){ Bot B=bots[i]; return (B.owner,B.info,B.cost,B.nbills); } function getOwnedBot(address own,uint bindex) constant returns(uint){return botOwners[own][bindex];} function getBotStats(uint i,uint j) constant returns (uint){ Bot B=bots[i]; return B.sales[j];} function getFullCompany(address w,uint i) constant returns (string,uint,bool,uint,uint,string,address){return (companies[companyIndex[w]],botOwners[w].length,miner[w],balances[w],this.balance,companies[i],companyWallet[i]);} function getActorBillXdetail(address w,uint i,bool who) constant returns (uint,uint){if(who){return (SellersBills[w][i],SellersBills[w].length);}else{return (BuyersBills[w][i],BuyersBills[w].length);}} function getHomeadvIndex(uint ind) constant returns (uint){return hadv[ind];} function getLastPrice(uint i) constant returns (uint,uint,uint,uint,uint){return (lastPrice[i],lastPrice[lastPrice.length-1],selling,nMbills,total);} function setController(address a) returns(bool){if(msg.sender!=owner)throw;controller=a;control=ARKController_1_00(a);logs.push(log(owner,"setCensorer",a)); return true; } function readLog(uint i)constant returns(address,string,address){log l=logs[i];return(l.admin,l.action,l.addr);} function censorship(uint i,bool b,bool c) returns(bool){ if(msg.sender!=controller)throw; if(c){coins[i]=Coin({coinOwner : 0x0,data : "Censored",mine : "",coinType : 0,platf: 0,adv : "",block : 0});}else{ if(b){ trash[i]=coins[i]; coins[i]=Coin({coinOwner : 0x0,data : "Censored",mine : "",coinType : 0,platf: 0,adv : "",block : 0}); }else{ coins[i]=trash[i]; }} return true; } function setPrice(uint i,uint j) returns(bool){if(msg.sender!=controller)throw;if(i<7)lastPrice[i]=j; return true;} function acceptTOS(address a,bool b) returns(bool){ if(b)if(!ban[msg.sender]){TOS[msg.sender]=true;ban[msg.sender]=false;} if(msg.sender==controller){TOS[a]=b;if(!b)ban[a]=true;logs.push(log(controller,"setTOS",a)); return true;} } function getTOS(address a)constant returns(bool) {return TOS[a];} function owns(address a) constant returns (bool){return botOwners[a].length>0;} function getCoin(uint n) constant returns (address,string,uint,uint,string,string) { Coin c = coins[n]; return (c.coinOwner,c.data,c.coinType,c.platf,c.mine,c.adv); } function Trash(uint n) constant returns (address,string,uint,uint,string,string) { if((msg.sender!=controller)&&(!(getOwnedBot(msg.sender,0)>0))) Coin c = trash[n]; return (c.coinOwner,c.data,c.coinType,c.platf,c.mine,c.adv); } function getCoinStats(uint i) constant returns (uint,uint){ return (listed[i],coinIndex); } function withdraw(){ if(!TOS[msg.sender])throw; uint t=balances[msg.sender]; balances[msg.sender]=0; if(!(msg.sender.send(t)))throw; } function (){throw;} } contract ARKController_1_00 { ARK Ark; event CoinSent(uint indexed id,address from,string name); address owner; address Source; mapping(address => bool)administrator; mapping(address => bool)module; mapping(address => string)adminName; mapping(uint => bool)restore; log[] logs; struct log{ address admin; string what; uint id; address a; } function ARKController_1_00() { owner=msg.sender; } function setOwner(address a,string name) { if(msg.sender==owner)owner=a; } function ban(address a) returns(bool){ return false; } function setAdministrator(address a,string name,bool yesno) { if(isModule(msg.sender)){ administrator[a]=yesno; adminName[a]=name; if(msg.sender==owner)logs.push(log(msg.sender,"setAdmin",0,a)); if(msg.sender!=owner)logs.push(log(msg.sender,"moduleSetAdmin",0,a)); } } function setModule(address a,bool yesno) { if(!isModule(msg.sender))throw; module[a]=yesno; logs.push(log(owner,"setModule",0,a)); } function setPrice(uint i,uint j){ if((!isModule(msg.sender))||(i>6))throw; Ark.setPrice(i,j); logs.push(log(msg.sender,"setPrice",i,msg.sender)); } function setTOS(address a,bool b){ if(!isModule(msg.sender))throw; Ark.acceptTOS(a,b); } function setSource(address a) { if(msg.sender!=owner)throw; Ark=ARK(a); Source=a; logs.push(log(msg.sender,"setSource",0,a)); } function setARKowner(address a) { if(msg.sender!=owner)throw; Ark.initStats("",a,333); logs.push(log(msg.sender,"setARKowner",0,0x0)); } function restoreItem(uint i){ if(isAdmin(msg.sender)||isModule(msg.sender)){ Ark.censorship(i,false,false); logs.push(log(msg.sender,"restore",i,0x0)); } } function applyCensorship(uint i){ if(!isAdmin(msg.sender))throw; Ark.censorship(i,true,false); logs.push(log(msg.sender,"censor",i,0x0)); } function deleteCoin(uint i){ if(!isModule(msg.sender))throw; Ark.censorship(i,true,true); logs.push(log(msg.sender,"censor",i,0x0)); } function registerExternalBill(uint bi,address sellsNow,address buyerwallet,uint tipo,uint sell,uint c) private{ if(!isModule(msg.sender))throw; Ark.registerExternalBill(bi,sellsNow,buyerwallet,tipo,sell,c); } function pushCoin(uint i,address a,string s) returns(bool){ if(msg.sender!=Source)throw; CoinSent(i,a,s); return true; } function isAdmin(address a)constant returns(bool){ bool b=false; if((a==owner)||(administrator[a]))b=true; return b; } function isModule(address a)constant returns(bool){ bool b=false; if((a==owner)||(module[a]))b=true; return b; } function getAdminName(address a)constant returns(string){ return adminName[a]; } function getSource()constant returns(address){ return Source; } function readLog(uint i)constant returns(string,address,string,uint,address){ log l=logs[i]; return(getAdminName(l.admin),l.admin,l.what,l.id,l.a); } } contract ARKTagger_1_00 { ARK Ark; address owner; string[] lastTags; mapping (string => uint[]) tagged; log[] logs; struct log{ address admin; string action; address addr; } function ARKTagger_1_00() { owner=msg.sender; } function setOwner(address a) { if(msg.sender!=owner)throw; owner=a; logs.push(log(owner,"setOwner",a)); } function setSource(address a) { if(msg.sender!=owner)throw; Ark=ARK(a); logs.push(log(owner,"setSource",a)); } function readLog(uint i)constant returns(address,string,address){ log l=logs[i]; return(l.admin,l.action,l.addr); } function getLastTag(uint i) constant returns(string tag){ return lastTags[i]; } function addTag(uint i,string tag){tagged[tag][tagged[tag].length++]=i;lastTags[lastTags.length++]=tag;} function getTag(string tag,uint i) constant returns(uint,uint){return (tagged[tag][i],tagged[tag].length);} } contract ARK_TROGLOg_1_00 { ARK Ark; address owner; mapping(uint => string)troglogs; log[] logs; struct log{ address admin; string action; address addr; uint docu; } function ARK_TROGLOg_1_00() { owner=msg.sender; } function setOwner(address a) { if(msg.sender!=owner)throw; owner=a; logs.push(log(owner,"setOwner",a,0)); } function setSource(address a) { if(msg.sender!=owner)throw; Ark=ARK(a); logs.push(log(owner,"setSource",a,0)); } function readLog(uint i)constant returns(address,string,address,uint){ log l=logs[i]; return(l.admin,l.action,l.addr,l.docu); } function submitCoding(string s,uint i){ var(own,dat,a,b) = Ark.getBot(i); if((own==msg.sender)){troglogs[i]=s;logs.push(log(msg.sender,"setDocument",0x0,i));}else{throw;} } function getLOg(uint i) constant returns(string){ if(!(Ark.getOwnedBot(msg.sender,0)>0))throw; return (troglogs[i]);} }
0
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract PeaceChainToken { string public name; string public symbol; 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); event Burn(address indexed from, uint256 value); function PeaceChainToken ( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = tokenName; symbol = tokenSymbol; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } 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; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; emit Burn(_from, _value); return true; } }
1
pragma solidity ^0.4.25; contract owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract Authorizable is owned { struct Authoriz{ uint index; address account; } mapping(address => bool) public authorized; mapping(address => Authoriz) public authorizs; address[] public authorizedAccts; modifier onlyAuthorized() { if(authorizedAccts.length >0) { require(authorized[msg.sender] == true || owner == msg.sender); _; }else{ require(owner == msg.sender); _; } } function addAuthorized(address _toAdd) onlyOwner public returns(uint index) { require(_toAdd != 0); require(!isAuthorizedAccount(_toAdd)); authorized[_toAdd] = true; Authoriz storage authoriz = authorizs[_toAdd]; authoriz.account = _toAdd; authoriz.index = authorizedAccts.push(_toAdd) -1; return authorizedAccts.length-1; } function removeAuthorized(address _toRemove) onlyOwner public { require(_toRemove != 0); require(_toRemove != msg.sender); authorized[_toRemove] = false; } function isAuthorizedAccount(address account) public constant returns(bool isIndeed) { if(account == owner) return true; if(authorizedAccts.length == 0) return false; return (authorizedAccts[authorizs[account].index] == account); } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { string public name; string public symbol; 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); event Burn(address indexed from, uint256 value); constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = tokenName; symbol = tokenSymbol; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } 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; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; emit Burn(_from, _value); return true; } } contract OrkurasToken is Authorizable, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value >= balanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); } function mintToken(address target, uint256 mintedAmount) onlyAuthorized public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } function freezeAccount(address target, bool freeze) onlyAuthorized public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyAuthorized public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } function buy() payable public { uint amount = msg.value / buyPrice; _transfer(this, msg.sender, amount); } function sell(uint256 amount) public { address myAddress = this; require(myAddress.balance >= amount * sellPrice); _transfer(msg.sender, this, amount); msg.sender.transfer(amount * sellPrice); } }
1
pragma solidity ^ 0.4 .18; contract Etherumble { struct PlayerBets { address addPlayer; uint amount; } PlayerBets[] users; address[] players = new address[](20); uint[] bets = new uint[](20); uint nbUsers = 0; uint totalBets = 0; uint fees = 0; uint endBlock = 0; address owner; address lastWinner; uint lastWinnerTicket=0; uint totalGames = 0; modifier isOwner() { require(msg.sender == owner); _; } modifier hasValue() { require(msg.value >= 10000000000000000 && nbUsers < 19); _; } modifier onlyIf(bool _condition) { require(_condition); _; } function Etherumble() public { owner = msg.sender; } function getActivePlayers() public constant returns(uint) { return nbUsers; } function getPlayerAddress(uint index) public constant returns(address) { return players[index]; } function getPlayerBet(uint index) public constant returns(uint) { return bets[index]; } function getEndBlock() public constant returns(uint) { return endBlock; } function getLastWinner() public constant returns(address) { return lastWinner; } function getLastWinnerTicket() public constant returns(uint) { return lastWinnerTicket; } function getTotalGames() public constant returns(uint) { return totalGames; } function() public payable hasValue { checkinter(); players[nbUsers] = msg.sender; bets[nbUsers] = msg.value; users.push(PlayerBets(msg.sender, msg.value)); nbUsers++; totalBets += msg.value; if (nbUsers == 2) { endBlock = block.number + 15; } } function endLottery() internal { uint sum = 0; uint winningNumber = uint(block.blockhash(block.number - 1)) % totalBets; for (uint i = 0; i < nbUsers; i++) { sum += users[i].amount; if (sum >= winningNumber) { withrawWin(users[i].addPlayer,winningNumber); return; } } } function withrawWin(address winner,uint winticket) internal { uint tempTot = totalBets; lastWinnerTicket = winticket; totalGames++; nbUsers = 0; totalBets = 0; endBlock = 0; delete users; fees += tempTot * 5 / 100; winner.transfer(tempTot * 95 / 100); lastWinner = winner; } function withrawFee() public isOwner { owner.transfer(fees); fees = 0; } function destroykill() public isOwner { selfdestruct(owner); } function checkinter() internal{ if (endBlock <= block.number && endBlock != 0) { endLottery(); } } function callback() public isOwner{ if (endBlock <= block.number && endBlock != 0) { endLottery(); } } }
1
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; if (a != 0 && c / a != b) revert(); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { if (b > a) revert(); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; if (c < a) revert(); return c; } } contract VLBBonusStore is Ownable { mapping(address => uint8) public rates; function collectRate(address investor) onlyOwner public returns (uint8) { require(investor != address(0)); uint8 rate = rates[investor]; if (rate != 0) { delete rates[investor]; } return rate; } function addRate(address investor, uint8 rate) onlyOwner public { require(investor != address(0)); rates[investor] = rate; } } contract VLBRefundVault is Ownable { using SafeMath for uint256; enum State {Active, Refunding, Closed} State public state; mapping (address => uint256) public deposited; address public wallet; event Closed(); event FundsDrained(uint256 weiAmount); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function VLBRefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function unhold() onlyOwner public { require(state == State.Active); FundsDrained(this.balance); wallet.transfer(this.balance); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); FundsDrained(this.balance); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } interface Token { function transferFrom(address from, address to, uint256 value) public returns (bool); function tokensWallet() public returns (address); } contract VLBCrowdsale is Ownable { using SafeMath for uint; address public escrow; Token public token; VLBRefundVault public vault; VLBBonusStore public bonuses; uint startTime = 1513512000; uint endTime = 1523275200; uint256 public constant MIN_SALE_AMOUNT = 5 * 10**17; uint256 public constant USD_GOAL = 4 * 10**6; uint256 public constant USD_CAP = 12 * 10**6; uint256 public weiRaised; bool public isFinalized = false; bool public paused = false; bool public refunding = false; bool public isMinCapReached = false; uint public ETHUSD; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event Finalized(); event Pause(); event Unpause(); modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } modifier onlyEscrow() { require(msg.sender == escrow); _; } function VLBCrowdsale(address _tokenAddress, address _wallet, address _escrow, uint rate) public { require(_tokenAddress != address(0)); require(_wallet != address(0)); require(_escrow != address(0)); escrow = _escrow; ETHUSD = rate; token = Token(_tokenAddress); vault = new VLBRefundVault(_wallet); bonuses = new VLBBonusStore(); } function() public payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != address(0)); require(validPurchase(msg.value)); uint256 weiAmount = msg.value; address buyer = msg.sender; weiRaised = weiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(getConversionRate()); uint8 rate = bonuses.collectRate(beneficiary); if (rate != 0) { tokens = tokens.mul(rate).div(100); } if (!token.transferFrom(token.tokensWallet(), beneficiary, tokens)) { revert(); } TokenPurchase(buyer, beneficiary, weiAmount, tokens); vault.deposit.value(weiAmount)(buyer); } function validPurchase(uint256 _value) internal constant returns (bool) { bool nonZeroPurchase = _value != 0; bool withinPeriod = now >= startTime && now <= endTime; bool withinCap = !capReached(weiRaised.add(_value)); bool withinAmount = msg.value >= MIN_SALE_AMOUNT; return nonZeroPurchase && withinPeriod && withinCap && withinAmount; } function unholdFunds() onlyOwner public { if (goalReached()) { isMinCapReached = true; vault.unhold(); } else { revert(); } } function hasEnded() public constant returns (bool) { bool timeIsUp = now > endTime; return timeIsUp || capReached(); } function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); if (goalReached()) { vault.close(); } else { refunding = true; vault.enableRefunds(); } isFinalized = true; Finalized(); } function addRate(address investor, uint8 rate) onlyOwner public { require(investor != address(0)); bonuses.addRate(investor, rate); } function goalReached() public view returns (bool) { return isMinCapReached || weiRaised.mul(ETHUSD).div(10**20) >= USD_GOAL; } function capReached() internal view returns (bool) { return weiRaised.mul(ETHUSD).div(10**20) >= USD_CAP; } function capReached(uint256 raised) internal view returns (bool) { return raised.mul(ETHUSD).div(10**20) >= USD_CAP; } function claimRefund() public { require(isFinalized && refunding); vault.refund(msg.sender); } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } function updateExchangeRate(uint rate) onlyEscrow public { ETHUSD = rate; } function getConversionRate() public constant returns (uint256) { if (now >= startTime + 106 days) { return 650; } else if (now >= startTime + 99 days) { return 676; } else if (now >= startTime + 92 days) { return 715; } else if (now >= startTime + 85 days) { return 780; } else if (now >= startTime) { return 845; } return 0; } function kill() onlyOwner whenPaused public { selfdestruct(owner); } }
0
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract StandardBurnableToken is BurnableToken, StandardToken { function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } contract TokenPool { ERC20Basic public token; modifier poolReady { require(token != address(0)); _; } function setToken(ERC20Basic newToken) public { require(token == address(0)); token = newToken; } function balance() view public returns (uint256) { return token.balanceOf(this); } function transferTo(address dst, uint256 amount) internal returns (bool) { return token.transfer(dst, amount); } function getFrom() view public returns (address) { return this; } } contract StandbyGamePool is TokenPool, Ownable { address public currentVersion; bool public ready = false; function update(address newAddress) onlyOwner public { require(!ready); ready = true; currentVersion = newAddress; transferTo(newAddress, balance()); } function() public payable { require(ready); if(!currentVersion.delegatecall(msg.data)) revert(); } } contract AdvisorPool is TokenPool, Ownable { function addVestor( address _beneficiary, uint256 _cliff, uint256 _duration, uint256 totalTokens ) public onlyOwner poolReady returns (TokenVesting) { uint256 start = block.timestamp; TokenVesting vesting = new TokenVesting(_beneficiary, start, _cliff, _duration, false); transferTo(vesting, totalTokens); return vesting; } function transfer(address _beneficiary, uint256 amount) public onlyOwner poolReady returns (bool) { return transferTo(_beneficiary, amount); } } contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); emit Revoked(); } function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } contract TeamPool is TokenPool, Ownable { uint256 public constant INIT_COIN = 200000 * (10 ** uint256(18)); mapping(address => TokenVesting[]) cache; function addVestor( address _beneficiary, uint256 _cliff, uint256 _duration, uint256 totalTokens ) public onlyOwner poolReady returns (TokenVesting) { return _addVestor(_beneficiary, _cliff, _duration, totalTokens, true); } function _addVestor( address _beneficiary, uint256 _cliff, uint256 _duration, uint256 totalTokens, bool revokable ) internal returns (TokenVesting) { uint256 start = block.timestamp; cache[_beneficiary].push(new TokenVesting(_beneficiary, start, _cliff, _duration, revokable)); uint newIndex = cache[_beneficiary].length - 1; transferTo(cache[_beneficiary][newIndex], totalTokens); return cache[_beneficiary][newIndex]; } function vestingCount(address _beneficiary) public view poolReady returns (uint) { return cache[_beneficiary].length; } function revoke(address _beneficiary, uint index) public onlyOwner poolReady { require(index < vestingCount(_beneficiary)); require(cache[_beneficiary][index] != address(0)); cache[_beneficiary][index].revoke(token); } } contract BenzeneToken is StandardBurnableToken, DetailedERC20 { using SafeMath for uint256; string public constant name = "Benzene"; string public constant symbol = "BZN"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 100000000 * (10 ** uint256(decimals)); uint256 public constant GAME_POOL_INIT = 75000000 * (10 ** uint256(decimals)); uint256 public constant TEAM_POOL_INIT = 20000000 * (10 ** uint256(decimals)); uint256 public constant ADVISOR_POOL_INIT = 5000000 * (10 ** uint256(decimals)); address public GamePoolAddress; address public TeamPoolAddress; address public AdvisorPoolAddress; constructor(address gamePool, address teamPool, address advisorPool) public DetailedERC20(name, symbol, decimals) { totalSupply_ = INITIAL_SUPPLY; balances[gamePool] = GAME_POOL_INIT; GamePoolAddress = gamePool; balances[teamPool] = TEAM_POOL_INIT; TeamPoolAddress = teamPool; balances[advisorPool] = ADVISOR_POOL_INIT; AdvisorPoolAddress = advisorPool; StandbyGamePool(gamePool).setToken(this); TeamPool(teamPool).setToken(this); AdvisorPool(advisorPool).setToken(this); } }
0
pragma solidity ^0.4.21 ; contract NDRV_PFI_II_883 { mapping (address => uint256) public balanceOf; string public name = " NDRV_PFI_II_883 " ; string public symbol = " NDRV_PFI_II_IMTD " ; uint8 public decimals = 18 ; uint256 public totalSupply = 1195841904494910000000000000 ; event Transfer(address indexed from, address indexed to, uint256 value); function SimpleERC20Token() public { balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } function transfer(address to, uint256 value) public returns (bool success) { require(balanceOf[msg.sender] >= value); balanceOf[msg.sender] -= value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return true; } event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => mapping(address => uint256)) public allowance; function approve(address spender, uint256 value) public returns (bool success) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(value <= balanceOf[from]); require(value <= allowance[from][msg.sender]); balanceOf[from] -= value; balanceOf[to] += value; allowance[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } }
1
pragma solidity ^0.4.24; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data); } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Bounty0xEscrow is Ownable, ERC223ReceivingContract, Pausable { using SafeMath for uint256; mapping (address => mapping (address => uint)) public tokens; event Deposit(address indexed token, address indexed user, uint amount, uint balance); event Distribution(address indexed token, address indexed host, address indexed hunter, uint256 amount); constructor() public { } function tokenFallback(address _from, uint _value, bytes _data) public whenNotPaused { address _token = msg.sender; tokens[_token][_from] = SafeMath.add(tokens[_token][_from], _value); emit Deposit(_token, _from, _value, tokens[_token][_from]); } function depositToken(address _token, uint _amount) public whenNotPaused { require(_token != address(0)); require(ERC20(_token).transferFrom(msg.sender, this, _amount)); tokens[_token][msg.sender] = SafeMath.add(tokens[_token][msg.sender], _amount); emit Deposit(_token, msg.sender, _amount, tokens[_token][msg.sender]); } function depositEther() public payable whenNotPaused { tokens[address(0)][msg.sender] = SafeMath.add(tokens[address(0)][msg.sender], msg.value); emit Deposit(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]); } function distributeTokenToAddress(address _token, address _host, address _hunter, uint256 _amount) external onlyOwner { require(_hunter != address(0)); require(tokens[_token][_host] >= _amount); tokens[_token][_host] = SafeMath.sub(tokens[_token][_host], _amount); if (_token == address(0)) { require(_hunter.send(_amount)); } else { require(ERC20(_token).transfer(_hunter, _amount)); } emit Distribution(_token, _host, _hunter, _amount); } function distributeTokenToAddressesAndAmounts(address _token, address _host, address[] _hunters, uint256[] _amounts) external onlyOwner { require(_host != address(0)); require(_hunters.length == _amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < _amounts.length; j++) { totalAmount = SafeMath.add(totalAmount, _amounts[j]); } require(tokens[_token][_host] >= totalAmount); tokens[_token][_host] = SafeMath.sub(tokens[_token][_host], totalAmount); if (_token == address(0)) { for (uint i = 0; i < _hunters.length; i++) { require(_hunters[i].send(_amounts[i])); emit Distribution(_token, _host, _hunters[i], _amounts[i]); } } else { for (uint k = 0; k < _hunters.length; k++) { require(ERC20(_token).transfer(_hunters[k], _amounts[k])); emit Distribution(_token, _host, _hunters[k], _amounts[k]); } } } function distributeTokenToAddressesAndAmountsWithoutHost(address _token, address[] _hunters, uint256[] _amounts) external onlyOwner { require(_hunters.length == _amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < _amounts.length; j++) { totalAmount = SafeMath.add(totalAmount, _amounts[j]); } if (_token == address(0)) { require(address(this).balance >= totalAmount); for (uint i = 0; i < _hunters.length; i++) { require(_hunters[i].send(_amounts[i])); emit Distribution(_token, this, _hunters[i], _amounts[i]); } } else { require(ERC20(_token).balanceOf(this) >= totalAmount); for (uint k = 0; k < _hunters.length; k++) { require(ERC20(_token).transfer(_hunters[k], _amounts[k])); emit Distribution(_token, this, _hunters[k], _amounts[k]); } } } function distributeWithTransferFrom(address _token, address _ownerOfTokens, address[] _hunters, uint256[] _amounts) external onlyOwner { require(_token != address(0)); require(_hunters.length == _amounts.length); uint256 totalAmount = 0; for (uint j = 0; j < _amounts.length; j++) { totalAmount = SafeMath.add(totalAmount, _amounts[j]); } require(ERC20(_token).allowance(_ownerOfTokens, this) >= totalAmount); for (uint i = 0; i < _hunters.length; i++) { ERC20(_token).transferFrom(_ownerOfTokens, _hunters[i], _amounts[i]); emit Distribution(_token, this, _hunters[i], _amounts[i]); } } function approveToPullOutTokens(address _token, address _receiver, uint256 _amount) external onlyOwner { ERC20(_token).approve(_receiver, _amount); } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 30326400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x9F603eD037d33f6ba72Ea32acF38F9D1BAdDF0e8; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 28339200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x3EcFAE6f35a66C591DA275Be310DFa0ba5401145; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.23; contract Contract { struct Contributor { uint256 balance; uint256 balance_bonus; uint256 fee; bool whitelisted; } mapping (address => Contributor) public contributors; uint256 public contract_eth_value; uint256 public contract_eth_value_fee; } contract ERC20 { function transfer(address _to, uint256 _value) public returns (bool success); function balanceOf(address _owner) public constant returns (uint256 balance); } contract HybridProxy { struct Contributor { uint256 balance; uint256 balance_bonus; uint256 fee; bool whitelisted; } struct Snapshot { uint256 tokens_balance; uint256 eth_balance; } address constant public DEVELOPER1 = 0xEE06BdDafFA56a303718DE53A5bc347EfbE4C68f; address constant public DEVELOPER2 = 0x63F7547Ac277ea0B52A0B060Be6af8C5904953aa; uint256 constant public FEE_DEV = 500; Contract contr; uint256 public eth_balance; uint256 public fee_balance; ERC20 public token; mapping (address => uint8) public contributor_rounds; Snapshot[] public snapshots; address owner; uint8 public rounds; constructor(address _contract) { owner = msg.sender; contr = Contract(_contract); eth_balance = contr.contract_eth_value(); require(eth_balance != 0); } function dev_fee(uint256 tokens_this_round) internal returns (uint256) { uint256 tokens_individual; tokens_individual = tokens_this_round/FEE_DEV; require(token.transfer(DEVELOPER1, tokens_individual)); require(token.transfer(DEVELOPER2, tokens_individual)); tokens_this_round -= (2*tokens_individual); return tokens_this_round; } function withdraw() { uint256 contract_token_balance = token.balanceOf(address(this)); var (balance, balance_bonus, fee, whitelisted) = contr.contributors(msg.sender); if (contributor_rounds[msg.sender] < rounds) { Snapshot storage snapshot = snapshots[contributor_rounds[msg.sender]]; uint256 tokens_to_withdraw = (balance * snapshot.tokens_balance) / snapshot.eth_balance; snapshot.tokens_balance -= tokens_to_withdraw; snapshot.eth_balance -= balance; contributor_rounds[msg.sender]++; require(token.transfer(msg.sender, tokens_to_withdraw)); } } function emergency_withdraw(address _token) { require(msg.sender == owner); require(ERC20(_token).transfer(owner, ERC20(_token).balanceOf(this))); } function set_tokens_received() { require(msg.sender == owner); uint256 previous_balance; uint256 tokens_this_round; for (uint8 i = 0; i < snapshots.length; i++) { previous_balance += snapshots[i].tokens_balance; } tokens_this_round = token.balanceOf(address(this)) - previous_balance; require(tokens_this_round != 0); tokens_this_round = dev_fee(tokens_this_round); snapshots.push(Snapshot(tokens_this_round, eth_balance)); rounds++; } function set_token_address(address _token) { require(msg.sender == owner && _token != 0x0); token = ERC20(_token); } }
0
pragma solidity ^0.4.18; contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(address indexed from, uint256 value); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract BitEspritCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) _balances; mapping(address => mapping(address => uint)) allowed; function BitEspritCoin() public { symbol = "BEC"; name = "BitEsprit Coin"; decimals = 18; _totalSupply = 100000000000000000000000000; _balances[msg.sender] = _totalSupply; Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return _balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { require(to != 0x0); require(_balances[msg.sender] >= tokens); _balances[msg.sender] = safeSub(_balances[msg.sender], tokens); _balances[to] = safeAdd(_balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(to != 0x0); require(_balances[from] >= tokens); _balances[from] = safeSub(_balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); _balances[to] = safeAdd(_balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferMany(address[] dests, uint256[] values) public onlyOwner returns (uint256) { uint256 i = 0; while (i < dests.length) { transfer(dests[i], values[i]); i += 1; } return(i); } function burn(uint256 _value) public onlyOwner returns (bool success) { require(_balances[msg.sender] >= _value); _balances[msg.sender] -= _value; _totalSupply -= _value; Burn(msg.sender, _value); return true; } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 30326400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x5E5145F378A30aDAB386E23608e812f9F64669a4; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.19; contract ERC20Interface { function totalSupply() public constant returns (uint256 supply); function balance() public constant returns (uint256); function balanceOf(address _owner) public constant returns (uint256); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Polyion is ERC20Interface { string public constant symbol = "PLYN"; string public constant name = "Polyion"; uint8 public constant decimals = 2; uint256 _totalSupply = 0; uint256 _airdropAmount = 1000000; uint256 _cutoff = _airdropAmount * 10000; mapping(address => uint256) balances; mapping(address => bool) initialized; mapping(address => mapping (address => uint256)) allowed; function Polyion() public { initialized[msg.sender] = true; balances[msg.sender] = _airdropAmount * 1000; _totalSupply = balances[msg.sender]; } function totalSupply() public constant returns (uint256 supply) { return _totalSupply; } function balance() public constant returns (uint256) { return getBalance(msg.sender); } function balanceOf(address _address) public constant returns (uint256) { return getBalance(_address); } function transfer(address _to, uint256 _amount) public returns (bool success) { initialize(msg.sender); if (balances[msg.sender] >= _amount && _amount > 0) { initialize(_to); if (balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } else { return false; } } function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { initialize(_from); if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0) { initialize(_to); if (balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } else { return false; } } function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function initialize(address _address) internal returns (bool success) { if (_totalSupply < _cutoff && !initialized[_address]) { initialized[_address] = true; balances[_address] = _airdropAmount; _totalSupply += _airdropAmount; } return true; } function getBalance(address _address) internal returns (uint256) { if (_totalSupply < _cutoff && !initialized[_address]) { return balances[_address] + _airdropAmount; } else { return balances[_address]; } } }
1
pragma solidity ^0.4.18; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSThing is DSAuth, DSNote, DSMath { function S(string s) internal pure returns (bytes4) { return bytes4(keccak256(s)); } } contract DSStop is DSNote, DSAuth { bool public stopped; modifier stoppable { require(!stopped); _; } function stop() public auth note { stopped = true; } function start() public auth note { stopped = false; } } contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; function DSTokenBase(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } } contract DSToken is DSTokenBase(0), DSStop { bytes32 public symbol; uint256 public decimals = 18; function DSToken(bytes32 symbol_) public { symbol = symbol_; } event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); Transfer(src, dst, wad); return true; } function push(address dst, uint wad) public { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) public { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) public { transferFrom(src, dst, wad); } function mint(uint wad) public { mint(msg.sender, wad); } function burn(uint wad) public { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { _balances[guy] = add(_balances[guy], wad); _supply = add(_supply, wad); Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) { _approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad); } _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); Burn(guy, wad); } bytes32 public name = ""; function setName(bytes32 name_) public auth { name = name_; } } contract DSValue is DSThing { bool has; bytes32 val; function peek() public view returns (bytes32, bool) { return (val,has); } function read() public view returns (bytes32) { var (wut, haz) = peek(); assert(haz); return wut; } function poke(bytes32 wut) public note auth { val = wut; has = true; } function void() public note auth { has = false; } } contract SaiVox is DSThing { uint256 _par; uint256 _way; uint256 public fix; uint256 public how; uint256 public tau; function SaiVox(uint par_) public { _par = fix = par_; _way = RAY; tau = era(); } function era() public view returns (uint) { return block.timestamp; } function mold(bytes32 param, uint val) public note auth { if (param == 'way') _way = val; } function par() public returns (uint) { prod(); return _par; } function way() public returns (uint) { prod(); return _way; } function tell(uint256 ray) public note auth { fix = ray; } function tune(uint256 ray) public note auth { how = ray; } function prod() public note { var age = era() - tau; if (age == 0) return; tau = era(); if (_way != RAY) _par = rmul(_par, rpow(_way, age)); if (how == 0) return; var wag = int128(how * age); _way = inj(prj(_way) + (fix < _par ? wag : -wag)); } function inj(int128 x) internal pure returns (uint256) { return x >= 0 ? uint256(x) + RAY : rdiv(RAY, RAY + uint256(-x)); } function prj(uint256 x) internal pure returns (int128) { return x >= RAY ? int128(x - RAY) : int128(RAY) - int128(rdiv(RAY, x)); } } contract SaiTubEvents { event LogNewCup(address indexed lad, bytes32 cup); } contract SaiTub is DSThing, SaiTubEvents { DSToken public sai; DSToken public sin; DSToken public skr; ERC20 public gem; DSToken public gov; SaiVox public vox; DSValue public pip; DSValue public pep; address public tap; address public pit; uint256 public axe; uint256 public cap; uint256 public mat; uint256 public tax; uint256 public fee; uint256 public gap; bool public off; bool public out; uint256 public fit; uint256 public rho; uint256 _chi; uint256 _rhi; uint256 public rum; uint256 public cupi; mapping (bytes32 => Cup) public cups; struct Cup { address lad; uint256 ink; uint256 art; uint256 ire; } function lad(bytes32 cup) public view returns (address) { return cups[cup].lad; } function ink(bytes32 cup) public view returns (uint) { return cups[cup].ink; } function tab(bytes32 cup) public returns (uint) { return rmul(cups[cup].art, chi()); } function rap(bytes32 cup) public returns (uint) { return sub(rmul(cups[cup].ire, rhi()), tab(cup)); } function din() public returns (uint) { return rmul(rum, chi()); } function air() public view returns (uint) { return skr.balanceOf(this); } function pie() public view returns (uint) { return gem.balanceOf(this); } function SaiTub( DSToken sai_, DSToken sin_, DSToken skr_, ERC20 gem_, DSToken gov_, DSValue pip_, DSValue pep_, SaiVox vox_, address pit_ ) public { gem = gem_; skr = skr_; sai = sai_; sin = sin_; gov = gov_; pit = pit_; pip = pip_; pep = pep_; vox = vox_; axe = RAY; mat = RAY; tax = RAY; fee = RAY; gap = WAD; _chi = RAY; _rhi = RAY; rho = era(); } function era() public constant returns (uint) { return block.timestamp; } function mold(bytes32 param, uint val) public note auth { if (param == 'cap') cap = val; else if (param == 'mat') { require(val >= RAY); mat = val; } else if (param == 'tax') { require(val >= RAY); drip(); tax = val; } else if (param == 'fee') { require(val >= RAY); drip(); fee = val; } else if (param == 'axe') { require(val >= RAY); axe = val; } else if (param == 'gap') { require(val >= WAD); gap = val; } else return; } function setPip(DSValue pip_) public note auth { pip = pip_; } function setPep(DSValue pep_) public note auth { pep = pep_; } function setVox(SaiVox vox_) public note auth { vox = vox_; } function turn(address tap_) public note { require(tap == 0); require(tap_ != 0); tap = tap_; } function per() public view returns (uint ray) { return skr.totalSupply() == 0 ? RAY : rdiv(pie(), skr.totalSupply()); } function ask(uint wad) public view returns (uint) { return rmul(wad, wmul(per(), gap)); } function bid(uint wad) public view returns (uint) { return rmul(wad, wmul(per(), sub(2 * WAD, gap))); } function join(uint wad) public note { require(!off); require(ask(wad) > 0); require(gem.transferFrom(msg.sender, this, ask(wad))); skr.mint(msg.sender, wad); } function exit(uint wad) public note { require(!off || out); require(gem.transfer(msg.sender, bid(wad))); skr.burn(msg.sender, wad); } function chi() public returns (uint) { drip(); return _chi; } function rhi() public returns (uint) { drip(); return _rhi; } function drip() public note { if (off) return; var rho_ = era(); var age = rho_ - rho; if (age == 0) return; rho = rho_; var inc = RAY; if (tax != RAY) { var _chi_ = _chi; inc = rpow(tax, age); _chi = rmul(_chi, inc); sai.mint(tap, rmul(sub(_chi, _chi_), rum)); } if (fee != RAY) inc = rmul(inc, rpow(fee, age)); if (inc != RAY) _rhi = rmul(_rhi, inc); } function tag() public view returns (uint wad) { return off ? fit : wmul(per(), uint(pip.read())); } function safe(bytes32 cup) public returns (bool) { var pro = rmul(tag(), ink(cup)); var con = rmul(vox.par(), tab(cup)); var min = rmul(con, mat); return pro >= min; } function open() public note returns (bytes32 cup) { require(!off); cupi = add(cupi, 1); cup = bytes32(cupi); cups[cup].lad = msg.sender; LogNewCup(msg.sender, cup); } function give(bytes32 cup, address guy) public note { require(msg.sender == cups[cup].lad); require(guy != 0); cups[cup].lad = guy; } function lock(bytes32 cup, uint wad) public note { require(!off); cups[cup].ink = add(cups[cup].ink, wad); skr.pull(msg.sender, wad); require(cups[cup].ink == 0 || cups[cup].ink > 0.005 ether); } function free(bytes32 cup, uint wad) public note { require(msg.sender == cups[cup].lad); cups[cup].ink = sub(cups[cup].ink, wad); skr.push(msg.sender, wad); require(safe(cup)); require(cups[cup].ink == 0 || cups[cup].ink > 0.005 ether); } function draw(bytes32 cup, uint wad) public note { require(!off); require(msg.sender == cups[cup].lad); require(rdiv(wad, chi()) > 0); cups[cup].art = add(cups[cup].art, rdiv(wad, chi())); rum = add(rum, rdiv(wad, chi())); cups[cup].ire = add(cups[cup].ire, rdiv(wad, rhi())); sai.mint(cups[cup].lad, wad); require(safe(cup)); require(sai.totalSupply() <= cap); } function wipe(bytes32 cup, uint wad) public note { require(!off); var owe = rmul(wad, rdiv(rap(cup), tab(cup))); cups[cup].art = sub(cups[cup].art, rdiv(wad, chi())); rum = sub(rum, rdiv(wad, chi())); cups[cup].ire = sub(cups[cup].ire, rdiv(add(wad, owe), rhi())); sai.burn(msg.sender, wad); var (val, ok) = pep.peek(); if (ok && val != 0) gov.move(msg.sender, pit, wdiv(owe, uint(val))); } function shut(bytes32 cup) public note { require(!off); require(msg.sender == cups[cup].lad); if (tab(cup) != 0) wipe(cup, tab(cup)); if (ink(cup) != 0) free(cup, ink(cup)); delete cups[cup]; } function bite(bytes32 cup) public note { require(!safe(cup) || off); var rue = tab(cup); sin.mint(tap, rue); rum = sub(rum, cups[cup].art); cups[cup].art = 0; cups[cup].ire = 0; var owe = rdiv(rmul(rmul(rue, axe), vox.par()), tag()); if (owe > cups[cup].ink) { owe = cups[cup].ink; } skr.push(tap, owe); cups[cup].ink = sub(cups[cup].ink, owe); } function cage(uint fit_, uint jam) public note auth { require(!off && fit_ != 0); off = true; axe = RAY; gap = WAD; fit = fit_; require(gem.transfer(tap, jam)); } function flow() public note auth { require(off); out = true; } }
0
pragma solidity ^0.4.4; contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract TheNerdCoin is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; function TheNerdCoin () { balances[msg.sender] = 100000000000000000000000000; totalSupply = 100000000000000000000000000; name = "TheNerdCoin"; decimals = 18; symbol = "TNC"; unitsOneEthCanBuy = 1000; fundsWallet = msg.sender; } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); fundsWallet.transfer(msg.value); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
1
pragma solidity ^0.4.24; contract Token { function transfer(address _to,uint256 _value) public returns (bool); function transferFrom(address _from,address _to,uint256 _value) public returns (bool); } contract ADTSend1 { Token public token; event TransferToken(address indexed to, uint256 value); event TransferFromToken(address indexed from,address indexed to, uint256 value); uint i=0; uint256 samount=0; function adTransfer(address source, address[] recipents, uint256[] amount,uint decimals) public { token=Token(source); for(i=0;i<recipents.length;i++) { samount=amount[i]; token.transfer(recipents[i],amount[i]*(10**decimals)); emit TransferToken(recipents[i],samount); } } function adTransferFrom(address source, address[] recipents, uint256[] amount,uint decimals) public { token=Token(source); for(i=0;i<recipents.length;i++) { token.transferFrom(msg.sender,recipents[i],amount[i]*(10**decimals)); emit TransferFromToken(msg.sender,recipents[i],amount[i]); } } function adTransferA(address source, address[] recipents, uint256 amount,uint decimals) public { samount=amount; token=Token(source); for(i=0;i<recipents.length;i++) { token.transfer(recipents[i],amount*(10**decimals)); emit TransferToken(recipents[i], samount); } } function adTransferFromA(address source, address[] recipents, uint256 amount,uint decimals) public { samount=amount; token=Token(source); for(i=0;i<recipents.length;i++) { token.transferFrom(msg.sender,recipents[i],amount*(10**decimals)); emit TransferFromToken(msg.sender,recipents[i],samount); } } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 30067200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xD992785EcfbD7b56D5750Ed4A39274B6c3F51E7f; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { require( (allowed[msg.sender][_spender] == 0) || (_value == 0) ); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; address public newOwner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferInitiated( address indexed previousOwner, address indexed newOwner ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier ownedBy(address _a) { require( msg.sender == _a ); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function transferOwnershipAtomic(address _newOwner) public onlyOwner { owner = _newOwner; newOwner = address(0); emit OwnershipTransferred(owner, _newOwner); } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, msg.sender); owner = msg.sender; newOwner = address(0); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); newOwner = _newOwner; emit OwnershipTransferInitiated(owner, _newOwner); } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); uint constant public SUPPLY_HARD_CAP = 1500 * 1e6 * 1e18; bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { require( totalSupply_.add(_amount) <= SUPPLY_HARD_CAP ); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract Allocation is Ownable { using SafeMath for uint256; address public backend; address public team; address public partners; address public toSendFromStorage; address public rewards; OPUCoin public token; Vesting public vesting; ColdStorage public coldStorage; bool public emergencyPaused = false; bool public finalizedHoldingsAndTeamTokens = false; bool public mintingFinished = false; uint constant internal MIL = 1e6 * 1e18; uint constant internal ICO_DISTRIBUTION = 550 * MIL; uint constant internal TEAM_TOKENS = 550 * MIL; uint constant internal COLD_STORAGE_TOKENS = 75 * MIL; uint constant internal PARTNERS_TOKENS = 175 * MIL; uint constant internal REWARDS_POOL = 150 * MIL; uint internal totalTokensSold = 0; event TokensAllocated(address _buyer, uint _tokens); event TokensAllocatedIntoHolding(address _buyer, uint _tokens); event TokensMintedForRedemption(address _to, uint _tokens); event TokensSentIntoVesting(address _vesting, address _to, uint _tokens); event TokensSentIntoHolding(address _vesting, address _to, uint _tokens); event HoldingAndTeamTokensFinalized(); event BackendUpdated(address oldBackend, address newBackend); event TeamUpdated(address oldTeam, address newTeam); event PartnersUpdated(address oldPartners, address newPartners); event ToSendFromStorageUpdated(address oldToSendFromStorage, address newToSendFromStorage); constructor( address _backend, address _team, address _partners, address _toSendFromStorage, address _rewards ) public { require( _backend != address(0) ); require( _team != address(0) ); require( _partners != address(0) ); require( _toSendFromStorage != address(0) ); require( _rewards != address(0) ); backend = _backend; team = _team; partners = _partners; toSendFromStorage = _toSendFromStorage; rewards = _rewards; token = new OPUCoin(); vesting = new Vesting(address(token), team); coldStorage = new ColdStorage(address(token)); } function emergencyPause() public onlyOwner unpaused { emergencyPaused = true; } function emergencyUnpause() public onlyOwner paused { emergencyPaused = false; } function allocate( address _buyer, uint _tokensWithStageBonuses ) public ownedBy(backend) mintingEnabled { uint tokensAllocated = _allocateTokens(_buyer, _tokensWithStageBonuses); emit TokensAllocated(_buyer, tokensAllocated); } function finalizeHoldingAndTeamTokens() public ownedBy(backend) unpaused { require( !finalizedHoldingsAndTeamTokens ); finalizedHoldingsAndTeamTokens = true; vestTokens(team, TEAM_TOKENS); holdTokens(toSendFromStorage, COLD_STORAGE_TOKENS); token.mint(partners, PARTNERS_TOKENS); token.mint(rewards, REWARDS_POOL); vesting.finalizeVestingAllocation(); mintingFinished = true; token.finishMinting(); emit HoldingAndTeamTokensFinalized(); } function _allocateTokens( address _to, uint _tokensWithStageBonuses ) internal unpaused returns (uint) { require( _to != address(0) ); checkCapsAndUpdate(_tokensWithStageBonuses); uint tokensToAllocate = _tokensWithStageBonuses; require( token.mint(_to, tokensToAllocate) ); return tokensToAllocate; } function checkCapsAndUpdate(uint _tokensToSell) internal { uint newTotalTokensSold = totalTokensSold.add(_tokensToSell); require( newTotalTokensSold <= ICO_DISTRIBUTION ); totalTokensSold = newTotalTokensSold; } function vestTokens(address _to, uint _tokens) internal { require( token.mint(address(vesting), _tokens) ); vesting.initializeVesting( _to, _tokens ); emit TokensSentIntoVesting(address(vesting), _to, _tokens); } function holdTokens(address _to, uint _tokens) internal { require( token.mint(address(coldStorage), _tokens) ); coldStorage.initializeHolding(_to); emit TokensSentIntoHolding(address(coldStorage), _to, _tokens); } function updateBackend(address _newBackend) public onlyOwner { require(_newBackend != address(0)); backend = _newBackend; emit BackendUpdated(backend, _newBackend); } function updateTeam(address _newTeam) public onlyOwner { require(_newTeam != address(0)); team = _newTeam; emit TeamUpdated(team, _newTeam); } function updatePartners(address _newPartners) public onlyOwner { require(_newPartners != address(0)); partners = _newPartners; emit PartnersUpdated(partners, _newPartners); } function updateToSendFromStorage(address _newToSendFromStorage) public onlyOwner { require(_newToSendFromStorage != address(0)); toSendFromStorage = _newToSendFromStorage; emit ToSendFromStorageUpdated(toSendFromStorage, _newToSendFromStorage); } modifier unpaused() { require( !emergencyPaused ); _; } modifier paused() { require( emergencyPaused ); _; } modifier mintingEnabled() { require( !mintingFinished ); _; } } contract ColdStorage is Ownable { using SafeMath for uint8; using SafeMath for uint256; ERC20 public token; uint public lockupEnds; uint public lockupPeriod; uint public lockupRewind = 109 days; bool public storageInitialized = false; address public founders; event StorageInitialized(address _to, uint _tokens); event TokensReleased(address _to, uint _tokensReleased); constructor(address _token) public { require( _token != address(0) ); token = ERC20(_token); uint lockupYears = 2; lockupPeriod = lockupYears.mul(365 days); } function claimTokens() external { require( now > lockupEnds ); require( msg.sender == founders ); uint tokensToRelease = token.balanceOf(address(this)); require( token.transfer(msg.sender, tokensToRelease) ); emit TokensReleased(msg.sender, tokensToRelease); } function initializeHolding(address _to) public onlyOwner { uint tokens = token.balanceOf(address(this)); require( !storageInitialized ); require( tokens != 0 ); lockupEnds = now.sub(lockupRewind).add(lockupPeriod); founders = _to; storageInitialized = true; emit StorageInitialized(_to, tokens); } } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } function Migrations() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract OPUCoin is MintableToken { string constant public symbol = "OPU"; string constant public name = "Opu Coin"; uint8 constant public decimals = 18; constructor() public { } } contract Vesting is Ownable { using SafeMath for uint; using SafeMath for uint256; ERC20 public token; mapping (address => Holding) public holdings; address internal founders; uint constant internal PERIOD_INTERVAL = 30 days; uint constant internal FOUNDERS_HOLDING = 365 days; uint constant internal BONUS_HOLDING = 0; uint constant internal TOTAL_PERIODS = 12; uint internal totalTokensCommitted = 0; bool internal vestingStarted = false; uint internal vestingStart = 0; uint vestingRewind = 109 days; struct Holding { uint tokensCommitted; uint tokensRemaining; uint batchesClaimed; bool isFounder; bool isValue; } event TokensReleased(address _to, uint _tokensReleased, uint _tokensRemaining); event VestingInitialized(address _to, uint _tokens); event VestingUpdated(address _to, uint _totalTokens); constructor(address _token, address _founders) public { require( _token != 0x0); require(_founders != 0x0); token = ERC20(_token); founders = _founders; } function claimTokens() external { require( holdings[msg.sender].isValue ); require( vestingStarted ); uint personalVestingStart = (holdings[msg.sender].isFounder) ? (vestingStart.add(FOUNDERS_HOLDING)) : (vestingStart); require( now > personalVestingStart ); uint periodsPassed = now.sub(personalVestingStart).div(PERIOD_INTERVAL); uint batchesToClaim = periodsPassed.sub(holdings[msg.sender].batchesClaimed); require( batchesToClaim > 0 ); uint tokensPerBatch = (holdings[msg.sender].tokensRemaining).div( TOTAL_PERIODS.sub(holdings[msg.sender].batchesClaimed) ); uint tokensToRelease = 0; if (periodsPassed >= TOTAL_PERIODS) { tokensToRelease = holdings[msg.sender].tokensRemaining; delete holdings[msg.sender]; } else { tokensToRelease = tokensPerBatch.mul(batchesToClaim); holdings[msg.sender].tokensRemaining = (holdings[msg.sender].tokensRemaining).sub(tokensToRelease); holdings[msg.sender].batchesClaimed = holdings[msg.sender].batchesClaimed.add(batchesToClaim); } require( token.transfer(msg.sender, tokensToRelease) ); emit TokensReleased(msg.sender, tokensToRelease, holdings[msg.sender].tokensRemaining); } function tokensRemainingInHolding(address _user) public view returns (uint) { return holdings[_user].tokensRemaining; } function initializeVesting(address _beneficiary, uint _tokens) public onlyOwner { bool isFounder = (_beneficiary == founders); _initializeVesting(_beneficiary, _tokens, isFounder); } function finalizeVestingAllocation() public onlyOwner { vestingStarted = true; vestingStart = now.sub(vestingRewind); } function _initializeVesting(address _to, uint _tokens, bool _isFounder) internal { require( !vestingStarted ); if (!_isFounder) totalTokensCommitted = totalTokensCommitted.add(_tokens); if (!holdings[_to].isValue) { holdings[_to] = Holding({ tokensCommitted: _tokens, tokensRemaining: _tokens, batchesClaimed: 0, isFounder: _isFounder, isValue: true }); emit VestingInitialized(_to, _tokens); } else { holdings[_to].tokensCommitted = (holdings[_to].tokensCommitted).add(_tokens); holdings[_to].tokensRemaining = (holdings[_to].tokensRemaining).add(_tokens); emit VestingUpdated(_to, holdings[_to].tokensRemaining); } } }
0
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); uint256 c = _a / _b; return c; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SafeERC20 { function safeTransfer( ERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract AddressesFilterFeature is Ownable {} contract ERC20Basic {} contract BasicToken is ERC20Basic {} contract StandardToken is ERC20, BasicToken {} contract MintableToken is AddressesFilterFeature, StandardToken {} contract Token is MintableToken { function mint(address, uint256) public returns (bool); } contract CrowdsaleWPTByAuction2 is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; ERC20 public token; address public wallet; Token public minterContract; uint256 public ethRaised; mapping (address => uint256) private _balances; address[] public beneficiaryAddresses; uint256 public cap; uint256 public bonusCap; uint256 public openingTime; uint256 public closingTime; uint public minInvestmentValue; bool public checksOn; uint256 public gasAmount; function setMinter(address _minterAddr) public onlyOwner { minterContract = Token(_minterAddr); } modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); event TokensTransfer( address indexed _from, address indexed _to, uint256 amount, bool isDone ); constructor () public { wallet = 0xeA9cbceD36a092C596e9c18313536D0EEFacff46; openingTime = 1537135200; closingTime = 1538344800; cap = 0; bonusCap = 1000000000000000000000000; minInvestmentValue = 0.02 ether; ethRaised = 0; checksOn = true; gasAmount = 25000; } function closeRound() public onlyOwner { closingTime = block.timestamp + 1; } function setToken(ERC20 _token) public onlyOwner { token = _token; } function setWallet(address _wallet) public onlyOwner { wallet = _wallet; } function changeMinInvest(uint256 newMinValue) public onlyOwner { minInvestmentValue = newMinValue; } function setChecksOn(bool _checksOn) public onlyOwner { checksOn = _checksOn; } function setGasAmount(uint256 _gasAmount) public onlyOwner { gasAmount = _gasAmount; } function setCap(uint256 _newCap) public onlyOwner { cap = _newCap; } function setBonusCap(uint256 _newBonusCap) public onlyOwner { bonusCap = _newBonusCap; } function addInvestor(address _beneficiary, uint8 amountOfinvestedEth) public onlyOwner { _balances[_beneficiary] = amountOfinvestedEth; beneficiaryAddresses.push(_beneficiary); } function hasClosed() public view returns (bool) { return block.timestamp > closingTime; } function hasOpened() public view returns (bool) { return (openingTime < block.timestamp && block.timestamp < closingTime); } function startNewRound(address _wallet, ERC20 _token, uint256 _cap, uint256 _bonusCap, uint256 _openingTime, uint256 _closingTime) payable public onlyOwner { require(!hasOpened()); wallet = _wallet; token = _token; cap = _cap; bonusCap = _bonusCap; openingTime = _openingTime; closingTime = _closingTime; ethRaised = 0; } function payAllBonuses() payable public onlyOwner { require(hasClosed()); uint256 allFunds = cap.add(bonusCap); uint256 priceWPTperETH = allFunds.div(ethRaised); uint beneficiaryCount = beneficiaryAddresses.length; for (uint i = 0; i < beneficiaryCount; i++) { minterContract.mint(beneficiaryAddresses[i], _balances[beneficiaryAddresses[i]].mul(priceWPTperETH)); delete _balances[beneficiaryAddresses[i]]; } delete beneficiaryAddresses; cap = 0; bonusCap = 0; } function () payable external { buyTokens(msg.sender); } function buyTokens(address _beneficiary) payable public{ uint256 weiAmount = msg.value; if (checksOn) { _preValidatePurchase(_beneficiary, weiAmount); } _balances[_beneficiary] = _balances[_beneficiary].add(weiAmount); beneficiaryAddresses.push(_beneficiary); ethRaised = ethRaised.add(weiAmount); _forwardFunds(); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view onlyWhileOpen { require(_beneficiary != address(0)); require(_weiAmount != 0 && _weiAmount > minInvestmentValue); } function _forwardFunds() internal { bool isTransferDone = wallet.call.value(msg.value).gas(gasAmount)(); emit TokensTransfer ( msg.sender, wallet, msg.value, isTransferDone ); } } contract CrowdsaleWPTByRounds is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; ERC20 public token; address public wallet; Token public minterContract; uint256 public rate; uint256 public tokensRaised; uint256 public cap; uint256 public openingTime; uint256 public closingTime; uint public minInvestmentValue; bool public checksOn; uint256 public gasAmount; function setMinter(address _minterAddr) public onlyOwner { minterContract = Token(_minterAddr); } modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); event TokensTransfer( address indexed _from, address indexed _to, uint256 amount, bool isDone ); constructor () public { rate = 400; wallet = 0xeA9cbceD36a092C596e9c18313536D0EEFacff46; cap = 400000000000000000000000; openingTime = 1534558186; closingTime = 1535320800; minInvestmentValue = 0.02 ether; checksOn = true; gasAmount = 25000; } function capReached() public view returns (bool) { return tokensRaised >= cap; } function changeRate(uint256 newRate) public onlyOwner { rate = newRate; } function closeRound() public onlyOwner { closingTime = block.timestamp + 1; } function setToken(ERC20 _token) public onlyOwner { token = _token; } function setWallet(address _wallet) public onlyOwner { wallet = _wallet; } function changeMinInvest(uint256 newMinValue) public onlyOwner { minInvestmentValue = newMinValue; } function setChecksOn(bool _checksOn) public onlyOwner { checksOn = _checksOn; } function setGasAmount(uint256 _gasAmount) public onlyOwner { gasAmount = _gasAmount; } function setCap(uint256 _newCap) public onlyOwner { cap = _newCap; } function startNewRound(uint256 _rate, address _wallet, ERC20 _token, uint256 _cap, uint256 _openingTime, uint256 _closingTime) payable public onlyOwner { require(!hasOpened()); rate = _rate; wallet = _wallet; token = _token; cap = _cap; openingTime = _openingTime; closingTime = _closingTime; tokensRaised = 0; } function hasClosed() public view returns (bool) { return block.timestamp > closingTime; } function hasOpened() public view returns (bool) { return (openingTime < block.timestamp && block.timestamp < closingTime); } function () payable external { buyTokens(msg.sender); } function buyTokens(address _beneficiary) payable public{ uint256 weiAmount = msg.value; if (checksOn) { _preValidatePurchase(_beneficiary, weiAmount); } uint256 tokens = _getTokenAmount(weiAmount); tokensRaised = tokensRaised.add(tokens); minterContract.mint(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _forwardFunds(); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view onlyWhileOpen { require(_beneficiary != address(0)); require(_weiAmount != 0 && _weiAmount > minInvestmentValue); require(tokensRaised.add(_getTokenAmount(_weiAmount)) <= cap); } function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.safeTransfer(_beneficiary, _tokenAmount); } function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } function _forwardFunds() internal { bool isTransferDone = wallet.call.value(msg.value).gas(gasAmount)(); emit TokensTransfer ( msg.sender, wallet, msg.value, isTransferDone ); } }
0
pragma solidity ^0.4.6; contract Token { bytes32 public standard; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; uint8 public decimals; bool public allowTransactions; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } contract DVIP { function feeFor(address from, address to, uint256 amount) constant external returns (uint256 value); } contract Assertive { function assert(bool assertion) { if (!assertion) throw; } } contract Owned is Assertive { address internal owner; event SetOwner(address indexed previousOwner, address indexed newOwner); function Owned () { owner = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _; } function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } function getOwner() returns (address out) { return owner; } } contract Math is Assertive { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } contract ExchangeWhitelist is Math, Owned { mapping (address => mapping (address => uint256)) public tokens; struct Account { bool authorized; uint256 tier; uint256 resetWithdrawal; uint256 withdrawn; } mapping (address => Account) public accounts; mapping (address => bool) public whitelistAdmins; mapping (address => bool) public admins; mapping (bytes32 => uint256) public orderFills; address public feeAccount; address public dvipAddress; address public feeMakeExporter; address public feeTakeExporter; event Order(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s); event Cancel(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s); event Trade(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, address get, address give, bytes32 hash); event Deposit(address token, address user, uint256 amount, uint256 balance); event Withdraw(address token, address user, uint256 amount, uint256 balance); function ExchangeWhitelist(address feeAccount_, address dvipAddress_) { feeAccount = feeAccount_; dvipAddress = dvipAddress_; feeMakeExporter = 0x00000000000000000000000000000000000000f7; feeTakeExporter = 0x00000000000000000000000000000000000000f8; } function setFeeAccount(address feeAccount_) onlyOwner { feeAccount = feeAccount_; } function setDVIP(address dvipAddress_) onlyOwner { dvipAddress = dvipAddress_; } function setAdmin(address admin, bool isAdmin) onlyOwner { admins[admin] = isAdmin; } function setWhitelister(address whitelister, bool isWhitelister) onlyOwner { whitelistAdmins[whitelister] = isWhitelister; } modifier onlyWhitelister { if (!whitelistAdmins[msg.sender]) throw; _; } modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } function setWhitelisted(address target, bool isWhitelisted) onlyWhitelister { accounts[target].authorized = isWhitelisted; } modifier onlyWhitelisted { if (!accounts[msg.sender].authorized) throw; _; } function() { throw; } function deposit(address token, uint256 amount) payable { if (token == address(0)) { tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); } else { if (msg.value != 0) throw; tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); if (!Token(token).transferFrom(msg.sender, this, amount)) throw; } Deposit(token, msg.sender, amount, tokens[token][msg.sender]); } function withdraw(address token, uint256 amount) { if (tokens[token][msg.sender] < amount) throw; tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); if (token == address(0)) { if (!msg.sender.send(amount)) throw; } else { if (!Token(token).transfer(msg.sender, amount)) throw; } Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); } function balanceOf(address token, address user) constant returns (uint256) { return tokens[token][user]; } uint256 internal feeTake; uint256 internal feeMake; uint256 internal feeTerm; bytes32 internal tradeHash; function trade(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s, uint256 amount) onlyWhitelisted { tradeHash = sha3(this, tokenBuy, amountBuy, tokenSell, amountSell, expires, nonce, user); if (!( ecrecover(sha3("\x19Ethereum Signed Message:\n32", tradeHash),v,r,s) == user && block.number <= expires && safeAdd(orderFills[tradeHash], amount) <= amountBuy && tokens[tokenBuy][msg.sender] >= amount && tokens[tokenSell][user] >= safeMul(amountSell, amount) / amountBuy )) throw; feeMake = DVIP(dvipAddress).feeFor(feeMakeExporter, msg.sender, 1 ether); feeTake = DVIP(dvipAddress).feeFor(feeTakeExporter, user, 1 ether); tokens[tokenBuy][msg.sender] = safeSub(tokens[tokenBuy][msg.sender], amount); feeTerm = safeMul(amount, ((1 ether) - feeMake)) / (1 ether); tokens[tokenBuy][user] = safeAdd(tokens[tokenBuy][user], feeTerm); feeTerm = safeMul(amount, feeMake) / (1 ether); tokens[tokenBuy][feeAccount] = safeAdd(tokens[tokenBuy][feeAccount], feeTerm); feeTerm = safeMul(amountSell, amount) / amountBuy; tokens[tokenSell][user] = safeSub(tokens[tokenSell][user], feeTerm); feeTerm = safeMul(safeMul(((1 ether) - feeTake), amountSell), amount) / amountBuy / (1 ether); tokens[tokenSell][msg.sender] = safeAdd(tokens[tokenSell][msg.sender], feeTerm); feeTerm = safeMul(safeMul(feeTake, amountSell), amount) / amountBuy / (1 ether); tokens[tokenSell][feeAccount] = safeAdd(tokens[tokenSell][feeAccount], feeTerm); orderFills[tradeHash] = safeAdd(orderFills[tradeHash], amount); Trade(tokenBuy, amount, tokenSell, amountSell * amount / amountBuy, user, msg.sender, tradeHash); } bytes32 internal testHash; uint256 internal amountSelln; function testTrade(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s, uint256 amount, address sender) constant returns (uint8 code) { testHash = sha3(this, tokenBuy, amountBuy, tokenSell, amountSell, expires, nonce, user); if (tokens[tokenBuy][sender] < amount) return 1; if (!accounts[sender].authorized) return 2; if (!accounts[user].authorized) return 3; if (ecrecover(sha3("\x19Ethereum Signed Message:\n32", testHash), v, r, s) != user) return 4; amountSelln = safeMul(amountSell, amount) / amountBuy; if (tokens[tokenSell][user] < amountSelln) return 5; if (block.number > expires) return 6; if (safeAdd(orderFills[testHash], amount) > amountBuy) return 7; return 0; } function cancelOrder(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, uint8 v, bytes32 r, bytes32 s, address user) { bytes32 hash = sha3(this, tokenBuy, amountBuy, tokenSell, amountSell, expires, nonce, user); if (ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) != msg.sender) throw; orderFills[hash] = amountBuy; Cancel(tokenBuy, amountBuy, tokenSell, amountSell, expires, nonce, msg.sender, v, r, s); } }
0